forked from samtools/bcftools
-
Notifications
You must be signed in to change notification settings - Fork 2
/
vcfstats.c
1913 lines (1793 loc) · 79.2 KB
/
vcfstats.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* vcfstats.c -- Produces stats which can be plotted using plot-vcfstats.
Copyright (C) 2012-2021 Genome Research Ltd.
Author: Petr Danecek <pd3@sanger.ac.uk>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
/*
Notes and known issues:
- SN ts/tv calculation includes all non-ref alleles listed in ALT while per-sample ts/tv
takes the first non-ref allele only, something to consider with many non-ref HETs.
*/
#include <stdio.h>
#include <stdarg.h>
#include <unistd.h>
#include <getopt.h>
#include <assert.h>
#include <math.h>
#include <htslib/vcf.h>
#include <htslib/synced_bcf_reader.h>
#include <htslib/vcfutils.h>
#include <htslib/faidx.h>
#include <inttypes.h>
#include "bcftools.h"
#include "filter.h"
#include "bin.h"
#include "dist.h"
// Logic of the filters: include or exclude sites which match the filters?
#define FLT_INCLUDE 1
#define FLT_EXCLUDE 2
#define HWE_STATS 1
#define QUAL_STATS 1
#define IRC_STATS 1
#define IRC_RLEN 10
#define NA_STRING "0"
typedef struct
{
char *tag;
float min, max;
uint64_t *vals_ts, *vals_tv;
void *val;
int nbins, type, m_val, idx;
}
user_stats_t;
typedef struct
{
int min, max, step, m_vals;
uint64_t *vals;
}
idist_t;
typedef struct
{
uint64_t n_snps, n_indels, n_mnps, n_others, n_mals, n_snp_mals, n_records, n_noalts;
int *af_ts, *af_tv, *af_snps; // first bin of af_* stats are singletons
#if HWE_STATS
int *af_hwe;
#endif
#if IRC_STATS
int n_repeat[IRC_RLEN][4], n_repeat_na; // number of indels which are repeat-consistent, repeat-inconsistent (dels and ins), and not applicable
int *af_repeats[3];
#endif
int ts_alt1, tv_alt1;
#if QUAL_STATS
// Values are rounded to one significant digit and 1 is added (Q*10+1); missing and negative values go in the first bin
// Only SNPs that are the 1st alternate allele are counted
dist_t *qual_ts, *qual_tv, *qual_indels;
#endif
int *insertions, *deletions, m_indel; // maximum indel length
int in_frame, out_frame, na_frame, in_frame_alt1, out_frame_alt1, na_frame_alt1;
int subst[15];
int *smpl_hets, *smpl_homRR, *smpl_homAA, *smpl_ts, *smpl_tv, *smpl_indels, *smpl_ndp, *smpl_sngl;
int *smpl_hapRef, *smpl_hapAlt, *smpl_missing;
int *smpl_ins_hets, *smpl_del_hets, *smpl_ins_homs, *smpl_del_homs;
int *smpl_frm_shifts; // not-applicable, in-frame, out-frame
unsigned long int *smpl_dp;
idist_t dp, dp_sites;
int nusr;
user_stats_t *usr;
double *dvaf; // distribution of the mean indel-allele frequency by length: -m_indel,-(m_indel-1),...-1,0,1,..,m_indel
uint32_t *nvaf;
}
stats_t;
typedef struct
{
uint64_t gt2gt[5][5]; // number of RR->RR, RR->RA, etc. matches/mismatches; see type2stats
/*
Pearson's R^2 is used for aggregate R^2
y, yy .. sum of dosage and squared dosage in the query VCF (second file)
x, xx .. sum of squared dosage in the truth VCF (first file)
n .. number of genotypes
*/
double y, yy, x, xx, yx, n;
}
gtcmp_t;
typedef struct
{
char *seq;
int pos, cnt, len;
}
_idc1_t;
typedef struct
{
faidx_t *ref;
_idc1_t *dat;
int ndat, mdat;
}
indel_ctx_t;
typedef struct
{
// stats
stats_t stats[3];
int *tmp_iaf, ntmp_iaf, m_af, m_qual, naf_hwe, mtmp_frm;
uint8_t *tmp_frm;
int dp_min, dp_max, dp_step;
gtcmp_t *smpl_gts_snps, *smpl_gts_indels;
gtcmp_t *af_gts_snps, *af_gts_indels; // first bin of af_* stats are singletons
bin_t *af_bins;
float *farr;
int mfarr;
// indel context
indel_ctx_t *indel_ctx;
char *ref_fname;
// user stats
int nusr;
user_stats_t *usr;
// other
bcf_srs_t *files;
bcf_sr_regions_t *exons;
char **argv, *exons_fname, *regions_list, *samples_list, *targets_list, *af_bins_list, *af_tag;
int argc, verbose_sites, first_allele_only, samples_is_file;
int split_by_id, nstats;
filter_t *filter[2];
char *filter_str;
int filter_logic; // include or exclude sites which match the filters? One of FLT_INCLUDE/FLT_EXCLUDE
int n_threads;
}
args_t;
static int type2dosage[6], type2ploidy[6], type2stats[7];
static void idist_init(idist_t *d, int min, int max, int step)
{
d->min = min; d->max = max; d->step = step;
d->m_vals = 4 + (d->max - d->min)/d->step;
d->vals = (uint64_t*) calloc(d->m_vals,sizeof(uint64_t));
}
static void idist_destroy(idist_t *d)
{
if ( d->vals ) free(d->vals);
}
static inline uint64_t *idist(idist_t *d, int val)
{
if ( val < d->min ) return &d->vals[0];
if ( val > d->max ) return &d->vals[d->m_vals-1];
return &d->vals[1 + (val - d->min) / d->step];
}
static inline int idist_i2bin(idist_t *d, int i)
{
if ( i<=0 ) return d->min;
if ( i>= d->m_vals ) return d->max;
return i-1+d->min;
}
#define IC_DBG 0
#if IC_DBG
static void _indel_ctx_print1(_idc1_t *idc)
{
int i;
fprintf(stdout, "%d\t", idc->cnt);
for (i=0; i<idc->len; i++)
fputc(idc->seq[i], stdout);
fputc('\n', stdout);
}
static void _indel_ctx_print(indel_ctx_t *ctx)
{
int i;
for (i=0; i<ctx->ndat; i++)
_indel_ctx_print1(&ctx->dat[i]);
fputc('\n',stdout);
}
#endif
static int _indel_ctx_lookup(indel_ctx_t *ctx, char *seq, int seq_len, int *hit)
{
// binary search
int min = 0, max = ctx->ndat - 1;
while ( min<=max )
{
int i = (min+max)/2;
int cmp = strncmp(seq, ctx->dat[i].seq, seq_len);
if ( cmp<0 ) max = i - 1;
else if ( cmp>0 ) min = i + 1;
else
{
if ( seq_len==ctx->dat[i].len )
{
*hit = 1;
return i;
}
else if ( seq_len<ctx->dat[i].len ) max = i - 1;
else min = i + 1;
}
}
*hit = 0;
return max;
}
static void _indel_ctx_insert(indel_ctx_t *ctx, char *seq, int seq_len, int pos)
{
int idat, hit, i;
idat = _indel_ctx_lookup(ctx, seq, seq_len, &hit);
if ( !hit )
{
if ( pos>0 ) return;
idat++;
ctx->ndat++;
hts_expand(_idc1_t, ctx->ndat+1, ctx->mdat, ctx->dat);
if ( idat<ctx->ndat && ctx->ndat>1 )
memmove(&ctx->dat[idat+1], &ctx->dat[idat], (ctx->ndat - idat - 1)*sizeof(_idc1_t));
ctx->dat[idat].len = seq_len;
ctx->dat[idat].cnt = 1;
ctx->dat[idat].pos = pos;
ctx->dat[idat].seq = (char*) malloc(sizeof(char)*(seq_len+1));
for (i=0; i<seq_len; i++) ctx->dat[idat].seq[i] = seq[i];
ctx->dat[idat].seq[i] = 0;
return;
}
if ( ctx->dat[idat].pos + seq_len == pos )
{
ctx->dat[idat].cnt++;
ctx->dat[idat].pos = pos;
}
}
indel_ctx_t *indel_ctx_init(char *fa_ref_fname)
{
indel_ctx_t *ctx = (indel_ctx_t *) calloc(1,sizeof(indel_ctx_t));
ctx->ref = fai_load(fa_ref_fname);
if ( !ctx->ref )
{
free(ctx);
return NULL;
}
return ctx;
}
void indel_ctx_destroy(indel_ctx_t *ctx)
{
fai_destroy(ctx->ref);
if ( ctx->mdat ) free(ctx->dat);
free(ctx);
}
/**
* indel_ctx_type() - determine indel context type
* @ctx:
* @chr: chromosome name
* @pos: position of the first @ref base, 1-based
* @ref: reference allele
* @alt: alternate allele. Only first of multiple comma-separated alleles is
* considered
* @nrep: number of repeated elements (w)
* @nlen: length of a single repeat element (w)
*
* Returns the INDEL length, negative for deletions, positive for insertions
*/
int indel_ctx_type(indel_ctx_t *ctx, char *chr, int pos, char *ref, char *alt, int *nrep, int *nlen)
{
const int win_size = 50; // hard-wired for now
const int rep_len = IRC_RLEN; // hard-wired for now
int ref_len = strlen(ref);
int alt_len = 0;
while ( alt[alt_len] && alt[alt_len]!=',' ) alt_len++;
int i, fai_ref_len;
char *fai_ref = faidx_fetch_seq(ctx->ref, chr, pos-1, pos+win_size, &fai_ref_len);
for (i=0; i<fai_ref_len; i++)
if ( (int)fai_ref[i]>96 ) fai_ref[i] -= 32;
// Sanity check: the reference sequence must match the REF allele
for (i=0; i<fai_ref_len && i<ref_len; i++)
if ( ref[i] != fai_ref[i] && ref[i] - 32 != fai_ref[i] && !iupac_consistent(fai_ref[i], ref[i]) )
error("\nSanity check failed, the reference sequence differs: %s:%d+%d .. %c vs %c\n", chr, pos, i, ref[i],fai_ref[i]);
// Count occurrences of all possible kmers
ctx->ndat = 0;
for (i=0; i<win_size; i++)
{
int k, kmax = rep_len <= i ? rep_len : i+1;
for (k=0; k<kmax; k++)
_indel_ctx_insert(ctx, &fai_ref[i-k+1], k+1, i-k);
}
#if IC_DBG
fprintf(stdout,"ref: %s\n", ref);
fprintf(stdout,"alt: %s\n", alt);
fprintf(stdout,"ctx: %s\n", fai_ref);
_indel_ctx_print(ctx);
#endif
int max_cnt = 0, max_len = 0;
for (i=0; i<ctx->ndat; i++)
{
if ( max_cnt < ctx->dat[i].cnt || (max_cnt==ctx->dat[i].cnt && max_len < ctx->dat[i].len) )
{
max_cnt = ctx->dat[i].cnt;
max_len = ctx->dat[i].len;
}
free(ctx->dat[i].seq);
}
free(fai_ref);
*nrep = max_cnt;
*nlen = max_len;
return alt_len - ref_len;
}
static void add_user_stats(args_t *args, char *str)
{
args->nusr++;
args->usr = (user_stats_t*) realloc(args->usr,sizeof(user_stats_t)*args->nusr);
user_stats_t *usr = &args->usr[args->nusr-1];
memset(usr,0,sizeof(*usr));
usr->min = 0;
usr->max = 1;
usr->nbins = 100;
usr->idx = 0;
char *tmp = str;
while ( *tmp && *tmp!=':' ) tmp++;
// Tag with an index or just tag? (e.g. PV4[1] vs DP)
if ( tmp > str && tmp[-1]==']' )
{
char *ptr = tmp;
while ( ptr>str && *ptr!='[' ) ptr--;
if ( *ptr=='[' )
{
char *ptr2;
usr->idx = strtol(ptr+1, &ptr2, 10);
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);
if ( usr->idx<0 ) error("Error: negative index is not allowed: \"%s\"\n", str);
*ptr = 0;
}
}
usr->tag = (char*)calloc(tmp-str+2,sizeof(char));
memcpy(usr->tag,str,tmp-str);
if ( *tmp )
{
char *ptr = ++tmp;
usr->min = strtod(tmp, &ptr);
if ( tmp==ptr ) error("Could not parse %s\n", str);
tmp = ptr+1;
}
if ( *tmp )
{
char *ptr = tmp;
usr->max = strtod(tmp, &ptr);
if ( tmp==ptr ) error("Could not parse %s\n", str);
tmp = ptr+1;
}
if ( *tmp )
{
char *ptr = tmp;
usr->nbins = strtol(tmp, &ptr, 10);
if ( tmp==ptr ) error("Could not parse %s\n", str);
if ( usr->nbins<=0 ) error("Number of bins does not make sense (%d): %s.\n", usr->nbins, str);
}
}
static void init_user_stats(args_t *args, bcf_hdr_t *hdr, stats_t *stats)
{
stats->nusr = args->nusr;
stats->usr = (user_stats_t*)malloc(sizeof(user_stats_t)*args->nusr);
memcpy(stats->usr,args->usr,args->nusr*sizeof(user_stats_t));
int i;
for (i=0; i<stats->nusr; i++)
{
user_stats_t *usr = &stats->usr[i];
usr->vals_ts = (uint64_t*)calloc(usr->nbins,sizeof(uint64_t));
usr->vals_tv = (uint64_t*)calloc(usr->nbins,sizeof(uint64_t));
int id = bcf_hdr_id2int(hdr,BCF_DT_ID,usr->tag);
if ( !bcf_hdr_idinfo_exists(hdr,BCF_HL_INFO,id) ) error("The INFO tag \"%s\" is not defined in the header\n", usr->tag);
usr->type = bcf_hdr_id2type(hdr,BCF_HL_INFO,id);
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);
}
}
static void init_stats(args_t *args)
{
int i;
args->nstats = args->files->nreaders==1 ? 1 : 3;
if ( args->split_by_id ) args->nstats = 2;
if ( args->filter_str )
{
args->filter[0] = filter_init(bcf_sr_get_header(args->files,0), args->filter_str);
if ( args->files->nreaders==2 )
args->filter[1] = filter_init(bcf_sr_get_header(args->files,1), args->filter_str);
args->files->max_unpack |= filter_max_unpack(args->filter[0]);
}
// AF corresponds to AC but is more robust to mixtures of haploid and diploid GTs
if ( !args->af_bins_list )
{
args->m_af = 101;
for (i=0; i<args->files->nreaders; i++)
if ( bcf_hdr_nsamples(args->files->readers[i].header) + 1> args->m_af )
args->m_af = bcf_hdr_nsamples(args->files->readers[i].header) + 1;
}
else
{
args->af_bins = bin_init(args->af_bins_list,0,1);
// m_af is used also for other af arrays, where the first bin is for
// singletons. However, since the last element is unused in af_bins
// (n boundaries form n-1 intervals), the m_af count is good for both.
args->m_af = bin_get_size(args->af_bins);
}
bcf_hdr_t *hdr = bcf_sr_get_header(args->files,0);
if ( args->af_tag && !bcf_hdr_idinfo_exists(hdr,BCF_HL_INFO,bcf_hdr_id2int(hdr,BCF_DT_ID,args->af_tag)) )
error("No such INFO tag: %s\n", args->af_tag);
#if QUAL_STATS
args->m_qual = 999;
#endif
#if HWE_STATS
args->naf_hwe = 100;
#endif
if ( args->samples_list )
{
if ( !bcf_sr_set_samples(args->files,args->samples_list,args->samples_is_file) )
{
if ( !bcf_hdr_nsamples(args->files->readers[0].header) )
error("No sample columns in %s\n", args->files->readers[0].fname);
error("Unable to parse the samples: \"%s\"\n", args->samples_list);
}
args->af_gts_snps = (gtcmp_t *) calloc(args->m_af,sizeof(gtcmp_t));
args->af_gts_indels = (gtcmp_t *) calloc(args->m_af,sizeof(gtcmp_t));
args->smpl_gts_snps = (gtcmp_t *) calloc(args->files->n_smpl,sizeof(gtcmp_t));
args->smpl_gts_indels = (gtcmp_t *) calloc(args->files->n_smpl,sizeof(gtcmp_t));
}
for (i=0; i<args->nstats; i++)
{
stats_t *stats = &args->stats[i];
stats->m_indel = 60;
stats->insertions = (int*) calloc(stats->m_indel,sizeof(int));
stats->deletions = (int*) calloc(stats->m_indel,sizeof(int));
stats->af_ts = (int*) calloc(args->m_af,sizeof(int));
stats->af_tv = (int*) calloc(args->m_af,sizeof(int));
stats->af_snps = (int*) calloc(args->m_af,sizeof(int));
int j;
for (j=0; j<3; j++) stats->af_repeats[j] = (int*) calloc(args->m_af,sizeof(int));
#if QUAL_STATS
stats->qual_ts = dist_init(5);
stats->qual_tv = dist_init(5);
stats->qual_indels = dist_init(5);
#endif
if ( args->files->n_smpl )
{
stats->smpl_missing = (int *) calloc(args->files->n_smpl,sizeof(int));
stats->smpl_hets = (int *) calloc(args->files->n_smpl,sizeof(int));
stats->smpl_homAA = (int *) calloc(args->files->n_smpl,sizeof(int));
stats->smpl_homRR = (int *) calloc(args->files->n_smpl,sizeof(int));
stats->smpl_hapRef = (int *) calloc(args->files->n_smpl,sizeof(int));
stats->smpl_hapAlt = (int *) calloc(args->files->n_smpl,sizeof(int));
stats->smpl_ins_hets = (int *) calloc(args->files->n_smpl,sizeof(int));
stats->smpl_del_hets = (int *) calloc(args->files->n_smpl,sizeof(int));
stats->smpl_ins_homs = (int *) calloc(args->files->n_smpl,sizeof(int));
stats->smpl_del_homs = (int *) calloc(args->files->n_smpl,sizeof(int));
stats->smpl_ts = (int *) calloc(args->files->n_smpl,sizeof(int));
stats->smpl_tv = (int *) calloc(args->files->n_smpl,sizeof(int));
stats->smpl_indels = (int *) calloc(args->files->n_smpl,sizeof(int));
stats->smpl_dp = (unsigned long int *) calloc(args->files->n_smpl,sizeof(unsigned long int));
stats->smpl_ndp = (int *) calloc(args->files->n_smpl,sizeof(int));
stats->smpl_sngl = (int *) calloc(args->files->n_smpl,sizeof(int));
#if HWE_STATS
stats->af_hwe = (int*) calloc(args->m_af*args->naf_hwe,sizeof(int));
#endif
if ( args->exons_fname )
stats->smpl_frm_shifts = (int*) calloc(args->files->n_smpl*3,sizeof(int));
stats->nvaf = (uint32_t*) calloc(stats->m_indel*2+1,sizeof(*stats->nvaf));
stats->dvaf = (double*) calloc(stats->m_indel*2+1,sizeof(*stats->dvaf));
}
idist_init(&stats->dp, args->dp_min,args->dp_max,args->dp_step);
idist_init(&stats->dp_sites, args->dp_min,args->dp_max,args->dp_step);
init_user_stats(args, i!=1 ? args->files->readers[0].header : args->files->readers[1].header, stats);
}
if ( args->exons_fname )
{
args->exons = bcf_sr_regions_init(args->exons_fname,1,0,1,2);
if ( !args->exons )
error("Error occurred while reading, was the file compressed with bgzip: %s?\n", args->exons_fname);
}
#if IRC_STATS
if ( args->ref_fname )
args->indel_ctx = indel_ctx_init(args->ref_fname);
#endif
type2dosage[GT_HOM_RR] = 0;
type2dosage[GT_HET_RA] = 1;
type2dosage[GT_HOM_AA] = 2;
type2dosage[GT_HET_AA] = 2;
type2dosage[GT_HAPL_R] = 0;
type2dosage[GT_HAPL_A] = 1;
type2ploidy[GT_HOM_RR] = 1;
type2ploidy[GT_HET_RA] = 1;
type2ploidy[GT_HOM_AA] = 1;
type2ploidy[GT_HET_AA] = 1;
type2ploidy[GT_HAPL_R] = -1;
type2ploidy[GT_HAPL_A] = -1;
type2stats[GT_HOM_RR] = 0;
type2stats[GT_HET_RA] = 1;
type2stats[GT_HOM_AA] = 2;
type2stats[GT_HET_AA] = 3;
type2stats[GT_HAPL_R] = 0;
type2stats[GT_HAPL_A] = 2;
type2stats[GT_UNKN] = 4;
}
static void destroy_stats(args_t *args)
{
int id, j;
for (id=0; id<args->nstats; id++)
{
stats_t *stats = &args->stats[id];
if (stats->af_ts) free(stats->af_ts);
if (stats->af_tv) free(stats->af_tv);
if (stats->af_snps) free(stats->af_snps);
for (j=0; j<3; j++)
if (stats->af_repeats[j]) free(stats->af_repeats[j]);
#if QUAL_STATS
if (stats->qual_ts) dist_destroy(stats->qual_ts);
if (stats->qual_tv) dist_destroy(stats->qual_tv);
if (stats->qual_indels) dist_destroy(stats->qual_indels);
#endif
#if HWE_STATS
free(stats->af_hwe);
#endif
free(stats->insertions);
free(stats->deletions);
free(stats->smpl_missing);
free(stats->smpl_hets);
free(stats->smpl_homAA);
free(stats->smpl_homRR);
free(stats->smpl_hapRef);
free(stats->smpl_hapAlt);
free(stats->smpl_ins_homs);
free(stats->smpl_del_homs);
free(stats->smpl_ins_hets);
free(stats->smpl_del_hets);
free(stats->smpl_ts);
free(stats->smpl_tv);
free(stats->smpl_indels);
free(stats->smpl_dp);
free(stats->smpl_ndp);
free(stats->smpl_sngl);
idist_destroy(&stats->dp);
idist_destroy(&stats->dp_sites);
for (j=0; j<stats->nusr; j++)
{
free(stats->usr[j].vals_ts);
free(stats->usr[j].vals_tv);
free(stats->usr[j].val);
}
free(stats->usr);
if ( args->exons ) free(stats->smpl_frm_shifts);
free(stats->nvaf);
free(stats->dvaf);
}
for (j=0; j<args->nusr; j++) free(args->usr[j].tag);
if ( args->af_bins ) bin_destroy(args->af_bins);
free(args->farr);
free(args->usr);
free(args->tmp_frm);
free(args->tmp_iaf);
if (args->exons) bcf_sr_regions_destroy(args->exons);
free(args->af_gts_snps);
free(args->af_gts_indels);
free(args->smpl_gts_snps);
free(args->smpl_gts_indels);
if (args->indel_ctx) indel_ctx_destroy(args->indel_ctx);
if (args->filter[0]) filter_destroy(args->filter[0]);
if (args->filter[1]) filter_destroy(args->filter[1]);
}
static void init_iaf(args_t *args, bcf_sr_t *reader)
{
bcf1_t *line = reader->buffer[0];
hts_expand(int32_t,line->n_allele,args->ntmp_iaf,args->tmp_iaf);
int i, ret;
if ( args->af_tag )
{
ret = bcf_get_info_float(reader->header, line, args->af_tag, &args->farr, &args->mfarr);
if ( ret<=0 || ret!=line->n_allele-1 )
{
// the AF tag is not present or wrong number of values, put in the singletons/unknown bin
for (i=0; i<line->n_allele; i++) args->tmp_iaf[i] = 0;
return;
}
args->tmp_iaf[0] = 0;
for (i=1; i<line->n_allele; i++)
{
float af = args->farr[i-1];
if ( af<0 ) af = 0;
else if ( af>1 ) af = 1;
int iaf = args->af_bins ? bin_get_idx(args->af_bins,af) : af*(args->m_af-2);
args->tmp_iaf[i] = iaf + 1; // the first tmp_iaf bin is reserved for singletons
}
return;
}
// tmp_iaf is first filled with AC counts in calc_ac and then transformed to
// an index to af_gts_snps
ret = bcf_calc_ac(reader->header, line, args->tmp_iaf, args->samples_list ? BCF_UN_INFO|BCF_UN_FMT : BCF_UN_INFO);
if ( !ret )
{
for (i=0; i<line->n_allele; i++) args->tmp_iaf[i] = 0; // singletons/unknown bin
return;
}
int an = 0;
for (i=0; i<line->n_allele; i++)
an += args->tmp_iaf[i];
args->tmp_iaf[0] = 0;
for (i=1; i<line->n_allele; i++)
{
if ( args->tmp_iaf[i]==1 )
args->tmp_iaf[i] = 0; // singletons into the first bin
else if ( !an )
args->tmp_iaf[i] = 1; // no genotype at all, put to the AF=0 bin
else
{
float af = (float) args->tmp_iaf[i] / an;
if ( af<0 ) af = 0;
else if ( af>1 ) af = 1;
int iaf = args->af_bins ? bin_get_idx(args->af_bins,af) : af*(args->m_af-2);
args->tmp_iaf[i] = iaf + 1;
}
}
}
static inline void do_mnp_stats(args_t *args, stats_t *stats, bcf_sr_t *reader)
{
stats->n_mnps++;
}
static inline void do_other_stats(args_t *args, stats_t *stats, bcf_sr_t *reader)
{
stats->n_others++;
}
static void do_indel_stats(args_t *args, stats_t *stats, bcf_sr_t *reader)
{
stats->n_indels++;
bcf1_t *line = reader->buffer[0];
#if QUAL_STATS
int iqual = (isnan(line->qual) || line->qual<0) ? 0 : 1 + (int)(line->qual*10);
dist_insert(stats->qual_indels, iqual);
#endif
// Check if the indel is near an exon for the frameshift statistics
int i, exon_overlap = 0;
if ( args->exons )
{
if ( !bcf_sr_regions_overlap(args->exons, bcf_seqname(reader->header,line),line->pos,line->pos) ) exon_overlap = 1;
hts_expand(uint8_t,line->n_allele,args->mtmp_frm,args->tmp_frm);
for (i=0; i<line->n_allele; i++) args->tmp_frm[i] = 0;
}
for (i=1; i<line->n_allele; i++)
{
if ( args->first_allele_only && i>1 ) break;
if ( bcf_get_variant_type(line,i)!=VCF_INDEL ) continue;
int len = line->d.var[i].n;
#if IRC_STATS
// Indel repeat consistency
if ( args->indel_ctx )
{
int nrep, nlen, ndel;
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);
if ( nlen<=1 || nrep<=1 )
{
// not a repeat or a single base repeat
stats->n_repeat_na++;
stats->af_repeats[2][ args->tmp_iaf[i] ]++;
}
else
{
if ( abs(ndel) % nlen )
{
// the length of the inserted/deleted sequence is not consistent with the repeat element
stats->n_repeat[nlen-1][ndel<0 ? 1 : 3]++;
stats->af_repeats[1][ args->tmp_iaf[i] ]++;
}
else
{
// the length consistent with the repeat
stats->n_repeat[nlen-1][ndel<0 ? 0 : 2]++;
stats->af_repeats[0][ args->tmp_iaf[i] ]++;
}
}
}
else
stats->af_repeats[2][ args->tmp_iaf[i] ]++;
#endif
// Check the frameshifts
int tlen = 0;
if ( args->exons && exon_overlap ) // there is an exon
{
if ( len>0 )
{
// insertion
if ( args->exons->start <= line->pos && args->exons->end > line->pos ) tlen = abs(len);
}
else if ( args->exons->start <= line->pos + abs(len) )
{
// deletion
tlen = abs(len);
if ( line->pos < args->exons->start ) // trim the beginning
tlen -= args->exons->start - line->pos + 1;
if ( args->exons->end < line->pos + abs(len) ) // trim the end
tlen -= line->pos + abs(len) - args->exons->end;
}
}
if ( tlen ) // there are some deleted/inserted bases in the exon
{
if ( tlen%3 ) { stats->out_frame++; args->tmp_frm[i] = 2; }
else { stats->in_frame++; args->tmp_frm[i] = 1; }
if ( i==1 )
{
if ( tlen%3 ) stats->out_frame_alt1++;
else stats->in_frame_alt1++;
}
}
else // no exon affected
{
if ( i==1 ) stats->na_frame_alt1++;
stats->na_frame++;
}
// Indel length distribution
int *ptr = stats->insertions;
if ( len<0 )
{
len *= -1;
ptr = stats->deletions;
}
if ( --len >= stats->m_indel ) len = stats->m_indel-1;
ptr[len]++;
}
}
static void do_user_stats(stats_t *stats, bcf_sr_t *reader, int is_ts)
{
int i, nval;
for (i=0; i<stats->nusr; i++)
{
user_stats_t *usr = &stats->usr[i];
uint64_t *vals = is_ts ? usr->vals_ts : usr->vals_tv;
float val;
if ( usr->type==BCF_HT_REAL )
{
if ( (nval=bcf_get_info_float(reader->header,reader->buffer[0],usr->tag,&usr->val,&usr->m_val))<=0 ) continue;
if ( usr->idx >= nval ) continue;
val = ((float*)usr->val)[usr->idx];
}
else
{
if ( (nval=bcf_get_info_int32(reader->header,reader->buffer[0],usr->tag,&usr->val,&usr->m_val))<=0 ) continue;
if ( usr->idx >= nval ) continue;
val = ((int32_t*)usr->val)[usr->idx];
}
int idx;
if ( val<=usr->min ) idx = 0;
else if ( val>=usr->max ) idx = usr->nbins - 1;
else idx = (val - usr->min)/(usr->max - usr->min) * (usr->nbins-1);
vals[idx]++;
}
}
static void do_snp_stats(args_t *args, stats_t *stats, bcf_sr_t *reader)
{
stats->n_snps++;
bcf1_t *line = reader->buffer[0];
int ref = bcf_acgt2int(*line->d.allele[0]);
if ( ref<0 ) return;
#if QUAL_STATS
int iqual = (isnan(line->qual) || line->qual<0) ? 0 : 1 + (int)(line->qual*10);
#endif
int i;
for (i=1; i<line->n_allele; i++)
{
if ( args->first_allele_only && i>1 ) break;
if ( !(bcf_get_variant_type(line,i)&VCF_SNP) ) continue;
int alt = bcf_acgt2int(*line->d.allele[i]);
if ( alt<0 || ref==alt ) continue;
stats->subst[ref<<2|alt]++;
int iaf = args->tmp_iaf[i];
stats->af_snps[iaf]++;
if ( abs(ref-alt)==2 )
{
if (i==1)
{
stats->ts_alt1++;
#if QUAL_STATS
dist_insert(stats->qual_ts,iqual);
#endif
do_user_stats(stats, reader, 1);
}
stats->af_ts[iaf]++;
}
else
{
if (i==1)
{
stats->tv_alt1++;
#if QUAL_STATS
dist_insert(stats->qual_tv,iqual);
#endif
do_user_stats(stats, reader, 0);
}
stats->af_tv[iaf]++;
}
}
}
static inline void update_dvaf(stats_t *stats, bcf1_t *line, bcf_fmt_t *fmt, int ismpl, int ial, int jal)
{
if ( !fmt ) return;
float dvaf;
#define BRANCH_INT(type_t,missing,vector_end) { \
type_t *p = (type_t *) (fmt->p + fmt->size*ismpl); \
if ( p[ial]==vector_end || p[jal]==vector_end ) return; \
if ( p[ial]==missing || p[jal]==missing ) return; \
if ( !p[ial] && !p[jal] ) return; \
dvaf = (float)p[ial]/(p[ial]+p[jal]); \
}
switch (fmt->type) {
case BCF_BT_INT8: BRANCH_INT(int8_t, bcf_int8_missing, bcf_int8_vector_end); break;
case BCF_BT_INT16: BRANCH_INT(int16_t, bcf_int16_missing, bcf_int16_vector_end); break;
case BCF_BT_INT32: BRANCH_INT(int32_t, bcf_int32_missing, bcf_int32_vector_end); break;
default: fprintf(stderr, "[E::%s] todo: %d\n", __func__, fmt->type); exit(1); break;
}
#undef BRANCH_INT
int len = line->d.var[ial].n;
if ( len < -stats->m_indel ) len = -stats->m_indel;
else if ( len > stats->m_indel ) len = stats->m_indel;
int bin = stats->m_indel + len;
stats->nvaf[bin]++;
stats->dvaf[bin] += dvaf;
}
static void do_sample_stats(args_t *args, stats_t *stats, bcf_sr_t *reader, int matched)
{
bcf_srs_t *files = args->files;
bcf1_t *line = reader->buffer[0];
bcf_fmt_t *fmt_ptr;
int nref_tot = 0, nhet_tot = 0, nalt_tot = 0;
int line_type = bcf_get_variant_types(line);
if ( (fmt_ptr = bcf_get_fmt(reader->header,reader->buffer[0],"GT")) )
{
bcf_fmt_t *ad_fmt_ptr = bcf_get_variant_types(line)&VCF_INDEL ? bcf_get_fmt(reader->header,reader->buffer[0],"AD") : NULL;
int ref = bcf_acgt2int(*line->d.allele[0]);
int is, n_nref = 0, i_nref = 0;
for (is=0; is<args->files->n_smpl; is++)
{
int ial, jal;
int gt = bcf_gt_type(fmt_ptr, reader->samples[is], &ial, &jal);
if ( gt==GT_UNKN )
{
stats->smpl_missing[is]++;
continue;
}
if ( gt==GT_HAPL_R || gt==GT_HAPL_A )
{
if ( line_type&VCF_INDEL && stats->smpl_frm_shifts )
{
assert( ial<line->n_allele );
stats->smpl_frm_shifts[is*3 + args->tmp_frm[ial]]++;
}
if ( gt == GT_HAPL_R ) stats->smpl_hapRef[is]++;
if ( gt == GT_HAPL_A ) stats->smpl_hapAlt[is]++;
continue;
}
if ( gt != GT_HOM_RR ) { n_nref++; i_nref = is; }
#if HWE_STATS
switch (gt)
{
case GT_HOM_RR: nref_tot++; break;
case GT_HET_RA: nhet_tot++; break;
case GT_HET_AA:
case GT_HOM_AA: nalt_tot++; break;
}
#endif
int var_type = 0;
if ( ial>0 ) var_type |= bcf_get_variant_type(line,ial);
if ( jal>0 ) var_type |= bcf_get_variant_type(line,jal);
if ( var_type&VCF_SNP || var_type==VCF_REF ) // count ALT=. as SNP
{
if ( gt == GT_HET_RA ) stats->smpl_hets[is]++;
else if ( gt == GT_HET_AA ) stats->smpl_hets[is]++;
else if ( gt == GT_HOM_RR ) stats->smpl_homRR[is]++;
else if ( gt == GT_HOM_AA ) stats->smpl_homAA[is]++;
if ( gt != GT_HOM_RR && line->d.var[ial].type&VCF_SNP ) // this is safe, bcf_get_variant_types has been already called
{
int alt = bcf_acgt2int(*line->d.allele[ial]);
if ( alt<0 ) continue;
if ( abs(ref-alt)==2 )
stats->smpl_ts[is]++;
else
stats->smpl_tv[is]++;
}
}
if ( var_type&VCF_INDEL )
{
if ( gt != GT_HOM_RR )
{
stats->smpl_indels[is]++;
if ( gt==GT_HET_RA || gt==GT_HET_AA )
{
int is_ins = 0, is_del = 0;
if ( bcf_get_variant_type(line,ial)&VCF_INDEL )
{
if ( line->d.var[ial].n < 0 ) is_del = 1;
else is_ins = 1;
update_dvaf(stats,line,ad_fmt_ptr,is,ial,jal);
}
if ( bcf_get_variant_type(line,jal)&VCF_INDEL )
{
if ( line->d.var[jal].n < 0 ) is_del = 1;
else is_ins = 1;
update_dvaf(stats,line,ad_fmt_ptr,is,jal,ial);
}
// Note that alt-het genotypes with both ins and del allele are counted twice!!
if ( is_del ) stats->smpl_del_hets[is]++;
if ( is_ins ) stats->smpl_ins_hets[is]++;
}
else if ( gt==GT_HOM_AA )
{
if ( line->d.var[ial].n < 0 ) stats->smpl_del_homs[is]++;
else stats->smpl_ins_homs[is]++;
}
}
if ( stats->smpl_frm_shifts )
{
assert( ial<line->n_allele && jal<line->n_allele );
stats->smpl_frm_shifts[is*3 + args->tmp_frm[ial]]++;
stats->smpl_frm_shifts[is*3 + args->tmp_frm[jal]]++;
}
}
}
if ( n_nref==1 ) stats->smpl_sngl[i_nref]++;