Debian Codegraph @

plink2_fasta.cc

raw
1 // This file is part of PLINK 2.0, copyright (C) 2005-2025 Shaun Purcell,
2 // Christopher Chang.
3 //
4 // This program is free software: you can redistribute it and/or modify it
5 // under the terms of the GNU General Public License as published by the Free
6 // Software Foundation, either version 3 of the License, or (at your option)
7 // any later version.
8 //
9 // This program is distributed in the hope that it will be useful, but WITHOUT
10 // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
12 // more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17
18 #include "plink2_fasta.h"
19
20 #ifdef __cplusplus
21 namespace plink2 {
22 #endif
23
24 PglErr RefFromFaContig(const uintptr_t* variant_include, const uint32_t* variant_bps, const uintptr_t* allele_idx_offsets, const char* const* allele_storage, const ChrInfo* cip, const char* seqbuf, uint32_t force, uint32_t chr_fo_idx, uint32_t variant_uidx_last, uint32_t bp_end, AlleleCode* allele_permute, uintptr_t* nonref_flags, uint32_t* changed_ct_ptr, uint32_t* validated_ct_ptr, uint32_t* downgraded_ct_ptr) {
25 uintptr_t variant_uidx_base;
26 uintptr_t cur_bits;
27 BitIter1Start(variant_include, cip->chr_fo_vidx_start[chr_fo_idx], &variant_uidx_base, &cur_bits);
28 uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
29 if (variant_bps[variant_uidx_last] >= bp_end) {
30 const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
31 if (!force) {
32 char* write_iter = strcpya_k(g_logbuf, "Error: Contig '");
33 write_iter = chrtoa(cip, chr_idx, write_iter);
34 snprintf(write_iter, kLogbufSize - kMaxIdSlen - 32, "' in --fa file is too short; it is likely to be mismatched with your data. Add the 'force' modifier if this wasn't a mistake, and you just want to mark all reference alleles past the end as provisional.\n");
35 WordWrapB(0);
36 logerrputsb();
37 return kPglRetInconsistentInput;
38 } else {
39 char* write_iter = strcpya_k(g_logbuf, "Warning: Contig '");
40 write_iter = chrtoa(cip, chr_idx, write_iter);
41 snprintf(write_iter, kLogbufSize - kMaxIdSlen - 32, "' in --fa file is too short; it is likely to be mismatched with your data.\n");
42 WordWrapB(0);
43 logerrputsb();
44 }
45 // bugfix (16 Sep 2023): variant_uidx == variant_uidx_last is possible
46 const uint32_t offset = LowerBoundU32(&(variant_bps[variant_uidx]), variant_uidx_last - variant_uidx, bp_end);
47
48 const uint32_t chr_vidx_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
49 // set all bits in [variant_uidx + offset, chr_vidx_end), and count how
50 // many relevant bits were set.
51 const uint32_t widx_full_end = chr_vidx_end / kBitsPerWord;
52 const uint32_t trailing_bit_ct = chr_vidx_end % kBitsPerWord;
53 const uint32_t chr_vidx_truncate = variant_uidx + offset;
54 uint32_t widx = chr_vidx_truncate / kBitsPerWord;
55 uint32_t downgraded_incr;
56 if (widx == widx_full_end) {
57 const uintptr_t cur_mask = (k1LU << trailing_bit_ct) - (k1LU << (chr_vidx_truncate % kBitsPerWord));
58 downgraded_incr = PopcountWord(variant_include[widx] & (~nonref_flags[widx]) & cur_mask);
59 nonref_flags[widx] |= cur_mask;
60 } else {
61 downgraded_incr = 0;
62 if (chr_vidx_truncate % kBitsPerWord) {
63 const uintptr_t cur_mask = (~k0LU) << (chr_vidx_truncate % kBitsPerWord);
64 downgraded_incr = PopcountWord(variant_include[widx] & (~nonref_flags[widx]) & cur_mask);
65 nonref_flags[widx] |= cur_mask;
66 ++widx;
67 }
68 assert(widx > widx_full_end);
69 for (; widx != widx_full_end; ++widx) {
70 downgraded_incr += PopcountWord(variant_include[widx] & (~nonref_flags[widx]));
71 nonref_flags[widx] = ~k0LU;
72 }
73 if (trailing_bit_ct) {
74 const uintptr_t cur_mask = (k1LU << trailing_bit_ct) - k1LU;
75 downgraded_incr += PopcountWord(variant_include[widx] & (~nonref_flags[widx]) & cur_mask);
76 nonref_flags[widx] |= cur_mask;
77 }
78 }
79 *downgraded_ct_ptr += downgraded_incr;
80 if (!offset) {
81 return kPglRetSuccess;
82 }
83 // We know that variant_bps[variant_uidx + offset - 1] < bp_end,
84 // variant_bps[variant_uidx + offset] >= bp_end, and that at least one
85 // variant_include[] bit is set in [variant_uidx, variant_uidx + offset)
86 // (since offset > 0). Find the last such bit.
87 variant_uidx_last = FindLast1BitBefore(variant_include, chr_vidx_truncate);
88 }
89 uint32_t changed_ct = *changed_ct_ptr;
90 uint32_t validated_ct = *validated_ct_ptr;
91 uint32_t allele_ct = 2;
92 for (; ; variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits)) {
93 const uint32_t cur_bp = variant_bps[variant_uidx];
94 uintptr_t allele_idx_offset_base = variant_uidx * 2;
95 if (allele_idx_offsets) {
96 allele_idx_offset_base = allele_idx_offsets[variant_uidx];
97 allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base;
98 }
99 const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
100 const char* cur_ref = &(seqbuf[cur_bp]);
101 int32_t consistent_allele_idx = -1;
102 for (uint32_t allele_idx = 0; allele_idx != allele_ct; ++allele_idx) {
103 const char* cur_allele = cur_alleles[allele_idx];
104 const uint32_t cur_allele_slen = strlen(cur_allele);
105 if (strcaseequal(cur_allele, cur_ref, cur_allele_slen)) {
106 if (consistent_allele_idx != -1) {
107 // Multiple alleles could be ref (this always happens for deletions).
108 // Don't try to do anything.
109 consistent_allele_idx = -2;
110 break;
111 }
112 consistent_allele_idx = allele_idx;
113 }
114 }
115 if (consistent_allele_idx >= 0) {
116 if (consistent_allele_idx) {
117 if ((!IsSet(nonref_flags, variant_uidx)) && (!force)) {
118 const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
119 char* write_iter = strcpya_k(g_logbuf, "Error: --ref-from-fa wants to change reference allele assignment at ");
120 write_iter = chrtoa(cip, chr_idx, write_iter);
121 *write_iter++ = ':';
122 write_iter = u32toa(cur_bp, write_iter);
123 snprintf(write_iter, kLogbufSize - kMaxIdSlen - 128, ", but it's marked as 'known'. Add the 'force' modifier to force this change through.\n");
124 WordWrapB(0);
125 logerrputsb();
126 return kPglRetInconsistentInput;
127 }
128 AlleleCode* cur_allele_permute = &(allele_permute[allele_idx_offset_base]);
129 cur_allele_permute[0] = consistent_allele_idx;
130 cur_allele_permute[1] = 0;
131 if (allele_ct > 2) {
132 for (uint32_t uii = 1; uii != S_CAST(uint32_t, consistent_allele_idx); ++uii) {
133 cur_allele_permute[uii + 1] = uii;
134 }
135 }
136 ++changed_ct;
137 } else {
138 ++validated_ct;
139 }
140 ClearBit(variant_uidx, nonref_flags);
141 } else if ((consistent_allele_idx == -1) && (!IsSet(nonref_flags, variant_uidx))) {
142 // okay to have multiple matches, but not zero matches
143 if (!force) {
144 const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
145 char* write_iter = strcpya_k(g_logbuf, "Error: Reference allele at ");
146 write_iter = chrtoa(cip, chr_idx, write_iter);
147 *write_iter++ = ':';
148 write_iter = u32toa(cur_bp, write_iter);
149 snprintf(write_iter, kLogbufSize - kMaxIdSlen - 64, " is marked as 'known', but is inconsistent with .fa file. Add the 'force' modifier to downgrade it to provisional.\n");
150 WordWrapB(0);
151 logerrputsb();
152 return kPglRetInconsistentInput;
153 }
154 SetBit(variant_uidx, nonref_flags);
155 *downgraded_ct_ptr += 1;
156 }
157 if (variant_uidx == variant_uidx_last) {
158 *changed_ct_ptr = changed_ct;
159 *validated_ct_ptr = validated_ct;
160 return kPglRetSuccess;
161 }
162 }
163 }
164
165 PglErr VNormalizeContig(const uintptr_t* variant_include, const char* const* variant_ids, const uintptr_t* allele_idx_offsets, const ChrInfo* cip, const char* seqbuf, uint32_t chr_fo_idx, uint32_t variant_uidx_last, uint32_t bp_end, uint32_t adjust_overlapping_deletions, uint32_t output_missing_geno_code, unsigned char** alloc_endp, UnsortedVar* vpos_sortstatusp, uint32_t* __restrict variant_bps, const char** allele_storage, uint32_t* __restrict nchanged_ct_ptr, char* nlist_flush, FILE* nlist_file, char** nlist_write_iterp, uint32_t* __restrict alen_buf, uintptr_t* __restrict allele_skip_buf) {
166 uintptr_t variant_uidx_base;
167 uintptr_t cur_bits;
168 BitIter1Start(variant_include, cip->chr_fo_vidx_start[chr_fo_idx], &variant_uidx_base, &cur_bits);
169 uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
170 if (variant_bps[variant_uidx_last] >= bp_end) {
171 const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
172 char* write_iter = strcpya_k(g_logbuf, "Error: Contig '");
173 write_iter = chrtoa(cip, chr_idx, write_iter);
174 snprintf(write_iter, kLogbufSize - kMaxIdSlen - 32, "' in --fa file is too short; it is likely to be mismatched with your data.\n");
175 WordWrapB(0);
176 logerrputsb();
177 return kPglRetInconsistentInput;
178 }
179 const char* star_str_adjust = adjust_overlapping_deletions? (&(g_one_char_strs[84])) : (&(g_one_char_strs[0]));
180 const char* missing_allele_str = &(g_one_char_strs[92]);
181 const uint32_t star_code_noadjust = adjust_overlapping_deletions? 0 : 42;
182 unsigned char* alloc_base = g_bigstack_base;
183 unsigned char* alloc_end = *alloc_endp;
184 char* nlist_write_iter = *nlist_write_iterp;
185 uint32_t nchanged_ct = *nchanged_ct_ptr;
186 uint32_t allele_ct = 2;
187 uint32_t prev_bp = 0;
188 uint32_t is_unsorted = ((*vpos_sortstatusp) / kfUnsortedVarBp) & 1;
189 uint32_t cur_bp;
190 goto VNormalizeContig_loop_start;
191 while (1) {
192 if (!is_unsorted) {
193 if (prev_bp > cur_bp) {
194 is_unsorted = 1;
195 }
196 prev_bp = cur_bp;
197 }
198 if (variant_uidx == variant_uidx_last) {
199 break;
200 }
201 variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
202 VNormalizeContig_loop_start:
203 cur_bp = variant_bps[variant_uidx];
204 uintptr_t allele_idx_offset_base = variant_uidx * 2;
205 if (allele_idx_offsets) {
206 allele_idx_offset_base = allele_idx_offsets[variant_uidx];
207 allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base;
208 }
209 const char** cur_alleles = &(allele_storage[allele_idx_offset_base]);
210 {
211 uint32_t aidx = 0;
212 // Common case: if all alleles have length 1, variant must already be
213 // normalized.
214 for (; aidx != allele_ct; ++aidx) {
215 if (cur_alleles[aidx][1]) {
216 break;
217 }
218 }
219 if (aidx == allele_ct) {
220 continue;
221 }
222 }
223 // Ignore missing (and possibly '*') alleles, get length of each allele,
224 // check if all right nucleotides match or all left nucleotides match
225 const uint32_t allele_ct_p1l = 1 + (allele_ct / kBitsPerWord);
226 ZeroWArr(allele_ct_p1l, allele_skip_buf);
227 uint32_t left_match = UINT32_MAX;
228 uint32_t right_match = UINT32_MAX;
229 uint32_t min_alen = 0;
230 for (uint32_t aidx = 0; aidx != allele_ct; ++aidx) {
231 const char* cur_allele = cur_alleles[aidx];
232 const uint32_t alen = strlen(cur_allele);
233 alen_buf[aidx] = alen;
234 const uint32_t first_code = ctou32(cur_allele[0]);
235 // Special case: if first character of any allele is '<', skip the entire
236 // variant.
237 if ((first_code == '<') || (first_code == star_code_noadjust)) {
238 left_match = UINT32_MAX;
239 right_match = UINT32_MAX;
240 break;
241 }
242 if ((cur_alleles[aidx] == missing_allele_str) || (cur_alleles[aidx] == star_str_adjust)) {
243 SetBit(aidx, allele_skip_buf);
244 continue;
245 }
246 const uint32_t last_code = ctou32(cur_allele[alen - 1]);
247 if (!min_alen) {
248 // must be first nonmissing allele
249 left_match = first_code;
250 right_match = last_code;
251 min_alen = alen;
252 } else {
253 if (first_code != left_match) {
254 left_match = UINT32_MAX;
255 }
256 if (last_code != right_match) {
257 right_match = UINT32_MAX;
258 }
259 if (alen < min_alen) {
260 min_alen = alen;
261 }
262 }
263 }
264 if (((left_match == UINT32_MAX) || (min_alen == 1)) && (right_match == UINT32_MAX)) {
265 continue;
266 }
267 const uint32_t first_aidx = AdvTo0Bit(allele_skip_buf, 0);
268 ++nchanged_ct;
269 if (nlist_write_iter) {
270 nlist_write_iter = strcpya(nlist_write_iter, variant_ids[variant_uidx]);
271 AppendBinaryEoln(&nlist_write_iter);
272 if (unlikely(fwrite_ck(nlist_flush, nlist_file, &nlist_write_iter))) {
273 return kPglRetWriteFail;
274 }
275 }
276 // Algorithm from Tan A, Abecasis GR, Kang HM (2015) Unified representation
277 // of genetic variants:
278 // while (alleles end with the same nucleotide) {
279 // truncate rightmost
280 // if there's now an empty allele, extend alleles 1 base to the left
281 // }
282 // while (all alleles length > 1 and start with same nucleotide) {
283 // truncate leftmost
284 // }
285 // https://genome.sph.umich.edu/wiki/Variant_Normalization also covers
286 // this.
287 const uint32_t rtrim_stop = cur_bp + min_alen - 1;
288 if ((right_match == UINT32_MAX) || (!rtrim_stop)) {
289 // Easy case: only left-trimming. We separate this out because bigstack
290 // allocation is never required.
291 const uint32_t min_alen_m1 = min_alen - 1;
292 uint32_t ltrim = 1;
293 uint32_t ltrim_p1;
294 for (; ltrim != min_alen_m1; ++ltrim) {
295 const char cc = cur_alleles[first_aidx][ltrim];
296 for (uint32_t aidx = first_aidx + 1; aidx != allele_ct; ++aidx) {
297 if (IsSet(allele_skip_buf, aidx)) {
298 continue;
299 }
300 if (cur_alleles[aidx][ltrim] != cc) {
301 goto VNormalizeContig_ltrim1_done;
302 }
303 }
304 }
305 VNormalizeContig_ltrim1_done:
306 ltrim_p1 = ltrim + 1;
307 for (uint32_t aidx = first_aidx; aidx != allele_ct; ++aidx) {
308 if (IsSet(allele_skip_buf, aidx)) {
309 continue;
310 }
311 if (alen_buf[aidx] == ltrim_p1) {
312 const uint32_t cur_code = ctou32(cur_alleles[aidx][ltrim]);
313 if ((cur_code == 46) || (cur_code == output_missing_geno_code)) {
314 const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
315 char* write_iter = strcpya_k(g_logbuf, "Error: Variant at ");
316 write_iter = chrtoa(cip, chr_idx, write_iter);
317 *write_iter++ = ':';
318 write_iter = u32toa(cur_bp, write_iter);
319 snprintf(write_iter, kLogbufSize - kMaxIdSlen - 128, " has an invalid normalized allele (conflicts with missing code).\n");
320 WordWrapB(0);
321 logerrputsb();
322 return kPglRetInconsistentInput;
323 }
324 cur_alleles[aidx] = &(g_one_char_strs[2 * cur_code]);
325 } else {
326 cur_alleles[aidx] = &(cur_alleles[aidx][ltrim]);
327 }
328 }
329 cur_bp += ltrim;
330 variant_bps[variant_uidx] = cur_bp;
331 continue;
332 }
333 // cur_bp == 0 is possible for e.g. an indel at the beginning of chr17.
334 const char* prev_ref = &(seqbuf[S_CAST(int32_t, cur_bp) - 1]);
335 uint32_t rtrim = 0;
336 uint32_t lshift = 0;
337 uint32_t ltrim = 0;
338 const char* shifted_ref = nullptr;
339 do {
340 ++rtrim;
341 uint32_t cur_alen = alen_buf[first_aidx];
342 if (rtrim >= cur_alen) {
343 right_match = ctou32(prev_ref[S_CAST(int32_t, cur_alen - rtrim)]);
344 } else {
345 right_match = ctou32(cur_alleles[first_aidx][cur_alen - 1 - rtrim]);
346 }
347 for (uint32_t aidx = first_aidx + 1; aidx != allele_ct; ++aidx) {
348 if (IsSet(allele_skip_buf, aidx)) {
349 continue;
350 }
351 cur_alen = alen_buf[aidx];
352 uint32_t cur_code;
353 if (rtrim >= cur_alen) {
354 cur_code = ctou32(prev_ref[S_CAST(int32_t, cur_alen - rtrim)]);
355 } else {
356 cur_code = ctou32(cur_alleles[aidx][cur_alen - 1 - rtrim]);
357 }
358 if (right_match != cur_code) {
359 goto VNormalizeContig_rtrim_done;
360 }
361 }
362 } while (rtrim != rtrim_stop);
363 VNormalizeContig_rtrim_done:
364 if (rtrim >= min_alen) {
365 lshift = rtrim + 1 - min_alen;
366 cur_bp -= lshift;
367 shifted_ref = &(seqbuf[cur_bp]);
368 // min_alen = 1;
369 variant_bps[variant_uidx] = cur_bp;
370 } else {
371 min_alen -= rtrim;
372 if ((left_match != UINT32_MAX) && (min_alen > 1)) {
373 const uint32_t min_alen_m1 = min_alen - 1;
374 ltrim = 1;
375 for (; ltrim != min_alen_m1; ++ltrim) {
376 left_match = ctou32(cur_alleles[first_aidx][ltrim]);
377 for (uint32_t aidx = first_aidx + 1; aidx != allele_ct; ++aidx) {
378 if (IsSet(allele_skip_buf, aidx)) {
379 continue;
380 }
381 const uint32_t cur_code = ctou32(cur_alleles[aidx][ltrim]);
382 if (left_match != cur_code) {
383 goto VNormalizeContig_ltrim2_done;
384 }
385 }
386 }
387 }
388 VNormalizeContig_ltrim2_done:
389 cur_bp += ltrim;
390 variant_bps[variant_uidx] = cur_bp;
391 }
392 for (uint32_t aidx = first_aidx; aidx != allele_ct; ++aidx) {
393 if (IsSet(allele_skip_buf, aidx)) {
394 continue;
395 }
396 const uint32_t orig_alen = alen_buf[aidx];
397 if (orig_alen <= rtrim) {
398 // Must be single-character from .fa.
399 cur_alleles[aidx] = &(g_one_char_strs[2 * ctou32(prev_ref[S_CAST(int32_t, orig_alen - rtrim)])]);
400 } else {
401 uint32_t new_slen = orig_alen + lshift - rtrim - ltrim;
402 const char* cur_allele = &(cur_alleles[aidx][ltrim]);
403 if (new_slen == 1) {
404 cur_alleles[aidx] = &(g_one_char_strs[2 * ctou32(cur_allele[0])]);
405 } else {
406 if (S_CAST(uintptr_t, alloc_end - alloc_base) <= new_slen) {
407 return kPglRetNomem;
408 }
409 alloc_end -= new_slen + 1;
410 char* new_allele = R_CAST(char*, alloc_end);
411 char* new_allele_iter = new_allele;
412 if (lshift) {
413 if (lshift < new_slen) {
414 new_allele_iter = memcpya(new_allele_iter, shifted_ref, lshift);
415 new_slen -= lshift;
416 } else {
417 new_allele_iter = memcpya(new_allele_iter, shifted_ref, new_slen);
418 new_slen = 0;
419 }
420 }
421 new_allele_iter = memcpya(new_allele_iter, cur_allele, new_slen);
422 *new_allele_iter = '\0';
423 cur_alleles[aidx] = new_allele;
424 }
425 }
426 }
427 }
428 *alloc_endp = alloc_end;
429 if (is_unsorted) {
430 *vpos_sortstatusp |= kfUnsortedVarBp;
431 }
432 *nchanged_ct_ptr = nchanged_ct;
433 *nlist_write_iterp = nlist_write_iter;
434 return kPglRetSuccess;
435 }
436
437 PglErr ProcessFa(const uintptr_t* variant_include, const char* const* variant_ids, const uintptr_t* allele_idx_offsets, const ChrInfo* cip, const char* fname, uint32_t max_allele_ct, uint32_t max_allele_slen, FaFlags flags, uint32_t output_missing_geno_code, uint32_t max_thread_ct, UnsortedVar* vpos_sortstatusp, uint32_t* variant_bps, const char** allele_storage, AlleleCode* allele_permute, uintptr_t* nonref_flags, uint32_t* contig_lens, char* outname, char* outname_end) {
438 unsigned char* bigstack_mark = g_bigstack_base;
439 uintptr_t line_idx = 0;
440 FILE* nlist_file = nullptr;
441 PglErr reterr = kPglRetSuccess;
442 TextStream fa_txs;
443 PreinitTextStream(&fa_txs);
444 {
445 const uint32_t chr_ct = cip->chr_ct;
446 char* chr_name_buf;
447 uintptr_t* chr_already_seen;
448 if (unlikely(bigstack_calloc_w(BitCtToWordCt(chr_ct), &chr_already_seen) ||
449 bigstack_alloc_c(kMaxIdBlen, &chr_name_buf))) {
450 goto ProcessFa_ret_NOMEM;
451 }
452 uint32_t* alen_buf = nullptr;
453 uintptr_t* allele_skip_buf = nullptr;
454 char* nlist_write_iter = nullptr;
455 char* nlist_flush = nullptr;
456 if (flags & kfFaNormalize) {
457 if (unlikely(bigstack_alloc_u32(max_allele_ct, &alen_buf) ||
458 bigstack_alloc_w(1 + (max_allele_ct / kBitsPerWord), &allele_skip_buf))) {
459 goto ProcessFa_ret_NOMEM;
460 }
461 if (flags & kfFaNormalizeList) {
462 snprintf(outname_end, kMaxOutfnameExtBlen, ".normalized");
463 if (unlikely(fopen_checked(outname, FOPEN_WB, &nlist_file))) {
464 goto ProcessFa_ret_OPEN_FAIL;
465 }
466 nlist_write_iter = g_textbuf;
467 nlist_flush = &(nlist_write_iter[kMaxMediumLine]);
468 }
469 }
470
471 // To simplify indel/complex-variant handling, we load an entire contig at
472 // a time. Determine an upper bound for the number of bases we must keep
473 // from a contig.
474 // (If a contig is longer than this, we don't load the trailing bases,
475 // since they are irrelevant to the
476 // normalization/REF-correction/length-count operation(s) we're currently
477 // performing.)
478 const uintptr_t* chr_mask = cip->chr_mask;
479 uint32_t seqbuf_size = 0;
480 for (uint32_t chr_fo_idx = 0; chr_fo_idx != chr_ct; ++chr_fo_idx) {
481 if (!IsSet(chr_mask, cip->chr_file_order[chr_fo_idx])) {
482 continue;
483 }
484 const int32_t chr_vidx_start_m1 = cip->chr_fo_vidx_start[chr_fo_idx] - 1;
485 const int32_t chr_vidx_last = FindLast1BitBeforeBounded(variant_include, cip->chr_fo_vidx_start[chr_fo_idx + 1], chr_vidx_start_m1);
486 if (chr_vidx_last != chr_vidx_start_m1) {
487 const uint32_t cur_bp = variant_bps[S_CAST(uint32_t, chr_vidx_last)];
488 if (cur_bp > seqbuf_size) {
489 seqbuf_size = cur_bp;
490 }
491 }
492 }
493 seqbuf_size += max_allele_slen + 1;
494 char* seqbuf;
495 if (unlikely(bigstack_alloc_c(seqbuf_size, &seqbuf))) {
496 goto ProcessFa_ret_NOMEM;
497 }
498 // May as well handle insertion before first contig base, and deletion of
499 // first base, correctly.
500 seqbuf[0] = 'N';
501
502 reterr = SizeAndInitTextStream(fname, bigstack_left(), MAXV(max_thread_ct - 1, 1), &fa_txs);
503 if (unlikely(reterr)) {
504 goto ProcessFa_ret_TSTREAM_FAIL;
505 }
506
507 unsigned char* tmp_alloc_end = g_bigstack_end;
508 char* seqbuf_end = nullptr;
509 char* seq_iter = nullptr;
510 // possible but low-priority todo: exploit .fai when it's present
511 uint32_t chr_fo_idx = UINT32_MAX;
512 uint32_t chr_idx = UINT32_MAX;
513 uint32_t cur_vidx_last = 0;
514 uint32_t skip_chr = 1;
515 uint32_t is_first_noncomment_line = 1;
516 uint32_t ref_changed_ct = 0;
517 uint32_t ref_validated_ct = 0;
518 uint32_t ref_downgraded_ct = 0;
519 uint32_t nchanged_ct = 0;
520
521 // If a contig contains a gap ('-'), we set the high bit of this value.
522 uint64_t skipped_base_ct = 0;
523
524 while (1) {
525 ++line_idx;
526 char* line_iter;
527 reterr = TextNextLine(&fa_txs, &line_iter);
528 if (reterr) {
529 if (likely(reterr == kPglRetEof)) {
530 reterr = kPglRetSuccess;
531 break;
532 }
533 goto ProcessFa_ret_TSTREAM_FAIL;
534 }
535 unsigned char ucc = line_iter[0];
536 if (ucc < 'A') {
537 // > = ascii 62
538 // ; = ascii 59
539 // bugfix (25 May 2021): newline is also valid
540 if ((ucc == ';') || ((ucc < 32) && (ucc != '\t'))) {
541 continue;
542 }
543 is_first_noncomment_line = 0;
544 if (unlikely(ucc != '>')) {
545 snprintf(g_logbuf, kLogbufSize, "Error: Unexpected character at beginning of line %" PRIuPTR " of --fa file.\n", line_idx);
546 goto ProcessFa_ret_MALFORMED_INPUT_WW;
547 }
548 if (chr_fo_idx != UINT32_MAX) {
549 *seq_iter = '\0';
550 const uint32_t bp_end = seq_iter - seqbuf;
551 if (flags & kfFaRefFrom) {
552 reterr = RefFromFaContig(variant_include, variant_bps, allele_idx_offsets, allele_storage, cip, seqbuf, flags & kfFaRefFromForce, chr_fo_idx, cur_vidx_last, bp_end, allele_permute, nonref_flags, &ref_changed_ct, &ref_validated_ct, &ref_downgraded_ct);
553 if (unlikely(reterr)) {
554 goto ProcessFa_ret_1;
555 }
556 }
557 if (flags & kfFaNormalize) {
558 reterr = VNormalizeContig(variant_include, variant_ids, allele_idx_offsets, cip, seqbuf, chr_fo_idx, cur_vidx_last, bp_end, flags & kfFaNormalizeAdjustOverlappingDeletions, output_missing_geno_code, &tmp_alloc_end, vpos_sortstatusp, variant_bps, allele_storage, &nchanged_ct, nlist_flush, nlist_file, &nlist_write_iter, alen_buf, allele_skip_buf);
559 if (unlikely(reterr)) {
560 goto ProcessFa_ret_1;
561 }
562 }
563 if (contig_lens && (!(skipped_base_ct >> 63))) {
564 // Subtract 1, since we inserted an 'N' in front to simplify indel
565 // handling.
566 const uint64_t contig_len = bp_end + skipped_base_ct - 1;
567 if (unlikely(contig_len > UINT32_MAX)) {
568 logerrputs("Error: " PROG_NAME_STR " does not currently support contigs >= 2^32 bases.\n");
569 reterr = kPglRetNotYetSupported;
570 goto ProcessFa_ret_1;
571 }
572 // Don't need explicit handling of contig_len == 0 case.
573 contig_lens[chr_idx] = S_CAST(uint32_t, contig_len);
574 }
575 }
576 char* chr_name_start = &(line_iter[1]);
577 if (unlikely(IsSpaceOrEoln(*chr_name_start))) {
578 snprintf(g_logbuf, kLogbufSize, "Error: Invalid contig description on line %" PRIuPTR " of --fa file.%s\n", line_idx, (*chr_name_start == ' ')? " (Spaces are not permitted between the leading '>' and the contig name.)" : "");
579 goto ProcessFa_ret_MALFORMED_INPUT_WW;
580 }
581 char* chr_name_end = CurTokenEnd(chr_name_start);
582 line_iter = AdvToDelim(chr_name_end, '\n');
583 *chr_name_end = '\0';
584 const uint32_t chr_name_slen = chr_name_end - chr_name_start;
585 chr_fo_idx = UINT32_MAX;
586 chr_idx = GetChrCode(chr_name_start, cip, chr_name_slen);
587 if ((!IsI32Neg(chr_idx)) && IsSet(cip->chr_mask, chr_idx)) {
588 chr_fo_idx = cip->chr_idx_to_foidx[chr_idx];
589 if (unlikely(IsSet(chr_already_seen, chr_fo_idx))) {
590 snprintf(g_logbuf, kLogbufSize, "Error: Duplicate contig name '%s' in --fa file.\n", chr_name_start);
591 goto ProcessFa_ret_MALFORMED_INPUT_WW;
592 }
593 SetBit(chr_fo_idx, chr_already_seen);
594 const int32_t chr_vidx_start_m1 = cip->chr_fo_vidx_start[chr_fo_idx] - 1;
595 const int32_t chr_vidx_last = FindLast1BitBeforeBounded(variant_include, cip->chr_fo_vidx_start[chr_fo_idx + 1], chr_vidx_start_m1);
596 if (chr_vidx_last == chr_vidx_start_m1) {
597 chr_fo_idx = UINT32_MAX;
598 } else {
599 cur_vidx_last = chr_vidx_last;
600 seqbuf_end = &(seqbuf[variant_bps[cur_vidx_last] + max_allele_slen]);
601 seq_iter = &(seqbuf[1]);
602 }
603 }
604 skip_chr = (chr_fo_idx == UINT32_MAX);
605 skipped_base_ct = 0;
606 *chr_name_end = '\n'; // bugfix (16 Apr 2018)
607 continue;
608 }
609 const char* line_start = line_iter;
610 line_iter = CurTokenEnd(line_iter);
611 const char* seqline_end = line_iter;
612 ucc = *seqline_end;
613 if (unlikely((ucc == ' ') || (ucc == '\t'))) {
614 snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of --fa file is malformed.\n", line_idx);
615 goto ProcessFa_ret_MALFORMED_INPUT_2;
616 }
617 uint32_t cur_seq_slen = seqline_end - line_start;
618 if (skip_chr) {
619 if (is_first_noncomment_line) {
620 logerrputs("Error: --fa file is not a valid FASTA.\n");
621 goto ProcessFa_ret_MALFORMED_INPUT;
622 }
623 if (seqbuf_end == seq_iter) {
624 skipped_base_ct += cur_seq_slen;
625 }
626 continue;
627 }
628 const uint32_t seq_rem = seqbuf_end - seq_iter;
629 if (seq_rem <= cur_seq_slen) {
630 skipped_base_ct += cur_seq_slen - seq_rem;
631 cur_seq_slen = seq_rem;
632 skip_chr = 1;
633 }
634 const char* gap_start = S_CAST(const char*, memchr(line_start, '-', cur_seq_slen));
635 if (gap_start) {
636 logerrprintfww("Warning: Indeterminate-length gap present on line %" PRIuPTR " of --fa file. Ignoring remainder of contig.\n", line_idx);
637 cur_seq_slen = gap_start - line_start;
638 skipped_base_ct = 1LLU << 63;
639 skip_chr = 1;
640 }
641 seq_iter = memcpya(seq_iter, line_start, cur_seq_slen);
642 // seq_iter = memcpya_toupper(seq_iter, loadbuf, cur_seq_slen);
643 }
644 if (flags & kfFaRefFrom) {
645 const uint32_t ref_from_fa_force = flags & kfFaRefFromForce;
646 if (chr_fo_idx != UINT32_MAX) {
647 *seq_iter = '\0';
648 const uint32_t bp_end = seq_iter - seqbuf;
649 reterr = RefFromFaContig(variant_include, variant_bps, allele_idx_offsets, allele_storage, cip, seqbuf, ref_from_fa_force, chr_fo_idx, cur_vidx_last, bp_end, allele_permute, nonref_flags, &ref_changed_ct, &ref_validated_ct, &ref_downgraded_ct);
650 if (unlikely(reterr)) {
651 goto ProcessFa_ret_1;
652 }
653 }
654 logprintf("--ref-from-fa%s: %u variant%s changed, %u validated.\n", ref_from_fa_force? " force" : "", ref_changed_ct, (ref_changed_ct == 1)? "" : "s", ref_validated_ct);
655 if (ref_downgraded_ct) {
656 logerrprintfww("Warning: %u reference allele%s downgraded from 'known' to 'provisional'.\n", ref_downgraded_ct, (ref_downgraded_ct == 1)? "" : "s");
657 }
658 }
659 if (flags & kfFaNormalize) {
660 if (chr_fo_idx != UINT32_MAX) {
661 // slightly redundant
662 *seq_iter = '\0';
663 const uint32_t bp_end = seq_iter - seqbuf;
664 reterr = VNormalizeContig(variant_include, variant_ids, allele_idx_offsets, cip, seqbuf, chr_fo_idx, cur_vidx_last, bp_end, flags & kfFaNormalizeAdjustOverlappingDeletions, output_missing_geno_code, &tmp_alloc_end, vpos_sortstatusp, variant_bps, allele_storage, &nchanged_ct, nlist_flush, nlist_file, &nlist_write_iter, alen_buf, allele_skip_buf);
665 if (unlikely(reterr)) {
666 goto ProcessFa_ret_1;
667 }
668 }
669 BigstackEndSet(tmp_alloc_end);
670 logprintf("--normalize: %u variant%s changed.\n", nchanged_ct, (nchanged_ct == 1)? "" : "s");
671 if (nlist_file) {
672 if (unlikely(fclose_flush_null(nlist_flush, nlist_write_iter, &nlist_file))) {
673 goto ProcessFa_ret_WRITE_FAIL;
674 }
675 logprintfww("Affected variant ID%s written to %s .\n", (nchanged_ct == 1)? "" : "s", outname);
676 }
677 if ((*vpos_sortstatusp) & kfUnsortedVarBp) {
678 logerrprintf("Warning: Base-pair positions are now unsorted!\n");
679 }
680 }
681 if (contig_lens) {
682 const uint32_t chr_code_ct = cip->max_code + 1 + cip->name_ct;
683 uint32_t scraped_contig_len_ct = 0;
684 for (uint32_t chr_code = 1; chr_code != chr_code_ct; ++chr_code) {
685 if (contig_lens[chr_code]) {
686 ++scraped_contig_len_ct;
687 }
688 }
689 logprintf("--fa: Length%s scraped for %u contig%s.\n", (scraped_contig_len_ct == 1)? "" : "s", scraped_contig_len_ct, (scraped_contig_len_ct == 1)? "" : "s");
690 }
691 }
692 while (0) {
693 ProcessFa_ret_NOMEM:
694 reterr = kPglRetNomem;
695 break;
696 ProcessFa_ret_OPEN_FAIL:
697 reterr = kPglRetOpenFail;
698 break;
699 ProcessFa_ret_TSTREAM_FAIL:
700 TextStreamErrPrint("--ref-from-fa file", &fa_txs);
701 break;
702 ProcessFa_ret_WRITE_FAIL:
703 reterr = kPglRetWriteFail;
704 break;
705 ProcessFa_ret_MALFORMED_INPUT_WW:
706 WordWrapB(0);
707 ProcessFa_ret_MALFORMED_INPUT_2:
708 logerrputsb();
709 ProcessFa_ret_MALFORMED_INPUT:
710 reterr = kPglRetMalformedInput;
711 break;
712 }
713 ProcessFa_ret_1:
714 fclose_cond(nlist_file);
715 CleanupTextStream2("--ref-from-fa file", &fa_txs, &reterr);
716 BigstackReset(bigstack_mark);
717 return reterr;
718 }
719
720 // Eventually want a standalone function which uses a .fa to fill in ref
721 // alleles for .ped and similar all-SNP datasets where the reference allele may
722 // have disappeared, and some of the resulting variants will become
723 // multiallelic. But wait till --pmerge is implemented, since this is mostly a
724 // subset of what --pmerge needs to do.
725
726 #ifdef __cplusplus
727 } // namespace plink2
728 #endif