Debian Codegraph @

bcftools/vcfroh.c

raw symbols SCIP
1 /* vcfroh.c -- HMM model for detecting runs of autozygosity.
2
3 Copyright (C) 2013-2022 Genome Research Ltd.
4
5 Author: Petr Danecek <[email protected]>
6
7 Permission is hereby granted, free of charge, to any person obtaining a copy
8 of this software and associated documentation files (the "Software"), to deal
9 in the Software without restriction, including without limitation the rights
10 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 copies of the Software, and to permit persons to whom the Software is
12 furnished to do so, subject to the following conditions:
13
14 The above copyright notice and this permission notice shall be included in
15 all copies or substantial portions of the Software.
16
17 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 THE SOFTWARE. */
24
25 #include <stdio.h>
26 #include <unistd.h>
27 #include <getopt.h>
28 #include <math.h>
29 #include <inttypes.h>
30 #include <htslib/vcf.h>
31 #include <htslib/synced_bcf_reader.h>
32 #include <htslib/kstring.h>
33 #include <htslib/kseq.h>
34 #include <htslib/bgzf.h>
35 #include <errno.h>
36 #include "bcftools.h"
37 #include "HMM.h"
38 #include "smpl_ilist.h"
39 #include "filter.h"
40
41 #define STATE_HW 0 // normal state, follows Hardy-Weinberg allele frequencies
42 #define STATE_AZ 1 // autozygous state
43
44 #define OUTPUT_ST (1<<1)
45 #define OUTPUT_RG (1<<2)
46 #define OUTPUT_GZ (1<<3)
47
48 // Logic of the filters: include or exclude sites which match the filters?
49 #define FLT_INCLUDE 1
50 #define FLT_EXCLUDE 2
51
52
53 /** Genetic map */
54 typedef struct
55 {
56 int pos;
57 double rate;
58 }
59 genmap_t;
60
61 /** HMM data for each sample */
62 typedef struct
63 {
64 double *eprob; // emission probs [2*nsites,msites]
65 uint32_t *sites; // positions [nsites,msites]
66 int nsites, msites;
67 int igenmap; // current position in genmap
68 int nused; // some stats to detect if things didn't go wrong
69 int nrid, *rid, *rid_off; // for viterbi training, keep all chromosomes
70 void *snapshot; // hmm snapshot
71 struct {
72 uint32_t beg,end,nqual;
73 double qual;
74 int rid, state;
75 } rg;
76 }
77 smpl_t;
78
79 typedef struct _args_t
80 {
81 bcf_srs_t *files;
82 bcf_hdr_t *hdr;
83 double t2AZ, t2HW; // P(AZ|HW) and P(HW|AZ) parameters
84 double unseen_PL, dflt_AF;
85
86 char *genmap_fname;
87 genmap_t *genmap;
88 int ngenmap, mgenmap, igenmap;
89 double rec_rate; // constant recombination rate if > 0
90
91 hmm_t *hmm;
92 double baum_welch_th;
93 int nrids, *rids, *rid_offs; // multiple chroms with vi_training
94 int nbuf_max, nbuf_olap;
95
96 float *AFs;
97 int32_t *itmp;
98 int mAFs, nitmp, mitmp, pl_hdr_id, gt_hdr_id;
99
100 double pl2p[256], *pdg;
101 int32_t skip_rid, prev_rid, prev_pos;
102
103 int ntot; // some stats to detect if things didn't go wrong
104 int nno_af; // number of sites rejected because AF could not be determined
105 int nfiltered; // .. because of filters
106 int nno_alt, nmultiallelic, ndup;
107 smpl_t *smpl; // HMM data for each sample
108 smpl_ilist_t *af_smpl; // list of samples to estimate AF from (--estimate-AF)
109 smpl_ilist_t *roh_smpl; // list of samples to analyze (--samples, --samples-file)
110 char *estimate_AF; // list of samples for AF estimate and query sample
111 int af_from_PL; // estimate AF from FMT/PL rather than FMT/GT
112 char **argv, *targets_list, *regions_list, *af_fname, *af_tag, *samples, *buffer_size, *output_fname;
113 int argc, fake_PLs, snps_only, vi_training, samples_is_file, output_type, skip_homref, n_threads;
114 int include_noalt_sites;
115 BGZF *out;
116 kstring_t str;
117
118 int filter_logic;
119 filter_t *filter;
120 char *filter_str;
121 }
122 args_t;
123
124 void set_tprob_genmap(hmm_t *hmm, uint32_t prev_pos, uint32_t pos, void *data, double *tprob);
125 void set_tprob_rrate(hmm_t *hmm, uint32_t prev_pos, uint32_t pos, void *data, double *tprob);
126
127 void *smalloc(size_t size)
128 {
129 void *mem = malloc(size);
130 if ( !mem ) error("malloc: Could not allocate %d bytes\n", (int)size);
131 return mem;
132 }
133
134 static inline int max255(int i)
135 {
136 return i < 256 ? i : 255;
137 }
138
139 static void init_data(args_t *args)
140 {
141 int i;
142
143 args->prev_rid = args->skip_rid = -1;
144 args->hdr = args->files->readers[0].header;
145
146 if ( !bcf_hdr_nsamples(args->hdr) ) error("No samples in the VCF?\n");
147
148 if ( args->filter_str )
149 args->filter = filter_init(args->hdr, args->filter_str);
150
151 if ( !args->fake_PLs )
152 {
153 args->pl_hdr_id = bcf_hdr_id2int(args->hdr, BCF_DT_ID, "PL");
154 if ( !bcf_hdr_idinfo_exists(args->hdr,BCF_HL_FMT,args->pl_hdr_id) )
155 error("Error: The FORMAT/PL tag not found in the header, consider running with -G\n");
156 if ( bcf_hdr_id2type(args->hdr,BCF_HL_FMT,args->pl_hdr_id)!=BCF_HT_INT )
157 error("Error: The FORMAT/PL tag not defined as Integer in the header\n");
158 }
159
160 if ( args->estimate_AF )
161 {
162 if ( !strncmp("GT,",args->estimate_AF,3) ) args->estimate_AF += 3;
163 else if ( !strncmp("PL,",args->estimate_AF,3) ) { args->estimate_AF += 3; args->af_from_PL = 1; }
164 if ( strcmp("-",args->estimate_AF) )
165 args->af_smpl = smpl_ilist_init(args->hdr, args->estimate_AF, 1, SMPL_NONE|SMPL_VERBOSE);
166 }
167
168 if ( args->estimate_AF || args->fake_PLs )
169 {
170 if ( args->af_from_PL )
171 {
172 args->pl_hdr_id = bcf_hdr_id2int(args->hdr, BCF_DT_ID, "PL");
173 if ( !bcf_hdr_idinfo_exists(args->hdr,BCF_HL_FMT,args->pl_hdr_id) )
174 error("Error: The FORMAT/PL tag not found in the header\n");
175 }
176 else
177 {
178 args->gt_hdr_id = bcf_hdr_id2int(args->hdr, BCF_DT_ID, "GT");
179 if ( !bcf_hdr_idinfo_exists(args->hdr,BCF_HL_FMT,args->gt_hdr_id) )
180 error("Error: The FORMAT/GT tag not found in the header\n");
181 }
182 }
183 if ( args->fake_PLs )
184 {
185 args->gt_hdr_id = bcf_hdr_id2int(args->hdr, BCF_DT_ID, "GT");
186 if ( !bcf_hdr_idinfo_exists(args->hdr,BCF_HL_FMT,args->gt_hdr_id) )
187 error("Error: The FORMAT/GT tag not found in the header\n");
188 }
189
190 args->roh_smpl = smpl_ilist_init(args->hdr, args->samples, args->samples_is_file, SMPL_NONE|SMPL_VERBOSE);
191 if ( args->samples )
192 {
193 // we may be able to subset to a few samples, for a text VCF this can be a major speedup
194 if ( (bcf_sr_get_reader(args->files,0))->file->format.format==vcf )
195 {
196 kstring_t str = {0,0,0};
197 smpl_ilist_t *tmp = args->roh_smpl, *rmme = NULL;
198 if ( args->af_smpl )
199 {
200 for (i=0; i<args->roh_smpl->n; i++)
201 {
202 if ( str.l ) kputc(',', &str);
203 kputs(args->hdr->samples[args->roh_smpl->idx[i]], &str);
204 }
205 for (i=0; i<args->af_smpl->n; i++)
206 {
207 kputc(',', &str);
208 kputs(args->hdr->samples[args->af_smpl->idx[i]], &str);
209 }
210 rmme = tmp = smpl_ilist_init(args->hdr, str.s, 0, SMPL_NONE);
211 }
212 if ( tmp->n < bcf_hdr_nsamples(args->hdr) )
213 {
214 str.l = 0;
215 for (i=0; i<tmp->n; i++)
216 {
217 if ( str.l ) kputc(',', &str);
218 kputs(args->hdr->samples[tmp->idx[i]], &str);
219 }
220 int ret = bcf_hdr_set_samples(args->hdr, str.s, 0);
221 if ( ret<0 ) error("Error parsing the list of samples: %s\n", str.s);
222 else if ( ret>0 ) error("The %d-th sample not found in the VCF: %s\n", ret,str.s);
223
224 // update sample ids
225 smpl_ilist_destroy(args->roh_smpl);
226 args->roh_smpl = smpl_ilist_init(args->hdr, args->samples, args->samples_is_file, SMPL_NONE);
227
228 if ( args->af_smpl )
229 {
230 smpl_ilist_destroy(args->af_smpl);
231 args->af_smpl = smpl_ilist_init(args->hdr, args->estimate_AF, 1, SMPL_NONE);
232 }
233 }
234 free(str.s);
235 if ( rmme )
236 smpl_ilist_destroy(rmme);
237 }
238 }
239
240 // check whether all samples are in this list. If so, the lookup will not be needed
241 if ( args->af_smpl && args->af_smpl->n == bcf_hdr_nsamples(args->hdr) )
242 {
243 // all samples are in this list
244 smpl_ilist_destroy(args->af_smpl);
245 args->af_smpl = NULL;
246 }
247
248 if ( args->buffer_size )
249 {
250 args->nbuf_olap = -1;
251 char *end;
252 double tmp = strtod(args->buffer_size,&end);
253 if ( *end )
254 {
255 if ( *end!=',') error("Could not parse: --buffer-size %s\n", args->buffer_size);
256 args->nbuf_olap = strtol(end+1,&end,10);
257 if ( *end || args->nbuf_olap<0 ) error("Could not parse: --buffer-size %s\n", args->buffer_size);
258 }
259 if ( tmp<0 )
260 args->nbuf_max = fabs(tmp)*1e6/(4+8*2)/args->roh_smpl->n;
261 else
262 args->nbuf_max = tmp;
263
264 if ( args->nbuf_olap<0 )
265 args->nbuf_olap = args->nbuf_max*0.01;
266 }
267 fprintf(stderr,"Number of target samples: %d\n", args->roh_smpl->n);
268 fprintf(stderr,"Number of --estimate-AF samples: %d\n", args->af_smpl ? args->af_smpl->n : (args->estimate_AF ? bcf_hdr_nsamples(args->hdr) : 0));
269 fprintf(stderr,"Number of sites in the buffer/overlap: ");
270 if ( args->nbuf_max ) fprintf(stderr,"%d/%d\n", args->nbuf_max,args->nbuf_olap);
271 else fprintf(stderr,"unlimited\n");
272
273 args->smpl = (smpl_t*) calloc(args->roh_smpl->n,sizeof(smpl_t));
274
275 for (i=0; i<256; i++) args->pl2p[i] = pow(10., -i/10.);
276
277 // Init transition matrix and HMM
278 double tprob[4];
279 MAT(tprob,2,STATE_HW,STATE_HW) = 1 - args->t2AZ;
280 MAT(tprob,2,STATE_HW,STATE_AZ) = args->t2HW;
281 MAT(tprob,2,STATE_AZ,STATE_HW) = args->t2AZ;
282 MAT(tprob,2,STATE_AZ,STATE_AZ) = 1 - args->t2HW;
283
284 args->hmm = hmm_init(2, tprob, 10000);
285 if ( args->genmap_fname )
286 hmm_set_tprob_func(args->hmm, set_tprob_genmap, args);
287 else if ( args->rec_rate > 0 )
288 hmm_set_tprob_func(args->hmm, set_tprob_rrate, args);
289
290 args->out = bgzf_open(strcmp("stdout",args->output_fname)?args->output_fname:"-", args->output_type&OUTPUT_GZ ? "wg" : "wu");
291 if ( !args->out ) error("Failed to open %s: %s\n", args->output_fname, strerror(errno));
292
293 // print header
294 args->str.l = 0;
295 ksprintf(&args->str, "# This file was produced by: bcftools roh(%s+htslib-%s)\n", bcftools_version(),hts_version());
296 ksprintf(&args->str, "# The command line was:\tbcftools %s", args->argv[0]);
297 for (i=1; i<args->argc; i++)
298 ksprintf(&args->str, " %s",args->argv[i]);
299 ksprintf(&args->str, "\n#\n");
300 if ( args->output_type & OUTPUT_RG )
301 {
302 i = 2;
303 ksprintf(&args->str, "# RG");
304 ksprintf(&args->str, "\t[%d]Sample", i++);
305 ksprintf(&args->str, "\t[%d]Chromosome", i++);
306 ksprintf(&args->str, "\t[%d]Start", i++);
307 ksprintf(&args->str, "\t[%d]End", i++);
308 ksprintf(&args->str, "\t[%d]Length (bp)", i++);
309 ksprintf(&args->str, "\t[%d]Number of markers", i++);
310 ksprintf(&args->str, "\t[%d]Quality (average fwd-bwd phred score)", i++);
311 ksprintf(&args->str, "\n");
312 }
313 if ( args->output_type & OUTPUT_ST )
314 {
315 i = 2;
316 ksprintf(&args->str, "# ST");
317 ksprintf(&args->str, "\t[%d]Sample", i++);
318 ksprintf(&args->str, "\t[%d]Chromosome", i++);
319 ksprintf(&args->str, "\t[%d]Position", i++);
320 ksprintf(&args->str, "\t[%d]State (0:HW, 1:AZ)", i++);
321 ksprintf(&args->str, "\t[%d]Quality (fwd-bwd phred score)", i++);
322 ksprintf(&args->str, "\n");
323 }
324 if ( args->vi_training)
325 {
326 i = 2;
327 ksprintf(&args->str, "# VT, Viterbi Training");
328 ksprintf(&args->str, "\t[%d]Sample", i++);
329 ksprintf(&args->str, "\t[%d]Iteration", i++);
330 ksprintf(&args->str, "\t[%d]dAZ", i++);
331 ksprintf(&args->str, "\t[%d]dHW", i++);
332 ksprintf(&args->str, "\t[%d]1 - P(HW|HW)", i++);
333 ksprintf(&args->str, "\t[%d]P(AZ|HW)", i++);
334 ksprintf(&args->str, "\t[%d]1 - P(AZ|AZ)", i++);
335 ksprintf(&args->str, "\t[%d]P(HW|AZ)", i++);
336 ksprintf(&args->str, "\n");
337 }
338 if ( bgzf_write(args->out, args->str.s, args->str.l) != args->str.l )
339 error("Error writing %s: %s\n", args->output_fname, strerror(errno));
340 }
341
342 static void destroy_data(args_t *args)
343 {
344 if ( args->filter ) filter_destroy(args->filter);
345 if ( bgzf_close(args->out)!=0 ) error("Error: close failed .. %s\n", args->output_fname);
346 int i;
347 for (i=0; i<args->roh_smpl->n; i++)
348 {
349 free(args->smpl[i].eprob);
350 free(args->smpl[i].sites);
351 free(args->smpl[i].rid);
352 free(args->smpl[i].rid_off);
353 free(args->smpl[i].snapshot);
354 }
355 free(args->str.s);
356 free(args->smpl);
357 if ( args->af_smpl ) smpl_ilist_destroy(args->af_smpl);
358 smpl_ilist_destroy(args->roh_smpl);
359 free(args->rids);
360 free(args->rid_offs);
361 hmm_destroy(args->hmm);
362 bcf_sr_destroy(args->files);
363 free(args->AFs); free(args->pdg);
364 free(args->genmap);
365 free(args->itmp);
366 free(args->samples);
367 }
368
369 static int load_genmap(args_t *args, const char *chr)
370 {
371 if ( !args->genmap_fname ) { args->ngenmap = 0; return 0; }
372
373 kstring_t str = {0,0,0};
374 char *fname = strstr(args->genmap_fname,"{CHROM}");
375 if ( fname )
376 {
377 kputsn(args->genmap_fname, fname - args->genmap_fname, &str);
378 kputs(chr, &str);
379 kputs(fname+7,&str);
380 fname = str.s;
381 }
382 else
383 fname = args->genmap_fname;
384
385 htsFile *fp = hts_open(fname, "rb");
386 if ( !fp )
387 {
388 args->ngenmap = 0;
389 return -1;
390 }
391
392 hts_getline(fp, KS_SEP_LINE, &str);
393 if ( strcmp(str.s,"position COMBINED_rate(cM/Mb) Genetic_Map(cM)") )
394 error("Unexpected header in %s, found:\n\t[%s], but expected:\n\t[position COMBINED_rate(cM/Mb) Genetic_Map(cM)]\n", fname, str.s);
395
396 args->ngenmap = args->igenmap = 0;
397 while ( hts_getline(fp, KS_SEP_LINE, &str) > 0 )
398 {
399 args->ngenmap++;
400 hts_expand(genmap_t,args->ngenmap,args->mgenmap,args->genmap);
401 genmap_t *gm = &args->genmap[args->ngenmap-1];
402
403 // position, convert to 0-based
404 char *tmp, *end;
405 gm->pos = strtol(str.s, &tmp, 10);
406 if ( str.s==tmp ) error("Could not parse %s: %s\n", fname, str.s);
407 gm->pos -= 1;
408
409 // skip second column
410 tmp++;
411 while ( *tmp && !isspace(*tmp) ) tmp++;
412
413 // read the genetic map in cM, scale from % to likelihood
414 gm->rate = strtod(tmp+1, &end);
415 if ( tmp+1==end ) error("Could not parse %s: %s\n", fname, str.s);
416 gm->rate *= 0.01;
417 }
418 if ( !args->ngenmap ) error("Genetic map empty?\n");
419 if ( hts_close(fp) ) error("Close failed\n");
420 free(str.s);
421 return 0;
422 }
423
424 static double get_genmap_rate(args_t *args, int start, int end)
425 {
426 // position i to be equal to or smaller than start
427 int i = args->igenmap;
428 if ( args->genmap[i].pos > start )
429 {
430 while ( i>0 && args->genmap[i].pos > start ) i--;
431 }
432 else
433 {
434 while ( i+1<args->ngenmap && args->genmap[i+1].pos < start ) i++;
435 }
436 // position j to be equal or larger than end
437 int j = i;
438 while ( j+1<args->ngenmap && args->genmap[j].pos < end ) j++;
439 if ( i==j )
440 {
441 args->igenmap = i;
442 return 0;
443 }
444
445 if ( start < args->genmap[i].pos ) start = args->genmap[i].pos;
446 if ( end > args->genmap[j].pos ) end = args->genmap[j].pos;
447 double rate = (args->genmap[j].rate - args->genmap[i].rate)/(args->genmap[j].pos - args->genmap[i].pos) * (end-start);
448 args->igenmap = j;
449 return rate;
450 }
451
452 void set_tprob_genmap(hmm_t *hmm, uint32_t prev_pos, uint32_t pos, void *data, double *tprob)
453 {
454 args_t *args = (args_t*) data;
455 double ci = get_genmap_rate(args, prev_pos, pos);
456 if ( args->rec_rate ) ci *= args->rec_rate;
457 if ( ci > 1 ) ci = 1;
458 MAT(tprob,2,STATE_HW,STATE_AZ) *= ci;
459 MAT(tprob,2,STATE_AZ,STATE_HW) *= ci;
460 MAT(tprob,2,STATE_AZ,STATE_AZ) = 1 - MAT(tprob,2,STATE_HW,STATE_AZ);
461 MAT(tprob,2,STATE_HW,STATE_HW) = 1 - MAT(tprob,2,STATE_AZ,STATE_HW);
462 }
463
464 void set_tprob_rrate(hmm_t *hmm, uint32_t prev_pos, uint32_t pos, void *data, double *tprob)
465 {
466 args_t *args = (args_t*) data;
467 double ci = (pos - prev_pos) * args->rec_rate;
468 if ( ci > 1 ) ci = 1;
469 MAT(tprob,2,STATE_HW,STATE_AZ) *= ci;
470 MAT(tprob,2,STATE_AZ,STATE_HW) *= ci;
471 MAT(tprob,2,STATE_AZ,STATE_AZ) = 1 - MAT(tprob,2,STATE_HW,STATE_AZ);
472 MAT(tprob,2,STATE_HW,STATE_HW) = 1 - MAT(tprob,2,STATE_AZ,STATE_HW);
473 }
474
475
476 /**
477 * This function implements the HMM model:
478 * D = Data, AZ = autozygosity, HW = Hardy-Weinberg (non-autozygosity),
479 * f = non-ref allele frequency
480 *
481 * Emission probabilities:
482 * oAZ = P_i(D|AZ) = (1-f)*P(D|RR) + f*P(D|AA)
483 * oHW = P_i(D|HW) = (1-f)^2 * P(D|RR) + f^2 * P(D|AA) + 2*f*(1-f)*P(D|RA)
484 *
485 * Transition probabilities:
486 * tAZ = P(AZ|HW) .. parameter
487 * tHW = P(HW|AZ) .. parameter
488 *
489 * ci = P_i(C) .. probability of cross-over at site i, from genetic map
490 *
491 * AZi = P_i(AZ) .. probability of site i being AZ/non-AZ, scaled so that AZi+HWi = 1
492 * HWi = P_i(HW)
493 *
494 * P_i(AZ|HW) = P(AZ|HW) * ci * HW{i-1} = tAZ * ci * (1 - AZ{i-1})
495 * P_i(HW|AZ) = P(HW|AZ) * ci * AZ{i-1} = tHW * ci * AZ{i-1}
496 * P_i(AZ|AZ) = 1 - P_i(HW|AZ)
497 * P_i(HW|HW) = 1 - P_i(AZ|HW)
498 *
499 */
500
501 static void flush_viterbi(args_t *args, int ismpl)
502 {
503 smpl_t *smpl = &args->smpl[ismpl];
504 if ( !smpl->nsites ) return;
505
506 const char *name = args->hdr->samples[ args->roh_smpl->idx[ismpl] ];
507
508 int i,j,k;
509
510 if ( !args->vi_training ) // single viterbi pass
511 {
512 hmm_restore(args->hmm, smpl->snapshot);
513 int end = (args->nbuf_max && smpl->nsites >= args->nbuf_max && smpl->nsites > args->nbuf_olap) ? smpl->nsites - args->nbuf_olap : smpl->nsites;
514 if ( end < smpl->nsites )
515 smpl->snapshot = hmm_snapshot(args->hmm, smpl->snapshot, smpl->sites[smpl->nsites - args->nbuf_olap - 1]);
516
517 args->igenmap = smpl->igenmap;
518 hmm_run_viterbi(args->hmm, smpl->nsites, smpl->eprob, smpl->sites);
519 hmm_run_fwd_bwd(args->hmm, smpl->nsites, smpl->eprob, smpl->sites);
520 double *fwd = hmm_get_fwd_bwd_prob(args->hmm);
521
522 const char *chr = bcf_hdr_id2name(args->hdr,args->prev_rid);
523 uint8_t *vpath = hmm_get_viterbi_path(args->hmm);
524
525 for (i=0; i<end; i++)
526 {
527 int state = vpath[i*2]==STATE_AZ ? 1 : 0;
528 double qual = phred_score(1.0 - fwd[i*2 + state]);
529 if ( args->output_type & OUTPUT_ST )
530 {
531 args->str.l = 0;
532 ksprintf(&args->str, "ST\t%s\t%s\t%d\t%d\t%.1f\n", name,chr,smpl->sites[i]+1, state, qual);
533 if ( bgzf_write(args->out, args->str.s, args->str.l) != args->str.l ) error("Error writing %s: %s\n", args->output_fname, strerror(errno));
534 }
535
536 if ( args->output_type & OUTPUT_RG )
537 {
538 if ( state!=smpl->rg.state )
539 {
540 if ( !state ) // the region ends, flush
541 {
542 args->str.l = 0;
543 ksprintf(&args->str, "RG\t%s\t%s\t%d\t%d\t%d\t%d\t%.1f\n",name,bcf_hdr_id2name(args->hdr,smpl->rg.rid),
544 smpl->rg.beg+1,smpl->rg.end+1,smpl->rg.end-smpl->rg.beg+1,smpl->rg.nqual,smpl->rg.qual/smpl->rg.nqual);
545 if ( bgzf_write(args->out, args->str.s, args->str.l) != args->str.l ) error("Error writing %s: %s\n", args->output_fname, strerror(errno));
546 smpl->rg.state = 0;
547 }
548 else
549 {
550 smpl->rg.state = 1;
551 smpl->rg.beg = smpl->sites[i];
552 smpl->rg.end = smpl->sites[i];
553 smpl->rg.rid = args->prev_rid;
554 smpl->rg.qual = qual;
555 smpl->rg.nqual = 1;
556 }
557 }
558 else if ( state )
559 {
560 smpl->rg.nqual++;
561 smpl->rg.qual += qual;
562 smpl->rg.end = smpl->sites[i];
563 }
564 }
565 }
566
567 if ( end < smpl->nsites )
568 {
569 end = smpl->nsites - args->nbuf_olap;
570 memmove(smpl->sites, smpl->sites + end, sizeof(*smpl->sites)*args->nbuf_olap);
571 memmove(smpl->eprob, smpl->eprob + end*2, sizeof(*smpl->eprob)*args->nbuf_olap*2);
572 smpl->nsites = args->nbuf_olap;
573 smpl->igenmap = args->igenmap;
574 }
575 else
576 {
577 smpl->nsites = 0;
578 smpl->igenmap = 0;
579
580 if ( smpl->rg.state )
581 {
582 args->str.l = 0;
583 ksprintf(&args->str, "RG\t%s\t%s\t%d\t%d\t%d\t%d\t%.1f\n",name,bcf_hdr_id2name(args->hdr,smpl->rg.rid),
584 smpl->rg.beg+1,smpl->rg.end+1,smpl->rg.end-smpl->rg.beg+1,smpl->rg.nqual,smpl->rg.qual/smpl->rg.nqual);
585 if ( bgzf_write(args->out, args->str.s, args->str.l) != args->str.l ) error("Error writing %s: %s\n", args->output_fname, strerror(errno));
586 smpl->rg.state = 0;
587 }
588 }
589
590 return;
591 }
592
593
594 // viterbi training, multiple chromosomes
595 double t2az_prev, t2hw_prev;
596 double deltaz, delthw;
597
598 double *tprob_arr = hmm_get_tprob(args->hmm);
599 MAT(tprob_arr,2,STATE_HW,STATE_HW) = 1 - args->t2AZ;
600 MAT(tprob_arr,2,STATE_HW,STATE_AZ) = args->t2HW;
601 MAT(tprob_arr,2,STATE_AZ,STATE_HW) = args->t2AZ;
602 MAT(tprob_arr,2,STATE_AZ,STATE_AZ) = 1 - args->t2HW;
603 hmm_set_tprob(args->hmm, tprob_arr, 10000);
604
605 int niter = 0;
606 do
607 {
608 tprob_arr = hmm_get_tprob(args->hmm);
609 t2az_prev = MAT(tprob_arr,2,STATE_AZ,STATE_HW); //args->t2AZ;
610 t2hw_prev = MAT(tprob_arr,2,STATE_HW,STATE_AZ); //args->t2HW;
611 double tprob_new[] = { 0,0,0,0 };
612 for (i=0; i<smpl->nrid; i++)
613 {
614 int ioff = smpl->rid_off[i];
615 int nsites = (i+1==smpl->nrid ? smpl->nsites : smpl->rid_off[i+1]) - ioff;
616 args->igenmap = 0;
617 tprob_arr = hmm_run_baum_welch(args->hmm, nsites, smpl->eprob+ioff*2, smpl->sites+ioff);
618 for (j=0; j<2; j++)
619 for (k=0; k<2; k++) MAT(tprob_new,2,j,k) += MAT(tprob_arr,2,j,k);
620 }
621 for (j=0; j<2; j++)
622 for (k=0; k<2; k++) MAT(tprob_new,2,j,k) /= smpl->nrid;
623
624 hmm_set_tprob(args->hmm, tprob_new, 10000);
625
626 deltaz = fabs(MAT(tprob_new,2,STATE_AZ,STATE_HW)-t2az_prev);
627 delthw = fabs(MAT(tprob_new,2,STATE_HW,STATE_AZ)-t2hw_prev);
628 niter++;
629 args->str.l = 0;
630 ksprintf(&args->str, "VT\t%s\t%d\t%e\t%e\t%e\t%e\t%e\t%e\n",
631 name,niter,deltaz,delthw,
632 1-MAT(tprob_new,2,STATE_HW,STATE_HW),MAT(tprob_new,2,STATE_AZ,STATE_HW),
633 1-MAT(tprob_new,2,STATE_AZ,STATE_AZ),MAT(tprob_new,2,STATE_HW,STATE_AZ));
634 if ( bgzf_write(args->out, args->str.s, args->str.l) != args->str.l ) error("Error writing %s: %s\n", args->output_fname, strerror(errno));
635 }
636 while ( deltaz > args->baum_welch_th || delthw > args->baum_welch_th );
637
638 // output the results
639 for (i=0; i<smpl->nrid; i++)
640 {
641 int ioff = smpl->rid_off[i];
642 int nsites = (i+1==smpl->nrid ? smpl->nsites : smpl->rid_off[i+1]) - ioff;
643 args->igenmap = 0;
644 hmm_run_viterbi(args->hmm, nsites, smpl->eprob+ioff*2, smpl->sites+ioff);
645 hmm_run_fwd_bwd(args->hmm, nsites, smpl->eprob+ioff*2, smpl->sites+ioff);
646 uint8_t *vpath = hmm_get_viterbi_path(args->hmm);
647 double *fwd = hmm_get_fwd_bwd_prob(args->hmm);
648
649 const char *chr = bcf_hdr_id2name(args->hdr,smpl->rid[i]);
650 for (j=0; j<nsites; j++)
651 {
652 int state = vpath[j*2]==STATE_AZ ? 1 : 0;
653 double *pval = fwd + j*2;
654 args->str.l = 0;
655 ksprintf(&args->str, "ROH\t%s\t%s\t%d\t%d\t%.1f\n", name,chr,smpl->sites[ioff+j]+1, state, phred_score(1.0-pval[state]));
656 if ( bgzf_write(args->out, args->str.s, args->str.l) != args->str.l ) error("Error writing %s: %s\n", args->output_fname, strerror(errno));
657 }
658 }
659 }
660
661 int read_AF(bcf_sr_regions_t *tgt, bcf1_t *line, double *alt_freq)
662 {
663 if ( tgt->nals < 2 )
664 error("Expected two comma-separated alleles (REF,ALT) in the third column of %s, found:\n\t%s\n", tgt->fname,tgt->line.s);
665 if ( tgt->nals != line->n_allele ) return -1; // number of alleles does not match
666
667 int i;
668 for (i=0; i<tgt->nals; i++)
669 if ( strcmp(line->d.allele[i],tgt->als[i]) ) break; // we could be smarter, see vcmp
670 if ( i<tgt->nals ) return -1;
671
672 char *tmp, *str = tgt->line.s;
673 i = 0;
674 while ( *str && i<3 )
675 {
676 if ( *str=='\t' ) i++;
677 str++;
678 }
679 *alt_freq = strtod(str, &tmp);
680 if ( *tmp && !isspace(*tmp) )
681 {
682 if ( str[0]=='.' && (!str[1] || isspace(str[1])) ) return -1; // missing value
683 error("Could not parse: [%s]\n", tgt->line.s);
684 }
685 if ( *alt_freq<0 || *alt_freq>1 ) error("Could not parse AF: [%s]\n", tgt->line.s);
686 return 0;
687 }
688
689 int8_t *get_GT(args_t *args, bcf1_t *line)
690 {
691 int i;
692 for (i=0; i<line->n_fmt; i++)
693 if ( line->d.fmt[i].id==args->gt_hdr_id ) break;
694 if ( i==line->n_fmt ) return NULL; // the tag is not present in this record
695
696 bcf_fmt_t *fmt = &line->d.fmt[i];
697 if ( fmt->n!=2 ) return NULL; // not diploid
698
699 if ( fmt->type!=BCF_BT_INT8 ) error("This is unexpected, GT type is %d\n", fmt->type);
700 return (int8_t*) fmt->p;
701 }
702
703 int estimate_AF_from_GT(args_t *args, int8_t *gt, double *alt_freq)
704 {
705 int i, nalt = 0, nref = 0;
706 if ( args->af_smpl ) // subset samples for AF estimate
707 {
708 for (i=0; i<args->af_smpl->n; i++)
709 {
710 int ismpl = args->af_smpl->idx[i];
711 if ( bcf_gt_is_missing(gt[2*ismpl]) || bcf_gt_is_missing(gt[2*ismpl+1]) ) continue;
712
713 if ( bcf_gt_allele(gt[2*ismpl]) ) nalt++;
714 else nref++;
715
716 if ( bcf_gt_allele(gt[2*ismpl+1]) ) nalt++;
717 else nref++;
718 }
719 }
720 else // all samples used in AF estimate
721 {
722 int8_t *end = gt + 2*bcf_hdr_nsamples(args->hdr);
723 while ( gt < end )
724 {
725 if ( bcf_gt_is_missing(gt[0]) || bcf_gt_is_missing(gt[1]) )
726 {
727 gt += 2;
728 continue;
729 }
730
731 if ( bcf_gt_allele(gt[0]) ) nalt++;
732 else nref++;
733
734 if ( bcf_gt_allele(gt[1]) ) nalt++;
735 else nref++;
736
737 gt += 2;
738 }
739 }
740 if ( !nalt && !nref ) return -1;
741
742 *alt_freq = (double)nalt / (nalt + nref);
743 return 0;
744 }
745
746 int estimate_AF_from_PL(args_t *args, bcf_fmt_t *fmt_pl, int ial, double *alt_freq)
747 {
748 double af = 0;
749 int i, j, naf = 0;
750
751 int irr = bcf_alleles2gt(0,0), ira = bcf_alleles2gt(0,ial), iaa = bcf_alleles2gt(ial,ial);
752 if ( iaa >= fmt_pl->n ) return -1; // not diploid or wrong number of fields
753
754 if ( args->af_smpl ) // subset samples for AF estimate
755 {
756 #define BRANCH(type_t) \
757 { \
758 for (i=0; i<args->af_smpl->n; i++) \
759 { \
760 int ismpl = args->af_smpl->idx[i]; \
761 type_t *p = (type_t*)fmt_pl->p + fmt_pl->n*ismpl; \
762 if ( p[irr]<0 || p[ira]<0 || p[iaa]<0 ) continue; /* missing value */ \
763 if ( p[irr]==p[ira] && p[irr]==p[iaa] ) continue; /* all values are the same */ \
764 double prob[3], norm = 0; \
765 prob[0] = args->pl2p[ max255(p[irr]) ]; \
766 prob[1] = args->pl2p[ max255(p[ira]) ]; \
767 prob[2] = args->pl2p[ max255(p[iaa]) ]; \
768 for (j=0; j<3; j++) norm += prob[j]; \
769 for (j=0; j<3; j++) prob[j] /= norm; \
770 af += 0.5*prob[1] + prob[2]; \
771 naf++; \
772 } \
773 }
774 switch (fmt_pl->type) {
775 case BCF_BT_INT8: BRANCH(int8_t); break;
776 case BCF_BT_INT16: BRANCH(int16_t); break;
777 case BCF_BT_INT32: BRANCH(int32_t); break;
778 default: fprintf(stderr,"Unknown format type for PL: %s:%d .. fmt->type=%d\n", __FILE__,__LINE__, fmt_pl->type); exit(1);
779 }
780 #undef BRANCH
781 }
782 else // all samples used in AF estimate
783 {
784 int nsmpl = bcf_hdr_nsamples(args->hdr);
785 #define BRANCH(type_t) \
786 { \
787 type_t *p = (type_t*)fmt_pl->p; \
788 p -= fmt_pl->n; \
789 for (i=0; i<nsmpl; i++) \
790 { \
791 p += fmt_pl->n; \
792 if ( p[irr]<0 || p[ira]<0 || p[iaa]<0 ) continue; /* missing value */ \
793 if ( p[irr]==p[ira] && p[irr]==p[iaa] ) continue; /* all values are the same */ \
794 double prob[3], norm = 0; \
795 prob[0] = args->pl2p[ max255(p[irr]) ]; \
796 prob[1] = args->pl2p[ max255(p[ira]) ]; \
797 prob[2] = args->pl2p[ max255(p[iaa]) ]; \
798 for (j=0; j<3; j++) norm += prob[j]; \
799 for (j=0; j<3; j++) prob[j] /= norm; \
800 af += 0.5*prob[1] + prob[2]; \
801 naf++; \
802 } \
803 }
804 switch (fmt_pl->type) {
805 case BCF_BT_INT8: BRANCH(int8_t); break;
806 case BCF_BT_INT16: BRANCH(int16_t); break;
807 case BCF_BT_INT32: BRANCH(int32_t); break;
808 default: fprintf(stderr,"Unknown format type for PL: %s:%d .. fmt->type=%d\n", __FILE__,__LINE__, fmt_pl->type); exit(1);
809 }
810 #undef BRANCH
811 }
812 if ( !naf ) return -1;
813
814 *alt_freq = af / naf;
815 return 0;
816 }
817
818 bcf_fmt_t *get_PL(args_t *args, bcf1_t *line)
819 {
820 int i;
821 for (i=0; i<line->n_fmt; i++)
822 if ( line->d.fmt[i].id==args->pl_hdr_id ) return &line->d.fmt[i];
823 return NULL;
824 }
825
826 int process_line(args_t *args, bcf1_t *line, int ial)
827 {
828 if ( !(line->unpacked & BCF_UN_FMT) ) bcf_unpack(line, BCF_UN_FMT);
829
830 double alt_freq;
831 int8_t *GTs = NULL;
832 bcf_fmt_t *fmt_pl = NULL;
833
834 // Set allele frequency
835 int ret = 0, i,j;
836 if ( args->af_tag )
837 {
838 // Use an INFO tag provided by the user
839 ret = bcf_get_info_float(args->hdr, line, args->af_tag, &args->AFs, &args->mAFs);
840 if ( ret>0 )
841 alt_freq = args->AFs[ial-1];
842 if ( ret==-2 )
843 error("Type mismatch for INFO/%s tag at %s:%"PRId64"\n", args->af_tag, bcf_seqname(args->hdr,line), (int64_t) line->pos+1);
844 }
845 else if ( args->af_fname )
846 {
847 // Read AF from a file
848 ret = read_AF(args->files->targets, line, &alt_freq);
849 }
850 else if ( args->dflt_AF > 0 )
851 {
852 alt_freq = args->dflt_AF;
853 }
854 else if ( args->estimate_AF )
855 {
856 // Estimate AF from GTs or PLs of all samples or samples listed in a file
857 if ( args->af_from_PL )
858 {
859 fmt_pl = get_PL(args, line);
860 if ( !fmt_pl ) return -1;
861 ret = estimate_AF_from_PL(args, fmt_pl, ial, &alt_freq);
862 }
863 else
864 {
865 GTs = get_GT(args, line);
866 if ( !GTs ) return -1;
867 ret = estimate_AF_from_GT(args, GTs, &alt_freq);
868 }
869 }
870 else
871 {
872 // Use AC/AN
873 int AC = -1, AN = 0;
874 ret = bcf_get_info_int32(args->hdr, line, "AN", &args->itmp, &args->mitmp);
875 if ( ret==1 )
876 {
877 AN = args->itmp[0];
878 ret = bcf_get_info_int32(args->hdr, line, "AC", &args->itmp, &args->mitmp);
879 if ( ret>0 )
880 AC = args->itmp[0];
881 }
882 if ( AN<=0 || AC<0 )
883 ret = -1;
884 else
885 alt_freq = (double) AC/AN;
886 }
887
888 if ( args->dflt_AF>0 && (ret<0 || alt_freq==0.0) ) alt_freq = args->dflt_AF;
889 else if ( ret<0 ) { args->nno_af++; return ret; }
890 else if ( alt_freq==0.0 ) { args->nno_af++; return -1; }
891
892 int irr = bcf_alleles2gt(0,0), ira = bcf_alleles2gt(0,ial), iaa = bcf_alleles2gt(ial,ial);
893 if ( args->fake_PLs )
894 {
895 if ( !GTs ) GTs = get_GT(args, line);
896 }
897 else
898 {
899 fmt_pl = get_PL(args, line);
900 if ( !fmt_pl ) return -1;
901 if ( iaa >= fmt_pl->n ) return -1; // not diploid or wrong number of fields
902 }
903
904 for (i=0; i<args->roh_smpl->n; i++)
905 {
906 int ismpl = args->roh_smpl->idx[i];
907
908 // set P(D|G)
909 double pdg[3];
910 if ( args->fake_PLs )
911 {
912 int8_t *gt = GTs + 2*ismpl;
913 if ( bcf_gt_is_missing(gt[0]) || bcf_gt_is_missing(gt[1]) ) continue;
914
915 int a = bcf_gt_allele(gt[0]);
916 int b = bcf_gt_allele(gt[1]);
917 if ( a!=b )
918 {
919 pdg[0] = pdg[2] = args->unseen_PL;
920 pdg[1] = 1 - 2*args->unseen_PL;
921 }
922 else if ( a==0 )
923 {
924 pdg[0] = 1 - args->unseen_PL - args->unseen_PL*args->unseen_PL;
925 pdg[1] = args->unseen_PL;
926 pdg[2] = args->unseen_PL*args->unseen_PL;
927 }
928 else
929 {
930 pdg[0] = args->unseen_PL*args->unseen_PL;
931 pdg[1] = args->unseen_PL;
932 pdg[2] = 1 - args->unseen_PL - args->unseen_PL*args->unseen_PL;
933 }
934 }
935 else
936 {
937 #define BRANCH(type_t) \
938 { \
939 type_t *p = (type_t*)fmt_pl->p + fmt_pl->n*ismpl; \
940 if ( p[irr]<0 || p[ira]<0 || p[iaa]<0 ) continue; /* missing value */ \
941 if ( p[irr]==p[ira] && p[irr]==p[iaa] ) continue; /* all values are the same */ \
942 pdg[0] = args->pl2p[ max255(p[irr]) ]; \
943 pdg[1] = args->pl2p[ max255(p[ira]) ]; \
944 pdg[2] = args->pl2p[ max255(p[iaa]) ]; \
945 }
946 switch (fmt_pl->type) {
947 case BCF_BT_INT8: BRANCH(int8_t); break;
948 case BCF_BT_INT16: BRANCH(int16_t); break;
949 case BCF_BT_INT32: BRANCH(int32_t); break;
950 default: fprintf(stderr,"Unknown format type for PL: %s:%d .. fmt->type=%d\n", __FILE__,__LINE__, fmt_pl->type); exit(1);
951 }
952 #undef BRANCH
953 }
954
955 double sum = pdg[0] + pdg[1] + pdg[2];
956 if ( !sum ) continue;
957 for (j=0; j<3; j++) pdg[j] /= sum;
958 if ( args->skip_homref && pdg[0]>0.99 ) continue;
959
960 smpl_t *smpl = &args->smpl[i];
961 smpl->nused++;
962
963 if ( smpl->nsites >= smpl->msites )
964 {
965 hts_expand(uint32_t,smpl->nsites+1,smpl->msites,smpl->sites);
966 smpl->eprob = (double*) realloc(smpl->eprob,sizeof(*smpl->eprob)*smpl->msites*2);
967 if ( !smpl->eprob ) error("Error: failed to alloc %"PRIu64" bytes\n", (uint64_t)(sizeof(*smpl->eprob)*smpl->msites*2));
968 }
969
970 // Calculate emission probabilities P(D|AZ) and P(D|HW)
971 double *eprob = &smpl->eprob[2*smpl->nsites];
972 eprob[STATE_AZ] = pdg[0]*(1-alt_freq) + pdg[2]*alt_freq;
973 eprob[STATE_HW] = pdg[0]*(1-alt_freq)*(1-alt_freq) + 2*pdg[1]*(1-alt_freq)*alt_freq + pdg[2]*alt_freq*alt_freq;
974
975 smpl->sites[smpl->nsites] = line->pos;
976 smpl->nsites++;
977
978 if ( args->vi_training )
979 {
980 if ( !smpl->nrid || line->rid!=smpl->rid[smpl->nrid-1] )
981 {
982 smpl->nrid++;
983 smpl->rid = (int*) realloc(smpl->rid,sizeof(*smpl->rid)*smpl->nrid);
984 smpl->rid[smpl->nrid-1] = line->rid;
985 smpl->rid_off = (int*) realloc(smpl->rid_off,sizeof(*smpl->rid_off)*smpl->nrid);
986 smpl->rid_off[smpl->nrid-1] = smpl->nsites - 1;
987 }
988 }
989 else if ( args->nbuf_max && smpl->nsites >= args->nbuf_max ) flush_viterbi(args, i);
990 }
991
992 return 0;
993 }
994
995 static void vcfroh(args_t *args, bcf1_t *line)
996 {
997 int i;
998
999 // Are we done?
1000 if ( !line )
1001 {
1002 for (i=0; i<args->roh_smpl->n; i++) flush_viterbi(args, i);
1003 return;
1004 }
1005
1006 // Skip unwanted lines, for simplicity we consider only biallelic sites
1007 if ( line->rid == args->skip_rid ) return;
1008
1009 // This can be raw callable VCF with the symbolic unseen allele <*>
1010 int ial = 0, nalt = line->n_allele - 1;
1011 for (i=1; i<line->n_allele; i++)
1012 {
1013 if ( !strcmp("<*>",line->d.allele[i]) || !strcmp("<NON_REF>",line->d.allele[i]) ) nalt--;
1014 else if ( !ial ) ial = i;
1015 }
1016
1017 if ( !nalt ) // no ALT allele
1018 {
1019 args->nno_alt++;
1020 if ( !args->include_noalt_sites ) return;
1021 }
1022 else if ( nalt>1 )
1023 {
1024 args->nmultiallelic++;
1025 return;
1026 }
1027
1028 if ( args->snps_only && !bcf_is_snp(line) ) return;
1029
1030 // Initialize genetic map
1031 int skip_rid = 0;
1032 if ( args->prev_rid<0 )
1033 skip_rid = load_genmap(args, bcf_seqname(args->hdr,line));
1034
1035 // New chromosome?
1036 if ( args->prev_rid!=line->rid )
1037 {
1038 if ( !args->vi_training )
1039 {
1040 for (i=0; i<args->roh_smpl->n; i++)
1041 {
1042 flush_viterbi(args, i);
1043 hmm_reset(args->hmm, args->smpl[i].snapshot);
1044 }
1045 }
1046 args->prev_rid = line->rid;
1047 args->prev_pos = line->pos;
1048 skip_rid = load_genmap(args, bcf_seqname(args->hdr,line));
1049 }
1050 else if ( args->prev_pos == line->pos )
1051 {
1052 args->ndup++;
1053 return; // skip duplicate positions
1054 }
1055
1056 if ( skip_rid )
1057 {
1058 fprintf(stderr,"Skipping the sequence, no genmap for %s\n", bcf_seqname(args->hdr,line));
1059 args->skip_rid = line->rid;
1060 return;
1061 }
1062 if ( args->prev_pos > line->pos ) error("The file is not sorted?!\n");
1063
1064 args->prev_rid = line->rid;
1065 args->prev_pos = line->pos;
1066
1067
1068 // parse the new line
1069 process_line(args, line, ial);
1070 }
1071
1072 static void usage(args_t *args)
1073 {
1074 fprintf(stderr, "\n");
1075 fprintf(stderr, "About: HMM model for detecting runs of autozygosity.\n");
1076 fprintf(stderr, "Usage: bcftools roh [options] <in.vcf.gz>\n");
1077 fprintf(stderr, "\n");
1078 fprintf(stderr, "General Options:\n");
1079 fprintf(stderr, " --AF-dflt <float> if AF is not known, use this allele frequency [skip]\n");
1080 fprintf(stderr, " --AF-tag <TAG> use TAG for allele frequency\n");
1081 fprintf(stderr, " --AF-file <file> read allele frequencies from file (CHR\\tPOS\\tREF,ALT\\tAF)\n");
1082 fprintf(stderr, " -b --buffer-size <int[,int]> buffer size and the number of overlapping sites, 0 for unlimited [0]\n");
1083 fprintf(stderr, " If the first number is negative, it is interpreted as the maximum memory to\n");
1084 fprintf(stderr, " use, in MB. The default overlap is set to roughly 1%% of the buffer size.\n");
1085 fprintf(stderr, " -e, --estimate-AF [TAG],<file> estimate AF from FORMAT/TAG (GT or PL) of all samples (\"-\") or samples listed\n");
1086 fprintf(stderr, " in <file>. If TAG is not given, the frequency is estimated from GT by default\n");
1087 fprintf(stderr, " --exclude <expr> exclude sites for which the expression is true\n");
1088 fprintf(stderr, " -G, --GTs-only <float> use GTs and ignore PLs, instead using <float> for PL of the two least likely genotypes.\n");
1089 fprintf(stderr, " Safe value to use is 30 to account for GT errors.\n");
1090 fprintf(stderr, " --include <expr> select sites for which the expression is true\n");
1091 fprintf(stderr, " -i, --ignore-homref skip hom-ref genotypes (0/0)\n");
1092 fprintf(stderr, " --include-noalt include sites with no ALT allele (ignored by default)\n");
1093 fprintf(stderr, " -I, --skip-indels skip indels as their genotypes are enriched for errors\n");
1094 fprintf(stderr, " -m, --genetic-map <file> genetic map in IMPUTE2 format, single file or mask, where string \"{CHROM}\"\n");
1095 fprintf(stderr, " is replaced with chromosome name\n");
1096 fprintf(stderr, " -M, --rec-rate <float> constant recombination rate per bp\n");
1097 fprintf(stderr, " -o, --output <file> write output to a file [standard output]\n");
1098 fprintf(stderr, " -O, --output-type [srz] output s:per-site, r:regions, z:compressed [sr]\n");
1099 fprintf(stderr, " -r, --regions <region> restrict to comma-separated list of regions\n");
1100 fprintf(stderr, " -R, --regions-file <file> restrict to regions listed in a file\n");
1101 fprintf(stderr, " --regions-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [1]\n");
1102 fprintf(stderr, " -s, --samples <list> list of samples to analyze [all samples]\n");
1103 fprintf(stderr, " -S, --samples-file <file> file of samples to analyze [all samples]\n");
1104 fprintf(stderr, " -t, --targets <region> similar to -r but streams rather than index-jumps\n");
1105 fprintf(stderr, " -T, --targets-file <file> similar to -R but streams rather than index-jumps\n");
1106 fprintf(stderr, " --targets-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [0]\n");
1107 fprintf(stderr, " --threads <int> use multithreading with <int> worker threads [0]\n");
1108 fprintf(stderr, "\n");
1109 fprintf(stderr, "HMM Options:\n");
1110 fprintf(stderr, " -a, --hw-to-az <float> P(AZ|HW) transition probability from HW (Hardy-Weinberg) to AZ (autozygous) state [6.7e-8]\n");
1111 fprintf(stderr, " -H, --az-to-hw <float> P(HW|AZ) transition probability from AZ to HW state [5e-9]\n");
1112 fprintf(stderr, " -V, --viterbi-training <float> estimate HMM parameters, <float> is the convergence threshold, e.g. 1e-10 (experimental)\n");
1113 fprintf(stderr, "\n");
1114 exit(1);
1115 }
1116
1117 int main_vcfroh(int argc, char *argv[])
1118 {
1119 int c;
1120 args_t *args = (args_t*) calloc(1,sizeof(args_t));
1121 args->argc = argc; args->argv = argv;
1122 args->files = bcf_sr_init();
1123 args->t2AZ = 6.7e-8;
1124 args->t2HW = 5e-9;
1125 args->rec_rate = 0;
1126 int regions_is_file = 0, targets_is_file = 0;
1127 int regions_overlap = 1;
1128 int targets_overlap = 0;
1129
1130 static struct option loptions[] =
1131 {
1132 {"AF-tag",1,0,0},
1133 {"AF-file",1,0,1},
1134 {"AF-dflt",1,0,2},
1135 {"include",1,0,3},
1136 {"exclude",1,0,4},
1137 {"include-noalt",0,0,5},
1138 {"buffer-size",1,0,'b'},
1139 {"ignore-homref",0,0,'i'},
1140 {"estimate-AF",1,0,'e'},
1141 {"output",1,0,'o'},
1142 {"output-type",1,0,'O'},
1143 {"GTs-only",1,0,'G'},
1144 {"samples",1,0,'s'},
1145 {"samples-file",1,0,'S'},
1146 {"hw-to-az",1,0,'a'},
1147 {"az-to-hw",1,0,'H'},
1148 {"viterbi-training",1,0,'V'},
1149 {"targets",1,0,'t'},
1150 {"targets-file",1,0,'T'},
1151 {"targets-overlap",required_argument,NULL,6},
1152 {"regions",1,0,'r'},
1153 {"regions-file",1,0,'R'},
1154 {"regions-overlap",required_argument,NULL,7},
1155 {"genetic-map",1,0,'m'},
1156 {"rec-rate",1,0,'M'},
1157 {"skip-indels",0,0,'I'},
1158 {"threads",1,0,9},
1159 {0,0,0,0}
1160 };
1161
1162 int naf_opts = 0;
1163 char *tmp;
1164 while ((c = getopt_long(argc, argv, "h?r:R:t:T:H:a:s:S:m:M:G:Ia:e:V:b:O:o:i",loptions,NULL)) >= 0) {
1165 switch (c) {
1166 case 0: args->af_tag = optarg; naf_opts++; break;
1167 case 1: args->af_fname = optarg; naf_opts++; break;
1168 case 2:
1169 args->dflt_AF = strtod(optarg,&tmp);
1170 if ( *tmp ) error("Could not parse: --AF-dflt %s\n", optarg);
1171 break;
1172 case 3 :
1173 if ( args->filter_str ) error("Error: only one --include or --exclude expression can be given, and they cannot be combined\n");
1174 args->filter_str = optarg; args->filter_logic |= FLT_INCLUDE; break;
1175 case 4 :
1176 if ( args->filter_str ) error("Error: only one --include or --exclude expression can be given, and they cannot be combined\n");
1177 args->filter_str = optarg; args->filter_logic |= FLT_EXCLUDE; break;
1178 case 5: args->include_noalt_sites = 1; break;
1179 case 'o': args->output_fname = optarg; break;
1180 case 'O':
1181 if ( strchr(optarg,'s') || strchr(optarg,'S') ) args->output_type |= OUTPUT_ST;
1182 if ( strchr(optarg,'r') || strchr(optarg,'R') ) args->output_type |= OUTPUT_RG;
1183 if ( strchr(optarg,'z') || strchr(optarg,'z') ) args->output_type |= OUTPUT_GZ;
1184 break;
1185 case 'e': args->estimate_AF = optarg; naf_opts++; break;
1186 case 'b': args->buffer_size = optarg; break;
1187 case 'i': args->skip_homref = 1; break;
1188 case 'I': args->snps_only = 1; break;
1189 case 'G':
1190 args->fake_PLs = 1;
1191 args->unseen_PL = strtod(optarg,&tmp);
1192 if ( *tmp ) error("Could not parse: -G %s\n", optarg);
1193 args->unseen_PL = pow(10,-args->unseen_PL/10.);
1194 break;
1195 case 'm': args->genmap_fname = optarg; break;
1196 case 'M':
1197 args->rec_rate = strtod(optarg,&tmp);
1198 if ( *tmp ) error("Could not parse: -M %s\n", optarg);
1199 break;
1200 case 's': args->samples = strdup(optarg); break;
1201 case 'S': args->samples = strdup(optarg); args->samples_is_file = 1; break;
1202 case 'a':
1203 args->t2AZ = strtod(optarg,&tmp);
1204 if ( *tmp ) error("Could not parse: -a %s\n", optarg);
1205 break;
1206 case 'H':
1207 args->t2HW = strtod(optarg,&tmp);
1208 if ( *tmp ) error("Could not parse: -H %s\n", optarg);
1209 break;
1210 case 't': args->targets_list = optarg; break;
1211 case 'T': args->targets_list = optarg; targets_is_file = 1; break;
1212 case 'r': args->regions_list = optarg; break;
1213 case 'R': args->regions_list = optarg; regions_is_file = 1; break;
1214 case 6 :
1215 targets_overlap = parse_overlap_option(optarg);
1216 if ( targets_overlap < 0 ) error("Could not parse: --targets-overlap %s\n",optarg);
1217 break;
1218 case 7 :
1219 regions_overlap = parse_overlap_option(optarg);
1220 if ( regions_overlap < 0 ) error("Could not parse: --regions-overlap %s\n",optarg);
1221 break;
1222 case 9 : args->n_threads = strtol(optarg, 0, 0); break;
1223 case 'V':
1224 args->vi_training = 1;
1225 args->baum_welch_th = strtod(optarg,&tmp);
1226 if ( *tmp ) error("Could not parse: --viterbi-training %s\n", optarg);
1227 break;
1228 case 'h':
1229 case '?': usage(args); break;
1230 default: error("Unknown argument: %s\n", optarg);
1231 }
1232 }
1233 if ( !args->output_fname ) args->output_fname = "stdout";
1234 if ( !args->output_type || args->output_type==OUTPUT_GZ ) args->output_type |= OUTPUT_ST|OUTPUT_RG;
1235 char *fname = NULL;
1236 if ( optind==argc )
1237 {
1238 if ( !isatty(fileno((FILE *)stdin)) ) fname = "-"; // reading from stdin
1239 else usage(args);
1240 }
1241 else fname = argv[optind];
1242
1243 if ( args->vi_training && args->buffer_size ) error("Error: cannot use -b with -V\n");
1244 if ( args->t2AZ<0 || args->t2AZ>1 ) error("Error: The parameter --hw-to-az is not in [0,1] .. %e\n", args->t2AZ);
1245 if ( args->t2HW<0 || args->t2HW>1 ) error("Error: The parameter --az-to-hw is not in [0,1] .. %e\n", args->t2HW);
1246 if ( naf_opts>1 ) error("Error: The options --AF-tag, --AF-file and -e are mutually exclusive\n");
1247 if ( args->af_fname && args->targets_list ) error("Error: The options --AF-file and -t are mutually exclusive\n");
1248 if ( args->regions_list )
1249 {
1250 bcf_sr_set_opt(args->files,BCF_SR_REGIONS_OVERLAP,regions_overlap);
1251 if ( bcf_sr_set_regions(args->files, args->regions_list, regions_is_file)<0 )
1252 error("Failed to read the regions: %s\n", args->regions_list);
1253 }
1254 if ( args->targets_list )
1255 {
1256 bcf_sr_set_opt(args->files,BCF_SR_TARGETS_OVERLAP,targets_overlap);
1257 if ( bcf_sr_set_targets(args->files, args->targets_list, targets_is_file, 0)<0 )
1258 error("Failed to read the targets: %s\n", args->targets_list);
1259 }
1260 if ( args->af_fname )
1261 {
1262 if ( bcf_sr_set_targets(args->files, args->af_fname, 1, 3)<0 )
1263 error("Failed to read the targets: %s\n", args->af_fname);
1264 }
1265 if ( args->n_threads && bcf_sr_set_threads(args->files, args->n_threads)<0)
1266 error("Failed to create threads\n");
1267 if ( !bcf_sr_add_reader(args->files, fname) ) error("Failed to read from %s: %s\n", !strcmp("-",fname)?"standard input":fname,bcf_sr_strerror(args->files->errnum));
1268
1269 init_data(args);
1270 while ( bcf_sr_next_line(args->files) )
1271 {
1272 args->ntot++;
1273 bcf1_t *line = bcf_sr_get_line(args->files,0);
1274 if ( args->filter )
1275 {
1276 int pass = filter_test(args->filter, line, NULL);
1277 if ( args->filter_logic & FLT_EXCLUDE ) pass = pass ? 0 : 1;
1278 if ( !pass ) { args->nfiltered++; continue; }
1279 }
1280 vcfroh(args, line);
1281 }
1282 vcfroh(args, NULL);
1283 int i, nmin = 0;
1284 for (i=0; i<args->roh_smpl->n; i++)
1285 if ( !i || args->smpl[i].nused < nmin ) nmin = args->smpl[i].nused;
1286 if ( args->af_fname )
1287 fprintf(stderr,"Number of lines overlapping with --AF-file/processed: %d/%d\n", args->ntot,nmin);
1288 else
1289 fprintf(stderr,"Number of lines total/processed: %d/%d\n", args->ntot,nmin);
1290 fprintf(stderr,"Number of lines filtered/no AF/no alt/multiallelic/dup: %d/%d/%d/%d/%d\n", args->nfiltered,args->nno_af,args->nno_alt,args->nmultiallelic,args->ndup);
1291 if ( nmin==0 )
1292 {
1293 fprintf(stderr,"No usable sites were found.\n");
1294 if ( !naf_opts && !args->dflt_AF ) fprintf(stderr, " Consider using one of the AF options.\n");
1295 }
1296 destroy_data(args);
1297 free(args);
1298 return 0;
1299 }
1300
1301