Debian Codegraph @

bcftools/vcfstats.c

raw symbols SCIP
1 /* vcfstats.c -- Produces stats which can be plotted using plot-vcfstats.
2
3 Copyright (C) 2012-2024 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 /*
26 Notes and known issues:
27 - SN ts/tv calculation includes all non-ref alleles listed in ALT while per-sample ts/tv
28 takes the first non-ref allele only, something to consider with many non-ref HETs.
29 */
30 #include <stdio.h>
31 #include <stdarg.h>
32 #include <unistd.h>
33 #include <getopt.h>
34 #include <assert.h>
35 #include <math.h>
36 #include <htslib/vcf.h>
37 #include <htslib/synced_bcf_reader.h>
38 #include <htslib/vcfutils.h>
39 #include <htslib/faidx.h>
40 #include <inttypes.h>
41 #include "bcftools.h"
42 #include "filter.h"
43 #include "bin.h"
44 #include "dist.h"
45
46 // Logic of the filters: include or exclude sites which match the filters?
47 #define FLT_INCLUDE 1
48 #define FLT_EXCLUDE 2
49
50 #define HWE_STATS 1
51 #define QUAL_STATS 1
52 #define IRC_STATS 1
53 #define IRC_RLEN 10
54 #define NA_STRING "0"
55
56 typedef struct
57 {
58 char *tag;
59 float min, max;
60 uint64_t *vals_ts, *vals_tv;
61 void *val;
62 int nbins, type, m_val, idx;
63 }
64 user_stats_t;
65
66 typedef struct
67 {
68 int min, max, step, m_vals;
69 uint64_t *vals;
70 }
71 idist_t;
72
73 // variant allele frequency (fraction of alt allele in pileup as determined from AD) collected into 0.05 bins
74 typedef struct
75 {
76 int snv[21], indel[21];
77 }
78 vaf_t;
79
80 typedef struct
81 {
82 uint64_t n_snps, n_indels, n_mnps, n_others, n_mals, n_snp_mals, n_records, n_noalts;
83 int *af_ts, *af_tv, *af_snps; // first bin of af_* stats are singletons
84 #if HWE_STATS
85 int *af_hwe;
86 #endif
87 #if IRC_STATS
88 int n_repeat[IRC_RLEN][4], n_repeat_na; // number of indels which are repeat-consistent, repeat-inconsistent (dels and ins), and not applicable
89 int *af_repeats[3];
90 #endif
91 int ts_alt1, tv_alt1;
92 #if QUAL_STATS
93 // Values are rounded to one significant digit and 1 is added (Q*10+1); missing and negative values go in the first bin
94 // Only SNPs that are the 1st alternate allele are counted
95 dist_t *qual_ts, *qual_tv, *qual_indels;
96 #endif
97 int *insertions, *deletions, m_indel; // maximum indel length
98 int in_frame, out_frame, na_frame, in_frame_alt1, out_frame_alt1, na_frame_alt1;
99 int subst[15];
100 int *smpl_hets, *smpl_homRR, *smpl_homAA, *smpl_ts, *smpl_tv, *smpl_indels, *smpl_ndp, *smpl_sngl;
101 int *smpl_hapRef, *smpl_hapAlt, *smpl_missing;
102 int *smpl_ins_hets, *smpl_del_hets, *smpl_ins_homs, *smpl_del_homs;
103 int *smpl_frm_shifts; // not-applicable, in-frame, out-frame
104 vaf_t vaf, *smpl_vaf; // total (INFO/AD) and per-sample (FMT/VAF) VAF distributions
105 unsigned long int *smpl_dp;
106 idist_t dp, dp_sites;
107 int nusr;
108 user_stats_t *usr;
109 double *dvaf; // distribution of the mean indel-allele frequency by length: -m_indel,-(m_indel-1),...-1,0,1,..,m_indel
110 uint32_t *nvaf;
111 }
112 stats_t;
113
114 typedef struct
115 {
116 uint64_t gt2gt[5][5]; // number of RR->RR, RR->RA, etc. matches/mismatches; see type2stats
117 /*
118 Pearson's R^2 is used for aggregate R^2
119 y, yy .. sum of dosage and squared dosage in the query VCF (second file)
120 x, xx .. sum of squared dosage in the truth VCF (first file)
121 n .. number of genotypes
122 */
123 double y, yy, x, xx, yx, n;
124 }
125 gtcmp_t;
126
127 typedef struct
128 {
129 char *seq;
130 int pos, cnt, len;
131 }
132 _idc1_t;
133 typedef struct
134 {
135 faidx_t *ref;
136 _idc1_t *dat;
137 int ndat, mdat;
138 }
139 indel_ctx_t;
140
141 typedef struct
142 {
143 // stats
144 stats_t stats[3];
145 int *tmp_iaf, ntmp_iaf, m_af, m_qual, naf_hwe, mtmp_frm;
146 uint8_t *tmp_frm;
147 int dp_min, dp_max, dp_step;
148 gtcmp_t *smpl_gts_snps, *smpl_gts_indels;
149 gtcmp_t *af_gts_snps, *af_gts_indels; // first bin of af_* stats are singletons
150 bin_t *af_bins;
151 float *farr;
152 int32_t *iarr;
153 int mfarr, miarr;
154 int nref_tot, nhet_tot, nalt_tot, n_nref, i_nref;
155
156 // indel context
157 indel_ctx_t *indel_ctx;
158 char *ref_fname;
159
160 // user stats
161 int nusr;
162 user_stats_t *usr;
163
164 // other
165 bcf_srs_t *files;
166 bcf_sr_regions_t *exons;
167 char **argv, *exons_fname, *regions_list, *samples_list, *targets_list, *af_bins_list, *af_tag;
168 int argc, verbose_sites, first_allele_only, samples_is_file;
169 int split_by_id, nstats;
170
171 filter_t *filter[2];
172 char *filter_str;
173 int filter_logic; // include or exclude sites which match the filters? One of FLT_INCLUDE/FLT_EXCLUDE
174 int n_threads;
175 }
176 args_t;
177
178 static int type2dosage[6], type2ploidy[6], type2stats[7];
179
180 static void idist_init(idist_t *d, int min, int max, int step)
181 {
182 d->min = min; d->max = max; d->step = step;
183 d->m_vals = 4 + (d->max - d->min)/d->step;
184 d->vals = (uint64_t*) calloc(d->m_vals,sizeof(uint64_t));
185 }
186 static void idist_destroy(idist_t *d)
187 {
188 if ( d->vals ) free(d->vals);
189 }
190 static inline uint64_t *idist(idist_t *d, int val)
191 {
192 if ( val < d->min ) return &d->vals[0];
193 if ( val > d->max ) return &d->vals[d->m_vals-1];
194 return &d->vals[1 + (val - d->min) / d->step];
195 }
196 static inline int idist_i2bin(idist_t *d, int i)
197 {
198 if ( i<=0 ) return d->min;
199 if ( i>= d->m_vals ) return d->max;
200 return i-1+d->min;
201 }
202
203 #define IC_DBG 0
204 #if IC_DBG
205 static void _indel_ctx_print1(_idc1_t *idc)
206 {
207 int i;
208 fprintf(stdout, "%d\t", idc->cnt);
209 for (i=0; i<idc->len; i++)
210 fputc(idc->seq[i], stdout);
211 fputc('\n', stdout);
212 }
213 static void _indel_ctx_print(indel_ctx_t *ctx)
214 {
215 int i;
216 for (i=0; i<ctx->ndat; i++)
217 _indel_ctx_print1(&ctx->dat[i]);
218 fputc('\n',stdout);
219 }
220 #endif
221 static int _indel_ctx_lookup(indel_ctx_t *ctx, char *seq, int seq_len, int *hit)
222 {
223 // binary search
224 int min = 0, max = ctx->ndat - 1;
225 while ( min<=max )
226 {
227 int i = (min+max)/2;
228 int cmp = strncmp(seq, ctx->dat[i].seq, seq_len);
229 if ( cmp<0 ) max = i - 1;
230 else if ( cmp>0 ) min = i + 1;
231 else
232 {
233 if ( seq_len==ctx->dat[i].len )
234 {
235 *hit = 1;
236 return i;
237 }
238 else if ( seq_len<ctx->dat[i].len ) max = i - 1;
239 else min = i + 1;
240 }
241 }
242 *hit = 0;
243 return max;
244 }
245 static void _indel_ctx_insert(indel_ctx_t *ctx, char *seq, int seq_len, int pos)
246 {
247 int idat, hit, i;
248 idat = _indel_ctx_lookup(ctx, seq, seq_len, &hit);
249 if ( !hit )
250 {
251 if ( pos>0 ) return;
252 idat++;
253 ctx->ndat++;
254 hts_expand(_idc1_t, ctx->ndat+1, ctx->mdat, ctx->dat);
255 if ( idat<ctx->ndat && ctx->ndat>1 )
256 memmove(&ctx->dat[idat+1], &ctx->dat[idat], (ctx->ndat - idat - 1)*sizeof(_idc1_t));
257 ctx->dat[idat].len = seq_len;
258 ctx->dat[idat].cnt = 1;
259 ctx->dat[idat].pos = pos;
260 ctx->dat[idat].seq = (char*) malloc(sizeof(char)*(seq_len+1));
261 for (i=0; i<seq_len; i++) ctx->dat[idat].seq[i] = seq[i];
262 ctx->dat[idat].seq[i] = 0;
263 return;
264 }
265 if ( ctx->dat[idat].pos + seq_len == pos )
266 {
267 ctx->dat[idat].cnt++;
268 ctx->dat[idat].pos = pos;
269 }
270 }
271 indel_ctx_t *indel_ctx_init(char *fa_ref_fname)
272 {
273 indel_ctx_t *ctx = (indel_ctx_t *) calloc(1,sizeof(indel_ctx_t));
274 ctx->ref = fai_load(fa_ref_fname);
275 if ( !ctx->ref )
276 {
277 free(ctx);
278 return NULL;
279 }
280 return ctx;
281 }
282 void indel_ctx_destroy(indel_ctx_t *ctx)
283 {
284 fai_destroy(ctx->ref);
285 if ( ctx->mdat ) free(ctx->dat);
286 free(ctx);
287 }
288 /**
289 * indel_ctx_type() - determine indel context type
290 * @ctx:
291 * @chr: chromosome name
292 * @pos: position of the first @ref base, 1-based
293 * @ref: reference allele
294 * @alt: alternate allele. Only first of multiple comma-separated alleles is
295 * considered
296 * @nrep: number of repeated elements (w)
297 * @nlen: length of a single repeat element (w)
298 *
299 * Returns the INDEL length, negative for deletions, positive for insertions
300 */
301 int indel_ctx_type(indel_ctx_t *ctx, char *chr, int pos, char *ref, char *alt, int *nrep, int *nlen)
302 {
303 const int win_size = 50; // hard-wired for now
304 const int rep_len = IRC_RLEN; // hard-wired for now
305
306 int ref_len = strlen(ref);
307 int alt_len = 0;
308 while ( alt[alt_len] && alt[alt_len]!=',' ) alt_len++;
309
310 int i, fai_ref_len;
311 char *fai_ref = faidx_fetch_seq(ctx->ref, chr, pos-1, pos+win_size, &fai_ref_len);
312 for (i=0; i<fai_ref_len; i++)
313 if ( (int)fai_ref[i]>96 ) fai_ref[i] -= 32;
314
315 // Sanity check: the reference sequence must match the REF allele
316 for (i=0; i<fai_ref_len && i<ref_len; i++)
317 if ( ref[i] != fai_ref[i] && ref[i] - 32 != fai_ref[i] && !iupac_consistent(fai_ref[i], ref[i]) )
318 error("\nSanity check failed, the reference sequence differs: %s:%d+%d .. %c vs %c\n", chr, pos, i, ref[i],fai_ref[i]);
319
320 // Count occurrences of all possible kmers
321 ctx->ndat = 0;
322 for (i=0; i<win_size; i++)
323 {
324 int k, kmax = rep_len <= i ? rep_len : i+1;
325 for (k=0; k<kmax; k++)
326 _indel_ctx_insert(ctx, &fai_ref[i-k+1], k+1, i-k);
327 }
328
329 #if IC_DBG
330 fprintf(stdout,"ref: %s\n", ref);
331 fprintf(stdout,"alt: %s\n", alt);
332 fprintf(stdout,"ctx: %s\n", fai_ref);
333 _indel_ctx_print(ctx);
334 #endif
335
336 int max_cnt = 0, max_len = 0;
337 for (i=0; i<ctx->ndat; i++)
338 {
339 if ( max_cnt < ctx->dat[i].cnt || (max_cnt==ctx->dat[i].cnt && max_len < ctx->dat[i].len) )
340 {
341 max_cnt = ctx->dat[i].cnt;
342 max_len = ctx->dat[i].len;
343 }
344 free(ctx->dat[i].seq);
345 }
346 free(fai_ref);
347
348 *nrep = max_cnt;
349 *nlen = max_len;
350 return alt_len - ref_len;
351 }
352
353 static void add_user_stats(args_t *args, char *str)
354 {
355 args->nusr++;
356 args->usr = (user_stats_t*) realloc(args->usr,sizeof(user_stats_t)*args->nusr);
357 user_stats_t *usr = &args->usr[args->nusr-1];
358 memset(usr,0,sizeof(*usr));
359 usr->min = 0;
360 usr->max = 1;
361 usr->nbins = 100;
362 usr->idx = 0;
363
364 char *tmp = str;
365 while ( *tmp && *tmp!=':' ) tmp++;
366
367 // Tag with an index or just tag? (e.g. PV4[1] vs DP)
368 if ( tmp > str && tmp[-1]==']' )
369 {
370 char *ptr = tmp;
371 while ( ptr>str && *ptr!='[' ) ptr--;
372 if ( *ptr=='[' )
373 {
374 char *ptr2;
375 usr->idx = strtol(ptr+1, &ptr2, 10);
376 if ( ptr+1==ptr2 || ptr2 != tmp-1 ) error("Could not parse the index in \"%s\" (ptr=%s;ptr2=%s(%p),tmp=%s(%p),idx=%d)\n", str,ptr,ptr2,ptr2,tmp,tmp,usr->idx);
377 if ( usr->idx<0 ) error("Error: negative index is not allowed: \"%s\"\n", str);
378 *ptr = 0;
379 }
380 }
381
382 usr->tag = (char*)calloc(tmp-str+2,sizeof(char));
383 memcpy(usr->tag,str,tmp-str);
384
385 if ( *tmp )
386 {
387 char *ptr = ++tmp;
388 usr->min = strtod(tmp, &ptr);
389 if ( tmp==ptr ) error("Could not parse %s\n", str);
390 tmp = ptr+1;
391 }
392 if ( *tmp )
393 {
394 char *ptr = tmp;
395 usr->max = strtod(tmp, &ptr);
396 if ( tmp==ptr ) error("Could not parse %s\n", str);
397 tmp = ptr+1;
398 }
399 if ( *tmp )
400 {
401 char *ptr = tmp;
402 usr->nbins = strtol(tmp, &ptr, 10);
403 if ( tmp==ptr ) error("Could not parse %s\n", str);
404 if ( usr->nbins<=0 ) error("Number of bins does not make sense (%d): %s.\n", usr->nbins, str);
405 }
406 }
407 static void init_user_stats(args_t *args, bcf_hdr_t *hdr, stats_t *stats)
408 {
409 stats->nusr = args->nusr;
410 stats->usr = (user_stats_t*)malloc(sizeof(user_stats_t)*args->nusr);
411 if (args->nusr)
412 memcpy(stats->usr,args->usr,args->nusr*sizeof(user_stats_t));
413 int i;
414 for (i=0; i<stats->nusr; i++)
415 {
416 user_stats_t *usr = &stats->usr[i];
417 usr->vals_ts = (uint64_t*)calloc(usr->nbins,sizeof(uint64_t));
418 usr->vals_tv = (uint64_t*)calloc(usr->nbins,sizeof(uint64_t));
419 int id = bcf_hdr_id2int(hdr,BCF_DT_ID,usr->tag);
420 if ( !bcf_hdr_idinfo_exists(hdr,BCF_HL_INFO,id) ) error("The INFO tag \"%s\" is not defined in the header\n", usr->tag);
421 usr->type = bcf_hdr_id2type(hdr,BCF_HL_INFO,id);
422 if ( usr->type!=BCF_HT_REAL && usr->type!=BCF_HT_INT ) error("The INFO tag \"%s\" is not of Float or Integer type (%d)\n", usr->tag, usr->type);
423 }
424 }
425 static void init_stats(args_t *args)
426 {
427 int i;
428 args->nstats = args->files->nreaders==1 ? 1 : 3;
429 if ( args->split_by_id ) args->nstats = 2;
430
431 if ( args->filter_str )
432 {
433 args->filter[0] = filter_init(bcf_sr_get_header(args->files,0), args->filter_str);
434 if ( args->files->nreaders==2 )
435 args->filter[1] = filter_init(bcf_sr_get_header(args->files,1), args->filter_str);
436 args->files->max_unpack |= filter_max_unpack(args->filter[0]);
437 }
438
439 // AF corresponds to AC but is more robust to mixtures of haploid and diploid GTs
440 if ( !args->af_bins_list )
441 {
442 args->m_af = 101;
443 for (i=0; i<args->files->nreaders; i++)
444 if ( bcf_hdr_nsamples(args->files->readers[i].header) + 1> args->m_af )
445 args->m_af = bcf_hdr_nsamples(args->files->readers[i].header) + 1;
446 }
447 else
448 {
449 args->af_bins = bin_init(args->af_bins_list,0,1);
450
451 // m_af is used also for other af arrays, where the first bin is for
452 // singletons. However, since the last element is unused in af_bins
453 // (n boundaries form n-1 intervals), the m_af count is good for both.
454 args->m_af = bin_get_size(args->af_bins);
455 }
456
457 bcf_hdr_t *hdr = bcf_sr_get_header(args->files,0);
458 if ( args->af_tag && !bcf_hdr_idinfo_exists(hdr,BCF_HL_INFO,bcf_hdr_id2int(hdr,BCF_DT_ID,args->af_tag)) )
459 error("No such INFO tag: %s\n", args->af_tag);
460
461 int id, has_fmt_ad = ((id=bcf_hdr_id2int(hdr,BCF_DT_ID,"AD"))>=0 && bcf_hdr_idinfo_exists(hdr,BCF_HL_FMT,id)) ? 1 : 0;
462
463 #if QUAL_STATS
464 args->m_qual = 999;
465 #endif
466 #if HWE_STATS
467 args->naf_hwe = 100;
468 #endif
469
470 if ( args->samples_list )
471 {
472 if ( !bcf_sr_set_samples(args->files,args->samples_list,args->samples_is_file) )
473 {
474 if ( !bcf_hdr_nsamples(args->files->readers[0].header) )
475 error("No sample columns in %s\n", args->files->readers[0].fname);
476 error("Unable to parse the samples: \"%s\"\n", args->samples_list);
477 }
478 args->af_gts_snps = (gtcmp_t *) calloc(args->m_af,sizeof(gtcmp_t));
479 args->af_gts_indels = (gtcmp_t *) calloc(args->m_af,sizeof(gtcmp_t));
480 args->smpl_gts_snps = (gtcmp_t *) calloc(args->files->n_smpl,sizeof(gtcmp_t));
481 args->smpl_gts_indels = (gtcmp_t *) calloc(args->files->n_smpl,sizeof(gtcmp_t));
482 }
483 for (i=0; i<args->nstats; i++)
484 {
485 stats_t *stats = &args->stats[i];
486 stats->m_indel = 60;
487 stats->insertions = (int*) calloc(stats->m_indel,sizeof(int));
488 stats->deletions = (int*) calloc(stats->m_indel,sizeof(int));
489 stats->af_ts = (int*) calloc(args->m_af,sizeof(int));
490 stats->af_tv = (int*) calloc(args->m_af,sizeof(int));
491 stats->af_snps = (int*) calloc(args->m_af,sizeof(int));
492 int j;
493 for (j=0; j<3; j++) stats->af_repeats[j] = (int*) calloc(args->m_af,sizeof(int));
494 #if QUAL_STATS
495 stats->qual_ts = dist_init(5);
496 stats->qual_tv = dist_init(5);
497 stats->qual_indels = dist_init(5);
498 #endif
499 if ( args->files->n_smpl )
500 {
501 stats->smpl_missing = (int *) calloc(args->files->n_smpl,sizeof(int));
502 stats->smpl_hets = (int *) calloc(args->files->n_smpl,sizeof(int));
503 stats->smpl_homAA = (int *) calloc(args->files->n_smpl,sizeof(int));
504 stats->smpl_homRR = (int *) calloc(args->files->n_smpl,sizeof(int));
505 stats->smpl_hapRef = (int *) calloc(args->files->n_smpl,sizeof(int));
506 stats->smpl_hapAlt = (int *) calloc(args->files->n_smpl,sizeof(int));
507 stats->smpl_ins_hets = (int *) calloc(args->files->n_smpl,sizeof(int));
508 stats->smpl_del_hets = (int *) calloc(args->files->n_smpl,sizeof(int));
509 stats->smpl_ins_homs = (int *) calloc(args->files->n_smpl,sizeof(int));
510 stats->smpl_del_homs = (int *) calloc(args->files->n_smpl,sizeof(int));
511 stats->smpl_ts = (int *) calloc(args->files->n_smpl,sizeof(int));
512 stats->smpl_tv = (int *) calloc(args->files->n_smpl,sizeof(int));
513 stats->smpl_indels = (int *) calloc(args->files->n_smpl,sizeof(int));
514 stats->smpl_dp = (unsigned long int *) calloc(args->files->n_smpl,sizeof(unsigned long int));
515 stats->smpl_ndp = (int *) calloc(args->files->n_smpl,sizeof(int));
516 stats->smpl_sngl = (int *) calloc(args->files->n_smpl,sizeof(int));
517 if ( has_fmt_ad )
518 stats->smpl_vaf = (vaf_t*) calloc(args->files->n_smpl,sizeof(vaf_t));
519 #if HWE_STATS
520 stats->af_hwe = (int*) calloc(args->m_af*args->naf_hwe,sizeof(int));
521 #endif
522 if ( args->exons_fname )
523 stats->smpl_frm_shifts = (int*) calloc(args->files->n_smpl*3,sizeof(int));
524 stats->nvaf = (uint32_t*) calloc(stats->m_indel*2+1,sizeof(*stats->nvaf));
525 stats->dvaf = (double*) calloc(stats->m_indel*2+1,sizeof(*stats->dvaf));
526 }
527 idist_init(&stats->dp, args->dp_min,args->dp_max,args->dp_step);
528 idist_init(&stats->dp_sites, args->dp_min,args->dp_max,args->dp_step);
529 init_user_stats(args, i!=1 ? args->files->readers[0].header : args->files->readers[1].header, stats);
530 }
531
532 if ( args->exons_fname )
533 {
534 args->exons = bcf_sr_regions_init(args->exons_fname,1,0,1,2);
535 if ( !args->exons )
536 error("Error occurred while reading, was the file compressed with bgzip: %s?\n", args->exons_fname);
537 }
538
539 #if IRC_STATS
540 if ( args->ref_fname )
541 args->indel_ctx = indel_ctx_init(args->ref_fname);
542 #endif
543
544 type2dosage[GT_HOM_RR] = 0;
545 type2dosage[GT_HET_RA] = 1;
546 type2dosage[GT_HOM_AA] = 2;
547 type2dosage[GT_HET_AA] = 2;
548 type2dosage[GT_HAPL_R] = 0;
549 type2dosage[GT_HAPL_A] = 1;
550
551 type2ploidy[GT_HOM_RR] = 1;
552 type2ploidy[GT_HET_RA] = 1;
553 type2ploidy[GT_HOM_AA] = 1;
554 type2ploidy[GT_HET_AA] = 1;
555 type2ploidy[GT_HAPL_R] = -1;
556 type2ploidy[GT_HAPL_A] = -1;
557
558 type2stats[GT_HOM_RR] = 0;
559 type2stats[GT_HET_RA] = 1;
560 type2stats[GT_HOM_AA] = 2;
561 type2stats[GT_HET_AA] = 3;
562 type2stats[GT_HAPL_R] = 0;
563 type2stats[GT_HAPL_A] = 2;
564 type2stats[GT_UNKN] = 4;
565
566 }
567 static void destroy_stats(args_t *args)
568 {
569 int id, j;
570 for (id=0; id<args->nstats; id++)
571 {
572 stats_t *stats = &args->stats[id];
573 if (stats->af_ts) free(stats->af_ts);
574 if (stats->af_tv) free(stats->af_tv);
575 if (stats->af_snps) free(stats->af_snps);
576 for (j=0; j<3; j++)
577 if (stats->af_repeats[j]) free(stats->af_repeats[j]);
578 #if QUAL_STATS
579 if (stats->qual_ts) dist_destroy(stats->qual_ts);
580 if (stats->qual_tv) dist_destroy(stats->qual_tv);
581 if (stats->qual_indels) dist_destroy(stats->qual_indels);
582 #endif
583 #if HWE_STATS
584 free(stats->af_hwe);
585 #endif
586 free(stats->insertions);
587 free(stats->deletions);
588 free(stats->smpl_missing);
589 free(stats->smpl_hets);
590 free(stats->smpl_homAA);
591 free(stats->smpl_homRR);
592 free(stats->smpl_hapRef);
593 free(stats->smpl_hapAlt);
594 free(stats->smpl_ins_homs);
595 free(stats->smpl_del_homs);
596 free(stats->smpl_ins_hets);
597 free(stats->smpl_del_hets);
598 free(stats->smpl_ts);
599 free(stats->smpl_tv);
600 free(stats->smpl_indels);
601 free(stats->smpl_dp);
602 free(stats->smpl_ndp);
603 free(stats->smpl_sngl);
604 free(stats->smpl_vaf);
605 idist_destroy(&stats->dp);
606 idist_destroy(&stats->dp_sites);
607 for (j=0; j<stats->nusr; j++)
608 {
609 free(stats->usr[j].vals_ts);
610 free(stats->usr[j].vals_tv);
611 free(stats->usr[j].val);
612 }
613 free(stats->usr);
614 if ( args->exons ) free(stats->smpl_frm_shifts);
615 free(stats->nvaf);
616 free(stats->dvaf);
617 }
618 for (j=0; j<args->nusr; j++) free(args->usr[j].tag);
619 if ( args->af_bins ) bin_destroy(args->af_bins);
620 free(args->farr);
621 free(args->iarr);
622 free(args->usr);
623 free(args->tmp_frm);
624 free(args->tmp_iaf);
625 if (args->exons) bcf_sr_regions_destroy(args->exons);
626 free(args->af_gts_snps);
627 free(args->af_gts_indels);
628 free(args->smpl_gts_snps);
629 free(args->smpl_gts_indels);
630 if (args->indel_ctx) indel_ctx_destroy(args->indel_ctx);
631 if (args->filter[0]) filter_destroy(args->filter[0]);
632 if (args->filter[1]) filter_destroy(args->filter[1]);
633 }
634
635 // The arary tmp_iaf keeps the index of AF bin for each allele, the first bin is for singletons.
636 // The number of bins, either m_af (101) or as given by the user in --af-bins
637 static void init_iaf(args_t *args, bcf_sr_t *reader)
638 {
639 bcf1_t *line = reader->buffer[0];
640 hts_expand(int32_t,line->n_allele,args->ntmp_iaf,args->tmp_iaf);
641
642 int i, ret;
643 if ( args->af_tag )
644 {
645 ret = bcf_get_info_float(reader->header, line, args->af_tag, &args->farr, &args->mfarr);
646 if ( ret<=0 || ret!=line->n_allele-1 )
647 {
648 // the AF tag is not present or wrong number of values, put in the singletons/unknown bin
649 for (i=0; i<line->n_allele; i++) args->tmp_iaf[i] = 0;
650 return;
651 }
652 args->tmp_iaf[0] = 0;
653 for (i=1; i<line->n_allele; i++)
654 {
655 float af = args->farr[i-1];
656 if ( af<0 ) af = 0;
657 else if ( af>1 ) af = 1;
658 int iaf = args->af_bins ? bin_get_idx(args->af_bins,af) : af*(args->m_af-2);
659 args->tmp_iaf[i] = iaf + 1; // the first tmp_iaf bin is reserved for singletons
660 }
661 return;
662 }
663
664 // tmp_iaf is first filled with AC counts in calc_ac and then transformed to
665 // an index to af_gts_snps
666 ret = bcf_calc_ac(reader->header, line, args->tmp_iaf, args->samples_list ? BCF_UN_INFO|BCF_UN_FMT : BCF_UN_INFO);
667 if ( !ret )
668 {
669 for (i=0; i<line->n_allele; i++) args->tmp_iaf[i] = 0; // singletons/unknown bin
670 return;
671 }
672
673 int an = 0;
674 for (i=0; i<line->n_allele; i++)
675 an += args->tmp_iaf[i];
676
677 args->tmp_iaf[0] = 0;
678 for (i=1; i<line->n_allele; i++)
679 {
680 if ( args->tmp_iaf[i]==1 )
681 args->tmp_iaf[i] = 0; // singletons into the first bin
682 else if ( !an )
683 args->tmp_iaf[i] = 1; // no genotype at all, put to the AF=0 bin
684 else
685 {
686 float af = (float) args->tmp_iaf[i] / an;
687 if ( af<0 ) af = 0;
688 else if ( af>1 ) af = 1;
689 int iaf = args->af_bins ? bin_get_idx(args->af_bins,af) : af*(args->m_af-2);
690 args->tmp_iaf[i] = iaf + 1;
691 }
692 }
693 }
694
695 static inline void do_mnp_stats(args_t *args, stats_t *stats, bcf_sr_t *reader)
696 {
697 stats->n_mnps++;
698 }
699
700 static inline void do_other_stats(args_t *args, stats_t *stats, bcf_sr_t *reader)
701 {
702 stats->n_others++;
703 }
704
705 static void do_indel_stats(args_t *args, stats_t *stats, bcf_sr_t *reader)
706 {
707 stats->n_indels++;
708
709 bcf1_t *line = reader->buffer[0];
710
711 #if QUAL_STATS
712 int iqual = (isnan(line->qual) || line->qual<0) ? 0 : 1 + (int)(line->qual*10);
713 dist_insert(stats->qual_indels, iqual);
714 #endif
715
716 // Check if the indel is near an exon for the frameshift statistics
717 int i, exon_overlap = 0;
718 if ( args->exons )
719 {
720 if ( !bcf_sr_regions_overlap(args->exons, bcf_seqname(reader->header,line),line->pos,line->pos) ) exon_overlap = 1;
721 hts_expand(uint8_t,line->n_allele,args->mtmp_frm,args->tmp_frm);
722 for (i=0; i<line->n_allele; i++) args->tmp_frm[i] = 0;
723 }
724
725 for (i=1; i<line->n_allele; i++)
726 {
727 if ( args->first_allele_only && i>1 ) break;
728 int is_indel = bcf_has_variant_type(line,i,VCF_INDEL);
729 if (is_indel < 0) error("bcf_has_variant_type() failed.");
730 if ( !is_indel ) continue;
731 int len = bcf_variant_length(line, i);
732
733 #if IRC_STATS
734 // Indel repeat consistency
735 if ( args->indel_ctx )
736 {
737 int nrep, nlen, ndel;
738 ndel = indel_ctx_type(args->indel_ctx, (char*)reader->header->id[BCF_DT_CTG][line->rid].key, line->pos+1, line->d.allele[0], line->d.allele[i], &nrep, &nlen);
739 if ( nlen<=1 || nrep<=1 )
740 {
741 // not a repeat or a single base repeat
742 stats->n_repeat_na++;
743 stats->af_repeats[2][ args->tmp_iaf[i] ]++;
744 }
745 else
746 {
747 if ( abs(ndel) % nlen )
748 {
749 // the length of the inserted/deleted sequence is not consistent with the repeat element
750 stats->n_repeat[nlen-1][ndel<0 ? 1 : 3]++;
751 stats->af_repeats[1][ args->tmp_iaf[i] ]++;
752 }
753 else
754 {
755 // the length consistent with the repeat
756 stats->n_repeat[nlen-1][ndel<0 ? 0 : 2]++;
757 stats->af_repeats[0][ args->tmp_iaf[i] ]++;
758 }
759 }
760 }
761 else
762 stats->af_repeats[2][ args->tmp_iaf[i] ]++;
763 #endif
764
765 // Check the frameshifts
766 int tlen = 0;
767 if ( args->exons && exon_overlap ) // there is an exon
768 {
769 if ( len>0 )
770 {
771 // insertion
772 if ( args->exons->start <= line->pos && args->exons->end > line->pos ) tlen = abs(len);
773 }
774 else if ( args->exons->start <= line->pos + abs(len) )
775 {
776 // deletion
777 tlen = abs(len);
778 if ( line->pos < args->exons->start ) // trim the beginning
779 tlen -= args->exons->start - line->pos + 1;
780 if ( args->exons->end < line->pos + abs(len) ) // trim the end
781 tlen -= line->pos + abs(len) - args->exons->end;
782 }
783 }
784 if ( tlen ) // there are some deleted/inserted bases in the exon
785 {
786 if ( tlen%3 ) { stats->out_frame++; args->tmp_frm[i] = 2; }
787 else { stats->in_frame++; args->tmp_frm[i] = 1; }
788
789 if ( i==1 )
790 {
791 if ( tlen%3 ) stats->out_frame_alt1++;
792 else stats->in_frame_alt1++;
793 }
794 }
795 else // no exon affected
796 {
797 if ( i==1 ) stats->na_frame_alt1++;
798 stats->na_frame++;
799 }
800
801
802 // Indel length distribution
803 int *ptr = stats->insertions;
804 if ( len<0 )
805 {
806 len *= -1;
807 ptr = stats->deletions;
808 }
809 if ( --len >= stats->m_indel ) len = stats->m_indel-1;
810 ptr[len]++;
811 }
812 }
813
814 static void do_user_stats(stats_t *stats, bcf_sr_t *reader, int is_ts)
815 {
816 int i, nval;
817 for (i=0; i<stats->nusr; i++)
818 {
819 user_stats_t *usr = &stats->usr[i];
820 uint64_t *vals = is_ts ? usr->vals_ts : usr->vals_tv;
821 float val;
822 if ( usr->type==BCF_HT_REAL )
823 {
824 if ( (nval=bcf_get_info_float(reader->header,reader->buffer[0],usr->tag,&usr->val,&usr->m_val))<=0 ) continue;
825 if ( usr->idx >= nval ) continue;
826 val = ((float*)usr->val)[usr->idx];
827 }
828 else
829 {
830 if ( (nval=bcf_get_info_int32(reader->header,reader->buffer[0],usr->tag,&usr->val,&usr->m_val))<=0 ) continue;
831 if ( usr->idx >= nval ) continue;
832 val = ((int32_t*)usr->val)[usr->idx];
833 }
834 int idx;
835 if ( val<=usr->min ) idx = 0;
836 else if ( val>=usr->max ) idx = usr->nbins - 1;
837 else idx = (val - usr->min)/(usr->max - usr->min) * (usr->nbins-1);
838 vals[idx]++;
839 }
840 }
841
842 static void do_snp_stats(args_t *args, stats_t *stats, bcf_sr_t *reader)
843 {
844 stats->n_snps++;
845
846 bcf1_t *line = reader->buffer[0];
847 int ref = bcf_acgt2int(*line->d.allele[0]);
848 if ( ref<0 ) return;
849
850 #if QUAL_STATS
851 int iqual = (isnan(line->qual) || line->qual<0) ? 0 : 1 + (int)(line->qual*10);
852 #endif
853
854 int i;
855 for (i=1; i<line->n_allele; i++)
856 {
857 if ( args->first_allele_only && i>1 ) break;
858 if ( !(bcf_get_variant_type(line,i)&VCF_SNP) ) continue;
859 int alt = bcf_acgt2int(*line->d.allele[i]);
860 if ( alt<0 || ref==alt ) continue;
861 stats->subst[ref<<2|alt]++;
862 int iaf = args->tmp_iaf[i];
863 stats->af_snps[iaf]++;
864 if ( abs(ref-alt)==2 )
865 {
866 if (i==1)
867 {
868 stats->ts_alt1++;
869 #if QUAL_STATS
870 dist_insert(stats->qual_ts,iqual);
871 #endif
872 do_user_stats(stats, reader, 1);
873 }
874 stats->af_ts[iaf]++;
875 }
876 else
877 {
878 if (i==1)
879 {
880 stats->tv_alt1++;
881 #if QUAL_STATS
882 dist_insert(stats->qual_tv,iqual);
883 #endif
884 do_user_stats(stats, reader, 0);
885 }
886 stats->af_tv[iaf]++;
887 }
888 }
889 }
890
891 // Returns the max non-ref AD value
892 static inline int get_ad(bcf1_t *line, bcf_fmt_t *ad_fmt_ptr, int ismpl, int *ial)
893 {
894 int iv, ad = 0;
895 *ial = 0;
896 #define BRANCH_INT(type_t,missing,vector_end) { \
897 type_t *ptr = (type_t *) (ad_fmt_ptr->p + ad_fmt_ptr->size*ismpl); \
898 for (iv=1; iv<ad_fmt_ptr->n && iv<line->n_allele; iv++) \
899 { \
900 if ( ptr[iv]==vector_end ) break; \
901 if ( ptr[iv]==missing ) continue; \
902 if ( ad < ptr[iv] ) { ad = ptr[iv]; *ial = iv; }\
903 } \
904 }
905 switch (ad_fmt_ptr->type) {
906 case BCF_BT_INT8: BRANCH_INT(int8_t, bcf_int8_missing, bcf_int8_vector_end); break;
907 case BCF_BT_INT16: BRANCH_INT(int16_t, bcf_int16_missing, bcf_int16_vector_end); break;
908 case BCF_BT_INT32: BRANCH_INT(int32_t, bcf_int32_missing, bcf_int32_vector_end); break;
909 default: fprintf(stderr, "[E::%s] todo: %d\n", __func__, ad_fmt_ptr->type); exit(1); break;
910 }
911 #undef BRANCH_INT
912 return ad;
913 }
914 static inline int get_iad(bcf1_t *line, bcf_fmt_t *ad_fmt_ptr, int ismpl, int ial)
915 {
916 #define BRANCH_INT(type_t,missing,vector_end) { \
917 type_t *ptr = (type_t *) (ad_fmt_ptr->p + ad_fmt_ptr->size*ismpl); \
918 if ( ptr[ial]==vector_end ) return 0; \
919 if ( ptr[ial]==missing ) return 0; \
920 return ptr[ial]; \
921 }
922 switch (ad_fmt_ptr->type) {
923 case BCF_BT_INT8: BRANCH_INT(int8_t, bcf_int8_missing, bcf_int8_vector_end); break;
924 case BCF_BT_INT16: BRANCH_INT(int16_t, bcf_int16_missing, bcf_int16_vector_end); break;
925 case BCF_BT_INT32: BRANCH_INT(int32_t, bcf_int32_missing, bcf_int32_vector_end); break;
926 default: fprintf(stderr, "[E::%s] todo: %d\n", __func__, ad_fmt_ptr->type); exit(1); break;
927 }
928 #undef BRANCH_INT
929 }
930 static inline void update_dvaf(stats_t *stats, bcf1_t *line, int ial, float vaf)
931 {
932 int len = line->d.var[ial].n;
933 if ( len < -stats->m_indel ) len = -stats->m_indel;
934 else if ( len > stats->m_indel ) len = stats->m_indel;
935 int bin = stats->m_indel + len;
936 stats->nvaf[bin]++;
937 stats->dvaf[bin] += vaf;
938 }
939 #define vaf2bin(vaf) ((int)nearbyintf((vaf)/0.05))
940 static inline void update_vaf(vaf_t *smpl_vaf, bcf1_t *line, int ial, float vaf)
941 {
942 if ( vaf>=0 && vaf<=1 )
943 {
944 int idx = vaf2bin(vaf);
945 if ( bcf_get_variant_type(line,ial)==VCF_SNP ) smpl_vaf->snv[idx]++;
946 else smpl_vaf->indel[idx]++;
947 }
948 }
949
950 static inline int calc_sample_depth(args_t *args, int ismpl, bcf_fmt_t *ad_fmt_ptr, bcf_fmt_t *dp_fmt_ptr)
951 {
952 if ( dp_fmt_ptr )
953 {
954 #define BRANCH_INT(type_t,missing,vector_end) { \
955 type_t *ptr = (type_t *) (dp_fmt_ptr->p + dp_fmt_ptr->size*ismpl); \
956 if ( *ptr==missing || *ptr==vector_end ) return -1; \
957 return *ptr; \
958 }
959 switch (dp_fmt_ptr->type) {
960 case BCF_BT_INT8: BRANCH_INT(int8_t, bcf_int8_missing, bcf_int8_vector_end); break;
961 case BCF_BT_INT16: BRANCH_INT(int16_t, bcf_int16_missing, bcf_int16_vector_end); break;
962 case BCF_BT_INT32: BRANCH_INT(int32_t, bcf_int32_missing, bcf_int32_vector_end); break;
963 default: fprintf(stderr, "[E::%s] todo: %d\n", __func__, dp_fmt_ptr->type); exit(1); break;
964 }
965 #undef BRANCH_INT
966 }
967 if ( ad_fmt_ptr )
968 {
969 int iv, dp = 0, has_value = 0;
970 #define BRANCH_INT(type_t,missing,vector_end) { \
971 type_t *ptr = (type_t *) (ad_fmt_ptr->p + ad_fmt_ptr->size*ismpl); \
972 for (iv=0; iv<ad_fmt_ptr->n; iv++) \
973 { \
974 if ( ptr[iv]==vector_end ) break; \
975 if ( ptr[iv]==missing ) continue; \
976 has_value = 1; \
977 dp += ptr[iv]; \
978 } \
979 }
980 switch (ad_fmt_ptr->type) {
981 case BCF_BT_INT8: BRANCH_INT(int8_t, bcf_int8_missing, bcf_int8_vector_end); break;
982 case BCF_BT_INT16: BRANCH_INT(int16_t, bcf_int16_missing, bcf_int16_vector_end); break;
983 case BCF_BT_INT32: BRANCH_INT(int32_t, bcf_int32_missing, bcf_int32_vector_end); break;
984 default: fprintf(stderr, "[E::%s] todo: %d\n", __func__, ad_fmt_ptr->type); exit(1); break;
985 }
986 #undef BRANCH_INT
987 if ( !has_value ) return -1;
988 return dp;
989 }
990 return -1;
991 }
992 static inline void sample_gt_stats(args_t *args, stats_t *stats, bcf1_t *line, int ismpl, int gt, int ial, int jal)
993 {
994 if ( gt==GT_UNKN )
995 {
996 stats->smpl_missing[ismpl]++;
997 return;
998 }
999
1000 int var_type = 0;
1001 if ( ial>0 ) var_type |= bcf_get_variant_type(line,ial);
1002 if ( jal>0 ) var_type |= bcf_get_variant_type(line,jal);
1003 if ( gt==GT_HAPL_R || gt==GT_HAPL_A )
1004 {
1005 if ( var_type&VCF_INDEL && stats->smpl_frm_shifts )
1006 {
1007 assert( ial<line->n_allele );
1008 stats->smpl_frm_shifts[ismpl*3 + args->tmp_frm[ial]]++;
1009 }
1010 if ( gt == GT_HAPL_R ) stats->smpl_hapRef[ismpl]++;
1011 if ( gt == GT_HAPL_A ) stats->smpl_hapAlt[ismpl]++;
1012 return;
1013 }
1014 if ( gt != GT_HOM_RR ) { args->n_nref++; args->i_nref = ismpl; }
1015 #if HWE_STATS
1016 switch (gt)
1017 {
1018 case GT_HOM_RR: args->nref_tot++; break;
1019 case GT_HET_RA: args->nhet_tot++; break;
1020 case GT_HET_AA:
1021 case GT_HOM_AA: args->nalt_tot++; break;
1022 }
1023 #endif
1024
1025 if ( var_type&VCF_SNP || var_type==VCF_REF ) // count ALT=. as SNP
1026 {
1027 if ( gt == GT_HET_RA ) stats->smpl_hets[ismpl]++;
1028 else if ( gt == GT_HET_AA ) stats->smpl_hets[ismpl]++;
1029 else if ( gt == GT_HOM_RR ) stats->smpl_homRR[ismpl]++;
1030 else if ( gt == GT_HOM_AA ) stats->smpl_homAA[ismpl]++;
1031 if ( gt != GT_HOM_RR && line->d.var[ial].type&VCF_SNP ) // this is safe, bcf_get_variant_types has been already called
1032 {
1033 int ref = bcf_acgt2int(*line->d.allele[0]);
1034 int alt = bcf_acgt2int(*line->d.allele[ial]);
1035 if ( alt<0 ) return;
1036 if ( abs(ref-alt)==2 )
1037 stats->smpl_ts[ismpl]++;
1038 else
1039 stats->smpl_tv[ismpl]++;
1040 }
1041 if ( gt != GT_HOM_RR && line->d.var[jal].type&VCF_SNP && ial!=jal )
1042 {
1043 int ref = bcf_acgt2int(*line->d.allele[0]);
1044 int alt = bcf_acgt2int(*line->d.allele[jal]);
1045 if ( alt<0 ) return;
1046 if ( abs(ref-alt)==2 )
1047 stats->smpl_ts[ismpl]++;
1048 else
1049 stats->smpl_tv[ismpl]++;
1050 }
1051 }
1052 if ( var_type&VCF_INDEL )
1053 {
1054 if ( gt != GT_HOM_RR )
1055 {
1056 stats->smpl_indels[ismpl]++;
1057 if ( gt==GT_HET_RA || gt==GT_HET_AA )
1058 {
1059 int is_ins = 0, is_del = 0;
1060 if ( bcf_get_variant_type(line,ial)&VCF_INDEL )
1061 {
1062 if ( line->d.var[ial].n < 0 ) is_del = 1;
1063 else is_ins = 1;
1064 }
1065 if ( bcf_get_variant_type(line,jal)&VCF_INDEL )
1066 {
1067 if ( line->d.var[jal].n < 0 ) is_del = 1;
1068 else is_ins = 1;
1069 }
1070 // Note that alt-het genotypes with both ins and del allele are counted twice!!
1071 if ( is_del ) stats->smpl_del_hets[ismpl]++;
1072 if ( is_ins ) stats->smpl_ins_hets[ismpl]++;
1073 }
1074 else if ( gt==GT_HOM_AA )
1075 {
1076 if ( line->d.var[ial].n < 0 ) stats->smpl_del_homs[ismpl]++;
1077 else stats->smpl_ins_homs[ismpl]++;
1078 }
1079 }
1080 if ( stats->smpl_frm_shifts )
1081 {
1082 assert( ial<line->n_allele && jal<line->n_allele );
1083 stats->smpl_frm_shifts[ismpl*3 + args->tmp_frm[ial]]++;
1084 stats->smpl_frm_shifts[ismpl*3 + args->tmp_frm[jal]]++;
1085 }
1086 }
1087 }
1088 static void do_sample_stats(args_t *args, stats_t *stats, bcf_sr_t *reader, int matched)
1089 {
1090 bcf_srs_t *files = args->files;
1091 bcf1_t *line = reader->buffer[0];
1092
1093 args->nref_tot = 0;
1094 args->nhet_tot = 0;
1095 args->nalt_tot = 0;
1096 args->n_nref = 0;
1097 args->i_nref = 0;
1098
1099 bcf_fmt_t *gt_fmt_ptr = bcf_get_fmt(reader->header,reader->buffer[0],"GT");
1100 bcf_fmt_t *ad_fmt_ptr = bcf_get_fmt(reader->header,reader->buffer[0],"AD");
1101 bcf_fmt_t *dp_fmt_ptr = bcf_get_fmt(reader->header,reader->buffer[0],"DP");
1102
1103 int is;
1104 for (is=0; is<args->files->n_smpl; is++)
1105 {
1106 // Determine depth
1107 int dp = calc_sample_depth(args,is,ad_fmt_ptr,dp_fmt_ptr);
1108 if ( dp>0 )
1109 {
1110 (*idist(&stats->dp, dp))++;
1111 stats->smpl_ndp[is]++;
1112 stats->smpl_dp[is] += dp;
1113 }
1114
1115 // Determine genotype
1116 int ial, jal, gt=GT_UNKN;
1117 if ( gt_fmt_ptr )
1118 {
1119 gt = bcf_gt_type(gt_fmt_ptr, reader->samples[is], &ial, &jal);
1120 sample_gt_stats(args,stats,line,is,gt,ial,jal);
1121 }
1122
1123 // Determine variant allele frequency
1124 if ( dp>0 && ad_fmt_ptr )
1125 {
1126 float iad = 0, jad = 0;
1127 if ( gt==GT_UNKN ) // GT not available
1128 {
1129 iad = get_ad(line,ad_fmt_ptr,is,&ial);
1130 }
1131 else if ( gt!=GT_UNKN )
1132 {
1133 iad = ial==0 ? 0 : get_iad(line,ad_fmt_ptr,is,ial);
1134 jad = jal==0 ? 0 : get_iad(line,ad_fmt_ptr,is,jal);
1135 }
1136 if ( iad )
1137 {
1138 update_dvaf(stats,line,ial,(float)iad/dp);
1139 update_vaf(&stats->smpl_vaf[is],line,ial,(float)iad/dp);
1140 }
1141 if ( jad && iad!=jad )
1142 {
1143 update_dvaf(stats,line,jal,(float)jad/dp);
1144 update_vaf(&stats->smpl_vaf[is],line,jal,(float)jad/dp);
1145 }
1146 }
1147 }
1148 if ( args->n_nref==1 ) stats->smpl_sngl[args->i_nref]++;
1149
1150 #if HWE_STATS
1151 if ( gt_fmt_ptr && line->n_allele > 1 && (args->nref_tot || args->nhet_tot || args->nalt_tot) )
1152 {
1153 // Number of heterozygous genotypes observed for any given allele frequency. This is used
1154 // by plot-vcfstats to show the observed vs expected number of hets. There the expected number
1155 // of hets is calculated from the probability P(het) = 2*AF*(1-AF).
1156 // The array af_hwe is organized as follows
1157 // m_af .. number of allele frequency bins
1158 // naf_hwe .. the number of het genotype frequency bins
1159 // iallele_freq*naf_hwe + ihet_freq
1160 //
1161 float het_frac = (float)args->nhet_tot / (args->nref_tot + args->nhet_tot + args->nalt_tot);
1162 int ihet_freq = het_frac * (args->naf_hwe - 1);
1163 int idx = ihet_freq + args->tmp_iaf[1] * args->naf_hwe;
1164 stats->af_hwe[idx]++;
1165 }
1166 #endif
1167
1168 if ( matched==3 )
1169 {
1170 int is;
1171 bcf_fmt_t *fmt0, *fmt1;
1172 fmt0 = bcf_get_fmt(files->readers[0].header,files->readers[0].buffer[0],"GT"); if ( !fmt0 ) return;
1173 fmt1 = bcf_get_fmt(files->readers[1].header,files->readers[1].buffer[0],"GT"); if ( !fmt1 ) return;
1174
1175 // only the first ALT allele is considered
1176 if (args->ntmp_iaf <= 1) return; // Do not consider invariate sites
1177 int iaf = args->tmp_iaf[1];
1178 int line_type = bcf_get_variant_types(files->readers[0].buffer[0]);
1179 gtcmp_t *af_stats = line_type&VCF_SNP ? args->af_gts_snps : args->af_gts_indels;
1180 gtcmp_t *smpl_stats = line_type&VCF_SNP ? args->smpl_gts_snps : args->smpl_gts_indels;
1181
1182 for (is=0; is<files->n_smpl; is++)
1183 {
1184 // Simplified comparison: only 0/0, 0/1, 1/1 is looked at as the identity of
1185 // actual alleles can be enforced by running without the -c option.
1186 int gt0 = bcf_gt_type(fmt0, files->readers[0].samples[is], NULL, NULL);
1187 int gt1 = bcf_gt_type(fmt1, files->readers[1].samples[is], NULL, NULL);
1188
1189 int idx0 = type2stats[gt0];
1190 int idx1 = type2stats[gt1];
1191 af_stats[iaf].gt2gt[idx0][idx1]++;
1192 smpl_stats[is].gt2gt[idx0][idx1]++;
1193
1194 if ( gt0 == GT_UNKN || gt1 == GT_UNKN ) continue;
1195 if ( type2ploidy[gt0]*type2ploidy[gt1] == -1 ) continue; // cannot compare diploid and haploid genotypes
1196
1197 float y = type2dosage[gt0];
1198 float x = type2dosage[gt1];
1199
1200 smpl_stats[is].yx += y*x;
1201 smpl_stats[is].x += x;
1202 smpl_stats[is].xx += x*x;
1203 smpl_stats[is].y += y;
1204 smpl_stats[is].yy += y*y;
1205 smpl_stats[is].n += 1;
1206
1207 af_stats[iaf].yx += y*x;
1208 af_stats[iaf].x += x;
1209 af_stats[iaf].xx += x*x;
1210 af_stats[iaf].y += y;
1211 af_stats[iaf].yy += y*y;
1212 af_stats[iaf].n += 1;
1213 }
1214
1215 if ( args->verbose_sites )
1216 {
1217 int nm = 0, nmm = 0, nrefm = 0;
1218 for (is=0; is<files->n_smpl; is++)
1219 {
1220 int gt = bcf_gt_type(fmt0, files->readers[0].samples[is], NULL, NULL);
1221 if ( gt == GT_UNKN ) continue;
1222 int gt2 = bcf_gt_type(fmt1, files->readers[1].samples[is], NULL, NULL);
1223 if ( gt2 == GT_UNKN ) continue;
1224 if ( gt != gt2 )
1225 {
1226 nmm++;
1227 bcf_sr_t *reader = &files->readers[0];
1228 printf("DBG\t%s\t%"PRId64"\t%s\t%d\t%d\n",reader->header->id[BCF_DT_CTG][reader->buffer[0]->rid].key,(int64_t) reader->buffer[0]->pos+1,files->samples[is],gt,gt2);
1229 }
1230 else
1231 {
1232 if ( gt!=GT_HOM_RR ) nrefm++;
1233 nm++;
1234 }
1235 }
1236 float nrd = nrefm+nmm ? 100.*nmm/(nrefm+nmm) : 0;
1237 printf("PSD\t%s\t%"PRId64"\t%d\t%d\t%f\n", reader->header->id[BCF_DT_CTG][reader->buffer[0]->rid].key,(int64_t) reader->buffer[0]->pos+1,nm,nmm,nrd);
1238 }
1239 }
1240 }
1241
1242 static void do_vcf_stats(args_t *args)
1243 {
1244 bcf_srs_t *files = args->files;
1245 assert( sizeof(int)>files->nreaders );
1246 while ( bcf_sr_next_line(files) )
1247 {
1248 bcf_sr_t *reader = NULL;
1249 bcf1_t *line = NULL;
1250 int ret = 0, i, pass = 1;
1251 for (i=0; i<files->nreaders; i++)
1252 {
1253 if ( !bcf_sr_has_line(files,i) ) continue;
1254 if ( args->filter[i] )
1255 {
1256 int is_ok = filter_test(args->filter[i], bcf_sr_get_line(files,i), NULL);
1257 if ( args->filter_logic & FLT_EXCLUDE ) is_ok = is_ok ? 0 : 1;
1258 if ( !is_ok ) { pass = 0; break; }
1259 }
1260 ret |= 1<<i;
1261 if ( !reader )
1262 {
1263 reader = &files->readers[i];
1264 line = bcf_sr_get_line(files,i);
1265 }
1266
1267 }
1268 if ( !pass ) continue;
1269
1270 int line_type = bcf_get_variant_types(line);
1271 init_iaf(args, reader);
1272
1273 stats_t *stats = &args->stats[ret-1];
1274 if ( args->split_by_id && line->d.id[0]=='.' && !line->d.id[1] )
1275 stats = &args->stats[1];
1276
1277 stats->n_records++;
1278
1279 if ( line_type==VCF_REF )
1280 stats->n_noalts++;
1281 if ( line_type&VCF_SNP )
1282 do_snp_stats(args, stats, reader);
1283 if ( line_type&VCF_INDEL )
1284 do_indel_stats(args, stats, reader);
1285 if ( line_type&VCF_MNP )
1286 do_mnp_stats(args, stats, reader);
1287 if ( line_type&VCF_OTHER )
1288 do_other_stats(args, stats, reader);
1289
1290 if ( line->n_allele>2 )
1291 {
1292 stats->n_mals++;
1293 if ( line_type == VCF_SNP ) stats->n_snp_mals++; // note: this will be fooled by C>C,T
1294 }
1295
1296 if ( files->n_smpl )
1297 do_sample_stats(args, stats, reader, ret);
1298
1299 if ( bcf_get_info_int32(reader->header,line,"DP",&args->iarr,&args->miarr)==1 )
1300 (*idist(&stats->dp_sites, args->iarr[0]))++;
1301 }
1302 }
1303
1304 static void print_header(args_t *args)
1305 {
1306 int i;
1307 printf("# This file was produced by bcftools stats (%s+htslib-%s) and can be plotted using plot-vcfstats.\n", bcftools_version(),hts_version());
1308 printf("# The command line was:\tbcftools %s ", args->argv[0]);
1309 for (i=1; i<args->argc; i++)
1310 printf(" %s",args->argv[i]);
1311 printf("\n#\n");
1312
1313 printf("# Definition of sets:\n# ID\t[2]id\t[3]tab-separated file names\n");
1314 if ( args->files->nreaders==1 )
1315 {
1316 const char *fname = strcmp("-",args->files->readers[0].fname) ? args->files->readers[0].fname : "<STDIN>";
1317 if ( args->split_by_id )
1318 {
1319 printf("ID\t0\t%s:known (sites with ID different from \".\")\n", fname);
1320 printf("ID\t1\t%s:novel (sites where ID column is \".\")\n", fname);
1321 }
1322 else
1323 printf("ID\t0\t%s\n", fname);
1324 }
1325 else
1326 {
1327 const char *fname0 = strcmp("-",args->files->readers[0].fname) ? args->files->readers[0].fname : "<STDIN>";
1328 const char *fname1 = strcmp("-",args->files->readers[1].fname) ? args->files->readers[1].fname : "<STDIN>";
1329 printf("ID\t0\t%s\n", fname0);
1330 printf("ID\t1\t%s\n", fname1);
1331 printf("ID\t2\t%s\t%s\n", fname0,fname1);
1332
1333 if ( args->verbose_sites )
1334 {
1335 printf(
1336 "# Verbose per-site discordance output.\n"
1337 "# PSD\t[2]CHROM\t[3]POS\t[4]Number of matches\t[5]Number of mismatches\t[6]NRD\n");
1338 printf(
1339 "# Verbose per-site and per-sample output. Genotype codes: %d:HomRefRef, %d:HomAltAlt, %d:HetAltRef, %d:HetAltAlt, %d:haploidRef, %d:haploidAlt\n"
1340 "# DBG\t[2]CHROM\t[3]POS\t[4]Sample\t[5]GT in %s\t[6]GT in %s\n",
1341 GT_HOM_RR, GT_HOM_AA, GT_HET_RA, GT_HET_AA, GT_HAPL_R, GT_HAPL_A, fname0,fname1);
1342 }
1343 }
1344 }
1345
1346 #define T2S(x) type2stats[x]
1347 static void print_stats(args_t *args)
1348 {
1349 int i, j,k, id;
1350 printf("# SN, Summary numbers:\n");
1351 printf("# number of records .. number of data rows in the VCF\n");
1352 printf("# number of no-ALTs .. reference-only sites, ALT is either \".\" or identical to REF\n");
1353 printf("# number of SNPs .. number of rows with a SNP\n");
1354 printf("# number of MNPs .. number of rows with a MNP, such as CC>TT\n");
1355 printf("# number of indels .. number of rows with an indel\n");
1356 printf("# number of others .. number of rows with other type, for example a symbolic allele or\n");
1357 printf("# a complex substitution, such as ACT>TCGA\n");
1358 printf("# number of multiallelic sites .. number of rows with multiple alternate alleles\n");
1359 printf("# number of multiallelic SNP sites .. number of rows with multiple alternate alleles, all SNPs\n");
1360 printf("# \n");
1361 printf("# Note that rows containing multiple types will be counted multiple times, in each\n");
1362 printf("# counter. For example, a row with a SNP and an indel increments both the SNP and\n");
1363 printf("# the indel counter.\n");
1364 printf("# \n");
1365 printf("# SN\t[2]id\t[3]key\t[4]value\n");
1366 for (id=0; id<args->files->nreaders; id++)
1367 printf("SN\t%d\tnumber of samples:\t%d\n", id, bcf_hdr_nsamples(args->files->readers[id].header));
1368 for (id=0; id<args->nstats; id++)
1369 {
1370 stats_t *stats = &args->stats[id];
1371 printf("SN\t%d\tnumber of records:\t%"PRIu64"\n", id, stats->n_records);
1372 printf("SN\t%d\tnumber of no-ALTs:\t%"PRIu64"\n", id, stats->n_noalts);
1373 printf("SN\t%d\tnumber of SNPs:\t%"PRIu64"\n", id, stats->n_snps);
1374 printf("SN\t%d\tnumber of MNPs:\t%"PRIu64"\n", id, stats->n_mnps);
1375 printf("SN\t%d\tnumber of indels:\t%"PRIu64"\n", id, stats->n_indels);
1376 printf("SN\t%d\tnumber of others:\t%"PRIu64"\n", id, stats->n_others);
1377 printf("SN\t%d\tnumber of multiallelic sites:\t%"PRIu64"\n", id, stats->n_mals);
1378 printf("SN\t%d\tnumber of multiallelic SNP sites:\t%"PRIu64"\n", id, stats->n_snp_mals);
1379 }
1380 printf("# TSTV, transitions/transversions\n"
1381 "# - transitions, see https://en.wikipedia.org/wiki/Transition_(genetics)\n"
1382 "# - transversions, see https://en.wikipedia.org/wiki/Transversion\n");
1383 printf("# TSTV\t[2]id\t[3]ts\t[4]tv\t[5]ts/tv\t[6]ts (1st ALT)\t[7]tv (1st ALT)\t[8]ts/tv (1st ALT)\n");
1384 for (id=0; id<args->nstats; id++)
1385 {
1386 stats_t *stats = &args->stats[id];
1387 int ts=0,tv=0;
1388 for (i=0; i<args->m_af; i++) { ts += stats->af_ts[i]; tv += stats->af_tv[i]; }
1389 printf("TSTV\t%d\t%d\t%d\t%.2f\t%d\t%d\t%.2f\n", id,ts,tv,tv?(float)ts/tv:0, stats->ts_alt1,stats->tv_alt1,stats->tv_alt1?(float)stats->ts_alt1/stats->tv_alt1:0);
1390 }
1391 if ( args->exons_fname )
1392 {
1393 printf("# FS, Indel frameshifts:\n# FS\t[2]id\t[3]in-frame\t[4]out-frame\t[5]not applicable\t[6]out/(in+out) ratio\t[7]in-frame (1st ALT)\t[8]out-frame (1st ALT)\t[9]not applicable (1st ALT)\t[10]out/(in+out) ratio (1st ALT)\n");
1394 for (id=0; id<args->nstats; id++)
1395 {
1396 int in=args->stats[id].in_frame, out=args->stats[id].out_frame, na=args->stats[id].na_frame;
1397 int in1=args->stats[id].in_frame_alt1, out1=args->stats[id].out_frame_alt1, na1=args->stats[id].na_frame_alt1;
1398 printf("FS\t%d\t%d\t%d\t%d\t%.2f\t%d\t%d\t%d\t%.2f\n", id, in,out,na,out?(float)out/(in+out):0,in1,out1,na1,out1?(float)out1/(in1+out1):0);
1399 }
1400 }
1401 if ( args->indel_ctx )
1402 {
1403 printf("# ICS, Indel context:\n"
1404 "# - repeat-consistent, inconsistent and n/a: experimental and useless stats [DEPRECATED]\n");
1405 printf("# ICS\t[2]id\t[3]repeat-consistent\t[4]repeat-inconsistent\t[5]not applicable\t[6]c/(c+i) ratio\n");
1406 for (id=0; id<args->nstats; id++)
1407 {
1408 int nc = 0, ni = 0, na = args->stats[id].n_repeat_na;
1409 for (i=0; i<IRC_RLEN; i++)
1410 {
1411 nc += args->stats[id].n_repeat[i][0] + args->stats[id].n_repeat[i][2];
1412 ni += args->stats[id].n_repeat[i][1] + args->stats[id].n_repeat[i][3];
1413 }
1414 printf("ICS\t%d\t%d\t%d\t%d\t%.4f\n", id, nc,ni,na,nc+ni ? (float)nc/(nc+ni) : 0.0);
1415 }
1416 printf("# ICL, Indel context by length:\n"
1417 "# - repeat-consistent, inconsistent and n/a: experimental and useless stats [DEPRECATED]\n");
1418 printf("# ICL\t[2]id\t[3]length of repeat element\t[4]repeat-consistent deletions)\t[5]repeat-inconsistent deletions\t[6]consistent insertions\t[7]inconsistent insertions\t[8]c/(c+i) ratio\n");
1419 for (id=0; id<args->nstats; id++)
1420 {
1421 for (i=1; i<IRC_RLEN; i++)
1422 {
1423 int nc = args->stats[id].n_repeat[i][0]+args->stats[id].n_repeat[i][2], ni = args->stats[id].n_repeat[i][1]+args->stats[id].n_repeat[i][3];
1424 printf("ICL\t%d\t%d\t%d\t%d\t%d\t%d\t%.4f\n", id, i+1,
1425 args->stats[id].n_repeat[i][0],args->stats[id].n_repeat[i][1],args->stats[id].n_repeat[i][2],args->stats[id].n_repeat[i][3],
1426 nc+ni ? (float)nc/(nc+ni) : 0.0);
1427 }
1428 }
1429 }
1430 printf("# SiS, Singleton stats:\n"
1431 "# - allele count, i.e. the number of singleton genotypes (AC=1)\n"
1432 "# - number of transitions, see above\n"
1433 "# - number of transversions, see above\n"
1434 "# - repeat-consistent, inconsistent and n/a: experimental and useless stats [DEPRECATED]\n");
1435 printf("# SiS\t[2]id\t[3]allele count\t[4]number of SNPs\t[5]number of transitions\t[6]number of transversions\t[7]number of indels\t[8]repeat-consistent\t[9]repeat-inconsistent\t[10]not applicable\n");
1436 for (id=0; id<args->nstats; id++)
1437 {
1438 stats_t *stats = &args->stats[id];
1439 printf("SiS\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\n", id,1,stats->af_snps[0],stats->af_ts[0],stats->af_tv[0],
1440 stats->af_repeats[0][0]+stats->af_repeats[1][0]+stats->af_repeats[2][0],stats->af_repeats[0][0],stats->af_repeats[1][0],stats->af_repeats[2][0]);
1441 // put the singletons stats into the first AF bin, note that not all of the stats is transferred (i.e. nrd mismatches)
1442 stats->af_snps[1] += stats->af_snps[0];
1443 stats->af_ts[1] += stats->af_ts[0];
1444 stats->af_tv[1] += stats->af_tv[0];
1445 stats->af_repeats[0][1] += stats->af_repeats[0][0];
1446 stats->af_repeats[1][1] += stats->af_repeats[1][0];
1447 stats->af_repeats[2][1] += stats->af_repeats[2][0];
1448 }
1449 // move the singletons stats into the first AF bin, singleton stats was collected separately because of init_iaf
1450 if ( args->af_gts_snps )
1451 {
1452 args->af_gts_snps[1].y += args->af_gts_snps[0].y;
1453 args->af_gts_snps[1].yy += args->af_gts_snps[0].yy;
1454 args->af_gts_snps[1].xx += args->af_gts_snps[0].xx;
1455 args->af_gts_snps[1].yx += args->af_gts_snps[0].yx;
1456 args->af_gts_snps[1].n += args->af_gts_snps[0].n;
1457 }
1458 if ( args->af_gts_indels )
1459 {
1460 args->af_gts_indels[1].y += args->af_gts_indels[0].y;
1461 args->af_gts_indels[1].yy += args->af_gts_indels[0].yy;
1462 args->af_gts_indels[1].xx += args->af_gts_indels[0].xx;
1463 args->af_gts_indels[1].yx += args->af_gts_indels[0].yx;
1464 args->af_gts_indels[1].n += args->af_gts_indels[0].n;
1465 }
1466
1467 printf("# AF, Stats by non-reference allele frequency:\n# AF\t[2]id\t[3]allele frequency\t[4]number of SNPs\t[5]number of transitions\t[6]number of transversions\t[7]number of indels\t[8]repeat-consistent\t[9]repeat-inconsistent\t[10]not applicable\n");
1468 for (id=0; id<args->nstats; id++)
1469 {
1470 stats_t *stats = &args->stats[id];
1471 for (i=1; i<args->m_af; i++) // note that af[1] now contains also af[0], see SiS stats output above
1472 {
1473 if ( stats->af_snps[i]+stats->af_ts[i]+stats->af_tv[i]+stats->af_repeats[0][i]+stats->af_repeats[1][i]+stats->af_repeats[2][i] == 0 ) continue;
1474 double af = args->af_bins ? (bin_get_value(args->af_bins,i)+bin_get_value(args->af_bins,i-1))*0.5 : (double)(i-1)/(args->m_af-1);
1475 printf("AF\t%d\t%f\t%d\t%d\t%d\t%d\t%d\t%d\t%d\n", id,af,stats->af_snps[i],stats->af_ts[i],stats->af_tv[i],
1476 stats->af_repeats[0][i]+stats->af_repeats[1][i]+stats->af_repeats[2][i],stats->af_repeats[0][i],stats->af_repeats[1][i],stats->af_repeats[2][i]);
1477 }
1478 }
1479 #if QUAL_STATS
1480 printf("# QUAL, Stats by quality\n# QUAL\t[2]id\t[3]Quality\t[4]number of SNPs\t[5]number of transitions (1st ALT)\t[6]number of transversions (1st ALT)\t[7]number of indels\n");
1481 for (id=0; id<args->nstats; id++)
1482 {
1483 stats_t *stats = &args->stats[id];
1484 int ndist_ts = dist_nbins(stats->qual_ts);
1485 int ndist_tv = dist_nbins(stats->qual_tv);
1486 int ndist_in = dist_nbins(stats->qual_indels);
1487 int ndist_max = ndist_ts;
1488 if ( ndist_max < ndist_tv ) ndist_max = ndist_tv;
1489 if ( ndist_max < ndist_in ) ndist_max = ndist_in;
1490 uint32_t beg, end;
1491 uint32_t nts, ntv, nin;
1492 for (i=0; i<ndist_max; i++)
1493 {
1494 nts = ntv = nin = 0;
1495 float qval = -1;
1496 if ( i < ndist_ts )
1497 {
1498 nts = dist_get(stats->qual_ts, i, &beg, &end);
1499 qval = beg>0 ? 0.1*(beg - 1) : -1;
1500 }
1501 if ( i < ndist_tv )
1502 {
1503 ntv = dist_get(stats->qual_tv, i, &beg, &end);
1504 if ( qval==-1 ) qval = beg > 0 ? 0.1*(beg - 1) : -1;
1505 }
1506 if ( i < ndist_in )
1507 {
1508 nin = dist_get(stats->qual_indels, i, &beg, &end);
1509 if ( qval==-1 ) qval = beg > 0 ? 0.1*(beg - 1) : -1;
1510 }
1511 if ( nts+ntv+nin==0 ) continue;
1512
1513 printf("QUAL\t%d\t",id);
1514 if ( qval==-1 ) printf(".");
1515 else printf("%.1f",qval);
1516 printf("\t%d\t%d\t%d\t%d\n",nts+ntv,nts,ntv,nin);
1517 }
1518 }
1519 #endif
1520 for (i=0; i<args->nusr; i++)
1521 {
1522 printf("# USR:%s/%d\t[2]id\t[3]%s/%d\t[4]number of SNPs\t[5]number of transitions (1st ALT)\t[6]number of transversions (1st ALT)\n",
1523 args->usr[i].tag,args->usr[i].idx,args->usr[i].tag,args->usr[i].idx);
1524 for (id=0; id<args->nstats; id++)
1525 {
1526 user_stats_t *usr = &args->stats[id].usr[i];
1527 int j;
1528 for (j=0; j<usr->nbins; j++)
1529 {
1530 if ( usr->vals_ts[j]+usr->vals_tv[j] == 0 ) continue; // skip empty bins
1531 float val = usr->min + (usr->max - usr->min)*j/(usr->nbins-1);
1532 const char * const fmt = usr->type==BCF_HT_REAL ? "USR:%s/%d\t%d\t%e\t%"PRIu64"\t%"PRIu64"\t%"PRIu64"\n" : "USR:%s/%d\t%d\t%.0f\t%"PRIu64"\t%"PRIu64"\t%"PRIu64"\n";
1533 printf(fmt,usr->tag,usr->idx,id,val,usr->vals_ts[j]+usr->vals_tv[j],usr->vals_ts[j],usr->vals_tv[j]);
1534 }
1535 }
1536 }
1537 printf("# IDD, InDel distribution:\n# IDD\t[2]id\t[3]length (deletions negative)\t[4]number of sites\t[5]number of genotypes\t[6]mean VAF\n");
1538 for (id=0; id<args->nstats; id++)
1539 {
1540 stats_t *stats = &args->stats[id];
1541 for (i=stats->m_indel-1; i>=0; i--)
1542 {
1543 if ( !stats->deletions[i] ) continue;
1544 // whops, differently organized arrow, dels are together with ins
1545 int bin = stats->m_indel - i - 1;
1546 printf("IDD\t%d\t%d\t%d\t", id,-i-1,stats->deletions[i]);
1547 if ( stats->nvaf && stats->nvaf[bin] )
1548 printf("%u\t%.2f",stats->nvaf[bin],stats->dvaf[bin]/stats->nvaf[bin]);
1549 else
1550 printf("0\t.");
1551 printf("\n");
1552 }
1553 for (i=0; i<stats->m_indel; i++)
1554 {
1555 if ( !stats->insertions[i] ) continue;
1556 int bin = stats->m_indel + i + 1;
1557 printf("IDD\t%d\t%d\t%d\t", id,i+1,stats->insertions[i]);
1558 if ( stats->nvaf && stats->nvaf[bin] )
1559 printf("%u\t%.2f",stats->nvaf[bin],stats->dvaf[bin]/stats->nvaf[bin]);
1560 else
1561 printf("0\t.");
1562 printf("\n");
1563 }
1564 }
1565 printf("# ST, Substitution types:\n# ST\t[2]id\t[3]type\t[4]count\n");
1566 for (id=0; id<args->nstats; id++)
1567 {
1568 int t;
1569 for (t=0; t<15; t++)
1570 {
1571 if ( t>>2 == (t&3) ) continue;
1572 printf("ST\t%d\t%c>%c\t%d\n", id, bcf_int2acgt(t>>2),bcf_int2acgt(t&3),args->stats[id].subst[t]);
1573 }
1574 }
1575 if ( args->files->nreaders>1 && args->files->n_smpl )
1576 {
1577 printf("SN\t%d\tnumber of samples:\t%d\n", 2, args->files->n_smpl);
1578
1579 int x;
1580 for (x=0; x<2; x++) // x=0: snps, x=1: indels
1581 {
1582 gtcmp_t *stats;
1583 if ( x==0 )
1584 {
1585 printf("# GCsAF, Genotype concordance by non-reference allele frequency (SNPs)\n# GCsAF\t[2]id\t[3]allele frequency\t[4]RR Hom matches\t[5]RA Het matches\t[6]AA Hom matches\t[7]RR Hom mismatches\t[8]RA Het mismatches\t[9]AA Hom mismatches\t[10]dosage r-squared\t[11]number of genotypes\n");
1586 stats = args->af_gts_snps;
1587 }
1588 else
1589 {
1590 printf("# GCiAF, Genotype concordance by non-reference allele frequency (indels)\n# GCiAF\t[2]id\t[3]allele frequency\t[4]RR Hom matches\t[5]RA Het matches\t[6]AA Hom matches\t[7]RR Hom mismatches\t[8]RA Het mismatches\t[9]AA Hom mismatches\t[10]dosage r-squared\t[11]number of genotypes\n");
1591 stats = args->af_gts_indels;
1592 }
1593 uint64_t nrd_m[4] = {0,0,0,0}, nrd_mm[4] = {0,0,0,0}; // across all bins
1594 for (i=0; i<args->m_af; i++)
1595 {
1596 int n = 0;
1597 uint64_t m[4] = {0,0,0,0}, mm[4] = {0,0,0,0}; // in i-th AF bin
1598 for (j=0; j<4; j++) // rr, ra, aa hom, aa het, ./.
1599 for (k=0; k<4; k++)
1600 {
1601 n += stats[i].gt2gt[j][k];
1602 if ( j==k )
1603 {
1604 nrd_m[j] += stats[i].gt2gt[j][k];
1605 m[j] += stats[i].gt2gt[j][k];
1606 }
1607 else
1608 {
1609 nrd_mm[j] += stats[i].gt2gt[j][k];
1610 mm[j] += stats[i].gt2gt[j][k];
1611 }
1612 }
1613 if ( !i || !n ) continue; // skip singleton stats and empty bins
1614
1615 // Pearson's r2
1616 double r2 = 0;
1617 if ( stats[i].n )
1618 {
1619 r2 = (stats[i].yx - stats[i].x*stats[i].y/stats[i].n);
1620 r2 /= sqrt((stats[i].xx - stats[i].x*stats[i].x/stats[i].n) * (stats[i].yy - stats[i].y*stats[i].y/stats[i].n));
1621 r2 *= r2;
1622 }
1623 double af = args->af_bins ? (bin_get_value(args->af_bins,i)+bin_get_value(args->af_bins,i-1))*0.5 : (double)(i-1)/(args->m_af-1);
1624 printf("GC%cAF\t2\t%f", x==0 ? 's' : 'i', af);
1625 printf("\t%"PRIu64"\t%"PRIu64"\t%"PRIu64"", m[T2S(GT_HOM_RR)],m[T2S(GT_HET_RA)],m[T2S(GT_HOM_AA)]);
1626 printf("\t%"PRIu64"\t%"PRIu64"\t%"PRIu64"", mm[T2S(GT_HOM_RR)],mm[T2S(GT_HET_RA)],mm[T2S(GT_HOM_AA)]);
1627 if ( stats[i].n && !isnan(r2) ) printf("\t%f", r2);
1628 else printf("\t"NA_STRING);
1629 printf("\t%.0f\n", stats[i].n);
1630 }
1631
1632 if ( x==0 )
1633 {
1634 printf("# NRD and discordance is calculated as follows:\n");
1635 printf("# m .. number of matches\n");
1636 printf("# x .. number of mismatches\n");
1637 printf("# NRD = 100 * (xRR + xRA + xAA) / (xRR + xRA + xAA + mRA + mAA)\n");
1638 printf("# RR discordance = 100 * xRR / (xRR + mRR)\n");
1639 printf("# RA discordance = 100 * xRA / (xRA + mRA)\n");
1640 printf("# AA discordance = 100 * xAA / (xAA + mAA)\n");
1641 printf("# Non-Reference Discordance (NRD), SNPs\n# NRDs\t[2]id\t[3]NRD\t[4]Ref/Ref discordance\t[5]Ref/Alt discordance\t[6]Alt/Alt discordance\n");
1642 }
1643 else
1644 printf("# Non-Reference Discordance (NRD), indels\n# NRDi\t[2]id\t[3]NRD\t[4]Ref/Ref discordance\t[5]Ref/Alt discordance\t[6]Alt/Alt discordance\n");
1645 uint64_t m = nrd_m[T2S(GT_HET_RA)] + nrd_m[T2S(GT_HOM_AA)] + nrd_m[T2S(GT_HET_AA)];
1646 uint64_t mm = nrd_mm[T2S(GT_HOM_RR)] + nrd_mm[T2S(GT_HET_RA)] + nrd_mm[T2S(GT_HOM_AA)] + nrd_mm[T2S(GT_HET_AA)];
1647 printf("NRD%c\t2\t%f\t%f\t%f\t%f\n", x==0 ? 's' : 'i',
1648 m+mm ? mm*100.0/(m+mm) : 0,
1649 nrd_m[T2S(GT_HOM_RR)]+nrd_mm[T2S(GT_HOM_RR)] ? nrd_mm[T2S(GT_HOM_RR)]*100.0/(nrd_m[T2S(GT_HOM_RR)]+nrd_mm[T2S(GT_HOM_RR)]) : 0,
1650 nrd_m[T2S(GT_HET_RA)]+nrd_mm[T2S(GT_HET_RA)] ? nrd_mm[T2S(GT_HET_RA)]*100.0/(nrd_m[T2S(GT_HET_RA)]+nrd_mm[T2S(GT_HET_RA)]) : 0,
1651 nrd_m[T2S(GT_HOM_AA)]+nrd_mm[T2S(GT_HOM_AA)] ? nrd_mm[T2S(GT_HOM_AA)]*100.0/(nrd_m[T2S(GT_HOM_AA)]+nrd_mm[T2S(GT_HOM_AA)]) : 0
1652 );
1653 }
1654
1655 for (x=0; x<2; x++) // x=0: snps, x=1: indels
1656 {
1657 gtcmp_t *stats;
1658 if ( x==0 )
1659 {
1660 printf("# GCsS, Genotype concordance by sample (SNPs)\n# GCsS\t[2]id\t[3]sample\t[4]non-reference discordance rate\t[5]RR Hom matches\t[6]RA Het matches\t[7]AA Hom matches\t[8]RR Hom mismatches\t[9]RA Het mismatches\t[10]AA Hom mismatches\t[11]dosage r-squared\n");
1661 stats = args->smpl_gts_snps;
1662 }
1663 else
1664 {
1665 printf("# GCiS, Genotype concordance by sample (indels)\n# GCiS\t[2]id\t[3]sample\t[4]non-reference discordance rate\t[5]RR Hom matches\t[6]RA Het matches\t[7]AA Hom matches\t[8]RR Hom mismatches\t[9]RA Het mismatches\t[10]AA Hom mismatches\t[11]dosage r-squared\n");
1666 stats = args->smpl_gts_indels;
1667 }
1668 for (i=0; i<args->files->n_smpl; i++)
1669 {
1670 uint64_t mm = 0, m = stats[i].gt2gt[T2S(GT_HET_RA)][T2S(GT_HET_RA)] + stats[i].gt2gt[T2S(GT_HOM_AA)][T2S(GT_HOM_AA)];
1671 for (j=0; j<3; j++)
1672 for (k=0; k<3; k++)
1673 if ( j!=k ) mm += stats[i].gt2gt[j][k];
1674
1675 // Pearson's r2
1676 double r2 = 0;
1677 if ( stats[i].n )
1678 {
1679 r2 = (stats[i].yx - stats[i].x*stats[i].y/stats[i].n);
1680 r2 /= sqrt((stats[i].xx - stats[i].x*stats[i].x/stats[i].n) * (stats[i].yy - stats[i].y*stats[i].y/stats[i].n));
1681 r2 *= r2;
1682 }
1683 printf("GC%cS\t2\t%s\t%.3f", x==0 ? 's' : 'i', args->files->samples[i], m+mm ? mm*100.0/(m+mm) : 0);
1684 printf("\t%"PRIu64"\t%"PRIu64"\t%"PRIu64"",
1685 stats[i].gt2gt[T2S(GT_HOM_RR)][T2S(GT_HOM_RR)],
1686 stats[i].gt2gt[T2S(GT_HET_RA)][T2S(GT_HET_RA)],
1687 stats[i].gt2gt[T2S(GT_HOM_AA)][T2S(GT_HOM_AA)]);
1688 printf("\t%"PRIu64"\t%"PRIu64"\t%"PRIu64"",
1689 stats[i].gt2gt[T2S(GT_HOM_RR)][T2S(GT_HET_RA)] + stats[i].gt2gt[T2S(GT_HOM_RR)][T2S(GT_HOM_AA)],
1690 stats[i].gt2gt[T2S(GT_HET_RA)][T2S(GT_HOM_RR)] + stats[i].gt2gt[T2S(GT_HET_RA)][T2S(GT_HOM_AA)],
1691 stats[i].gt2gt[T2S(GT_HOM_AA)][T2S(GT_HOM_RR)] + stats[i].gt2gt[T2S(GT_HOM_AA)][T2S(GT_HET_RA)]);
1692 if ( stats[i].n && !isnan(r2) ) printf("\t%f\n", r2);
1693 else printf("\t"NA_STRING"\n");
1694 }
1695 }
1696 for (x=0; x<2; x++) // x=0: snps, x=1: indels
1697 {
1698 //printf("# GCiS, Genotype concordance by sample (indels)\n# GCiS\t[2]id\t[3]sample\t[4]non-reference discordance rate\t[5]RR Hom matches\t[6]RA Het matches\t[7]AA Hom matches\t[8]RR Hom mismatches\t[9]RA Het mismatches\t[10]AA Hom mismatches\t[11]dosage r-squared\n");
1699
1700 gtcmp_t *stats;
1701 if ( x==0 )
1702 {
1703 printf("# GCTs, Genotype concordance table (SNPs)\n# GCTs");
1704 stats = args->smpl_gts_snps;
1705 }
1706 else
1707 {
1708 printf("# GCTi, Genotype concordance table (indels)\n# GCTi");
1709 stats = args->smpl_gts_indels;
1710 }
1711 i = 1;
1712 printf("\t[%d]sample", ++i);
1713 printf("\t[%d]RR Hom -> RR Hom", ++i);
1714 printf("\t[%d]RR Hom -> RA Het", ++i);
1715 printf("\t[%d]RR Hom -> AA Hom", ++i);
1716 printf("\t[%d]RR Hom -> AA Het", ++i);
1717 printf("\t[%d]RR Hom -> missing", ++i);
1718 printf("\t[%d]RA Het -> RR Hom", ++i);
1719 printf("\t[%d]RA Het -> RA Het", ++i);
1720 printf("\t[%d]RA Het -> AA Hom", ++i);
1721 printf("\t[%d]RA Het -> AA Het", ++i);
1722 printf("\t[%d]RA Het -> missing", ++i);
1723 printf("\t[%d]AA Hom -> RR Hom", ++i);
1724 printf("\t[%d]AA Hom -> RA Het", ++i);
1725 printf("\t[%d]AA Hom -> AA Hom", ++i);
1726 printf("\t[%d]AA Hom -> AA Het", ++i);
1727 printf("\t[%d]AA Hom -> missing", ++i);
1728 printf("\t[%d]AA Het -> RR Hom", ++i);
1729 printf("\t[%d]AA Het -> RA Het", ++i);
1730 printf("\t[%d]AA Het -> AA Hom", ++i);
1731 printf("\t[%d]AA Het -> AA Het", ++i);
1732 printf("\t[%d]AA Het -> missing", ++i);
1733 printf("\t[%d]missing -> RR Hom", ++i);
1734 printf("\t[%d]missing -> RA Het", ++i);
1735 printf("\t[%d]missing -> AA Hom", ++i);
1736 printf("\t[%d]missing -> AA Het", ++i);
1737 printf("\t[%d]missing -> missing\n", ++i);
1738
1739 for (i=0; i<args->files->n_smpl; i++)
1740 {
1741 printf("GCT%c\t%s", x==0 ? 's' : 'i', args->files->samples[i]);
1742 for (j=0; j<5; j++)
1743 for (k=0; k<5; k++)
1744 printf("\t%"PRIu64, stats[i].gt2gt[j][k]);
1745 printf("\n");
1746 }
1747 }
1748 }
1749
1750 printf("# DP, depth:\n"
1751 "# - set id, see above\n"
1752 "# - the depth bin, corresponds to the depth (unless --depth was given)\n"
1753 "# - number of genotypes with this depth (zero unless -s/-S was given)\n"
1754 "# - fraction of genotypes with this depth (zero unless -s/-S was given)\n"
1755 "# - number of sites with this depth\n"
1756 "# - fraction of sites with this depth\n");
1757 printf("# DP, Depth distribution\n# DP\t[2]id\t[3]bin\t[4]number of genotypes\t[5]fraction of genotypes (%%)\t[6]number of sites\t[7]fraction of sites (%%)\n");
1758 for (id=0; id<args->nstats; id++)
1759 {
1760 stats_t *stats = &args->stats[id];
1761 long unsigned int sum = 0, sum_sites = 0;
1762 for (i=0; i<stats->dp.m_vals; i++) { sum += stats->dp.vals[i]; sum_sites += stats->dp_sites.vals[i]; }
1763 for (i=0; i<stats->dp.m_vals; i++)
1764 {
1765 if ( stats->dp.vals[i]==0 && stats->dp_sites.vals[i]==0 ) continue;
1766 printf("DP\t%d\t", id);
1767 if ( i==0 ) printf("<%d", stats->dp.min);
1768 else if ( i+1==stats->dp.m_vals ) printf(">%d", stats->dp.max);
1769 else printf("%d", idist_i2bin(&stats->dp,i));
1770 printf("\t%"PRIu64"\t%f", stats->dp.vals[i], sum ? stats->dp.vals[i]*100./sum : 0);
1771 printf("\t%"PRIu64"\t%f\n", stats->dp_sites.vals[i], sum_sites ? stats->dp_sites.vals[i]*100./sum_sites : 0);
1772 }
1773 }
1774
1775 if ( args->files->n_smpl )
1776 {
1777 printf("# PSC, Per-sample counts. Note that the ref/het/hom counts include only SNPs, for indels see PSI. The rest include both SNPs and indels.\n");
1778 printf("# PSC\t[2]id\t[3]sample\t[4]nRefHom\t[5]nNonRefHom\t[6]nHets\t[7]nTransitions\t[8]nTransversions\t[9]nIndels\t[10]average depth\t[11]nSingletons"
1779 "\t[12]nHapRef\t[13]nHapAlt\t[14]nMissing\n");
1780 for (id=0; id<args->nstats; id++)
1781 {
1782 stats_t *stats = &args->stats[id];
1783 for (i=0; i<args->files->n_smpl; i++)
1784 {
1785 float dp = stats->smpl_ndp[i] ? stats->smpl_dp[i]/(float)stats->smpl_ndp[i] : 0;
1786 printf("PSC\t%d\t%s\t%d\t%d\t%d\t%d\t%d\t%d\t%.1f\t%d\t%d\t%d\t%d\n", id,args->files->samples[i],
1787 stats->smpl_homRR[i], stats->smpl_homAA[i], stats->smpl_hets[i], stats->smpl_ts[i],
1788 stats->smpl_tv[i], stats->smpl_indels[i],dp, stats->smpl_sngl[i], stats->smpl_hapRef[i],
1789 stats->smpl_hapAlt[i], stats->smpl_missing[i]);
1790 }
1791 }
1792
1793 printf("# PSI, Per-Sample Indels. Note that alt-het genotypes with both ins and del allele are counted twice, in both nInsHets and nDelHets.\n");
1794 printf("# PSI\t[2]id\t[3]sample\t[4]in-frame\t[5]out-frame\t[6]not applicable\t[7]out/(in+out) ratio\t[8]nInsHets\t[9]nDelHets\t[10]nInsAltHoms\t[11]nDelAltHoms\n");
1795 for (id=0; id<args->nstats; id++)
1796 {
1797 stats_t *stats = &args->stats[id];
1798 for (i=0; i<args->files->n_smpl; i++)
1799 {
1800 int na = 0, in = 0, out = 0;
1801 if ( args->exons )
1802 {
1803 na = stats->smpl_frm_shifts[i*3 + 0];
1804 in = stats->smpl_frm_shifts[i*3 + 1];
1805 out = stats->smpl_frm_shifts[i*3 + 2];
1806 }
1807 printf("PSI\t%d\t%s\t%d\t%d\t%d\t%.2f\t%d\t%d\t%d\t%d\n", id,args->files->samples[i], in,out,na,in+out?1.0*out/(in+out):0,
1808 stats->smpl_ins_hets[i],stats->smpl_del_hets[i],stats->smpl_ins_homs[i],stats->smpl_del_homs[i]);
1809 }
1810 }
1811
1812 #ifdef HWE_STATS
1813 printf("# HWE\n# HWE\t[2]id\t[3]1st ALT allele frequency\t[4]Number of observations\t[5]25th percentile\t[6]median\t[7]75th percentile\n");
1814 for (id=0; id<args->nstats; id++)
1815 {
1816 stats_t *stats = &args->stats[id];
1817 for (i=0; i<args->naf_hwe; i++) stats->af_hwe[i+args->naf_hwe] += stats->af_hwe[i]; // singletons
1818 for (i=1; i<args->m_af; i++)
1819 {
1820 unsigned int sum_tot = 0, sum_tmp = 0;
1821 int j, *ptr = &stats->af_hwe[i*args->naf_hwe];
1822 for (j=0; j<args->naf_hwe; j++) sum_tot += ptr[j];
1823 if ( !sum_tot ) continue;
1824
1825 double af = args->af_bins ? (bin_get_value(args->af_bins,i)+bin_get_value(args->af_bins,i-1))*0.5 : (double)(i-1)/(args->m_af-1);
1826
1827 int nprn = 3;
1828 printf("HWE\t%d\t%f\t%d",id,af,sum_tot);
1829 for (j=0; j<args->naf_hwe; j++)
1830 {
1831 sum_tmp += ptr[j];
1832 float frac = (float)sum_tmp/sum_tot;
1833 if ( frac >= 0.75 )
1834 {
1835 while (nprn>0) { printf("\t%f", (float)j/args->naf_hwe); nprn--; }
1836 break;
1837 }
1838 if ( frac >= 0.5 )
1839 {
1840 while (nprn>1) { printf("\t%f", (float)j/args->naf_hwe); nprn--; }
1841 continue;
1842 }
1843 if ( frac >= 0.25 )
1844 {
1845 while (nprn>2) { printf("\t%f", (float)j/args->naf_hwe); nprn--; }
1846 }
1847 }
1848 assert(nprn==0);
1849 printf("\n");
1850 }
1851 }
1852 #endif
1853 }
1854
1855 if ( args->stats[0].smpl_vaf )
1856 {
1857 printf("# VAF, Variant Allele Frequency determined as fraction of alternate reads in FORMAT/AD\n");
1858 printf("# VAF\t[2]id\t[3]sample\t[4]SNV VAF distribution\t[5]indel VAF distribution\n");
1859 for (id=0; id<args->nstats; id++)
1860 {
1861 stats_t *stats = &args->stats[id];
1862 for (i=0; i<args->files->n_smpl; i++)
1863 {
1864 printf("VAF\t%d\t%s\t", id,args->files->samples[i]);
1865 for (j=0; j<21; j++) printf("%s%d",j?",":"",stats->smpl_vaf[i].snv[j]);
1866 printf("\t");
1867 for (j=0; j<21; j++) printf("%s%d",j?",":"",stats->smpl_vaf[i].indel[j]);
1868 printf("\n");
1869 }
1870 }
1871 }
1872 }
1873
1874 static void usage(void)
1875 {
1876 fprintf(stderr, "\n");
1877 fprintf(stderr, "About: Parses VCF or BCF and produces stats which can be plotted using plot-vcfstats.\n");
1878 fprintf(stderr, " When two files are given, the program generates separate stats for intersection\n");
1879 fprintf(stderr, " and the complements. By default only sites are compared, -s/-S must given to include\n");
1880 fprintf(stderr, " also sample columns.\n");
1881 fprintf(stderr, "Usage: bcftools stats [options] <A.vcf.gz> [<B.vcf.gz>]\n");
1882 fprintf(stderr, "\n");
1883 fprintf(stderr, "Options:\n");
1884 fprintf(stderr, " --af-bins LIST Allele frequency bins, a list (0.1,0.5,1) or a file (0.1\\n0.5\\n1)\n");
1885 fprintf(stderr, " --af-tag STRING Allele frequency tag to use, by default estimated from AN,AC or GT\n");
1886 fprintf(stderr, " -1, --1st-allele-only Include only 1st allele at multiallelic sites\n");
1887 fprintf(stderr, " -c, --collapse STRING Treat as identical records with <snps|indels|both|all|some|none>, see man page for details [none]\n");
1888 fprintf(stderr, " -d, --depth INT,INT,INT Depth distribution: min,max,bin size [0,500,1]\n");
1889 fprintf(stderr, " -e, --exclude EXPR Exclude sites for which the expression is true (see man page for details)\n");
1890 fprintf(stderr, " -E, --exons FILE.gz Tab-delimited file with exons for indel frameshifts (chr,beg,end; 1-based, inclusive, bgzip compressed)\n");
1891 fprintf(stderr, " -f, --apply-filters LIST Require at least one of the listed FILTER strings (e.g. \"PASS,.\")\n");
1892 fprintf(stderr, " -F, --fasta-ref FILE Faidx indexed reference sequence file to determine INDEL context\n");
1893 fprintf(stderr, " -i, --include EXPR Select sites for which the expression is true (see man page for details)\n");
1894 fprintf(stderr, " -I, --split-by-ID Collect stats for sites with ID separately (known vs novel)\n");
1895 fprintf(stderr, " -r, --regions REGION Restrict to comma-separated list of regions\n");
1896 fprintf(stderr, " -R, --regions-file FILE Restrict to regions listed in a file\n");
1897 fprintf(stderr, " --regions-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [1]\n");
1898 fprintf(stderr, " -s, --samples LIST List of samples for sample stats, \"-\" to include all samples\n");
1899 fprintf(stderr, " -S, --samples-file FILE File of samples to include\n");
1900 fprintf(stderr, " -t, --targets REGION Similar to -r but streams rather than index-jumps\n");
1901 fprintf(stderr, " -T, --targets-file FILE Similar to -R but streams rather than index-jumps\n");
1902 fprintf(stderr, " --targets-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [0]\n");
1903 fprintf(stderr, " -u, --user-tstv TAG[:min:max:n] Collect Ts/Tv stats for any tag using the given binning [0:1:100]\n");
1904 fprintf(stderr, " A subfield can be selected as e.g. 'PV4[0]', here the first value of the PV4 tag\n");
1905 fprintf(stderr, " --threads INT Use multithreading with <int> worker threads [0]\n");
1906 fprintf(stderr, " -v, --verbose Produce verbose per-site and per-sample output\n");
1907 fprintf(stderr, "\n");
1908 exit(1);
1909 }
1910
1911 int main_vcfstats(int argc, char *argv[])
1912 {
1913 int c;
1914 args_t *args = (args_t*) calloc(1,sizeof(args_t));
1915 args->files = bcf_sr_init();
1916 args->argc = argc; args->argv = argv;
1917 args->dp_min = 0; args->dp_max = 500; args->dp_step = 1;
1918 int regions_is_file = 0, targets_is_file = 0;
1919 int regions_overlap = 1;
1920 int targets_overlap = 0;
1921
1922 static struct option loptions[] =
1923 {
1924 {"af-bins",1,0,1},
1925 {"af-tag",1,0,2},
1926 {"1st-allele-only",0,0,'1'},
1927 {"include",1,0,'i'},
1928 {"exclude",1,0,'e'},
1929 {"help",0,0,'h'},
1930 {"collapse",1,0,'c'},
1931 {"regions",1,0,'r'},
1932 {"regions-file",1,0,'R'},
1933 {"regions-overlap",required_argument,NULL,3},
1934 {"verbose",0,0,'v'},
1935 {"depth",1,0,'d'},
1936 {"apply-filters",1,0,'f'},
1937 {"exons",1,0,'E'},
1938 {"samples",1,0,'s'},
1939 {"samples-file",1,0,'S'},
1940 {"split-by-ID",0,0,'I'},
1941 {"targets",1,0,'t'},
1942 {"targets-file",1,0,'T'},
1943 {"targets-overlap",required_argument,NULL,4},
1944 {"fasta-ref",1,0,'F'},
1945 {"user-tstv",1,0,'u'},
1946 {"threads",1,0,9},
1947 {0,0,0,0}
1948 };
1949 while ((c = getopt_long(argc, argv, "hc:r:R:e:s:S:d:i:t:T:F:f:1u:vIE:",loptions,NULL)) >= 0) {
1950 switch (c) {
1951 case 1 : args->af_bins_list = optarg; break;
1952 case 2 : args->af_tag = optarg; break;
1953 case 'u': add_user_stats(args,optarg); break;
1954 case '1': args->first_allele_only = 1; break;
1955 case 'F': args->ref_fname = optarg; break;
1956 case 't': args->targets_list = optarg; break;
1957 case 'T': args->targets_list = optarg; targets_is_file = 1; break;
1958 case 'c':
1959 if ( !strcmp(optarg,"snps") ) args->files->collapse |= COLLAPSE_SNPS;
1960 else if ( !strcmp(optarg,"indels") ) args->files->collapse |= COLLAPSE_INDELS;
1961 else if ( !strcmp(optarg,"both") ) args->files->collapse |= COLLAPSE_SNPS | COLLAPSE_INDELS;
1962 else if ( !strcmp(optarg,"any") ) args->files->collapse |= COLLAPSE_ANY;
1963 else if ( !strcmp(optarg,"all") ) args->files->collapse |= COLLAPSE_ANY;
1964 else if ( !strcmp(optarg,"some") ) args->files->collapse |= COLLAPSE_SOME;
1965 else if ( !strcmp(optarg,"none") ) args->files->collapse = COLLAPSE_NONE;
1966 else error("The --collapse string \"%s\" not recognised.\n", optarg);
1967 break;
1968 case 'v': args->verbose_sites = 1; break;
1969 case 'd':
1970 if ( sscanf(optarg,"%d,%d,%d",&args->dp_min,&args->dp_max,&args->dp_step)!=3 )
1971 error("Could not parse --depth %s\n", optarg);
1972 if ( args->dp_min<0 || args->dp_min >= args->dp_max || args->dp_step > args->dp_max - args->dp_min + 1 )
1973 error("Is this a typo? --depth %s\n", optarg);
1974 break;
1975 case 'f': args->files->apply_filters = optarg; break;
1976 case 'r': args->regions_list = optarg; break;
1977 case 'R': args->regions_list = optarg; regions_is_file = 1; break;
1978 case 'E': args->exons_fname = optarg; break;
1979 case 's': args->samples_list = optarg; break;
1980 case 'S': args->samples_list = optarg; args->samples_is_file = 1; break;
1981 case 'I': args->split_by_id = 1; break;
1982 case 'e':
1983 if ( args->filter_str ) error("Error: only one -i or -e expression can be given, and they cannot be combined\n");
1984 args->filter_str = optarg; args->filter_logic |= FLT_EXCLUDE; break;
1985 case 'i':
1986 if ( args->filter_str ) error("Error: only one -i or -e expression can be given, and they cannot be combined\n");
1987 args->filter_str = optarg; args->filter_logic |= FLT_INCLUDE; break;
1988 case 3 :
1989 regions_overlap = parse_overlap_option(optarg);
1990 if ( regions_overlap < 0 ) error("Could not parse: --regions-overlap %s\n",optarg);
1991 break;
1992 case 4 :
1993 targets_overlap = parse_overlap_option(optarg);
1994 if ( targets_overlap < 0 ) error("Could not parse: --targets-overlap %s\n",optarg);
1995 break;
1996 case 9 : args->n_threads = strtol(optarg, 0, 0); break;
1997 case 'h':
1998 case '?': usage(); break;
1999 default: error("Unknown argument: %s\n", optarg);
2000 }
2001 }
2002 char *fname = NULL;
2003 if ( optind==argc )
2004 {
2005 if ( !isatty(fileno((FILE *)stdin)) ) fname = "-"; // reading from stdin
2006 else usage();
2007 }
2008 else fname = argv[optind];
2009
2010 if ( argc-optind>2 ) usage();
2011 if ( argc-optind>1 )
2012 {
2013 args->files->require_index = 1;
2014 if ( args->split_by_id ) error("Only one file can be given with -i.\n");
2015 }
2016 if ( !args->samples_list ) args->files->max_unpack = BCF_UN_INFO;
2017 else args->files->max_unpack = BCF_UN_FMT;
2018 if ( args->targets_list )
2019 {
2020 bcf_sr_set_opt(args->files,BCF_SR_TARGETS_OVERLAP,targets_overlap);
2021 if ( bcf_sr_set_targets(args->files, args->targets_list, targets_is_file, 0)<0 )
2022 error("Failed to read the targets: %s\n", args->targets_list);
2023 }
2024 if ( args->regions_list)
2025 {
2026 bcf_sr_set_opt(args->files,BCF_SR_REGIONS_OVERLAP,regions_overlap);
2027 if ( bcf_sr_set_regions(args->files, args->regions_list, regions_is_file)<0 )
2028 error("Failed to read the regions: %s\n", args->regions_list);
2029 }
2030 if ( args->n_threads && bcf_sr_set_threads(args->files, args->n_threads)<0)
2031 error("Failed to create threads\n");
2032
2033 while (fname)
2034 {
2035 if ( !bcf_sr_add_reader(args->files, fname) )
2036 error("Failed to read from %s: %s\n", !strcmp("-",fname)?"standard input":fname,bcf_sr_strerror(args->files->errnum));
2037 fname = ++optind < argc ? argv[optind] : NULL;
2038 }
2039
2040 init_stats(args);
2041 print_header(args);
2042 do_vcf_stats(args);
2043 print_stats(args);
2044 destroy_stats(args);
2045 bcf_sr_destroy(args->files);
2046 free(args);
2047 return 0;
2048 }
2049