Debian Codegraph @

bcftools/vcfroh.c.pysam.c

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