#!/bin/bash

## Calculate Allelic Balance of Heterozygous SNP calls
## Then average allelic balance across all heterozygous SNP calls per single SNP

# specify the input VCF file
vcf_file="/path/to/input/vcf_file/inputfile.vcf"

# specify the output txt file that contains tha average allelic balance per SNP: chrom | pos | ref | alt | avg_allelic_balance | num_het_calls | allelic_balance_per_het_call
output_file="/path/to/output/txt_file/outputfile.txt"

bcftools query -i 'GT="het"' -f '%CHROM\t%POS\t%REF\t%ALT[\t%AD]\n' $vcf_file | \
    awk 'BEGIN {OFS=FS="\t"} {sum=0; count=0; for(i=5; i<=NF; i++) {split($i, a, ","); if(a[2]+a[1]!=0) {$i=a[1]/(a[1]+a[2]); sum+=$i; count++;} else $i="NA"} print $1, $2, $3, $4, (count==0 ? "NA" : sum/count), count, substr($0, index($0,$5))}' > $output_file