Debian Codegraph @

utils/vcf_subset/vcf_subset.cc

raw
1 // Copyright (C) 2024-2025 Christopher Chang.
2 //
3 // This library is free software: you can redistribute it and/or modify it
4 // under the terms of the GNU Lesser General Public License as published by the
5 // Free Software Foundation; either version 3 of the License, or (at your
6 // option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful, but WITHOUT
9 // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10 // FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
11 // for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public License
14 // along with this library. If not, see <http://www.gnu.org/licenses/>.
15
16 #include "../../include/plink2_bits.h"
17 #include "../../include/plink2_htable.h"
18 #include "../../include/plink2_memory.h"
19 #include "../../include/plink2_text.h"
20 #include <errno.h>
21
22 #ifdef __cplusplus
23 namespace plink2 {
24 #endif
25
26 static const char ver_str[] = "vcf_subset v1.0.4"
27
28 #ifdef __LP64__
29 # ifdef USE_AVX2
30 " AVX2"
31 # elif defined(__APPLE__) && !defined(__x86_64__)
32 " M1"
33 # elif defined(USE_SSE42)
34 " SSE4.2"
35 # else
36 " 64-bit"
37 # endif
38 #else
39 " 32-bit"
40 #endif
41
42 " (23 Jan 2025)";
43 static const char ver_str2[] =
44 // include leading space if day < 10, so character length stays the same
45 ""
46
47 // length of architecture string + this string should be 7 characterrs
48 #ifdef __LP64__
49 # ifdef USE_AVX2
50 " "
51 # elif defined(__APPLE__) && !defined(__x86_64__)
52 " "
53 # elif defined(USE_SSE42)
54 ""
55 # else
56 ""
57 # endif
58 #else
59 ""
60 #endif
61 " cog-genomics.org/plink/2.0/\n"
62 "(C) 2024-2025 Christopher Chang GNU LGPL v3\n";
63
64 void PrintVer() {
65 fputs(ver_str, stdout);
66 fputs(ver_str2, stdout);
67 }
68
69 void DispUsage(FILE* dst_stream) {
70 PrintVer();
71 fputs(
72 "Usage: vcf_subset [options...] --in <input VCF path> --out <output VCF path>\n"
73 "Optional flags:\n"
74 " --allow-any-paths : By default, the program errors out if the input and\n"
75 " output paths don't end in '.vcf', '.vcf.gz', or\n"
76 " '.vcf.bgz'. Use this flag to remove the restriction.\n"
77 " --allow-no-samples : By default, the program errors out if --indv and/or\n"
78 " --keep causes no samples to remain. Use this flag to\n"
79 " remove the restriction.\n"
80 " --bgz-level <#> : Set bgzip compression level (1-12, default 6). Note\n"
81 " that compression occurs iff the --out path ends in '.gz'\n"
82 " or '.bgz'.\n"
83 " --erase-info : Remove INFO header lines, set all INFO entries to '.'.\n"
84 " --help : Just display this help text.\n"
85 " --indv <ID> : Keep only the sample with the given ID.\n"
86 " --keep <filename> : Keep only samples with IDs in the given file.\n"
87 " --memory <#> : Set size, in MiB, of initial workspace malloc attempt.\n"
88 " --no-samples : Remove all samples.\n"
89 " --threads <#> : Set maximum number of compute threads.\n"
90 " --version : Just display version string.\n"
91 , dst_stream);
92 }
93
94 // Mostly used as a buffer for error messages.
95 CONSTI32(kTextbufSize, 2 * kMaxMediumLine + 256);
96 char g_textbuf[kTextbufSize];
97
98 void TextErrPrint(const char* file_descrip, const char* errmsg, PglErr reterr) {
99 assert(reterr != kPglRetSuccess);
100 if (reterr == kPglRetOpenFail) {
101 fprintf(stderr, kErrprintfFopen, file_descrip, errmsg);
102 } else if (reterr == kPglRetReadFail) {
103 fprintf(stderr, kErrprintfFread, file_descrip, errmsg);
104 } else if (reterr == kPglRetDecompressFail) {
105 fprintf(stderr, kErrprintfDecompress, file_descrip, errmsg);
106 } else if (reterr == kPglRetMalformedInput) {
107 if (errmsg == kShortErrInteriorEmptyLine) {
108 fprintf(stderr, "Error: Unexpected interior empty line in %s.\n", file_descrip);
109 } else {
110 assert(errmsg == kShortErrLongLine);
111 fprintf(stderr, "Error: Pathologically long line in %s.\n", file_descrip);
112 }
113 }
114 // kPglRetRewindFail not used here
115 }
116
117 static inline BoolErr bgzfwrite_ck(char* buf_flush, BgzfCompressStream* bgzfp, char** write_iter_ptr) {
118 if ((*write_iter_ptr) < buf_flush) {
119 return 0;
120 }
121 char* buf = &(buf_flush[-kMaxMediumLine]);
122 char* buf_end = *write_iter_ptr;
123 *write_iter_ptr = buf;
124 return BgzfWrite(buf, buf_end - buf, bgzfp);
125 }
126
127 BoolErr bgzfclose_flush(char* buf_flush, char* write_iter, BgzfCompressStream* bgzfp, PglErr* reterrp) {
128 char* buf = &(buf_flush[-kMaxMediumLine]);
129
130 // safe to ignore this error-return since CleanupBgzfCompressStream will also
131 // error-return
132 BgzfWrite(buf, write_iter - buf, bgzfp);
133
134 return CleanupBgzfCompressStream(bgzfp, reterrp);
135 }
136
137 PglErr VcfSubset(unsigned char* bigstack_base, unsigned char* bigstack_end, const char* inpath, const char* indv_str, const char* keeppath, const char* outpath, uint32_t outpath_slen, uint32_t allow_no_samples, uint32_t bgz_level, uint32_t erase_info, uint32_t no_samples, uint32_t max_thread_ct) {
138 uintptr_t line_idx = 1;
139 PglErr reterr = kPglRetSuccess;
140 TextStream in_txs;
141 BgzfCompressStream out_bgzf;
142 PreinitTextStream(&in_txs);
143 PreinitBgzfCompressStream(&out_bgzf);
144 {
145 const uint32_t max_line_blen = MINV((bigstack_end - bigstack_base) / 4, kMaxLongLine);
146 uintptr_t max_header_blen = S_CAST(uintptr_t, bigstack_end - bigstack_base) / 2;
147 #ifdef __LP64__
148 if (max_header_blen > (1LLU << 32)) {
149 max_header_blen = 1LLU << 32;
150 }
151 #endif
152 char* readbuf;
153 char* writebuf;
154 if (unlikely(arena_alloc_c(bigstack_end, max_line_blen + kDecompressChunkSize, &bigstack_base, &readbuf) ||
155 arena_alloc_c(bigstack_end, max_line_blen + kBytesPerVec + kMaxMediumLine, &bigstack_base, &writebuf))) {
156 goto VcfSubset_ret_NOMEM;
157 }
158 char* write_iter = writebuf;
159 char* writebuf_flush = &(writebuf[kMaxMediumLine]);
160 // If output is uncompressed, allow reader to use MAX(1, max_thread_ct - 2)
161 // threads, leaving one thread for copy-subsetting and one thread for
162 // flushing.
163 // Otherwise, start by reserving ~half of threads to reader. Then, scan
164 // final header line, estimate what fraction of the file we're keeping
165 // (currently affected by --indv, --keep, --no-samples), and set the number
166 // of compression threads under the assumption that compression is 5x as
167 // expensive as decompression (and consequently some of the decompression
168 // threads may be expected to be fairly idle).
169 uint32_t clvl = 0; // 0 = no compression
170 uint32_t decompress_thread_ct = 1;
171 if (StrEndsWith(outpath, ".gz", outpath_slen) ||
172 StrEndsWith(outpath, ".bgz", outpath_slen)) {
173 clvl = bgz_level;
174 if (max_thread_ct >= 4) {
175 decompress_thread_ct = max_thread_ct / 2;
176 }
177 } else {
178 if (max_thread_ct >= 4) {
179 decompress_thread_ct = max_thread_ct - 2;
180 }
181 }
182 reterr = TextStreamOpenEx(inpath, kMaxLongLine, max_line_blen + kDecompressChunkSize, decompress_thread_ct, nullptr, readbuf, &in_txs);
183 if (unlikely(reterr)) {
184 goto VcfSubset_ret_IN_TSTREAM_FAIL;
185 }
186 // Can only be >1 if bgzf. (But that's the expected case.)
187 decompress_thread_ct = MAXV(1, TextDecompressThreadCt(&in_txs));
188
189 // Array of length (2 * sample_include_interval_ct). For each k in [0,
190 // sample_include_interval_ct), the samples in
191 // [sample_include_endpoints[2k], sample_include_endpoints[2k+1]) are
192 // included; and no others are. This minimizes the number of
193 // memory-copies we need to perform.
194 uint32_t* sample_include_endpoints = nullptr;
195 char* line_start = TextLineEnd(&in_txs);
196 uint32_t raw_sample_ct = 0;
197 uint32_t raw_sample_ctl = 0;
198 uint32_t sample_ct = 0;
199 uint32_t sample_include_interval_ct = 0;
200 {
201 unsigned char* bigstack_mark2 = bigstack_base;
202 unsigned char* bigstack_end_mark = bigstack_end;
203 char* header = R_CAST(char*, bigstack_base);
204 char* header_limit = &(header[max_header_blen]);
205 char* header_write_iter = header;
206 for (; ; ++line_idx) {
207 reterr = TextNextLineUnsafe(&in_txs, &line_start);
208 if (unlikely(reterr)) {
209 if (reterr == kPglRetEof) {
210 fputs("Error: No #CHROM header line or variant records in --in file.\n", stderr);
211 goto VcfSubset_ret_MALFORMED_INPUT;
212 }
213 goto VcfSubset_ret_IN_TSTREAM_FAIL;
214 }
215 if (unlikely(*line_start != '#')) {
216 if ((line_idx == 1) && memequal_sk(line_start, "BCF")) {
217 if (line_start[3] == 2) {
218 snprintf(g_textbuf, kTextbufSize, "Error: %s appears to be a BCF2 file; this program only supports VCF for now. You can use 'bcftools view' to convert it to a VCF.\n", inpath);
219 goto VcfSubset_ret_MALFORMED_INPUT_WW;
220 }
221 if (line_start[3] == 4) {
222 snprintf(g_textbuf, kTextbufSize, "Error: %s appears to be a BCF1 file. You can use 'bcftools view' to convert it to a VCF.\n", inpath);
223 goto VcfSubset_ret_MALFORMED_INPUT_WW;
224 }
225 }
226 fputs("Error: No #CHROM header line in --in file.\n", stderr);
227 goto VcfSubset_ret_MALFORMED_INPUT;
228 }
229 if (line_start[1] != '#') {
230 break;
231 }
232 // convert LF / CR-LF into OS-appropriate newline
233 char* line_lf = AdvToDelim(line_start, '\n');
234 char* line_end = &(line_lf[1]);
235 if (erase_info && StrStartsWithUnsafe(&(line_start[2]), "INFO=<")) {
236 line_start = line_end;
237 continue;
238 }
239 uintptr_t line_slen = line_lf - line_start;
240 if (line_lf[-1] == '\r') {
241 --line_slen;
242 }
243 if (unlikely(S_CAST(uintptr_t, header_limit - header_write_iter) < line_slen + strlen(EOLN_STR))) {
244 #ifdef __LP64__
245 if (max_header_blen == (1LLU << 32)) {
246 fputs("Error: VCF header too large (>= 4 GiB, note that this isn't allowed by the BCF\nspecification).\n", stderr);
247 goto VcfSubset_ret_MALFORMED_INPUT;
248 }
249 #endif
250 fputs("Error: VCF header too large to fit in memory.\n", stderr);
251 goto VcfSubset_ret_NOMEM;
252 }
253 header_write_iter = memcpya(header_write_iter, line_start, line_slen);
254 AppendBinaryEoln(&header_write_iter);
255 line_start = line_end;
256 }
257
258 if (unlikely(!StrStartsWithUnsafe(line_start, "#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO"))) {
259 snprintf(g_textbuf, kTextbufSize, "Error: Header line %" PRIuPTR " of --in file does not have expected field sequence after #CHROM.\n", line_idx);
260 goto VcfSubset_ret_MALFORMED_INPUT_WW;
261 }
262 char* chrom_line_lf = AdvToDelim(line_start, '\n');
263 uintptr_t chrom_line_slen = chrom_line_lf - line_start;
264 if (chrom_line_lf[-1] == '\r') {
265 --chrom_line_slen;
266 }
267 if (unlikely(S_CAST(uintptr_t, header_limit - header_write_iter) < chrom_line_slen + strlen(EOLN_STR))) {
268 #ifdef __LP64__
269 if (max_header_blen == (1LLU << 32)) {
270 fputs("Error: VCF header too large (>= 4 GiB, note that this isn't allowed by the BCF\nspecification).\n", stderr);
271 goto VcfSubset_ret_MALFORMED_INPUT;
272 }
273 #endif
274 fputs("Error: VCF header too large to fit in memory.\n", stderr);
275 goto VcfSubset_ret_NOMEM;
276 }
277 // Note that some sample columns in this last header line may not be
278 // copied, so this may overallocate. Not a big deal, we soon free this
279 // memory.
280 ArenaBaseSet(&(header_write_iter[chrom_line_slen + strlen(EOLN_STR)]), &bigstack_base);
281
282 char* info_end = &(line_start[strlen("#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO")]);
283 header_write_iter = memcpya(header_write_iter, line_start, info_end - line_start);
284 uintptr_t* sample_include = nullptr;
285 if (StrStartsWithUnsafe(info_end, "\tFORMAT\t")) {
286 char* first_sample_id_start = &(info_end[strlen("\tFORMAT\t")]);
287 // 1. count number of samples
288 // 2. allocate sample_include off bigstack_end
289 // 3. construct sample ID hash table, error out if any ID duplicated,
290 // apply --indv/--keep if present
291 // 4. generate output header line
292 // 5. convert sample_include to sample_include_endpoints
293 raw_sample_ct = 1 + CountByte(first_sample_id_start, '\t', chrom_line_lf - first_sample_id_start);
294 raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
295 // Convenient to initialize a zero bit past the end of sample_include.
296 const char** sample_ids;
297 if (unlikely(arena_alloc_kcp(bigstack_end, raw_sample_ct, &bigstack_base, &sample_ids) ||
298 arena_alloc_w(bigstack_end, 1 + (raw_sample_ct / kBitsPerWord), &bigstack_base, &sample_include))) {
299 goto VcfSubset_ret_NOMEM;
300 }
301 sample_include[raw_sample_ct / kBitsPerWord] = 0;
302 SetAllBits(raw_sample_ct, sample_include);
303 const uint32_t raw_sample_ctm1 = raw_sample_ct - 1;
304 // Construct array of C-strings, pointing to (now-null-terminated)
305 // IDs in the input line buffer.
306 char* sample_id_iter = first_sample_id_start;
307 for (uint32_t sample_uidx = 0; sample_uidx != raw_sample_ctm1; ++sample_uidx) {
308 char* sample_id_end = AdvToDelim(sample_id_iter, '\t');
309 *sample_id_end = '\0';
310 sample_ids[sample_uidx] = sample_id_iter;
311 sample_id_iter = &(sample_id_end[1]);
312 }
313 char* last_sample_id_end = AdvToDelim(sample_id_iter, '\n');
314 if (last_sample_id_end[-1] == '\r') {
315 --last_sample_id_end;
316 }
317 *last_sample_id_end = '\0';
318 sample_ids[raw_sample_ctm1] = sample_id_iter;
319
320 uint32_t dup_found;
321 if (keeppath) {
322 reterr = NondupIdLoad(bigstack_base, bigstack_end, sample_ids, keeppath, raw_sample_ct, raw_sample_ct, MAXV(1, max_thread_ct - 1), sample_include, &dup_found, g_textbuf);
323 if (unlikely(reterr)) {
324 if (g_textbuf[0]) {
325 fputs(g_textbuf, stderr);
326 }
327 goto VcfSubset_ret_1;
328 }
329 if (unlikely(dup_found)) {
330 fputs("Error: #CHROM header line in --in file contains duplicate sample IDs.\n", stderr);
331 goto VcfSubset_ret_MALFORMED_INPUT;
332 }
333 sample_ct = PopcountWords(sample_include, raw_sample_ctl);
334 if (!sample_ct) {
335 if (unlikely(!allow_no_samples)) {
336 snprintf(g_textbuf, kTextbufSize, "Error: #CHROM header line does not any sample IDs in %s. (Use --allow-no-samples to permit this.)\n", keeppath);
337 goto VcfSubset_ret_INCONSISTENT_INPUT_WW;
338 }
339 }
340 } else {
341 uint32_t* sample_id_htable;
342 uint32_t sample_id_htable_size;
343 reterr = AllocAndPopulateNondupHtableMt(bigstack_end, sample_include, sample_ids, raw_sample_ct, MAXV(1, max_thread_ct - 1), &bigstack_base, &sample_id_htable, &sample_id_htable_size, &dup_found);
344 if (unlikely(reterr)) {
345 goto VcfSubset_ret_1;
346 }
347 if (unlikely(dup_found)) {
348 fputs("Error: #CHROM header line in --in file contains duplicate sample IDs.\n", stderr);
349 goto VcfSubset_ret_MALFORMED_INPUT;
350 }
351 if (no_samples || indv_str) {
352 ZeroWArr(raw_sample_ctl, sample_include);
353 sample_ct = 0;
354 if (indv_str) {
355 const uint32_t sample_uidx = IdHtableFind(indv_str, sample_ids, sample_id_htable, strlen(indv_str), sample_id_htable_size);
356 if (sample_uidx == UINT32_MAX) {
357 if (unlikely(!allow_no_samples)) {
358 snprintf(g_textbuf, kTextbufSize, "Error: #CHROM header line does not contain sample ID '%s'.\n", indv_str);
359 goto VcfSubset_ret_INCONSISTENT_INPUT_WW;
360 }
361 } else {
362 SetBit(sample_uidx, sample_include);
363 sample_ct = 1;
364 }
365 }
366 } else {
367 sample_ct = raw_sample_ct;
368 }
369 }
370 // Only copy FORMAT column if there's at least one sample.
371 if (sample_ct != 0) {
372 header_write_iter = memcpya(header_write_iter, info_end, first_sample_id_start - info_end);
373 uintptr_t sample_uidx_base = 0;
374 uintptr_t cur_bits = sample_include[0];
375 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
376 const uint32_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &cur_bits);
377 header_write_iter = strcpyax(header_write_iter, sample_ids[sample_uidx], '\t');
378 }
379 --header_write_iter;
380 }
381 }
382 // Now we can provide a good thread count to the compressor (in the
383 // likely case where we're compressing). Open --out file for writing,
384 // flush header.
385 uint32_t compress_thread_ct = 1;
386 if ((max_thread_ct > 2) && clvl) {
387 // In this estimate, we treat the INFO column as if it were as
388 // expensive as 40 sample columns, and the other header columns as if
389 // they were like 10 samples. Could tune this more and/or make this
390 // configurable, but I expect this is good enough the vast majority of
391 // the time.
392 // Update (23 Jan 2025): compression:decompression cost ratio estimate
393 // raised from 5 to 10 after a bit of benchmarking.
394 const uint64_t decompress_weight = 50 + raw_sample_ct;
395 const uint64_t compress_weight = 10LLU * (50 - 40 * erase_info + sample_ct);
396 const uint64_t denom = compress_weight + decompress_weight;
397 compress_thread_ct = MAXV(1, (compress_weight * max_thread_ct + denom / 2) / denom);
398 }
399 reterr = InitBgzfCompressStreamEx(outpath, 0, clvl, compress_thread_ct, &out_bgzf);
400 if (unlikely(reterr)) {
401 if (reterr == kPglRetOpenFail) {
402 snprintf(g_textbuf, kTextbufSize, kErrprintfFopen, outpath, strerror(errno));
403 WordWrap(0, g_textbuf);
404 fputs(g_textbuf, stderr);
405 }
406 goto VcfSubset_ret_1;
407 }
408 AppendBinaryEoln(&header_write_iter);
409 if ((raw_sample_ct == 0) || (sample_ct > 0)) {
410 if (unlikely(BgzfWrite(header, header_write_iter - header, &out_bgzf))) {
411 goto VcfSubset_ret_WRITE_FAIL;
412 }
413 } else {
414 // Also remove FORMAT header lines.
415 for (char* header_reread_iter = header; header_reread_iter < header_write_iter; ) {
416 char* read_line_end = AdvPastDelim(header_reread_iter, '\n');
417 if (StrStartsWithUnsafe(header_reread_iter, "##FORMAT=<")) {
418 header_reread_iter = read_line_end;
419 continue;
420 }
421 write_iter = memcpya(write_iter, header_reread_iter, read_line_end - header_reread_iter);
422 if (unlikely(bgzfwrite_ck(writebuf_flush, &out_bgzf, &write_iter))) {
423 goto VcfSubset_ret_WRITE_FAIL;
424 }
425 header_reread_iter = read_line_end;
426 }
427 }
428 bigstack_base = bigstack_mark2;
429 line_start = &(chrom_line_lf[1]);
430 if (sample_ct > 0) {
431 // Number of endpoints can't be larger than raw_sample_ct+1, since no
432 // endpoint is repeated (we'd have two touching intervals that can be
433 // merged).
434 // Number of endpoints also can't be larger than sample_ct*2.
435 const uint32_t endpoint_ct_ub = MINV(raw_sample_ct + 1, sample_ct * 2);
436 if (unlikely(arena_alloc_u32(bigstack_end, endpoint_ct_ub, &bigstack_base, &sample_include_endpoints))) {
437 goto VcfSubset_ret_NOMEM;
438 }
439 uint32_t samples_accounted_for = 0;
440 for (uint32_t sample_uidx = 0; ; ) {
441 const uint32_t intv_start = AdvTo1Bit(sample_include, sample_uidx);
442 const uint32_t intv_end = AdvTo0Bit(sample_include, intv_start + 1);
443 sample_include_endpoints[2 * sample_include_interval_ct] = intv_start;
444 sample_include_endpoints[2 * sample_include_interval_ct + 1] = intv_end;
445 ++sample_include_interval_ct;
446 samples_accounted_for += intv_end - intv_start;
447 if (samples_accounted_for == sample_ct) {
448 break;
449 }
450 sample_uidx = intv_end + 1;
451 }
452 // technically not needed
453 bigstack_end = bigstack_end_mark;
454 }
455 }
456 ++line_idx;
457 const uintptr_t first_variant_line_idx = line_idx;
458 // There is more room for parallelization here: plink2 still beats this on
459 // wall-clock time in some denser cases, despite doing more work.
460 for (; TextGetUnsafe2(&in_txs, &line_start); ++line_idx) {
461 char* line_end = AdvPastDelim(line_start, '\n');
462 char* filter_end = AdvToNthDelimChecked(line_start, line_end, 7, '\t');
463 if (unlikely(!filter_end)) {
464 goto VcfSubset_ret_MISSING_TOKENS;
465 }
466 char* info_start = &(filter_end[1]);
467 char* info_end = strchrnul_n(info_start, '\t');
468 if (!erase_info) {
469 write_iter = memcpya(write_iter, line_start, info_end - line_start);
470 } else {
471 write_iter = memcpyax(write_iter, line_start, info_start - line_start, '.');
472 }
473 if (sample_ct != 0) {
474 if (unlikely(*info_end == '\n')) {
475 goto VcfSubset_ret_MISSING_TOKENS;
476 }
477 char* format_start = &(info_end[1]);
478 // This count is efficient enough that we may as well do it up front,
479 // and remove the corresponding check from the sample-filtering inner
480 // loop.
481 // (Tried moving this into the main loop, barely made a difference.)
482 const uint32_t line_raw_sample_ct = CountByte(format_start, '\t', line_end - format_start);
483 if (unlikely(line_raw_sample_ct != raw_sample_ct)) {
484 if (line_raw_sample_ct < raw_sample_ct) {
485 goto VcfSubset_ret_MISSING_TOKENS;
486 } else {
487 fprintf(stderr, "Error: Line %" PRIuPTR " of --in file has more tokens than expected.\n", line_idx);
488 goto VcfSubset_ret_MALFORMED_INPUT;
489 }
490 }
491 char* line_crlf = &(line_end[-1]);
492 if (*line_crlf == '\r') {
493 --line_crlf;
494 }
495 // This lets us avoid special-casing the last sample.
496 *line_crlf = '\t';
497
498 const char* sample_read_iter = AdvPastDelim(format_start, '\t');
499 const char* info_end_k = info_end;
500 write_iter = memcpya(write_iter, info_end, sample_read_iter - info_end_k);
501
502 #ifdef __LP64__
503 // Small variable-length memcpys can get expensive if we're doing
504 // thousands of them per line. Instead, explicitly copy entire
505 // 16-/32-byte vectors at a time and overwrite or ignore trailing
506 // bytes.
507 const VecUc all_tab_vvec = vecuc_set1(9);
508 #endif
509 // Loop precondition: sample_read_iter points to the tab at the end of
510 // the sample_uidx entry (or, on the first iteration, the tab at the
511 // end of FORMAT).
512 --sample_read_iter;
513 // intentional wraparound
514 uint32_t sample_uidx = UINT32_MAX;
515 for (uint32_t intv_idx = 0; intv_idx != sample_include_interval_ct; ++intv_idx) {
516 const uint32_t intv_start = sample_include_endpoints[intv_idx * 2];
517 const uint32_t intv_end = sample_include_endpoints[intv_idx * 2 + 1];
518 const char* copy_prestart = AdvToNthDelimOverread(sample_read_iter, intv_start - sample_uidx, '\t');
519 #ifdef __LP64__
520 sample_read_iter = &(copy_prestart[1]);
521 for (uint32_t keep_tabs_remaining = intv_end - intv_start; ; sample_read_iter = &(sample_read_iter[kBytesPerVec]), write_iter = &(write_iter[kBytesPerVec])) {
522 const VecUc cur_vvec = vecuc_loadu(sample_read_iter);
523 vecuc_storeu(write_iter, cur_vvec);
524 const VecUc cur_tab_vvec = (cur_vvec == all_tab_vvec);
525 const uint32_t cur_tab_ct = vec0255_set_ct(cur_tab_vvec);
526 if (keep_tabs_remaining <= cur_tab_ct) {
527 const char* sample_read_iter_vstart = sample_read_iter;
528 while (1) {
529 const char cc = *sample_read_iter++;
530 if (cc != '\t') {
531 continue;
532 }
533 if (!(--keep_tabs_remaining)) {
534 break;
535 }
536 }
537 write_iter = &(write_iter[sample_read_iter - sample_read_iter_vstart]);
538 break;
539 }
540 keep_tabs_remaining -= cur_tab_ct;
541 }
542 #else
543 const char* copy_start = &(copy_prestart[1]);
544 const char* copy_last = AdvToNthDelim(copy_start, intv_end - intv_start, '\t');
545 const char* copy_end = &(copy_last[1]);
546 write_iter = memcpya(write_iter, copy_start, copy_end - copy_start);
547
548 sample_read_iter = copy_end;
549 #endif
550 sample_uidx = intv_end;
551 }
552 --write_iter;
553 }
554 AppendBinaryEoln(&write_iter);
555 if (unlikely(bgzfwrite_ck(writebuf_flush, &out_bgzf, &write_iter))) {
556 goto VcfSubset_ret_WRITE_FAIL;
557 }
558 line_start = line_end;
559 }
560 if (unlikely(TextStreamErrcode2(&in_txs, &reterr))) {
561 goto VcfSubset_ret_IN_TSTREAM_FAIL;
562 }
563 if (unlikely(bgzfclose_flush(writebuf_flush, write_iter, &out_bgzf, &reterr))) {
564 goto VcfSubset_ret_1;
565 }
566 const uintptr_t variant_ct = line_idx - first_variant_line_idx;
567 if (raw_sample_ct == 0) {
568 snprintf(g_textbuf, kTextbufSize, "vcf_subset: %" PRIuPTR " variant%s written to %s .\n", variant_ct, (variant_ct == 1)? "" : "s", outpath);
569 } else {
570 snprintf(g_textbuf, kTextbufSize, "vcf_subset: %u/%u sample%s and %" PRIuPTR " variant%s written to %s .\n", sample_ct, raw_sample_ct, (raw_sample_ct == 1)? "" : "s", variant_ct, (variant_ct == 1)? "" : "s", outpath);
571 }
572 WordWrap(0, g_textbuf);
573 fputs(g_textbuf, stdout);
574 }
575 while (0) {
576 VcfSubset_ret_NOMEM:
577 reterr = kPglRetNomem;
578 break;
579 VcfSubset_ret_WRITE_FAIL:
580 reterr = kPglRetWriteFail;
581 break;
582 VcfSubset_ret_MISSING_TOKENS:
583 fprintf(stderr, "Error: Line %" PRIuPTR " of --in file has fewer tokens than expected.\n", line_idx);
584 reterr = kPglRetMalformedInput;
585 break;
586 VcfSubset_ret_MALFORMED_INPUT_WW:
587 WordWrap(0, g_textbuf);
588 fputs(g_textbuf, stderr);
589 VcfSubset_ret_MALFORMED_INPUT:
590 reterr = kPglRetMalformedInput;
591 break;
592 VcfSubset_ret_INCONSISTENT_INPUT_WW:
593 WordWrap(0, g_textbuf);
594 fputs(g_textbuf, stderr);
595 reterr = kPglRetInconsistentInput;
596 break;
597 VcfSubset_ret_IN_TSTREAM_FAIL:
598 putc_unlocked('\n', stdout);
599 TextErrPrint("--in file", TextStreamError(&in_txs), TextStreamErrcode(&in_txs));
600 break;
601 }
602 VcfSubset_ret_1:
603 CleanupBgzfCompressStream(&out_bgzf, &reterr);
604 if (unlikely(CleanupTextStream(&in_txs, &reterr))) {
605 snprintf(g_textbuf, kTextbufSize, kErrprintfFread, inpath, strerror(errno));
606 WordWrap(0, g_textbuf);
607 fputs(g_textbuf, stderr);
608 }
609 return reterr;
610 }
611
612 void PrintExitMsg(PglErr reterr) {
613 if (!reterr) {
614 return;
615 }
616 if (reterr == kPglRetNomem) {
617 putc_unlocked('\n', stdout);
618 fputs(kErrstrNomem, stderr);
619 if (g_failed_alloc_attempt_size) {
620 fprintf(stderr, "Failed allocation size: %" PRIu64 "\n", g_failed_alloc_attempt_size);
621 }
622 } else if (reterr == kPglRetWriteFail) {
623 putc_unlocked('\n', stdout);
624 if (errno) {
625 fprintf(stderr, kErrstrWrite, strerror(errno));
626 } else {
627 // Defensive.
628 fputs("Error: File write failure: Untracked cause.", stderr);
629 }
630 } else if (reterr == kPglRetThreadCreateFail) {
631 putc_unlocked('\n', stdout);
632 fputs(kErrstrThreadCreate, stderr);
633 } else if (reterr == kPglRetLongLine) {
634 putc_unlocked('\n', stdout);
635 fputs("Error: Unhandled internal line-too-long message.\n", stderr);
636 } else if (reterr == kPglRetEof) {
637 putc_unlocked('\n', stdout);
638 fputs("Error: Unhandled internal EOF message.\n", stderr);
639 }
640 }
641
642 #ifndef __LP64__
643 // 2047 seems to consistently fail on both OS X and Windows
644 # ifdef _WIN32
645 CONSTI32(kMalloc32bitMibMax, 1792);
646 # else
647 # ifdef __APPLE__
648 CONSTI32(kMalloc32bitMibMax, 1952);
649 # else
650 CONSTI32(kMalloc32bitMibMax, 2047);
651 # endif
652 # endif
653 #endif
654
655 #ifdef __cplusplus
656 } // namespace plink2
657 #endif
658
659 int main(int argc, char** argv) {
660 #ifdef __cplusplus
661 using namespace plink2;
662 #endif
663 unsigned char* bigstack_ua = nullptr;
664 PglErr reterr = kPglRetSuccess;
665 {
666 // not actually unlikely, but may as well be consistent re: unlikely() and
667 // returning a nonzero error code
668 if (unlikely(argc <= 1)) {
669 DispUsage(stderr);
670 reterr = kPglRetSkipped;
671 goto main_ret_1;
672 }
673 // doesn't use plink2_cmdline; flags may not be processed in alphabetical
674 // order, etc.
675 const uintptr_t bigstack_min_mib = 640;
676 const uintptr_t nonstack_min_mib = 64;
677 // 2 GiB for input line buffer, 2 GiB for output line buffer, other stuff
678 // should take less than 4 GiB combined (including temporary header load:
679 // BCF does not support l_text >= 2^32).
680 const uintptr_t max_default_mib = 8192;
681
682 const uint32_t argc_u = S_CAST(uint32_t, argc);
683 // These just point to argv when initialized, so they must not be freed on
684 // exit.
685 char* inpath = nullptr;
686 char* indv_str = nullptr;
687 char* keeppath = nullptr;
688 char* outpath = nullptr;
689
690 uint32_t allow_any_paths = 0;
691 uint32_t allow_no_samples = 0;
692 uint32_t bgz_level = 0;
693 uint32_t erase_info = 0;
694 uintptr_t malloc_size_mib = 0;
695 uint32_t no_samples = 0;
696 uint32_t thread_ct = 0;
697 for (uint32_t arg_idx = 1; arg_idx < argc_u; ++arg_idx) {
698 const char* cur_arg = argv[arg_idx];
699 if (unlikely((cur_arg[0] != '-') || ((cur_arg[1] == '-') && (cur_arg[2] == '-')))) {
700 snprintf(g_textbuf, kTextbufSize, "Error: '%s' is not a flag (should start with one or two dashes).\n", cur_arg);
701 goto main_ret_INVALID_CMDLINE_WW;
702 }
703 const char* flagname_p = &(cur_arg[1 + (cur_arg[1] == '-')]);
704 const uint32_t flagname_slen = strlen(flagname_p);
705 if (strequal_k(flagname_p, "allow-any-paths", flagname_slen)) {
706 allow_any_paths = 1;
707 continue;
708 }
709 if (strequal_k(flagname_p, "allow-no-samples", flagname_slen)) {
710 allow_no_samples = 1;
711 continue;
712 }
713 if (strequal_k(flagname_p, "bgz-level", flagname_slen)) {
714 if (unlikely(bgz_level)) {
715 fputs("Error: Multiple instances of --bgz-level.\n", stderr);
716 goto main_ret_INVALID_CMDLINE;
717 }
718 ++arg_idx;
719 if (unlikely(arg_idx == argc_u)) {
720 fputs("Error: Missing --bgz-level parameter.\n", stderr);
721 goto main_ret_INVALID_CMDLINE;
722 }
723 if (unlikely(ScanPosintDefcapx(argv[arg_idx], &bgz_level) || (bgz_level > 12))) {
724 snprintf(g_textbuf, kTextbufSize, "Error: Invalid --bgz-level argument '%s' (must be an integer 1-12).\n", argv[arg_idx]);
725 goto main_ret_INVALID_CMDLINE_WW;
726 }
727 continue;
728 }
729 if (strequal_k(flagname_p, "erase-info", flagname_slen)) {
730 // doesn't matter if there are multiple instances of this flag
731 erase_info = 1;
732 continue;
733 }
734 if (strequal_k(flagname_p, "help", flagname_slen)) {
735 if (argc_u > 2) {
736 // No need for plink-style keyword-based subsetting.
737 fputs("Note: --help present; ignoring rest of command line.\n", stdout);
738 }
739 DispUsage(stdout);
740 goto main_ret_1;
741 }
742 if (strequal_k(flagname_p, "in", flagname_slen)) {
743 if (unlikely(inpath)) {
744 fputs("Error: Multiple instances of --in.\n", stderr);
745 goto main_ret_INVALID_CMDLINE;
746 }
747 ++arg_idx;
748 if (unlikely(arg_idx == argc_u)) {
749 fputs("Error: Missing --in parameter.\n", stderr);
750 goto main_ret_INVALID_CMDLINE;
751 }
752 inpath = argv[arg_idx];
753 continue;
754 }
755 if (strequal_k(flagname_p, "indv", flagname_slen)) {
756 if (unlikely(indv_str)) {
757 fputs("Error: Multiple instances of --indv.\n", stderr);
758 goto main_ret_INVALID_CMDLINE;
759 }
760 ++arg_idx;
761 if (unlikely(arg_idx == argc_u)) {
762 fputs("Error: Missing --indv parameter.\n", stderr);
763 goto main_ret_INVALID_CMDLINE;
764 }
765 indv_str = argv[arg_idx];
766 continue;
767 }
768 if (strequal_k(flagname_p, "keep", flagname_slen)) {
769 if (unlikely(keeppath)) {
770 fputs("Error: Multiple instances of --keep.\n", stderr);
771 goto main_ret_INVALID_CMDLINE;
772 }
773 ++arg_idx;
774 if (unlikely(arg_idx == argc_u)) {
775 fputs("Error: Missing --keep parameter.\n", stderr);
776 goto main_ret_INVALID_CMDLINE;
777 }
778 keeppath = argv[arg_idx];
779 continue;
780 }
781 if (strequal_k(flagname_p, "memory", flagname_slen)) {
782 if (unlikely(malloc_size_mib)) {
783 fputs("Error: Multiple instances of --memory.\n", stderr);
784 goto main_ret_INVALID_CMDLINE;
785 }
786 ++arg_idx;
787 if (unlikely(arg_idx == argc_u)) {
788 fputs("Error: Missing --memory parameter.\n", stderr);
789 goto main_ret_INVALID_CMDLINE;
790 }
791 if (unlikely(ScanPosintptrx(argv[arg_idx], &malloc_size_mib))) {
792 snprintf(g_textbuf, kTextbufSize, "Error: Invalid --memory argument '%s'.\n", argv[arg_idx]);
793 goto main_ret_INVALID_CMDLINE_WW;
794 }
795 if (unlikely(malloc_size_mib < bigstack_min_mib)) {
796 snprintf(g_textbuf, kTextbufSize, "Error: Invalid --memory argument '%s' (minimum %" PRIuPTR ").\n", argv[arg_idx], bigstack_min_mib);
797 goto main_ret_INVALID_CMDLINE_WW;
798 }
799 #ifndef __LP64__
800 if (unlikely(malloc_size_mib > kMalloc32bitMibMax)) {
801 fprintf(stderr, "Error: --memory argument too large for 32-bit version (max %u).\n", kMalloc32bitMibMax);
802 goto main_ret_INVALID_CMDLINE;
803 }
804 #endif
805 continue;
806 }
807 if (strequal_k(flagname_p, "no-samples", flagname_slen)) {
808 no_samples = 1;
809 continue;
810 }
811 if (strequal_k(flagname_p, "out", flagname_slen)) {
812 if (unlikely(outpath)) {
813 fputs("Error: Multiple instances of --out.\n", stderr);
814 goto main_ret_INVALID_CMDLINE;
815 }
816 ++arg_idx;
817 if (unlikely(arg_idx == argc_u)) {
818 fputs("Error: Missing --out parameter.\n", stderr);
819 goto main_ret_INVALID_CMDLINE;
820 }
821 outpath = argv[arg_idx];
822 continue;
823 }
824 if (strequal_k(flagname_p, "threads", flagname_slen)) {
825 if (unlikely(thread_ct)) {
826 fputs("Error: Multiple instances of --threads.\n", stderr);
827 goto main_ret_INVALID_CMDLINE;
828 }
829 ++arg_idx;
830 if (unlikely(arg_idx == argc_u)) {
831 fputs("Error: Missing --threads parameter.\n", stderr);
832 goto main_ret_INVALID_CMDLINE;
833 }
834 if (unlikely(ScanPosintDefcapx(argv[arg_idx], &thread_ct))) {
835 snprintf(g_textbuf, kTextbufSize, "Error: Invalid --threads argument '%s'.\n", argv[arg_idx]);
836 goto main_ret_INVALID_CMDLINE_WW;
837 }
838 continue;
839 }
840 if (likely(strequal_k(flagname_p, "version", flagname_slen))) {
841 if (argc_u > 2) {
842 fputs("Warning: --version present; ignoring rest of command line.\n", stderr);
843 }
844 fputs(ver_str, stdout);
845 putc_unlocked('\n', stdout);
846 goto main_ret_1;
847 }
848 snprintf(g_textbuf, kTextbufSize, "Error: Unrecognized flag '%s'.\n", argv[arg_idx]);
849 goto main_ret_INVALID_CMDLINE_WW;
850 } // end of initial command-line parsing loop
851 PrintVer();
852
853 // 1. require --in and --out
854 // 2. enforce path restrictions
855 // 3. count cores, allocate workspace
856 // 4. open --in file, load all ## header lines
857 // 5. count number of samples, apply --indv or --keep
858 // 6. open --out file, process remaining lines
859 if ((!inpath) || (!outpath)) {
860 fputs("Error: --in and --out are required.\n", stderr);
861 goto main_ret_INVALID_CMDLINE;
862 }
863 if (indv_str && keeppath) {
864 fputs("Error: --indv and --keep cannot be used simultaneously.\n", stderr);
865 goto main_ret_INVALID_CMDLINE;
866 }
867
868 const uint32_t inpath_slen = strlen(inpath);
869 const uint32_t outpath_slen = strlen(outpath);
870 if (!allow_any_paths) {
871 if (unlikely((!StrEndsWith(inpath, ".vcf", inpath_slen)) &&
872 (!StrEndsWith(inpath, ".vcf.gz", inpath_slen)) &&
873 (!StrEndsWith(inpath, ".vcf.bgz", inpath_slen)))) {
874 fputs("Error: --in argument does not end with an expected file extension (.vcf,\n.vcf.gz, .vcf.bgz). You can override this sanity check with --allow-any-paths.\n", stderr);
875 goto main_ret_INVALID_CMDLINE;
876 }
877 if (unlikely((!StrEndsWith(outpath, ".vcf", outpath_slen)) &&
878 (!StrEndsWith(outpath, ".vcf.gz", outpath_slen)) &&
879 (!StrEndsWith(outpath, ".vcf.bgz", outpath_slen)))) {
880 fputs("Error: --out argument does not end with an expected file extension (.vcf,\n.vcf.gz, .vcf.bgz). You can override this sanity check with --allow-any-paths.\n", stderr);
881 goto main_ret_INVALID_CMDLINE;
882 }
883 }
884
885 if (!thread_ct) {
886 thread_ct = NumCpu(nullptr);
887 if (thread_ct > kMaxThreads) {
888 thread_ct = kMaxThreads;
889 }
890 }
891 if (thread_ct > 8) {
892 printf("Using up to %u threads (change this with --threads).\n", thread_ct);
893 } else {
894 printf("Using %s%u compute thread%s.\n", (thread_ct > 1)? "up to " : "", thread_ct, (thread_ct == 1)? "" : "s");
895 }
896
897 // todo: move most/all of this logic from CmdlineParsePhase3() to helper(s)
898 // in plink2_memory
899 const uint64_t total_mib = DetectMib();
900 if (!malloc_size_mib) {
901 if (!total_mib) {
902 malloc_size_mib = max_default_mib;
903 } else if (total_mib < (bigstack_min_mib * 2)) {
904 malloc_size_mib = bigstack_min_mib;
905 } else {
906 #ifdef __LP64__
907 malloc_size_mib = total_mib / 2;
908 #else
909 malloc_size_mib = MINV(2047, total_mib / 2);
910 #endif
911 if (malloc_size_mib > max_default_mib) {
912 malloc_size_mib = max_default_mib;
913 }
914 }
915 }
916 assert(malloc_size_mib > bigstack_min_mib);
917 #ifndef __LP64__
918 if (malloc_size_mib > kMalloc32bitMibMax) {
919 malloc_size_mib = kMalloc32bitMibMax;
920 }
921 #endif
922 if (total_mib) {
923 const uint64_t mem_available_kib = GetMemAvailableKib(kMaxMediumLine, g_textbuf);
924 if (mem_available_kib == (~0LLU)) {
925 printf("%" PRIu64 " MiB RAM detected; reserving %" PRIuPTR " MiB for main workspace.\n", total_mib, malloc_size_mib);
926 } else {
927 const uint64_t mem_available_mib = mem_available_kib / 1024;
928 if (mem_available_mib < malloc_size_mib + nonstack_min_mib) {
929 if (mem_available_mib < bigstack_min_mib + nonstack_min_mib) {
930 malloc_size_mib = bigstack_min_mib;
931 } else {
932 malloc_size_mib = mem_available_mib - nonstack_min_mib;
933 }
934 }
935 printf("%" PRIu64 " MiB RAM detected, ~%" PRIu64 " available; reserving %" PRIuPTR " MiB for main workspace.\n", total_mib, mem_available_mib, malloc_size_mib);
936 }
937 } else {
938 printf("Failed to determine total system memory. Attempting to reserve %" PRIuPTR " MiB.\n", malloc_size_mib);
939 }
940
941 // guarantee contiguous address space outside of main workspace
942 // ...though this is pointless with overcommit on, may want to
943 // conditionally compile this out, and/or conditionally skip this
944 unsigned char* bigstack_base;
945 unsigned char* bigstack_end;
946 uintptr_t malloc_mib_final = malloc_size_mib;
947 {
948 unsigned char* bubble;
949 if (unlikely(pgl_malloc(nonstack_min_mib << 20, &bubble))) {
950 goto main_ret_NOMEM;
951 }
952
953 // don't use pgl_malloc here since we don't automatically want to set
954 // g_failed_alloc_attempt_size on failure
955 bigstack_ua = S_CAST(unsigned char*, malloc(malloc_mib_final << 20));
956 while (!bigstack_ua) {
957 malloc_mib_final = (malloc_mib_final * 3) / 4;
958 if (malloc_mib_final < bigstack_min_mib) {
959 malloc_mib_final = bigstack_min_mib;
960 }
961 bigstack_ua = S_CAST(unsigned char*, malloc(malloc_mib_final << 20));
962 if (unlikely((!bigstack_ua) && (malloc_mib_final == bigstack_min_mib))) {
963 g_failed_alloc_attempt_size = bigstack_min_mib << 20;
964 free(bubble);
965 goto main_ret_NOMEM;
966 }
967 }
968 // force 64-byte align to make cache line sensitivity work
969 unsigned char* bigstack_initial_base = R_CAST(unsigned char*, RoundUpPow2(R_CAST(uintptr_t, bigstack_ua), kCacheline));
970 bigstack_base = bigstack_initial_base;
971 // no g_one_char_strs here, just have a 64 byte overread buffer
972 bigstack_end = &(bigstack_initial_base[RoundDownPow2((malloc_mib_final << 20) - 64 - S_CAST(uintptr_t, bigstack_initial_base - bigstack_ua), kCacheline)]);
973 free(bubble);
974 }
975 if (malloc_size_mib != malloc_mib_final) {
976 printf("Allocated %" PRIuPTR " MiB successfully, after larger attempt(s) failed.\n", malloc_mib_final);
977 }
978
979 if (!bgz_level) {
980 bgz_level = kBgzfDefaultClvl;
981 }
982 reterr = VcfSubset(bigstack_base, bigstack_end, inpath, indv_str, keeppath, outpath, outpath_slen, allow_no_samples, bgz_level, erase_info, no_samples, thread_ct);
983 if (unlikely(reterr)) {
984 goto main_ret_1;
985 }
986 }
987 while (0) {
988 main_ret_NOMEM:
989 reterr = kPglRetNomem;
990 break;
991 main_ret_INVALID_CMDLINE_WW:
992 WordWrap(0, g_textbuf);
993 fputs(g_textbuf, stderr);
994 main_ret_INVALID_CMDLINE:
995 reterr = kPglRetInvalidCmdline;
996 break;
997 }
998 main_ret_1:
999 PrintExitMsg(reterr);
1000 free_cond(bigstack_ua);
1001 return S_CAST(int32_t, reterr);
1002 }