Debian Codegraph @

bcftools/vcfconcat.c.pysam.c

raw symbols SCIP
1 #include "bcftools.pysam.h"
2
3 /* vcfconcat.c -- Concatenate or combine VCF/BCF files.
4
5 Copyright (C) 2013-2023 Genome Research Ltd.
6
7 Author: Petr Danecek <[email protected]>
8
9 Permission is hereby granted, free of charge, to any person obtaining a copy
10 of this software and associated documentation files (the "Software"), to deal
11 in the Software without restriction, including without limitation the rights
12 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 copies of the Software, and to permit persons to whom the Software is
14 furnished to do so, subject to the following conditions:
15
16 The above copyright notice and this permission notice shall be included in
17 all copies or substantial portions of the Software.
18
19 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 THE SOFTWARE. */
26
27 #include <stdio.h>
28 #include <unistd.h>
29 #include <getopt.h>
30 #include <string.h>
31 #include <assert.h>
32 #include <errno.h>
33 #include <math.h>
34 #include <stdint.h>
35 #include <inttypes.h>
36 #include <htslib/vcf.h>
37 #include <htslib/synced_bcf_reader.h>
38 #include <htslib/kseq.h>
39 #include <htslib/bgzf.h>
40 #include <htslib/tbx.h> // for hts_get_bgzfp()
41 #include <htslib/thread_pool.h>
42 #include <htslib/hts_endian.h>
43 #include <sys/time.h>
44 #include "bcftools.h"
45
46 typedef struct _args_t
47 {
48 bcf_srs_t *files;
49 htsFile *out_fh;
50 int output_type, n_threads, record_cmd_line, clevel;
51 bcf_hdr_t *out_hdr;
52 int *seen_seq;
53 char *index_fn;
54 int write_index;
55
56 // phasing
57 int *start_pos, start_tid, ifname;
58 int *swap_phase, nswap, *nmatch, *nmism;
59 bcf1_t **buf;
60 uint8_t *buf_mask;
61 int nbuf, mbuf, prev_chr, min_PQ, prev_pos_check;
62 int32_t *GTa, *GTb, mGTa, mGTb, *phase_qual, *phase_set;
63
64 char **argv, *output_fname, *file_list, **fnames, *remove_dups, *regions_list;
65 int argc, nfnames, allow_overlaps, phased_concat, regions_is_file, regions_overlap;
66 int compact_PS, phase_set_changed, naive_concat, naive_concat_trust_headers;
67 int verbose, explicit_output_type, ligate_force, ligate_warn;
68 int sites_only;
69 htsThreadPool *tpool;
70 }
71 args_t;
72
73 static bcf_hdr_t *drop_hdr_genotypes(args_t *args, bcf_hdr_t *hdr)
74 {
75 if ( !args->sites_only ) return hdr;
76 bcf_hdr_t *rmme = hdr;
77 hdr = bcf_hdr_subset(rmme, 0, 0, 0);
78 bcf_hdr_remove(hdr, BCF_HL_FMT, NULL);
79 bcf_hdr_destroy(rmme);
80 return hdr;
81 }
82
83 static void init_data(args_t *args)
84 {
85 bcf1_t *line = NULL;
86
87 // With phased concat, the chunks overlap and come in the right order. To
88 // avoid opening all files at once, store start positions to recognise need
89 // for the next one. This way we can keep only two open chunks at once.
90 if ( args->phased_concat )
91 {
92 args->start_pos = (int*) malloc(sizeof(int)*args->nfnames);
93 line = bcf_init();
94 }
95
96 if ( args->verbose ) fprintf(bcftools_stderr,"Checking the headers and starting positions of %d files\n", args->nfnames);
97 kstring_t str = {0,0,0};
98 int i, prev_chrid = -1;
99 for (i=0; i<args->nfnames; i++)
100 {
101 htsFile *fp = hts_open(args->fnames[i], "r"); if ( !fp ) error("Failed to open: %s\n", args->fnames[i]);
102 bcf_hdr_t *hdr = bcf_hdr_read(fp); if ( !hdr ) error("Failed to parse header: %s\n", args->fnames[i]);
103 hdr = drop_hdr_genotypes(args, hdr);
104
105 args->out_hdr = bcf_hdr_merge(args->out_hdr,hdr);
106 if ( bcf_hdr_nsamples(hdr) != bcf_hdr_nsamples(args->out_hdr) )
107 error("Different number of samples in %s. Perhaps \"bcftools merge\" is what you are looking for?\n", args->fnames[i]);
108
109 int j;
110 for (j=0; j<bcf_hdr_nsamples(hdr); j++)
111 if ( strcmp(args->out_hdr->samples[j],hdr->samples[j]) )
112 error("Different sample names in %s. Perhaps \"bcftools merge\" is what you are looking for?\n", args->fnames[i]);
113
114 if ( args->phased_concat )
115 {
116 int ret = bcf_read(fp, hdr, line);
117 if ( ret!=0 ) args->start_pos[i] = -2; // empty file
118 else
119 {
120 int chrid = bcf_hdr_id2int(args->out_hdr,BCF_DT_CTG,bcf_seqname(hdr,line));
121 args->start_pos[i] = chrid==prev_chrid ? line->pos : -1;
122 prev_chrid = chrid;
123 }
124 }
125 bcf_hdr_destroy(hdr);
126 if ( hts_close(fp)!=0 ) error("[%s] Error: close failed .. %s\n", __func__,args->fnames[i]);
127 }
128 free(str.s);
129 if ( line ) bcf_destroy(line);
130
131 args->seen_seq = (int*) calloc(args->out_hdr->n[BCF_DT_CTG],sizeof(int));
132
133 if ( args->phased_concat )
134 {
135 bcf_hdr_append(args->out_hdr,"##FORMAT=<ID=PQ,Number=1,Type=Integer,Description=\"Phasing Quality (bigger is better)\">");
136 bcf_hdr_append(args->out_hdr,"##FORMAT=<ID=PS,Number=1,Type=Integer,Description=\"Phase Set\">");
137 }
138 if (args->record_cmd_line) bcf_hdr_append_version(args->out_hdr, args->argc, args->argv, "bcftools_concat");
139 char wmode[8];
140 set_wmode(wmode,args->output_type,args->output_fname,args->clevel);
141 args->out_fh = hts_open(args->output_fname ? args->output_fname : "-", wmode);
142 if ( args->out_fh == NULL ) error("Can't write to \"%s\": %s\n", args->output_fname, strerror(errno));
143 if ( args->allow_overlaps || args->phased_concat )
144 {
145 args->files = bcf_sr_init();
146 args->files->require_index = 1;
147 }
148 if ( args->n_threads )
149 {
150 if ( args->files )
151 {
152 if ( bcf_sr_set_threads(args->files, args->n_threads)<0 ) error("Failed to create threads\n");
153 args->tpool = args->files->p;
154 }
155 else
156 {
157 args->tpool = (htsThreadPool*) calloc(1, sizeof(htsThreadPool));
158 if ( !args->tpool ) error("Failed to allocate memory\n");
159 if ( !(args->tpool->pool = hts_tpool_init(args->n_threads)) ) error("Failed to initialize %d threads\n",args->n_threads);
160 }
161 hts_set_opt(args->out_fh, HTS_OPT_THREAD_POOL, args->tpool);
162 }
163 if ( bcf_hdr_write(args->out_fh, args->out_hdr)!=0 ) error("[%s] Error: cannot write the header to %s\n", __func__,args->output_fname);
164 if ( init_index2(args->out_fh,args->out_hdr,args->output_fname,
165 &args->index_fn, args->write_index)<0 )
166 error("Error: failed to initialise index for %s\n",args->output_fname);
167
168 if ( args->allow_overlaps )
169 {
170 if ( args->regions_list )
171 {
172 bcf_sr_set_opt(args->files,BCF_SR_REGIONS_OVERLAP,args->regions_overlap);
173 if ( bcf_sr_set_regions(args->files, args->regions_list, args->regions_is_file)<0 )
174 error("Failed to read the regions: %s\n", args->regions_list);
175 }
176 if ( args->remove_dups )
177 {
178 if ( !strcmp(args->remove_dups,"snps") ) args->files->collapse |= COLLAPSE_SNPS;
179 else if ( !strcmp(args->remove_dups,"indels") ) args->files->collapse |= COLLAPSE_INDELS;
180 else if ( !strcmp(args->remove_dups,"both") ) args->files->collapse |= COLLAPSE_SNPS | COLLAPSE_INDELS;
181 else if ( !strcmp(args->remove_dups,"any") ) args->files->collapse |= COLLAPSE_ANY;
182 else if ( !strcmp(args->remove_dups,"all") ) args->files->collapse |= COLLAPSE_ANY;
183 else if ( !strcmp(args->remove_dups,"none") ) args->files->collapse = COLLAPSE_NONE;
184 else if ( !strcmp(args->remove_dups,"exact") ) args->files->collapse = COLLAPSE_NONE;
185 else error("The -D string \"%s\" not recognised.\n", args->remove_dups);
186 }
187 for (i=0; i<args->nfnames; i++)
188 if ( !bcf_sr_add_reader(args->files,args->fnames[i]) ) error("Failed to open %s: %s\n", args->fnames[i],bcf_sr_strerror(args->files->errnum));
189 }
190 else if ( args->phased_concat )
191 {
192 // Remove empty files from the list
193 int nok = 0;
194 while (1)
195 {
196 while ( nok<args->nfnames && args->start_pos[nok]!=-2 ) nok++;
197 if ( nok==args->nfnames ) break;
198
199 i = nok;
200 while ( i<args->nfnames && args->start_pos[i]==-2 ) i++;
201 if ( i==args->nfnames ) break;
202
203 int tmp = args->start_pos[nok]; args->start_pos[nok] = args->start_pos[i]; args->start_pos[i] = tmp;
204 char *str = args->fnames[nok]; args->fnames[nok] = args->fnames[i]; args->fnames[i] = str;
205 }
206 for (i=nok; i<args->nfnames; i++) free(args->fnames[i]);
207 args->nfnames = nok;
208
209 for (i=1; i<args->nfnames; i++)
210 if ( args->start_pos[i-1]!=-1 && args->start_pos[i]!=-1 && args->start_pos[i]<args->start_pos[i-1] )
211 error("The files not in ascending order: %d in %s, %d in %s\n", args->start_pos[i-1]+1,args->fnames[i-1],args->start_pos[i]+1,args->fnames[i]);
212
213 args->prev_chr = -1;
214 args->swap_phase = (int*) calloc(bcf_hdr_nsamples(args->out_hdr),sizeof(int));
215 args->nmatch = (int*) calloc(bcf_hdr_nsamples(args->out_hdr),sizeof(int));
216 args->nmism = (int*) calloc(bcf_hdr_nsamples(args->out_hdr),sizeof(int));
217 args->phase_qual = (int32_t*) malloc(bcf_hdr_nsamples(args->out_hdr)*sizeof(int32_t));
218 args->phase_set = (int32_t*) malloc(bcf_hdr_nsamples(args->out_hdr)*sizeof(int32_t));
219 args->ifname = 0;
220 }
221 }
222
223 static void destroy_data(args_t *args)
224 {
225 int i;
226 if ( args->out_fh )
227 {
228 if ( args->write_index )
229 {
230 if ( bcf_idx_save(args->out_fh)<0 )
231 {
232 if ( hts_close(args->out_fh)!=0 ) error("Error: close failed .. %s\n", args->output_fname?args->output_fname:"bcftools_stdout");
233 error("Error: cannot write to index %s\n", args->index_fn);
234 }
235 free(args->index_fn);
236 }
237 if ( hts_close(args->out_fh)!=0 ) error("Error: close failed .. %s\n",args->output_fname?args->output_fname:"bcftools_stdout");
238 }
239 if ( args->tpool && !args->files )
240 {
241 hts_tpool_destroy(args->tpool->pool);
242 free(args->tpool);
243 }
244 if ( args->files ) bcf_sr_destroy(args->files);
245 if ( args->out_hdr ) bcf_hdr_destroy(args->out_hdr);
246 free(args->seen_seq);
247 free(args->start_pos);
248 free(args->swap_phase);
249 for (i=0; i<args->mbuf; i++) bcf_destroy(args->buf[i]);
250 free(args->buf);
251 free(args->buf_mask);
252 free(args->GTa);
253 free(args->GTb);
254 free(args->nmatch);
255 free(args->nmism);
256 free(args->phase_qual);
257 free(args->phase_set);
258 for (i=0; i<args->nfnames; i++) free(args->fnames[i]);
259 free(args->fnames);
260 }
261
262 int vcf_write_line(htsFile *fp, kstring_t *line);
263
264 #define SWAP(type_t, a, b) { type_t t = a; a = b; b = t; }
265 static void phase_update(args_t *args, bcf_hdr_t *hdr, bcf1_t *rec)
266 {
267 int i, nGTs = bcf_get_genotypes(hdr, rec, &args->GTa, &args->mGTa);
268 if ( nGTs <= 0 ) return; // GT field is not present
269 for (i=0; i<bcf_hdr_nsamples(hdr); i++)
270 {
271 if ( !args->swap_phase[i] ) continue;
272 int *gt = &args->GTa[i*2];
273 if ( bcf_gt_is_missing(gt[0]) || gt[1]==bcf_int32_vector_end ) continue;
274 if ( !bcf_gt_is_phased(gt[1]) ) continue;
275 SWAP(int, gt[0], gt[1]);
276 gt[1] |= 1;
277 }
278 bcf_update_genotypes(hdr,rec,args->GTa,nGTs);
279 }
280
281 static void phased_flush(args_t *args)
282 {
283 if ( !args->nbuf ) return;
284
285 bcf_hdr_t *ahdr = args->files->readers[0].header;
286 bcf_hdr_t *bhdr = args->files->readers[1].header;
287
288 int i, j, nsmpl = bcf_hdr_nsamples(args->out_hdr);
289 static int gt_absent_warned = 0;
290 for (i=0; i<args->nbuf; i+=2)
291 {
292 if ( args->buf_mask[i/2]!=3 ) continue;
293
294 bcf1_t *arec = args->buf[i];
295 bcf1_t *brec = args->buf[i+1];
296
297 int nGTs = bcf_get_genotypes(ahdr, arec, &args->GTa, &args->mGTa);
298 if ( nGTs < 0 )
299 {
300 if ( !gt_absent_warned )
301 {
302 fprintf(bcftools_stderr,"GT is not present at %s:%"PRId64". (This warning is printed only once.)\n", bcf_seqname(ahdr,arec), (int64_t) arec->pos+1);
303 gt_absent_warned = 1;
304 }
305 continue;
306 }
307 if ( nGTs != 2*nsmpl ) continue; // not diploid
308 nGTs = bcf_get_genotypes(bhdr, brec, &args->GTb, &args->mGTb);
309 if ( nGTs < 0 )
310 {
311 if ( !gt_absent_warned )
312 {
313 fprintf(bcftools_stderr,"GT is not present at %s:%"PRId64". (This warning is printed only once.)\n", bcf_seqname(bhdr,brec), (int64_t) brec->pos+1);
314 gt_absent_warned = 1;
315 }
316 continue;
317 }
318 if ( nGTs != 2*nsmpl ) continue; // not diploid
319
320 for (j=0; j<nsmpl; j++)
321 {
322 int *gta = &args->GTa[j*2];
323 int *gtb = &args->GTb[j*2];
324 if ( gta[1]==bcf_int32_vector_end || gtb[1]==bcf_int32_vector_end ) continue;
325 if ( bcf_gt_is_missing(gta[0]) || bcf_gt_is_missing(gta[1]) || bcf_gt_is_missing(gtb[0]) || bcf_gt_is_missing(gtb[1]) ) continue;
326 if ( !bcf_gt_is_phased(gta[1]) || !bcf_gt_is_phased(gtb[1]) ) continue;
327 if ( bcf_gt_allele(gta[0])==bcf_gt_allele(gta[1]) || bcf_gt_allele(gtb[0])==bcf_gt_allele(gtb[1]) ) continue;
328 if ( bcf_gt_allele(gta[0])==bcf_gt_allele(gtb[0]) && bcf_gt_allele(gta[1])==bcf_gt_allele(gtb[1]) )
329 {
330 if ( args->swap_phase[j] ) args->nmism[j]++; else args->nmatch[j]++;
331 }
332 if ( bcf_gt_allele(gta[0])==bcf_gt_allele(gtb[1]) && bcf_gt_allele(gta[1])==bcf_gt_allele(gtb[0]) )
333 {
334 if ( args->swap_phase[j] ) args->nmatch[j]++; else args->nmism[j]++;
335 }
336 }
337 }
338 for (i=0; i<args->nbuf/2; i+=2)
339 {
340 bcf1_t *rec;
341 bcf_hdr_t *hdr;
342 int mask = args->buf_mask[i/2];
343 if ( mask & 1 ) { rec = args->buf[i]; hdr = args->files->readers[0].header; }
344 else { rec = args->buf[i+1]; hdr = args->files->readers[1].header; }
345 bcf_translate(args->out_hdr, hdr, rec);
346 if ( args->nswap && (mask&1) )
347 phase_update(args, args->out_hdr, rec);
348 if ( !args->compact_PS || args->phase_set_changed )
349 {
350 bcf_update_format_int32(args->out_hdr,rec,"PS",args->phase_set,nsmpl);
351 args->phase_set_changed = 0;
352 }
353 if ( bcf_write(args->out_fh, args->out_hdr, rec)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->output_fname);
354
355 if ( rec->pos < args->prev_pos_check ) error("FIXME, disorder: %s:%"PRId64" vs %d [1]\n", bcf_seqname(hdr,rec),(int64_t)rec->pos+1,args->prev_pos_check+1);
356 args->prev_pos_check = rec->pos;
357 }
358 args->nswap = 0;
359 for (j=0; j<nsmpl; j++)
360 {
361 if ( args->nmatch[j] >= args->nmism[j] )
362 args->swap_phase[j] = 0;
363 else
364 {
365 args->swap_phase[j] = 1;
366 args->nswap++;
367 }
368 if ( args->nmatch[j] && args->nmism[j] )
369 {
370 // Entropy-inspired quality. The factor 0.7 shifts and scales to (0,1)
371 double f = (double)args->nmatch[j]/(args->nmatch[j]+args->nmism[j]);
372 args->phase_qual[j] = 99*(0.7 + f*log(f) + (1-f)*log(1-f))/0.7;
373 }
374 else
375 args->phase_qual[j] = 99;
376 args->nmatch[j] = 0;
377 args->nmism[j] = 0;
378 }
379 int PQ_printed = 0;
380 for (; i<args->nbuf; i+=2)
381 {
382 bcf1_t *rec;
383 bcf_hdr_t *hdr;
384 int mask = args->buf_mask[i/2];
385 if ( mask & 2 ) { rec = args->buf[i+1]; hdr = args->files->readers[1].header; }
386 else { rec = args->buf[i]; hdr = args->files->readers[0].header; }
387 bcf_translate(args->out_hdr, hdr, rec);
388 if ( !PQ_printed && mask==3 )
389 {
390 bcf_update_format_int32(args->out_hdr,rec,"PQ",args->phase_qual,nsmpl);
391 PQ_printed = 1;
392 for (j=0; j<nsmpl; j++)
393 if ( args->phase_qual[j] < args->min_PQ )
394 {
395 args->phase_set[j] = rec->pos+1;
396 args->phase_set_changed = 1;
397 }
398 else if ( args->compact_PS ) args->phase_set[j] = bcf_int32_missing;
399 }
400 if ( args->nswap )
401 phase_update(args, args->out_hdr, rec);
402 if ( !args->compact_PS || args->phase_set_changed )
403 {
404 bcf_update_format_int32(args->out_hdr,rec,"PS",args->phase_set,nsmpl);
405 args->phase_set_changed = 0;
406 }
407 if ( bcf_write(args->out_fh, args->out_hdr, rec)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->output_fname);
408
409 if ( rec->pos < args->prev_pos_check ) error("FIXME, disorder: %s:%"PRId64" vs %d [2]\n", bcf_seqname(hdr,rec),(int64_t)rec->pos+1,args->prev_pos_check+1);
410 args->prev_pos_check = rec->pos;
411 }
412 args->nbuf = 0;
413 }
414
415 static void phased_push(args_t *args, bcf1_t *arec, bcf1_t *brec, int is_overlap)
416 {
417 bcf_hdr_t *ahdr = arec ? bcf_sr_get_header(args->files,0) : NULL;
418 bcf_hdr_t *bhdr = brec ? bcf_sr_get_header(args->files,1) : NULL;
419
420 if ( arec && arec->errcode )
421 error("Parse error at %s:%"PRId64", cannot proceed: %s\n", bcf_seqname(ahdr,arec),(int64_t) arec->pos+1, args->files->readers[0].fname);
422 if ( brec && brec->errcode )
423 error("Parse error at %s:%"PRId64", cannot proceed: %s\n", bcf_seqname(bhdr,brec),(int64_t) brec->pos+1, args->files->readers[1].fname);
424
425 int i, nsmpl = bcf_hdr_nsamples(args->out_hdr);
426 int chr_id = arec ? bcf_hdr_name2id(args->out_hdr,bcf_seqname(ahdr,arec)) : bcf_hdr_name2id(args->out_hdr,bcf_seqname(bhdr,brec));
427 if ( args->prev_chr<0 || args->prev_chr!=chr_id )
428 {
429 if ( args->prev_chr>=0 ) phased_flush(args);
430
431 for (i=0; i<nsmpl; i++)
432 args->phase_set[i] = arec ? arec->pos+1 : brec->pos+1;
433 args->phase_set_changed = 1;
434
435 if ( args->seen_seq[chr_id] ) error("The chromosome block %s is not contiguous\n", arec ? bcf_seqname(ahdr,arec) : bcf_seqname(bhdr,brec));
436 args->seen_seq[chr_id] = 1;
437 args->prev_chr = chr_id;
438 args->prev_pos_check = -1;
439 }
440
441 if ( !is_overlap )
442 {
443 assert(arec);
444
445 bcf_translate(args->out_hdr, ahdr, arec);
446 if ( args->nswap )
447 phase_update(args, args->out_hdr, arec);
448 if ( !args->compact_PS || args->phase_set_changed )
449 {
450 bcf_update_format_int32(args->out_hdr,arec,"PS",args->phase_set,nsmpl);
451 args->phase_set_changed = 0;
452 }
453 if ( bcf_write(args->out_fh, args->out_hdr, arec)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->output_fname);
454
455 if ( arec->pos < args->prev_pos_check )
456 error("FIXME, disorder: %s:%"PRId64" in %s vs %d written [3]\n", bcf_seqname(ahdr,arec), (int64_t) arec->pos+1,args->files->readers[0].fname, args->prev_pos_check+1);
457 args->prev_pos_check = arec->pos;
458 return;
459 }
460
461 int m = args->mbuf;
462 args->nbuf += 2;
463 hts_expand(bcf1_t*,args->nbuf,args->mbuf,args->buf);
464 if ( m < args->mbuf ) args->buf_mask = (uint8_t*)realloc(args->buf_mask,sizeof(*args->buf_mask)*args->mbuf);
465 for (i=m; i<args->mbuf; i++)
466 args->buf[i] = bcf_init1();
467
468 if ( arec ) SWAP(bcf1_t*, args->files->readers[0].buffer[0], args->buf[args->nbuf-2]);
469 if ( brec ) SWAP(bcf1_t*, args->files->readers[1].buffer[0], args->buf[args->nbuf-1]);
470 args->buf_mask[args->nbuf/2-1] = (arec?1:0) | (brec?2:0);
471 }
472
473 static int _get_active_index(bcf_srs_t *sr)
474 {
475 int i;
476 for (i=0; i<sr->nreaders; i++)
477 if ( bcf_sr_has_line(sr,i) ) return i;
478 return -1;
479 }
480
481 static void concat(args_t *args)
482 {
483 static int site_drop_warned = 0;
484 int i;
485 if ( args->phased_concat ) // phased concat
486 {
487 // keep only two open files at a time
488 while ( args->ifname < args->nfnames )
489 {
490 int new_file = 0;
491 while ( args->files->nreaders < 2 && args->ifname < args->nfnames )
492 {
493 if ( !bcf_sr_add_reader(args->files,args->fnames[args->ifname]) ) error("Failed to open %s: %s\n", args->fnames[args->ifname],bcf_sr_strerror(args->files->errnum));
494 new_file = 1;
495
496 args->ifname++;
497 if ( args->start_pos[args->ifname-1]==-1 ) break; // new chromosome, start with only one file open
498 if ( args->ifname < args->nfnames && args->start_pos[args->ifname]==-1 ) break; // next file starts on a different chromosome
499 }
500
501 // is there a line from the previous run? Seek the newly opened reader to that position
502 int seek_pos = -1;
503 int seek_chr = -1;
504 if ( bcf_sr_has_line(args->files,0) )
505 {
506 bcf1_t *line = bcf_sr_get_line(args->files,0);
507 bcf_sr_seek(args->files, bcf_seqname(args->files->readers[0].header,line), line->pos);
508 seek_pos = line->pos;
509 seek_chr = bcf_hdr_name2id(args->out_hdr, bcf_seqname(args->files->readers[0].header,line));
510 }
511 else if ( new_file )
512 bcf_sr_seek(args->files,NULL,0); // set to start
513
514 int nret, ir;
515 while ( (nret = bcf_sr_next_line(args->files)) )
516 {
517 int is_overlap = args->files->nreaders==1 ? 0 : 1;
518 if ( !bcf_sr_has_line(args->files,0) ) // no input from the first reader
519 {
520 // We are assuming that there is a perfect overlap, sites which are not present in both files are dropped
521 if ( bcf_sr_region_done(args->files,0) )
522 {
523 phased_flush(args);
524 bcf_sr_remove_reader(args->files, 0);
525 is_overlap = 0;
526 }
527 else if ( args->ligate_warn )
528 {
529 if ( !site_drop_warned )
530 {
531 ir = _get_active_index(args->files);
532 fprintf(bcftools_stderr,
533 "Warning: Dropping the site %s:%"PRId64". The --ligate option is intended for VCFs with perfect\n"
534 " overlap, sites in overlapping regions present in one but missing in other are dropped.\n"
535 " This warning is printed only once.\n",
536 bcf_seqname(bcf_sr_get_header(args->files,ir),bcf_sr_get_line(args->files,ir)), (int64_t) bcf_sr_get_line(args->files,ir)->pos+1);
537 site_drop_warned = 1;
538 }
539 continue;
540 }
541 else if ( !args->ligate_force )
542 {
543 ir = _get_active_index(args->files);
544 error("Error: The --ligate option is intended for VCFs with perfect overlap, the site %s:%"PRId64" breaks the assumption\n",
545 bcf_seqname(bcf_sr_get_header(args->files,ir),bcf_sr_get_line(args->files,ir)), (int64_t) bcf_sr_get_line(args->files,ir)->pos+1);
546 }
547 }
548
549 // Get a line to learn about current position
550 ir = _get_active_index(args->files);
551 bcf1_t *line = bcf_sr_get_line(args->files,ir);
552
553 // This can happen after bcf_sr_seek: indel may start before the coordinate which we seek to.
554 if ( seek_chr>=0 && seek_pos>line->pos && seek_chr==bcf_hdr_name2id(args->out_hdr, bcf_seqname(args->files->readers[ir].header,line)) ) continue;
555 seek_pos = seek_chr = -1;
556
557 // Check if the position overlaps with the next, yet unopened, reader
558 int must_seek = 0;
559 while ( args->ifname < args->nfnames && args->start_pos[args->ifname]!=-1 && line->pos >= args->start_pos[args->ifname] )
560 {
561 must_seek = 1;
562 if ( !bcf_sr_add_reader(args->files,args->fnames[args->ifname]) ) error("Failed to open %s: %s\n", args->fnames[args->ifname],bcf_sr_strerror(args->files->errnum));
563 args->ifname++;
564 }
565 if ( must_seek )
566 {
567 bcf_sr_seek(args->files, bcf_seqname(args->files->readers[ir].header,line), line->pos);
568 seek_pos = line->pos;
569 seek_chr = bcf_hdr_name2id(args->out_hdr, bcf_seqname(args->files->readers[ir].header,line));
570 continue;
571 }
572
573 // We are assuming that there is a perfect overlap, sites which are not present in both files are dropped
574 if ( args->files->nreaders>1 && !bcf_sr_has_line(args->files,1) && !bcf_sr_region_done(args->files,1) && !args->ligate_force )
575 {
576 if ( args->ligate_warn && !site_drop_warned )
577 {
578 ir = _get_active_index(args->files);
579 fprintf(bcftools_stderr,
580 "Warning: Dropping the site %s:%"PRId64". The --ligate option is intended for VCFs with perfect\n"
581 " overlap, sites in overlapping regions present in one but missing in other are dropped.\n"
582 " This warning is printed only once.\n",
583 bcf_seqname(bcf_sr_get_header(args->files,ir),line), (int64_t) line->pos+1);
584 site_drop_warned = 1;
585 }
586 else if ( !args->ligate_warn )
587 {
588 ir = _get_active_index(args->files);
589 error("Error: The --ligate option is intended for VCFs with perfect overlap, the site %s:%"PRId64" breaks the assumption\n",
590 bcf_seqname(bcf_sr_get_header(args->files,ir),bcf_sr_get_line(args->files,ir)), (int64_t) bcf_sr_get_line(args->files,ir)->pos+1);
591 }
592 continue;
593 }
594
595 bcf1_t *line0 = bcf_sr_get_line(args->files,0);
596 bcf1_t *line1 = args->files->nreaders > 1 ? bcf_sr_get_line(args->files,1) : NULL;
597 phased_push(args, line0, line1, is_overlap);
598 }
599
600 if ( args->files->nreaders )
601 {
602 phased_flush(args);
603 while ( args->files->nreaders )
604 bcf_sr_remove_reader(args->files, 0);
605 }
606 }
607 }
608 else if ( args->files ) // combining overlapping files, using synced reader
609 {
610 while ( bcf_sr_next_line(args->files) )
611 {
612 for (i=0; i<args->files->nreaders; i++)
613 {
614 bcf1_t *line = bcf_sr_get_line(args->files,i);
615 if ( !line ) continue;
616 if ( args->sites_only ) bcf_subset(args->out_hdr, line, 0, 0);
617 bcf_translate(args->out_hdr, args->files->readers[i].header, line);
618 if ( bcf_write1(args->out_fh, args->out_hdr, line)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->output_fname);
619 if ( args->remove_dups ) break;
620 }
621 }
622 }
623 else // concatenate as is
624 {
625 struct timeval t0, t1;
626 kstring_t tmp = {0,0,0};
627 int prev_chr_id = -1, prev_pos;
628 bcf1_t *line = bcf_init();
629 for (i=0; i<args->nfnames; i++)
630 {
631 if ( args->verbose )
632 {
633 fprintf(bcftools_stderr,"Concatenating %s", args->fnames[i]);
634 gettimeofday(&t0, NULL);
635 }
636 htsFile *fp = hts_open(args->fnames[i], "r"); if ( !fp ) error("\nFailed to open: %s\n", args->fnames[i]);
637 if ( args->n_threads ) hts_set_opt(fp, HTS_OPT_THREAD_POOL, args->tpool);
638 bcf_hdr_t *hdr = bcf_hdr_read(fp); if ( !hdr ) error("\nFailed to parse header: %s\n", args->fnames[i]);
639 if ( args->sites_only )
640 {
641 bcf_hdr_t *hdr_ori = hdr;
642 hdr = bcf_hdr_subset(hdr_ori, 0, 0, 0);
643 bcf_hdr_remove(hdr, BCF_HL_FMT, NULL);
644 bcf_hdr_destroy(hdr_ori);
645 }
646 if ( !fp->is_bin && args->output_type&FT_VCF )
647 {
648 line->max_unpack = BCF_UN_STR;
649 // if VCF is on both input and output, avoid VCF to BCF conversion
650 while ( hts_getline(fp, KS_SEP_LINE, &fp->line) >=0 )
651 {
652 char *str = fp->line.s;
653
654 // remove genotypes
655 if ( args->sites_only )
656 {
657 int ntab = 0;
658 while ( *str )
659 {
660 if ( *str == '\t' && ++ntab==8 )
661 {
662 *str = 0;
663 break;
664 }
665 str++;
666 }
667 str = fp->line.s;
668 }
669 while ( *str && *str!='\t' ) str++;
670 tmp.l = 0;
671 kputsn(fp->line.s,str-fp->line.s,&tmp);
672 int chr_id = bcf_hdr_name2id(args->out_hdr, tmp.s);
673 if ( chr_id<0 ) error("\nThe sequence \"%s\" not defined in the header: %s\n(Quick workaround: index the file.)\n", tmp.s, args->fnames[i]);
674 if ( prev_chr_id!=chr_id )
675 {
676 prev_pos = -1;
677 if ( args->seen_seq[chr_id] )
678 error("\nThe chromosome block %s is not contiguous, consider running with -a.\n", tmp.s);
679 }
680 char *end;
681 int pos = strtol(str+1,&end,10) - 1;
682 if ( end==str+1 ) error("Could not parse line: %s\n", fp->line.s);
683 if ( prev_pos > pos )
684 error("\nThe chromosome block %s is not sorted, consider running with -a.\n", tmp.s);
685 args->seen_seq[chr_id] = 1;
686 prev_chr_id = chr_id;
687
688 if ( vcf_write_line(args->out_fh, &fp->line)!=0 ) error("\nFailed to write %"PRIu64" bytes\n", (uint64_t)fp->line.l);
689 }
690 }
691 else
692 {
693 // BCF conversion is required
694 line->max_unpack = 0;
695 while ( bcf_read(fp, hdr, line)==0 )
696 {
697 if ( args->sites_only ) bcf_subset(args->out_hdr, line, 0, 0);
698 bcf_translate(args->out_hdr, hdr, line);
699
700 if ( prev_chr_id!=line->rid )
701 {
702 prev_pos = -1;
703 if ( args->seen_seq[line->rid] )
704 error("\nThe chromosome block %s is not contiguous, consider running with -a.\n", bcf_seqname(args->out_hdr, line));
705 }
706 if ( prev_pos > line->pos )
707 error("\nThe chromosome block %s is not sorted, consider running with -a.\n", bcf_seqname(args->out_hdr, line));
708 args->seen_seq[line->rid] = 1;
709 prev_chr_id = line->rid;
710
711 if ( bcf_write(args->out_fh, args->out_hdr, line)!=0 ) error("\nFailed to write\n");
712 }
713 }
714 bcf_hdr_destroy(hdr);
715 hts_close(fp);
716 if ( args->verbose )
717 {
718 gettimeofday(&t1, NULL);
719 double delta = (t1.tv_sec - t0.tv_sec) * 1e6 + (t1.tv_usec - t0.tv_usec);
720 fprintf(bcftools_stderr,"\t%f seconds\n",delta/1e6);
721 }
722 }
723 bcf_destroy(line);
724 free(tmp.s);
725 }
726 }
727
728 int print_vcf_gz_header(BGZF *fp, BGZF *bgzf_out, int print_header, kstring_t *tmp)
729 {
730 char *buffer = (char*) fp->uncompressed_block;
731
732 // Read the header and find the position of the data block
733 if ( buffer[0]!='#' ) error("Could not parse the header, expected '#', found '%c'\n", buffer[0]);
734
735 int nskip = 1; // end of the header in the current uncompressed block
736 while (1)
737 {
738 if ( buffer[nskip]=='\n' )
739 {
740 nskip++;
741 if ( nskip>=fp->block_length )
742 {
743 kputsn(buffer,nskip,tmp);
744 if ( bgzf_read_block(fp) != 0 ) return -1;
745 if ( !fp->block_length ) break;
746 nskip = 0;
747 }
748 // The header has finished
749 if ( buffer[nskip]!='#' )
750 {
751 kputsn(buffer,nskip,tmp);
752 break;
753 }
754 }
755 nskip++;
756 if ( nskip>=fp->block_length )
757 {
758 kputsn(buffer,fp->block_length,tmp);
759 if ( bgzf_read_block(fp) != 0 ) return -1;
760 if ( !fp->block_length ) break;
761 nskip = 0;
762 }
763 }
764 if ( print_header )
765 {
766 if ( bgzf_write(bgzf_out,tmp->s,tmp->l) != tmp->l ) error("Failed to write %"PRIu64" bytes\n", (uint64_t)tmp->l);
767 tmp->l = 0;
768 }
769 return nskip;
770 }
771
772 static inline int unpackInt16(const uint8_t *buffer)
773 {
774 return buffer[0] | buffer[1] << 8;
775 }
776 static int check_header(const uint8_t *header)
777 {
778 if ( header[0] != 31 || header[1] != 139 || header[2] != 8 ) return -2;
779 return ((header[3] & 4) != 0
780 && unpackInt16((uint8_t*)&header[10]) == 6
781 && header[12] == 'B' && header[13] == 'C'
782 && unpackInt16((uint8_t*)&header[14]) == 2) ? 0 : -1;
783 }
784 static void _check_hrecs(const bcf_hdr_t *hdr0, const bcf_hdr_t *hdr, char *fname0, char *fname)
785 {
786 int j;
787 for (j=0; j<hdr0->nhrec; j++)
788 {
789 bcf_hrec_t *hrec0 = hdr0->hrec[j];
790 if ( hrec0->type!=BCF_HL_FLT && hrec0->type!=BCF_HL_INFO && hrec0->type!=BCF_HL_FMT && hrec0->type!=BCF_HL_CTG ) continue; // skip fields w/o IDX
791 int itag = bcf_hrec_find_key(hrec0, "ID");
792 bcf_hrec_t *hrec = bcf_hdr_get_hrec(hdr, hrec0->type, "ID", hrec0->vals[itag], NULL);
793
794 char *type = NULL;
795 if ( hrec0->type==BCF_HL_FLT ) type = "FILTER";
796 if ( hrec0->type==BCF_HL_INFO ) type = "INFO";
797 if ( hrec0->type==BCF_HL_FMT ) type = "FORMAT";
798 if ( hrec0->type==BCF_HL_CTG ) type = "contig";
799
800 if ( !hrec )
801 error("Cannot use --naive, incompatible headers, the tag %s/%s not present in %s\n",type,hrec0->vals[itag],fname);
802
803 int idx0 = bcf_hrec_find_key(hrec0, "IDX");
804 int idx = bcf_hrec_find_key(hrec, "IDX");
805 if ( idx0<0 || idx<0 )
806 error("fixme: unexpected IDX<0 for %s/%s in %s or %s\n",type,hrec0->vals[itag],fname0,fname);
807 if ( strcmp(hrec0->vals[idx0],hrec->vals[idx]) )
808 error("Cannot use --naive, use --naive-force instead: different order the tag %s/%s in %s vs %s\n",type,hrec0->vals[itag],fname0,fname);
809 }
810 }
811 static void naive_concat_check_headers(args_t *args)
812 {
813 fprintf(bcftools_stderr,"Checking the headers of %d files.\n",args->nfnames);
814 bcf_hdr_t *hdr0 = NULL;
815 int i,j;
816 for (i=0; i<args->nfnames; i++)
817 {
818 htsFile *fp = hts_open(args->fnames[i], "r"); if ( !fp ) error("Failed to open: %s\n", args->fnames[i]);
819 bcf_hdr_t *hdr = bcf_hdr_read(fp); if ( !hdr ) error("Failed to parse header: %s\n", args->fnames[i]);
820 htsFormat type = *hts_get_format(fp);
821 hts_close(fp);
822
823 if ( i==0 )
824 {
825 hdr0 = hdr;
826 continue;
827 }
828
829 // check the samples
830 if ( bcf_hdr_nsamples(hdr0)!=bcf_hdr_nsamples(hdr) )
831 error("Cannot concatenate, different number of samples: %d vs %d in %s vs %s\n",bcf_hdr_nsamples(hdr0),bcf_hdr_nsamples(hdr),args->fnames[0],args->fnames[i]);
832 for (j=0; j<bcf_hdr_nsamples(hdr0); j++)
833 if ( strcmp(hdr0->samples[j],hdr->samples[j]) )
834 error("Cannot concatenate, different samples in %s vs %s\n",args->fnames[0],args->fnames[i]);
835
836 // if BCF, check if tag IDs are consistent in the dictionary of strings
837 if ( type.compression!=bgzf )
838 error("The --naive option works only for compressed BCFs or VCFs, sorry :-/\n");
839
840 _check_hrecs(hdr0,hdr,args->fnames[0],args->fnames[i]);
841 _check_hrecs(hdr,hdr0,args->fnames[i],args->fnames[0]);
842
843 bcf_hdr_destroy(hdr);
844 }
845 if ( hdr0 ) bcf_hdr_destroy(hdr0);
846 fprintf(bcftools_stderr,"Done, the headers are compatible.\n");
847 }
848 static void naive_concat(args_t *args)
849 {
850 if ( !args->naive_concat_trust_headers )
851 naive_concat_check_headers(args);
852
853 // only compressed BCF atm
854 BGZF *bgzf_out = bgzf_open(args->output_fname,"w");;
855
856 htsFormat output_type;
857 output_type.format = (args->output_type & FT_VCF) ? vcf : bcf;
858 output_type.compression = (args->output_type & FT_GZ) ? bgzf : no_compression;
859
860 struct timeval t0, t1;
861 const size_t page_size = BGZF_MAX_BLOCK_SIZE;
862 uint8_t *buf = (uint8_t*) malloc(page_size);
863 kstring_t tmp = {0,0,0};
864 int i, file_types = 0;
865 for (i=0; i<args->nfnames; i++)
866 {
867 if ( args->verbose )
868 {
869 fprintf(bcftools_stderr,"Concatenating %s", args->fnames[i]);
870 gettimeofday(&t0, NULL);
871 }
872 htsFile *hts_fp = hts_open(args->fnames[i],"r");
873 if ( !hts_fp ) error("\nFailed to open: %s\n", args->fnames[i]);
874 htsFormat type = *hts_get_format(hts_fp);
875
876 if ( type.compression!=bgzf )
877 error("\nThe --naive option works only for compressed BCFs or VCFs\n");
878 file_types |= type.format==vcf ? 1 : 2;
879 if ( file_types==3 )
880 error("\nThe --naive option works only for compressed files of the same type, all BCFs or all VCFs\n");
881 if ( args->explicit_output_type )
882 {
883 if ( output_type.format!=type.format )
884 error("\nThe --naive option works only for the output of the same type, all BCFs or all VCFs\n");
885 if ( output_type.compression!=type.compression )
886 error("\nThe --naive option works only for the output of the same compression type\n");
887 }
888
889 BGZF *fp = hts_get_bgzfp(hts_fp);
890 if ( !fp || bgzf_read_block(fp) != 0 || !fp->block_length )
891 error("\nFailed to read %s: %s\n", args->fnames[i], strerror(errno));
892
893 int nskip;
894 if ( type.format==bcf )
895 {
896 const size_t magic_len = 5 + 4; // "Magic" string + header length
897 uint8_t magic[magic_len];
898 if ( bgzf_read(fp, magic, magic_len) != magic_len ) error("\nFailed to read the BCF header in %s\n", args->fnames[i]);
899 // First five bytes are the "Magic" string
900 if (strncmp((char*)magic, "BCF\2\2", 5) != 0) error("\nInvalid BCF magic string in %s\n", args->fnames[i]);
901 // Next four are the header length (little-endian)
902 tmp.l = le_to_u32(magic + 5);
903 hts_expand(char,tmp.l,tmp.m,tmp.s);
904 if ( bgzf_read(fp, tmp.s, tmp.l) != tmp.l ) error("\nFailed to read the BCF header in %s\n", args->fnames[i]);
905
906 // write only the first header
907 if ( i==0 )
908 {
909 if ( bgzf_write(bgzf_out, magic, magic_len) != magic_len ) error("\nFailed to write %zu bytes to %s\n", magic_len,args->output_fname);
910 if ( bgzf_write(bgzf_out, tmp.s, tmp.l) != tmp.l) error("\nFailed to write %"PRId64" bytes to %s\n", (uint64_t)tmp.l,args->output_fname);
911 }
912 nskip = fp->block_offset;
913 }
914 else
915 {
916 nskip = print_vcf_gz_header(fp, bgzf_out, i==0?1:0, &tmp);
917 if ( nskip==-1 ) error("\nError reading %s\n", args->fnames[i]);
918 }
919
920 // Output all non-header data that were read together with the header block
921 if ( fp->block_length - nskip > 0 )
922 {
923 if ( bgzf_write(bgzf_out, (char *)fp->uncompressed_block+nskip, fp->block_length-nskip)<0 ) error("\nError: %d\n",fp->errcode);
924 }
925 if ( bgzf_flush(bgzf_out)<0 ) error("\nError: %d\n",bgzf_out->errcode);
926
927
928 // Stream the rest of the file as it is, without recompressing, but remove BGZF EOF blocks
929 // The final bgzf eof block will be added by bgzf_close.
930 ssize_t nread, nblock, nwr;
931 const int nheader = 18, neof = 28;
932 const uint8_t *eof = (uint8_t*) "\037\213\010\4\0\0\0\0\0\377\6\0\102\103\2\0\033\0\3\0\0\0\0\0\0\0\0\0";
933 while (1)
934 {
935 nread = bgzf_raw_read(fp, buf, nheader);
936 if ( !nread ) break;
937 if ( nread != nheader || check_header(buf)!=0 ) error("\nCould not parse the header of a bgzf block: %s\n",args->fnames[i]);
938 nblock = unpackInt16(buf+16) + 1;
939 assert( nblock <= page_size && nblock >= nheader );
940 nread += bgzf_raw_read(fp, buf+nheader, nblock - nheader);
941 if ( nread!=nblock ) error("\nCould not read %"PRId64" bytes: %s\n",(uint64_t)nblock,args->fnames[i]);
942 if ( nread==neof && !memcmp(buf,eof,neof) ) continue;
943 nwr = bgzf_raw_write(bgzf_out, buf, nread);
944 if ( nwr != nread ) error("\nWrite failed, wrote %"PRId64" instead of %d bytes.\n", (uint64_t)nwr,(int)nread);
945 }
946 if (hts_close(hts_fp)) error("\nClose failed: %s\n",args->fnames[i]);
947 if ( args->verbose )
948 {
949 gettimeofday(&t1, NULL);
950 double delta = (t1.tv_sec - t0.tv_sec) * 1e6 + (t1.tv_usec - t0.tv_usec);
951 fprintf(bcftools_stderr,"\t%f seconds\n",delta/1e6);
952 }
953 }
954 free(buf);
955 free(tmp.s);
956 if (bgzf_close(bgzf_out) < 0) error("Error: %d\n",bgzf_out->errcode);
957 }
958
959 static void usage(args_t *args)
960 {
961 fprintf(bcftools_stderr, "\n");
962 fprintf(bcftools_stderr, "About: Concatenate or combine VCF/BCF files. All source files must have the same sample\n");
963 fprintf(bcftools_stderr, " columns appearing in the same order. The program can be used, for example, to\n");
964 fprintf(bcftools_stderr, " concatenate chromosome VCFs into one VCF, or combine a SNP VCF and an indel\n");
965 fprintf(bcftools_stderr, " VCF into one. The input files must be sorted by chr and position. The files\n");
966 fprintf(bcftools_stderr, " must be given in the correct order to produce sorted VCF on output unless\n");
967 fprintf(bcftools_stderr, " the -a, --allow-overlaps option is specified. With the --naive option, the files\n");
968 fprintf(bcftools_stderr, " are concatenated without being recompressed, which is very fast.\n");
969 fprintf(bcftools_stderr, "Usage: bcftools concat [options] <A.vcf.gz> [<B.vcf.gz> [...]]\n");
970 fprintf(bcftools_stderr, "\n");
971 fprintf(bcftools_stderr, "Options:\n");
972 fprintf(bcftools_stderr, " -a, --allow-overlaps First coordinate of the next file can precede last record of the current file.\n");
973 fprintf(bcftools_stderr, " -c, --compact-PS Do not output PS tag at each site, only at the start of a new phase set block.\n");
974 fprintf(bcftools_stderr, " -d, --rm-dups STRING Output duplicate records present in multiple files only once: <snps|indels|both|all|exact>\n");
975 fprintf(bcftools_stderr, " -D, --remove-duplicates Alias for -d exact\n");
976 fprintf(bcftools_stderr, " -f, --file-list FILE Read the list of files from a file.\n");
977 fprintf(bcftools_stderr, " -G, --drop-genotypes Drop individual genotype information.\n");
978 fprintf(bcftools_stderr, " -l, --ligate Ligate phased VCFs by matching phase at overlapping haplotypes\n");
979 fprintf(bcftools_stderr, " --ligate-force Ligate even non-overlapping chunks, keep all sites\n");
980 fprintf(bcftools_stderr, " --ligate-warn Drop sites in imperfect overlaps\n");
981 fprintf(bcftools_stderr, " --no-version Do not append version and command line to the header\n");
982 fprintf(bcftools_stderr, " -n, --naive Concatenate files without recompression, a header check compatibility is performed\n");
983 fprintf(bcftools_stderr, " --naive-force Same as --naive, but header compatibility is not checked. Dangerous, use with caution.\n");
984 fprintf(bcftools_stderr, " -o, --output FILE Write output to a file [standard output]\n");
985 fprintf(bcftools_stderr, " -O, --output-type u|b|v|z[0-9] u/b: un/compressed BCF, v/z: un/compressed VCF, 0-9: compression level [v]\n");
986 fprintf(bcftools_stderr, " -q, --min-PQ INT Break phase set if phasing quality is lower than <int> [30]\n");
987 fprintf(bcftools_stderr, " -r, --regions REGION Restrict to comma-separated list of regions\n");
988 fprintf(bcftools_stderr, " -R, --regions-file FILE Restrict to regions listed in a file\n");
989 fprintf(bcftools_stderr, " --regions-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [1]\n");
990 fprintf(bcftools_stderr, " --threads INT Use multithreading with <int> worker threads [0]\n");
991 fprintf(bcftools_stderr, " -v, --verbose 0|1 Set verbosity level [1]\n");
992 fprintf(bcftools_stderr, " -W, --write-index[=FMT] Automatically index the output files [off]\n");
993 fprintf(bcftools_stderr, "\n");
994 bcftools_exit(1);
995 }
996
997 int main_vcfconcat(int argc, char *argv[])
998 {
999 int c;
1000 args_t *args = (args_t*) calloc(1,sizeof(args_t));
1001 args->argc = argc; args->argv = argv;
1002 args->output_fname = "-";
1003 args->output_type = FT_VCF;
1004 args->n_threads = 0;
1005 args->record_cmd_line = 1;
1006 args->min_PQ = 30;
1007 args->verbose = 1;
1008 args->clevel = -1;
1009
1010 static struct option loptions[] =
1011 {
1012 {"verbose",required_argument,NULL,'v'},
1013 {"naive",no_argument,NULL,'n'},
1014 {"naive-force",no_argument,NULL,7},
1015 {"compact-PS",no_argument,NULL,'c'},
1016 {"regions",required_argument,NULL,'r'},
1017 {"regions-file",required_argument,NULL,'R'},
1018 {"regions-overlap",required_argument,NULL,12},
1019 {"remove-duplicates",no_argument,NULL,'D'},
1020 {"rm-dups",required_argument,NULL,'d'},
1021 {"allow-overlaps",no_argument,NULL,'a'},
1022 {"ligate",no_argument,NULL,'l'},
1023 {"ligate-force",no_argument,NULL,10},
1024 {"ligate-warn",no_argument,NULL,11},
1025 {"output",required_argument,NULL,'o'},
1026 {"output-type",required_argument,NULL,'O'},
1027 {"threads",required_argument,NULL,9},
1028 {"file-list",required_argument,NULL,'f'},
1029 {"min-PQ",required_argument,NULL,'q'},
1030 {"no-version",no_argument,NULL,8},
1031 {"write-index",optional_argument,NULL,'W'},
1032 {"drop-genotypes",no_argument,NULL,'G'},
1033 {NULL,0,NULL,0}
1034 };
1035 char *tmp;
1036 while ((c = getopt_long(argc, argv, "h:?o:O:f:alq:Dd:Gr:R:cnv:W::",loptions,NULL)) >= 0)
1037 {
1038 switch (c) {
1039 case 'c': args->compact_PS = 1; break;
1040 case 'r': args->regions_list = optarg; break;
1041 case 'R': args->regions_list = optarg; args->regions_is_file = 1; break;
1042 case 'd': args->remove_dups = optarg; break;
1043 case 'D': args->remove_dups = "exact"; break;
1044 case 'q':
1045 args->min_PQ = strtol(optarg,&tmp,10);
1046 if ( *tmp ) error("Could not parse argument: --min-PQ %s\n", optarg);
1047 break;
1048 case 'n': args->naive_concat = 1; break;
1049 case 'a': args->allow_overlaps = 1; break;
1050 case 'l': args->phased_concat = 1; break;
1051 case 'f': args->file_list = optarg; break;
1052 case 'G': args->sites_only = 1; break;
1053 case 'o': args->output_fname = optarg; break;
1054 case 'O':
1055 args->explicit_output_type = 1;
1056 switch (optarg[0]) {
1057 case 'b': args->output_type = FT_BCF_GZ; break;
1058 case 'u': args->output_type = FT_BCF; break;
1059 case 'z': args->output_type = FT_VCF_GZ; break;
1060 case 'v': args->output_type = FT_VCF; break;
1061 default:
1062 {
1063 args->clevel = strtol(optarg,&tmp,10);
1064 if ( *tmp || args->clevel<0 || args->clevel>9 ) error("The output type \"%s\" not recognised\n", optarg);
1065 }
1066 };
1067 if ( optarg[1] )
1068 {
1069 args->clevel = strtol(optarg+1,&tmp,10);
1070 if ( *tmp || args->clevel<0 || args->clevel>9 ) error("Could not parse argument: --compression-level %s\n", optarg+1);
1071 }
1072 break;
1073 case 10 : args->ligate_force = 1; break;
1074 case 11 : args->ligate_warn = 1; break;
1075 case 9 : args->n_threads = strtol(optarg, 0, 0); break;
1076 case 8 : args->record_cmd_line = 0; break;
1077 case 7 : args->naive_concat = 1; args->naive_concat_trust_headers = 1; break;
1078 case 12 :
1079 args->regions_overlap = parse_overlap_option(optarg);
1080 if ( args->regions_overlap < 0 ) error("Could not parse: --regions-overlap %s\n",optarg);
1081 break;
1082 case 'v':
1083 args->verbose = strtol(optarg, &tmp, 0);
1084 if ( *tmp || args->verbose<0 || args->verbose>1 ) error("Error: currently only --verbose 0 or --verbose 1 is supported\n");
1085 break;
1086 case 'W':
1087 if (!(args->write_index = write_index_parse(optarg)))
1088 error("Unsupported index format '%s'\n", optarg);
1089 break;
1090 case 'h':
1091 case '?': usage(args); break;
1092 default: error("Unknown argument: %s\n", optarg);
1093 }
1094 }
1095 while ( optind<argc )
1096 {
1097 args->nfnames++;
1098 args->fnames = (char **)realloc(args->fnames,sizeof(char*)*args->nfnames);
1099 args->fnames[args->nfnames-1] = strdup(argv[optind]);
1100 optind++;
1101 }
1102 if ( args->ligate_force && args->ligate_warn ) error("The options cannot be combined: --ligate-force and --ligate-warn\n");
1103 if ( args->allow_overlaps && args->phased_concat ) error("The options -a and -l should not be combined. Please run with -l only.\n");
1104 if ( args->sites_only && args->phased_concat ) error("The options --drop-genotypes and --ligate cannot be combined\n");
1105 if ( args->compact_PS && !args->phased_concat ) error("The -c option is intended only with -l\n");
1106 if ( args->file_list )
1107 {
1108 if ( args->nfnames ) error("Cannot combine -l with file names on command line.\n");
1109 args->fnames = hts_readlines(args->file_list, &args->nfnames);
1110 if ( !args->fnames ) error("Could not read the file: %s\n", args->file_list);
1111 }
1112 if ( !args->nfnames ) usage(args);
1113 if ( args->remove_dups && !args->allow_overlaps ) error("The -D option is supported only with -a\n");
1114 if ( args->regions_list && !args->allow_overlaps ) error("The -r/-R option is supported only with -a\n");
1115 if ( args->naive_concat )
1116 {
1117 if ( args->write_index ) error("Error: cannot --write-index in the %s mode\n",args->naive_concat_trust_headers?"--naive-force":"--naive");
1118 if ( args->allow_overlaps ) error("The option --naive cannot be combined with --allow-overlaps\n");
1119 if ( args->phased_concat ) error("The option --naive cannot be combined with --ligate\n");
1120 if ( args->sites_only ) error("The option --naive cannot be combined with --drop-genotypes\n");
1121 naive_concat(args);
1122 destroy_data(args);
1123 free(args);
1124 return 0;
1125 }
1126 init_data(args);
1127 concat(args);
1128 destroy_data(args);
1129 free(args);
1130 return 0;
1131 }