Debian Codegraph @

bcftools/reheader.c.pysam.c

raw symbols SCIP
1 #include "bcftools.pysam.h"
2
3 /* reheader.c -- reheader subcommand.
4
5 Copyright (C) 2014-2022,2024 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 <ctype.h>
31 #include <string.h>
32 #include <errno.h>
33 #include <sys/stat.h>
34 #include <sys/types.h>
35 #include <inttypes.h>
36 #include <fcntl.h>
37 #include <math.h>
38 #ifdef _WIN32
39 #include <windows.h>
40 #endif
41 #include <htslib/vcf.h>
42 #include <htslib/bgzf.h>
43 #include <htslib/tbx.h> // for hts_get_bgzfp()
44 #include <htslib/kseq.h>
45 #include <htslib/thread_pool.h>
46 #include <htslib/faidx.h>
47 #include <htslib/khash_str2int.h>
48 #include "bcftools.h"
49 #include "khash_str2str.h"
50
51 typedef struct _args_t
52 {
53 char **argv, *fname, *samples_fname, *header_fname, *output_fname;
54 char *fai_fname;
55 htsFile *fp;
56 faidx_t *fai;
57 htsFormat type;
58 htsThreadPool *threads;
59 int argc, n_threads;
60 }
61 args_t;
62
63 static inline int is_escaped(const char *min, const char *str)
64 {
65 int n = 0;
66 while ( --str>=min && *str=='\\' ) n++;
67 return n%2;
68 }
69 static char *copy_and_update_contig_line(faidx_t *fai, char *line, void *chr_seen, kstring_t *dst)
70 {
71 kstring_t key = {0,0,0}, val = {0,0,0}, tmp = {0,0,0};
72 char *chr_name = NULL, *p, *q = line + 9; // skip ##contig=
73 char *end = q;
74 int nopen = 1;
75 hts_pos_t chr_len = 0;
76 while ( *end && *end!='\n' ) end++;
77 while ( *q && *q!='\n' && nopen>0 )
78 {
79 p = ++q;
80 while ( *q && (*q==' ' || *q=='\t') ) { p++; q++; }
81 // ^[A-Za-z_][0-9A-Za-z_.]*$
82 if (p==q && *q && (isalpha(*q) || *q=='_'))
83 {
84 q++;
85 while ( *q && (isalnum(*q) || *q=='_' || *q=='.') ) q++;
86 }
87 int n = q-p;
88 int m = 0;
89 while ( *q && (*q==' ' || *q=='\t') ) { q++; m++; }
90 if ( *q!='=' || !n )
91 {
92 char *x = q;
93 while ( *x && *x!='\n' ) x++;
94 *x = '\0';
95 error("Could not parse the line: %s [%s][%s]\n", line,p,q);
96 }
97 key.l = 0;
98 kputsn(p,q-p-m,&key);
99 p = ++q;
100 while ( *q && (*q==' ' || *q=='\t') ) { p++; q++; }
101 int quoted = *p=='"' ? 1 : 0;
102 if ( quoted ) p++, q++;
103 while ( *q && *q != '\n' )
104 {
105 if ( quoted ) { if ( *q=='"' && !is_escaped(p,q) ) break; }
106 else
107 {
108 if ( *q=='<' ) nopen++;
109 if ( *q=='>' ) nopen--;
110 if ( !nopen ) break;
111 if ( *q==',' && nopen==1 ) break;
112 }
113 q++;
114 }
115 char *r = q;
116 while ( r > p && r[-1] == ' ' ) r--;
117 val.l = 0;
118 kputsn(p,r-p,&val);
119 if ( quoted && *q=='"' ) q++;
120 if ( *q=='>' ) { nopen--; q++; }
121 if ( !strcmp("length",key.s) ) continue;
122 if ( !strcmp("ID",key.s) )
123 {
124 if ( khash_str2int_has_key(chr_seen,val.s) ) continue;
125 chr_len = faidx_seq_len64(fai, val.s);
126 if ( chr_len==-1 )
127 {
128 free(val.s); free(key.s); free(tmp.s);
129 return end; // the sequence is not in fai, remove
130 }
131 chr_name = strdup(val.s);
132 khash_str2int_inc(chr_seen, chr_name);
133 continue;
134 }
135 kputc(',',&tmp);
136 kputs(key.s,&tmp);
137 kputc('=',&tmp);
138 if ( quoted ) kputc('"',&tmp);
139 kputs(val.s,&tmp);
140 if ( quoted ) kputc('"',&tmp);
141 }
142 if ( !chr_name ) return end;
143 ksprintf(dst,"##contig=<ID=%s,length=%"PRIhts_pos"%s>",chr_name,chr_len,tmp.l ? tmp.s : "");
144 free(key.s); free(val.s); free(tmp.s);
145 return q;
146 }
147 char *init_tmp_prefix(const char *tmp_prefix)
148 {
149 kstring_t prefix = {0,0,0};
150 if ( tmp_prefix )
151 {
152 ksprintf(&prefix,"%sXXXXXX",tmp_prefix);
153 return prefix.s;
154 }
155
156 char *tmpdir = getenv("TMPDIR");
157 if ( tmpdir )
158 kputs(tmpdir, &prefix);
159 else
160 {
161 #ifdef _WIN32
162 char tmp_path[MAX_PATH];
163 int ret = GetTempPath(MAX_PATH, tmp_path);
164 if (!ret || ret > MAX_PATH)
165 error("Could not get the path to the temporary folder\n");
166 kputs(tmp_path, &prefix);
167 #else
168 kputs("/tmp", &prefix);
169 #endif
170 }
171 kputs("/bcftools.XXXXXX", &prefix);
172 return prefix.s;
173 }
174 static void update_from_fai(faidx_t *fai, kstring_t *hdr_txt)
175 {
176 kstring_t hdr_txt_new = {0,0,0};
177
178 // update the existing contig lines and remove lines not present in the fai file
179 void *chr_seen = khash_str2int_init();
180 char *tmp, *beg = hdr_txt->s;
181 while ( beg && *beg )
182 {
183 tmp = strstr(beg, "\n##contig=<");
184 if ( !tmp ) break;
185 kputsn(beg, tmp-beg+1, &hdr_txt_new);
186 size_t l_prev = hdr_txt_new.l;
187 beg = copy_and_update_contig_line(fai,tmp+1,chr_seen, &hdr_txt_new);
188 if ( l_prev==hdr_txt_new.l ) hdr_txt_new.l--; // nothing was added, remove the newline
189 }
190 if ( !beg || !(tmp=strstr(beg,"\n#CHROM")) ) error("Failed to parse the header, #CHROM not found\n");
191 kputsn(beg, tmp-beg+1, &hdr_txt_new);
192
193 // add any new contig lines
194 int i, n = faidx_nseq(fai);
195 for (i=0; i<n; i++)
196 {
197 if ( khash_str2int_has_key(chr_seen,faidx_iseq(fai,i)) ) continue;
198 ksprintf(&hdr_txt_new,"##contig=<ID=%s,length=%"PRIhts_pos">\n",faidx_iseq(fai,i),faidx_seq_len64(fai,faidx_iseq(fai,i)));
199 }
200 kputs(tmp+1,&hdr_txt_new);
201
202 // Switch the new header content for the old
203 free(hdr_txt->s);
204 memcpy(hdr_txt, &hdr_txt_new, sizeof(*hdr_txt));
205
206 khash_str2int_destroy_free(chr_seen);
207 }
208
209 static void read_header_file(char *fname, kstring_t *hdr)
210 {
211 kstring_t tmp = {0,0,0};
212 hdr->l = 0;
213
214 htsFile *fp = hts_open(fname, "r");
215 if ( !fp ) error("Could not read: %s\n", fname);
216 while ( hts_getline(fp, KS_SEP_LINE, &tmp) > 0 )
217 {
218 kputsn(tmp.s,tmp.l,hdr);
219 kputc('\n',hdr);
220 }
221 if ( hts_close(fp) ) error("Close failed: %s\n", fname);
222 free(tmp.s);
223
224 while ( hdr->l>0 && isspace(hdr->s[hdr->l-1]) ) hdr->l--; // remove trailing newlines
225 kputc('\n',hdr);
226 }
227
228 static int set_sample_pairs(char **samples, int nsamples, kstring_t *hdr, int idx)
229 {
230 int i, j, n;
231 kstring_t key = {0,0,0};
232 kstring_t val = {0,0,0};
233
234 // Are these samples "old-name new-name" pairs?
235 void *hash = khash_str2str_init();
236 for (i=0; i<nsamples; i++)
237 {
238 char *ptr = samples[i];
239 key.l = val.l = 0;
240 int escaped = 0;
241 while ( *ptr )
242 {
243 if ( *ptr=='\\' && !escaped ) { escaped = 1; ptr++; continue; }
244 if ( isspace(*ptr) && !escaped ) break;
245 kputc(*ptr, &key);
246 escaped = 0;
247 ptr++;
248 }
249 if ( !*ptr ) break;
250 while ( *ptr && isspace(*ptr) ) ptr++;
251 while ( *ptr )
252 {
253 if ( *ptr=='\\' && !escaped ) { escaped = 1; ptr++; continue; }
254 if ( isspace(*ptr) && !escaped ) break;
255 kputc(*ptr, &val);
256 escaped = 0;
257 ptr++;
258 }
259 khash_str2str_set(hash,strdup(key.s),strdup(val.s));
260 }
261 free(key.s);
262 free(val.s);
263 if ( i!=nsamples ) // not "old-name new-name" pairs
264 {
265 khash_str2str_destroy_free_all(hash);
266 return 0;
267 }
268
269 while ( hdr->l>0 && isspace(hdr->s[hdr->l-1]) ) hdr->l--; // remove trailing newlines
270 hdr->s[hdr->l] = 0;
271
272 kstring_t tmp = {0,0,0};
273 i = j = n = 0; // i:traverse the #CHROM line 1 by 1; j:points to the last column
274 while ( hdr->s[idx+i] )
275 {
276 if ( hdr->s[idx+i]=='\t' )
277 {
278 hdr->s[idx+i] = 0;
279
280 if ( ++n>9 )
281 {
282 char *new_name = khash_str2str_get(hash,hdr->s+idx+j);
283 kputs(new_name ? new_name : hdr->s+idx+j, &tmp);
284 }
285 else
286 kputs(hdr->s+idx+j, &tmp);
287
288 kputc('\t',&tmp);
289
290 j = ++i;
291 continue;
292 }
293 i++;
294 }
295 char *new_name = khash_str2str_get(hash,hdr->s+idx+j);
296 kputs(new_name ? new_name : hdr->s+idx+j, &tmp);
297
298 khash_str2str_destroy_free_all(hash);
299
300 hdr->l = idx;
301 kputs(tmp.s, hdr);
302 kputc('\n', hdr);
303 free(tmp.s);
304
305 return 1;
306 }
307
308 static void set_samples(char **samples, int nsamples, kstring_t *hdr)
309 {
310 // Find the beginning of the #CHROM line
311 int i = hdr->l - 2, ncols = 0;
312 while ( i>=0 && hdr->s[i]!='\n' )
313 {
314 if ( hdr->s[i]=='\t' ) ncols++;
315 i--;
316 }
317 if ( i<0 || strncmp(hdr->s+i+1,"#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT",45) )
318 {
319 if ( i>0 && !strncmp(hdr->s+i+1,"#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO",38) )
320 error("Error: missing FORMAT fields, cowardly refusing to add samples\n");
321
322 error("Could not parse the header: %s\n", hdr->s);
323 }
324
325 // Are the samples "old-sample new-sample" pairs?
326 if ( set_sample_pairs(samples,nsamples,hdr, i+1) ) return;
327
328 // Replace all samples
329 if ( ncols!=nsamples+8 )
330 fprintf(bcftools_stderr, "Warning: different number of samples: %d vs %d\n", nsamples,ncols-8);
331
332 ncols = 0;
333 while ( ncols!=9 )
334 {
335 i++;
336 if ( hdr->s[i]=='\t' ) ncols++;
337 }
338 hdr->l = i;
339
340 for (i=0; i<nsamples; i++)
341 {
342 kputc('\t', hdr);
343 kputs(samples[i], hdr);
344 }
345 kputc('\n', hdr);
346 }
347
348 BGZF *hts_get_bgzfp(htsFile *fp);
349 static void reheader_vcf_gz(args_t *args)
350 {
351 BGZF *fp = hts_get_bgzfp(args->fp);
352 if ( !fp || bgzf_read_block(fp) != 0 || !fp->block_length )
353 error("Failed to read %s: %s\n", args->fname, strerror(errno));
354
355 kstring_t hdr = {0,0,0};
356 char *buffer = (char*) fp->uncompressed_block;
357
358 // Read the header and find the position of the data block
359 if ( buffer[0]!='#' ) error("Could not parse the header, expected '#', found '%c'\n", buffer[0]);
360
361 int skip_until = 1; // end of the header in the current uncompressed block
362 while (1)
363 {
364 if ( buffer[skip_until]=='\n' )
365 {
366 skip_until++;
367 if ( skip_until>=fp->block_length )
368 {
369 kputsn(buffer,skip_until,&hdr);
370 if ( bgzf_read_block(fp) != 0 ) error("Error reading %s\n", args->fname);
371 if ( !fp->block_length ) break;
372 skip_until = 0;
373 }
374 // The header has finished
375 if ( buffer[skip_until]!='#' )
376 {
377 kputsn(buffer,skip_until,&hdr);
378 break;
379 }
380 }
381 skip_until++;
382 if ( skip_until>=fp->block_length )
383 {
384 kputsn(buffer,fp->block_length,&hdr);
385 if ( bgzf_read_block(fp) != 0 ) error("Error reading %s\n", args->fname);
386 if ( !fp->block_length ) break;
387 skip_until = 0;
388 }
389 }
390
391 int nsamples = 0;
392 char **samples = NULL;
393 if ( args->samples_fname )
394 {
395 samples = hts_readlines(args->samples_fname, &nsamples);
396 if ( !samples || !nsamples ) error("Error reading the --samples file \"%s\"\n", args->samples_fname);
397 }
398 if ( args->header_fname )
399 {
400 free(hdr.s); hdr.s = NULL; hdr.l = hdr.m = 0;
401 read_header_file(args->header_fname, &hdr);
402 }
403
404 if ( args->fai )
405 update_from_fai(args->fai, &hdr);
406
407 if ( samples )
408 {
409 set_samples(samples, nsamples, &hdr);
410 int i;
411 for (i=0; i<nsamples; i++) free(samples[i]);
412 free(samples);
413 }
414
415 // Output the modified header
416 BGZF *bgzf_out = bgzf_open(args->output_fname ? args->output_fname : "-","w");;
417 if ( bgzf_write(bgzf_out, hdr.s, hdr.l) < 0 ) error("Can't write BGZF header (code %d)\n", bgzf_out->errcode);
418 free(hdr.s);
419
420 // Output all remaining data read with the header block
421 if ( fp->block_length - skip_until > 0 )
422 {
423 if ( bgzf_write(bgzf_out, buffer+skip_until, fp->block_length-skip_until)<0 ) error("Error: %d\n",fp->errcode);
424 }
425 if ( bgzf_flush(bgzf_out)<0 ) error("Error: %d\n",bgzf_out->errcode);
426
427 // Stream the rest of the file without as it is, without decompressing
428 ssize_t nread;
429 const size_t page_size = 32768;
430 char *buf = (char*) malloc(page_size);
431 while (1)
432 {
433 nread = bgzf_raw_read(fp, buf, page_size);
434 if ( nread<=0 ) break;
435
436 int count = bgzf_raw_write(bgzf_out, buf, nread);
437 if (count != nread) error("Write failed, wrote %d instead of %d bytes.\n", count,(int)nread);
438 }
439 if (bgzf_close(bgzf_out) < 0) error("Error closing %s: %d\n",args->output_fname ? args->output_fname : "-",bgzf_out->errcode);
440 if (hts_close(args->fp)) error("Error closing %s: %d\n",args->fname,fp->errcode);
441 free(buf);
442 }
443 static void reheader_vcf(args_t *args)
444 {
445 kstring_t hdr = {0,0,0};
446 htsFile *fp = args->fp;
447 while ( hts_getline(fp, KS_SEP_LINE, &fp->line) >=0 )
448 {
449 kputc('\n',&fp->line); // hts_getline eats the newline character
450 if ( fp->line.s[0]!='#' ) break;
451 kputsn(fp->line.s,fp->line.l,&hdr);
452 }
453
454 int nsamples = 0;
455 char **samples = NULL;
456 if ( args->samples_fname )
457 {
458 samples = hts_readlines(args->samples_fname, &nsamples);
459 if ( !samples || !nsamples ) error("Error reading the --samples file \"%s\"\n", args->samples_fname);
460 }
461 if ( args->header_fname )
462 {
463 free(hdr.s); hdr.s = NULL; hdr.l = hdr.m = 0;
464 read_header_file(args->header_fname, &hdr);
465 }
466
467 if ( args->fai )
468 update_from_fai(args->fai, &hdr);
469
470 if ( samples )
471 {
472 set_samples(samples, nsamples, &hdr);
473 int i;
474 for (i=0; i<nsamples; i++) free(samples[i]);
475 free(samples);
476 }
477
478 int out = args->output_fname ? open(args->output_fname, O_WRONLY|O_CREAT|O_TRUNC, 0666) : STDOUT_FILENO;
479 if ( out==-1 ) error("%s: %s\n", args->output_fname,strerror(errno));
480 if ( write(out, hdr.s, hdr.l)!=hdr.l ) error("Failed to write %"PRIu64" bytes\n", (uint64_t)hdr.l);
481 free(hdr.s);
482 if ( fp->line.l )
483 {
484 if ( write(out, fp->line.s, fp->line.l)!=fp->line.l ) error("Failed to write %"PRIu64" bytes\n", (uint64_t)fp->line.l);
485 }
486 while ( hts_getline(fp, KS_SEP_LINE, &fp->line) >=0 ) // uncompressed file implies small size, we don't worry about speed
487 {
488 kputc('\n',&fp->line);
489 if ( write(out, fp->line.s, fp->line.l)!=fp->line.l ) error("Failed to write %"PRIu64" bytes\n", (uint64_t)fp->line.l);
490 }
491 if ( hts_close(fp)!=0 ) error("[%s] Error: close failed .. %s\n", __func__,args->fname);
492 if ( close(out)!=0 ) error("[%s] Error: close failed .. %s\n", __func__,args->output_fname);
493 }
494
495 static bcf_hdr_t *strip_header(bcf_hdr_t *src, bcf_hdr_t *dst)
496 {
497 bcf_hrec_t *src_hrec, *dst_hrec, *tmp;
498 bcf_hdr_t *out = bcf_hdr_init("r");
499 int i;
500 for (i=0; i<dst->nhrec; i++)
501 {
502 // first insert lines which do not code BCF ids, their order does not matter
503 dst_hrec = dst->hrec[i];
504 if ( dst_hrec->type==BCF_HL_FLT || dst_hrec->type==BCF_HL_INFO || dst_hrec->type==BCF_HL_FMT || dst_hrec->type== BCF_HL_CTG ) continue;
505 bcf_hdr_add_hrec(out, bcf_hrec_dup(dst_hrec));
506 }
507 for (i=0; i<src->nhrec; i++)
508 {
509 // now transfer header lines which define BCF ids
510 src_hrec = src->hrec[i];
511
512 if ( src_hrec->type==BCF_HL_FLT || src_hrec->type==BCF_HL_INFO || src_hrec->type==BCF_HL_FMT || src_hrec->type== BCF_HL_CTG )
513 {
514 int j = bcf_hrec_find_key(src_hrec, "ID");
515 dst_hrec = bcf_hdr_get_hrec(dst, src_hrec->type, "ID", src_hrec->vals[j], NULL);
516 if ( !dst_hrec ) continue;
517
518 tmp = bcf_hrec_dup(dst_hrec);
519
520 j = bcf_hrec_find_key(src_hrec, "IDX");
521 if ( j>=0 )
522 {
523 j = atoi(src_hrec->vals[j]);
524 if (hrec_add_idx(tmp, j) < 0)
525 error_errno("[%s] Failed to add IDX header", __func__);
526 }
527 bcf_hdr_add_hrec(out, tmp);
528 }
529 }
530 if (bcf_hdr_sync(out) < 0)
531 error_errno("[%s] Failed to update header", __func__);
532 for (i=0; i<dst->nhrec; i++)
533 {
534 // finally add new structured fields
535 dst_hrec = dst->hrec[i];
536 if ( dst_hrec->type==BCF_HL_FLT || dst_hrec->type==BCF_HL_INFO || dst_hrec->type==BCF_HL_FMT || dst_hrec->type== BCF_HL_CTG )
537 {
538 int j = bcf_hrec_find_key(dst_hrec, "ID");
539 tmp = bcf_hdr_get_hrec(out, dst_hrec->type, "ID", dst_hrec->vals[j], NULL);
540 if ( !tmp )
541 bcf_hdr_add_hrec(out, bcf_hrec_dup(dst_hrec));
542 }
543 }
544 for (i=0; i<dst->n[BCF_DT_SAMPLE]; i++) bcf_hdr_add_sample(out, dst->samples[i]);
545 bcf_hdr_destroy(dst);
546 return out;
547 }
548
549 static void reheader_bcf(args_t *args, int is_compressed)
550 {
551 htsFile *fp = args->fp;
552
553 if ( args->n_threads > 0 )
554 {
555 args->threads = (htsThreadPool *) calloc(1, sizeof(htsThreadPool));
556 if ( !args->threads ) error("Could not allocate memory\n");
557 if ( !(args->threads->pool = hts_tpool_init(args->n_threads)) ) error("Could not initialize threading\n");
558 hts_set_thread_pool(fp, args->threads);
559 }
560
561 bcf_hdr_t *hdr = bcf_hdr_read(fp); if ( !hdr ) error("Failed to read the header: %s\n", args->fname);
562 kstring_t htxt = {0,0,0};
563 bcf_hdr_format(hdr, 1, &htxt);
564
565 int i, nsamples = 0;
566 char **samples = NULL;
567 if ( args->samples_fname )
568 {
569 samples = hts_readlines(args->samples_fname, &nsamples);
570 if ( !samples || !nsamples ) error("Error reading the --samples file \"%s\"\n", args->samples_fname);
571 }
572 if ( args->header_fname )
573 {
574 free(htxt.s); htxt.s = NULL; htxt.l = htxt.m = 0;
575 read_header_file(args->header_fname, &htxt);
576 }
577
578 if ( args->fai )
579 update_from_fai(args->fai, &htxt);
580
581 if ( samples )
582 {
583 set_samples(samples, nsamples, &htxt);
584 for (i=0; i<nsamples; i++) free(samples[i]);
585 free(samples);
586 }
587
588 bcf_hdr_t *hdr_out = bcf_hdr_init("r");
589 if ( bcf_hdr_parse(hdr_out, htxt.s) < 0 ) error("An error occurred while parsing the header\n");
590 if ( args->header_fname ) hdr_out = strip_header(hdr, hdr_out);
591
592 // write the header and the body
593 htsFile *fp_out = hts_open(args->output_fname ? args->output_fname : "-",is_compressed ? "wb" : "wbu");
594 if ( !fp_out ) error("%s: %s\n", args->output_fname ? args->output_fname : "-", strerror(errno));
595 if ( args->threads )
596 hts_set_thread_pool(fp_out, args->threads);
597 if ( bcf_hdr_write(fp_out, hdr_out)!=0 ) error("[%s] Error: cannot write the header to %s\n", __func__,args->output_fname ? args->output_fname : "standard output");
598
599 bcf1_t *rec = bcf_init();
600 while ( bcf_read(fp, hdr, rec)==0 )
601 {
602 // sanity checking, this slows things down. Make it optional?
603 bcf_unpack(rec, BCF_UN_ALL);
604 if ( rec->rid >= hdr_out->n[BCF_DT_CTG] || strcmp(bcf_hdr_int2id(hdr,BCF_DT_CTG,rec->rid),bcf_hdr_int2id(hdr_out,BCF_DT_CTG,rec->rid)) )
605 error("The CHROM is not defined: \"%s\"\n", bcf_hdr_int2id(hdr,BCF_DT_CTG,rec->rid));
606
607 for (i=0; i<rec->d.n_flt; i++)
608 {
609 int id = rec->d.flt[i];
610 if ( id >= hdr_out->n[BCF_DT_ID] ) break;
611 if ( !bcf_hdr_idinfo_exists(hdr_out,BCF_HL_FLT,id) ) break;
612 if ( strcmp(hdr->id[BCF_DT_ID][id].key,hdr_out->id[BCF_DT_ID][id].key) )
613 error("FIXME: Broken FILTER ids: %s vs %s\n", hdr->id[BCF_DT_ID][id].key,hdr_out->id[BCF_DT_ID][id].key);
614 }
615 if ( i!=rec->d.n_flt )
616 error("The FILTER is not defined: \"%s\"\n", bcf_hdr_int2id(hdr,BCF_DT_ID,rec->d.flt[i]));
617
618 for (i=0; i<rec->n_info; i++)
619 {
620 int id = rec->d.info[i].key;
621 if ( id >= hdr_out->n[BCF_DT_ID] ) break;
622 if ( !hdr_out->id[BCF_DT_ID][id].key ) break;
623 if ( !bcf_hdr_idinfo_exists(hdr_out,BCF_HL_INFO,id) ) break;
624 if ( strcmp(hdr->id[BCF_DT_ID][id].key,hdr_out->id[BCF_DT_ID][id].key) )
625 error("FIXME: Broken INFO ids: %s vs %s\n", hdr->id[BCF_DT_ID][id].key,hdr_out->id[BCF_DT_ID][id].key);
626 }
627 if ( i!=rec->n_info )
628 error("The INFO tag is not defined: \"%s\"\n", bcf_hdr_int2id(hdr,BCF_DT_ID,rec->d.info[i].key));
629
630 for (i=0; i<rec->n_fmt; i++)
631 {
632 int id = rec->d.fmt[i].id;
633 if ( id >= hdr_out->n[BCF_DT_ID] ) break;
634 if ( !hdr_out->id[BCF_DT_ID][id].key ) break;
635 if ( !bcf_hdr_idinfo_exists(hdr_out,BCF_HL_FMT,id) ) break;
636 if ( strcmp(hdr->id[BCF_DT_ID][id].key,hdr_out->id[BCF_DT_ID][id].key) )
637 error("FIXME: Broken FORMAT ids: %s vs %s\n", hdr->id[BCF_DT_ID][id].key,hdr_out->id[BCF_DT_ID][id].key);
638 }
639 if ( i!=rec->n_fmt )
640 error("The FORMAT tag is not defined: \"%s\"\n", bcf_hdr_int2id(hdr,BCF_DT_ID,rec->d.fmt[i].id));
641
642 if ( bcf_write(fp_out,hdr_out,rec)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->output_fname ? args->output_fname : "standard output");
643 }
644 bcf_destroy(rec);
645
646 free(htxt.s);
647 if ( hts_close(fp_out)!=0 ) error("[%s] Error: failed to close the file %s\n",__func__,args->output_fname ? args->output_fname : "standard output");
648 if ( hts_close(fp)!=0 ) error("[%s] Error: close failed .. %s\n", __func__,args->fname);
649 bcf_hdr_destroy(hdr_out);
650 bcf_hdr_destroy(hdr);
651 if ( args->threads )
652 {
653 hts_tpool_destroy(args->threads->pool);
654 free(args->threads);
655 }
656 }
657
658
659 static void usage(args_t *args)
660 {
661 fprintf(bcftools_stderr, "\n");
662 fprintf(bcftools_stderr, "About: Modify header of VCF/BCF files, change sample names.\n");
663 fprintf(bcftools_stderr, "Usage: bcftools reheader [OPTIONS] <in.vcf.gz>\n");
664 fprintf(bcftools_stderr, "\n");
665 fprintf(bcftools_stderr, "Options:\n");
666 fprintf(bcftools_stderr, " -f, --fai FILE update sequences and their lengths from the .fai file\n");
667 fprintf(bcftools_stderr, " -h, --header FILE new header\n");
668 fprintf(bcftools_stderr, " -o, --output FILE write output to a file [standard output]\n");
669 fprintf(bcftools_stderr, " -s, --samples FILE new sample names\n");
670 fprintf(bcftools_stderr, " -T, --temp-prefix PATH ignored; was template for temporary file name\n");
671 fprintf(bcftools_stderr, " --threads INT use multithreading with <int> worker threads (BCF only) [0]\n");
672 fprintf(bcftools_stderr, "\n");
673 fprintf(bcftools_stderr, "Example:\n");
674 fprintf(bcftools_stderr, " # Write out the header to be modified\n");
675 fprintf(bcftools_stderr, " bcftools view -h old.bcf > header.txt\n");
676 fprintf(bcftools_stderr, "\n");
677 fprintf(bcftools_stderr, " # Edit the header using your favorite text editor\n");
678 fprintf(bcftools_stderr, " vi header.txt\n");
679 fprintf(bcftools_stderr, "\n");
680 fprintf(bcftools_stderr, " # Reheader the file\n");
681 fprintf(bcftools_stderr, " bcftools reheader -h header.txt -o new.bcf old.bcf\n");
682 fprintf(bcftools_stderr, "\n");
683 bcftools_exit(1);
684 }
685
686 int main_reheader(int argc, char *argv[])
687 {
688 int c;
689 args_t *args = (args_t*) calloc(1,sizeof(args_t));
690 args->argc = argc; args->argv = argv;
691
692 static struct option loptions[] =
693 {
694 {"temp-prefix",1,0,'T'},
695 {"fai",1,0,'f'},
696 {"output",1,0,'o'},
697 {"header",1,0,'h'},
698 {"samples",1,0,'s'},
699 {"threads",1,NULL,1},
700 {0,0,0,0}
701 };
702 while ((c = getopt_long(argc, argv, "s:h:o:f:T:",loptions,NULL)) >= 0)
703 {
704 switch (c)
705 {
706 case 1 : args->n_threads = strtol(optarg, 0, 0); break;
707 case 'T': break; // unused - was temp file prefix
708 case 'f': args->fai_fname = optarg; break;
709 case 'o': args->output_fname = optarg; break;
710 case 's': args->samples_fname = optarg; break;
711 case 'h': args->header_fname = optarg; break;
712 case '?': usage(args); break;
713 default: error("Unknown argument: %s\n", optarg);
714 }
715 }
716
717 if ( optind>=argc )
718 {
719 if ( !isatty(fileno((FILE *)stdin)) ) args->fname = "-"; // reading from stdin
720 else usage(args);
721 }
722 else args->fname = argv[optind];
723
724 if ( args->fai_fname ) {
725 args->fai = fai_load3(args->fai_fname,args->fai_fname,NULL,FAI_FASTA);
726 if ( !args->fai ) error("Could not parse %s\n", args->fai_fname);
727 }
728 if ( !args->samples_fname && !args->header_fname && !args->fai) usage(args);
729 if ( !args->fname ) usage(args);
730
731 args->fp = hts_open(args->fname,"r");
732 if ( !args->fp ) error("Failed to read from %s\n", !strcmp("-",args->fname)?"standard input":args->fname);
733 args->type = *hts_get_format(args->fp);
734
735 if ( args->type.format==vcf )
736 {
737 if ( args->type.compression==bgzf )
738 reheader_vcf_gz(args);
739 else if ( args->type.compression==no_compression )
740 reheader_vcf(args);
741 else if ( args->type.compression==gzip )
742 error("Error: cannot reheader gzip-compressed files, first convert with `bcftools view --output-type` to a supported format\n");
743 else
744 error("Error: the compression type of \"%s\" is not recognised/supported\n", args->fname);
745 }
746 else
747 reheader_bcf(args, args->type.compression==bgzf || args->type.compression==gzip);
748
749 if (args->fai)
750 fai_destroy(args->fai);
751 free(args);
752 return 0;
753 }