Debian Codegraph @

bcftools/vcfgtcheck.c.pysam.c

raw symbols SCIP
1 #include "bcftools.pysam.h"
2
3 /* vcfgtcheck.c -- Check sample identity.
4
5 Copyright (C) 2013-2024 Genome Research Ltd.
6
7 Author: Petr Danecek <[email protected]>
8
9 Permission is hereby granted, free of charge, to any person obtaining a copy
10 of this software and associated documentation files (the "Software"), to deal
11 in the Software without restriction, including without limitation the rights
12 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 copies of the Software, and to permit persons to whom the Software is
14 furnished to do so, subject to the following conditions:
15
16 The above copyright notice and this permission notice shall be included in
17 all copies or substantial portions of the Software.
18
19 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 THE SOFTWARE. */
26
27 #include <stdio.h>
28 #include <stdarg.h>
29 #include <unistd.h>
30 #include <getopt.h>
31 #include <assert.h>
32 #include <ctype.h>
33 #include <string.h>
34 #include <strings.h>
35 #include <errno.h>
36 #include <sys/stat.h>
37 #include <sys/types.h>
38 #include <math.h>
39 #include <htslib/vcf.h>
40 #include <htslib/synced_bcf_reader.h>
41 #include <htslib/vcfutils.h>
42 #include <htslib/kbitset.h>
43 #include <htslib/hts_os.h>
44 #include <htslib/bgzf.h>
45 #include <inttypes.h>
46 #include <sys/time.h>
47 #include "bcftools.h"
48 #include "extsort.h"
49 //#include "hclust.h"
50 #include "filter.h"
51
52 // Logic of the filters: include or exclude sites which match the filters?
53 #define FLT_INCLUDE 1
54 #define FLT_EXCLUDE 2
55
56 typedef struct
57 {
58 int iqry, igt;
59 }
60 pair_t;
61
62 typedef struct
63 {
64 bcf_srs_t *files; // first reader is the query VCF - single sample normally or multi-sample for cross-check
65 bcf_hdr_t *gt_hdr, *qry_hdr; // VCF with genotypes to compare against and the query VCF
66 char *cwd, **argv, *gt_samples, *qry_samples, *regions, *targets, *qry_fname, *gt_fname, *pair_samples;
67 char *output_fname;
68 int argc, gt_samples_is_file, qry_samples_is_file, regions_is_file, targets_is_file, pair_samples_is_file, output_type;;
69 int regions_overlap, targets_overlap, clevel;
70 int qry_use_GT,gt_use_GT, nqry_smpl,ngt_smpl, *qry_smpl,*gt_smpl;
71 int nused[2][2];
72 double *pdiff, *qry_prob, *gt_prob;
73 uint32_t *ndiff,*ncnt,*nmatch,ncmp, npairs;
74 int32_t *qry_arr,*gt_arr, nqry_arr,ngt_arr;
75 uint8_t *qry_dsg, *gt_dsg;
76 pair_t *pairs;
77 double *hwe_prob, dsg2prob[8][3], pl2prob[256];
78 double min_inter_err, max_intra_err;
79 int all_sites, hom_only, ntop, cross_check, calc_hwe_prob, sort_by_hwe, dry_run, gt_err;
80 BGZF *out_fh;
81 unsigned int nskip_no_match, nskip_not_ba, nskip_mono, nskip_no_data, nskip_dip_GT, nskip_dip_PL, nskip_filter;
82 kstring_t kstr;
83
84 // for --distinctive-sites
85 double distinctive_sites;
86 kbitset_t *kbs_diff;
87 size_t diff_sites_size;
88 extsort_t *es;
89 char *es_tmp_prefix, *es_max_mem;
90
91 // include or exclude sites which match the filters
92 filter_t *qry_filter, *gt_filter;
93 char *qry_filter_str, *gt_filter_str;
94 int qry_filter_logic, gt_filter_logic; // FLT_INCLUDE or FLT_EXCLUDE
95 }
96 args_t;
97
98 static void set_cwd(args_t *args)
99 {
100 int i;
101 char *buf;
102 size_t nbuf = 500;
103 args->cwd = (char*) malloc(sizeof(char)*nbuf);
104 for (i=0; i<5; i++)
105 {
106 if ( (buf = getcwd(args->cwd, nbuf)) ) break;
107 nbuf *= 2;
108 args->cwd = (char*) realloc(args->cwd, sizeof(char)*nbuf);
109 }
110 assert(buf);
111 }
112 static void print_header(args_t *args)
113 {
114 args->kstr.l = 0;
115 ksprintf(&args->kstr, "# This file was produced by bcftools (%s+htslib-%s), the command line was:\n", bcftools_version(), hts_version());
116 ksprintf(&args->kstr, "# \t bcftools %s ", args->argv[0]);
117 int i;
118 for (i=1; i<args->argc; i++)
119 ksprintf(&args->kstr, " %s",args->argv[i]);
120 ksprintf(&args->kstr, "\n# and the working directory was:\n");
121 ksprintf(&args->kstr, "# \t %s\n#\n", args->cwd);
122 if ( bgzf_write(args->out_fh, args->kstr.s, args->kstr.l)!=args->kstr.l ) error("Failed to write to %s\n", args->output_fname);
123 }
124
125 static int cmp_int(const void *_a, const void *_b)
126 {
127 int a = *((int*)_a);
128 int b = *((int*)_b);
129 if ( a < b ) return -1;
130 if ( a > b ) return 1;
131 return 0;
132 }
133 static int cmp_pair(const void *_a, const void *_b)
134 {
135 pair_t *a = (pair_t*)_a;
136 pair_t *b = (pair_t*)_b;
137 if ( a->iqry < b->iqry ) return -1;
138 if ( a->iqry > b->iqry ) return 1;
139 if ( a->igt < b->igt ) return -1;
140 if ( a->igt > b->igt ) return 1;
141 return 0;
142 }
143
144 typedef struct
145 {
146 uint32_t ndiff,rid,pos,rand; // rand is to shuffle sites with the same ndiff from across all chromosomes
147 unsigned long kbs_dat[1];
148 }
149 diff_sites_t;
150 #if DBG
151 static void diff_sites_debug_print(args_t *args, diff_sites_t *ds)
152 {
153 int i;
154 memcpy(args->kbs_diff->b,ds->kbs_dat,args->kbs_diff->n*sizeof(unsigned long));
155 fprintf(bcftools_stderr,"%s:%d\t%d\t",bcf_hdr_id2name(args->qry_hdr,ds->rid),ds->pos+1,ds->ndiff);
156 for (i=0; i<args->npairs; i++) fprintf(bcftools_stderr,"%d",kbs_exists(args->kbs_diff,i)?1:0);
157 fprintf(bcftools_stderr,"\n");
158 }
159 #endif
160 static int diff_sites_cmp(const void *aptr, const void *bptr)
161 {
162 diff_sites_t *a = *((diff_sites_t**)aptr);
163 diff_sites_t *b = *((diff_sites_t**)bptr);
164 if ( a->ndiff < b->ndiff ) return 1; // descending order
165 if ( a->ndiff > b->ndiff ) return -1;
166 if ( a->rand < b->rand ) return -1;
167 if ( a->rand > b->rand ) return 1;
168 return 0;
169 }
170 static void diff_sites_init(args_t *args)
171 {
172 int nsites = args->distinctive_sites<=1 ? args->npairs*args->distinctive_sites : args->distinctive_sites;
173 if ( nsites<=0 ) error("The value for --distinctive-sites was set too low: %d\n",nsites);
174 if ( nsites > args->npairs )
175 {
176 fprintf(bcftools_stderr,"Warning: The value for --distinctive-sites is bigger than is the number of pairs, all discordant sites be printed.\n");
177 nsites = args->npairs;
178 args->distinctive_sites = args->npairs + 1;
179 }
180 else
181 args->distinctive_sites = nsites;
182 args->kbs_diff = kbs_init(args->npairs);
183 size_t n = (args->npairs + KBS_ELTBITS-1) / KBS_ELTBITS;
184 assert( n==args->kbs_diff->n );
185 args->diff_sites_size = sizeof(diff_sites_t) + (n-1)*sizeof(unsigned long);
186 args->es = extsort_alloc();
187 extsort_set_opt(args->es,size_t,DAT_SIZE,args->diff_sites_size);
188 extsort_set_opt(args->es,const char*,TMP_PREFIX,args->es_tmp_prefix);
189 extsort_set_opt(args->es,const char*,MAX_MEM,args->es_max_mem);
190 extsort_set_opt(args->es,extsort_cmp_f,FUNC_CMP,diff_sites_cmp);
191 extsort_init(args->es);
192 }
193 static void diff_sites_destroy(args_t *args)
194 {
195 kbs_destroy(args->kbs_diff);
196 extsort_destroy(args->es);
197 }
198 static inline void diff_sites_reset(args_t *args)
199 {
200 kbs_clear(args->kbs_diff);
201 }
202 static inline void diff_sites_push(args_t *args, int ndiff, int rid, int pos)
203 {
204 diff_sites_t *dat = (diff_sites_t*) malloc(args->diff_sites_size);
205 memset(dat,0,sizeof(*dat)); // for debugging: prevent warnings about uninitialized memory coming from struct padding (not needed after rand added)
206 dat->ndiff = ndiff;
207 dat->rid = rid;
208 dat->pos = pos;
209 dat->rand = hts_lrand48();
210 memcpy(dat->kbs_dat,args->kbs_diff->b,args->kbs_diff->n*sizeof(unsigned long));
211 extsort_push(args->es,dat);
212 }
213 static inline int diff_sites_shift(args_t *args, int *ndiff, int *rid, int *pos)
214 {
215 diff_sites_t *dat = (diff_sites_t*) extsort_shift(args->es);
216 if ( !dat ) return 0;
217 *ndiff = dat->ndiff;
218 *rid = dat->rid;
219 *pos = dat->pos;
220 memcpy(args->kbs_diff->b,dat->kbs_dat,args->kbs_diff->n*sizeof(unsigned long));
221 return 1;
222 }
223
224 static void init_samples(char *list, int list_is_file, int **smpl, int *nsmpl, bcf_hdr_t *hdr, char *vcf_fname)
225 {
226 int i;
227 if ( !strcmp(list,"-") )
228 {
229 *nsmpl = bcf_hdr_nsamples(hdr);
230 *smpl = (int*) malloc(sizeof(**smpl)*(*nsmpl));
231 for (i=0; i<*nsmpl; i++) (*smpl)[i] = i;
232 return;
233 }
234
235 char **tmp = hts_readlist(list, list_is_file, nsmpl);
236 if ( !tmp || !*nsmpl ) error("Failed to parse %s\n", list);
237 *smpl = (int*) malloc(sizeof(**smpl)*(*nsmpl));
238 for (i=0; i<*nsmpl; i++)
239 {
240 int idx = bcf_hdr_id2int(hdr, BCF_DT_SAMPLE, tmp[i]);
241 if ( idx<0 ) error("No such sample in %s: [%s]\n",vcf_fname,tmp[i]);
242 (*smpl)[i] = idx;
243 free(tmp[i]);
244 }
245 free(tmp);
246 qsort(*smpl,*nsmpl,sizeof(**smpl),cmp_int);
247 // check for duplicates
248 for (i=1; i<*nsmpl; i++)
249 if ( (*smpl)[i-1]==(*smpl)[i] )
250 error("Error: the sample \"%s\" is listed twice in %s\n", hdr->samples[(*smpl)[i]],list);
251 }
252
253 static void init_data(args_t *args)
254 {
255 hts_srand48(0);
256
257 args->files = bcf_sr_init();
258 if ( args->regions )
259 {
260 bcf_sr_set_opt(args->files,BCF_SR_REGIONS_OVERLAP,args->regions_overlap);
261 if ( bcf_sr_set_regions(args->files, args->regions, args->regions_is_file)<0 ) error("Failed to read the regions: %s\n", args->regions);
262 }
263 if ( args->targets )
264 {
265 bcf_sr_set_opt(args->files,BCF_SR_TARGETS_OVERLAP,args->targets_overlap);
266 if ( bcf_sr_set_targets(args->files, args->targets, args->targets_is_file, 0)<0 ) error("Failed to read the targets: %s\n", args->targets);
267 }
268
269 if ( args->gt_fname ) bcf_sr_set_opt(args->files, BCF_SR_REQUIRE_IDX);
270 if ( !bcf_sr_add_reader(args->files,args->qry_fname) ) error("Failed to open %s: %s\n", args->qry_fname,bcf_sr_strerror(args->files->errnum));
271 if ( args->gt_fname && !bcf_sr_add_reader(args->files, args->gt_fname) )
272 error("Failed to read from %s: %s\n", !strcmp("-",args->gt_fname)?"standard input":args->gt_fname,bcf_sr_strerror(args->files->errnum));
273
274 args->qry_hdr = bcf_sr_get_header(args->files,0);
275 if ( !bcf_hdr_nsamples(args->qry_hdr) ) error("No samples in %s?\n", args->qry_fname);
276 if ( args->gt_fname )
277 {
278 args->gt_hdr = bcf_sr_get_header(args->files,1);
279 if ( !bcf_hdr_nsamples(args->gt_hdr) ) error("No samples in %s?\n", args->gt_fname);
280 }
281
282 if ( args->gt_hdr && args->gt_filter_str ) args->gt_filter = filter_init(args->gt_hdr, args->gt_filter_str);
283 if ( args->qry_hdr && args->qry_filter_str ) args->qry_filter = filter_init(args->qry_hdr, args->qry_filter_str);
284
285 // Determine whether GT or PL will be used
286 if ( args->qry_use_GT==-1 ) // not set by -u, qry uses PL by default
287 {
288 if ( bcf_hdr_id2int(args->qry_hdr,BCF_DT_ID,"PL")>=0 )
289 args->qry_use_GT = 0;
290 else if ( bcf_hdr_id2int(args->qry_hdr,BCF_DT_ID,"GT")>=0 )
291 args->qry_use_GT = 1;
292 else
293 error("[E::%s] Neither PL nor GT tag is present in the header of %s\n", __func__, args->qry_fname);
294 }
295 else if ( args->qry_use_GT==1 )
296 {
297 if ( bcf_hdr_id2int(args->qry_hdr,BCF_DT_ID,"GT")<0 )
298 error("[E::%s] The GT tag is not present in the header of %s\n", __func__, args->qry_fname);
299 }
300 else if ( bcf_hdr_id2int(args->qry_hdr,BCF_DT_ID,"PL")<0 )
301 error("[E::%s] The PL tag is not present in the header of %s\n", __func__, args->qry_fname);
302
303 if ( args->gt_hdr )
304 {
305 if ( args->gt_use_GT==-1 ) // not set by -u, gt uses GT by default
306 {
307 if ( bcf_hdr_id2int(args->gt_hdr,BCF_DT_ID,"GT")>=0 )
308 args->gt_use_GT = 1;
309 else if ( bcf_hdr_id2int(args->gt_hdr,BCF_DT_ID,"PL")>=0 )
310 args->gt_use_GT = 0;
311 else
312 error("[E::%s] Neither PL nor GT tag is present in the header of %s\n", __func__, args->gt_fname);
313 }
314 else if ( args->gt_use_GT==1 )
315 {
316 if ( bcf_hdr_id2int(args->gt_hdr,BCF_DT_ID,"GT")<0 )
317 error("[E::%s] The GT tag is not present in the header of %s\n", __func__, args->gt_fname);
318 }
319 else if ( bcf_hdr_id2int(args->gt_hdr,BCF_DT_ID,"PL")<0 )
320 error("[E::%s] The PL tag is not present in the header of %s\n", __func__, args->gt_fname);
321 }
322 else
323 args->gt_use_GT = args->qry_use_GT;
324
325 // Prepare samples
326 int i,j;
327 args->nqry_smpl = bcf_hdr_nsamples(args->qry_hdr);
328 if ( args->qry_samples )
329 {
330 init_samples(args->qry_samples, args->qry_samples_is_file, &args->qry_smpl, &args->nqry_smpl, args->qry_hdr, args->qry_fname);
331 }
332 if ( args->gt_samples )
333 {
334 init_samples(args->gt_samples, args->gt_samples_is_file, &args->gt_smpl, &args->ngt_smpl,
335 args->gt_hdr ? args->gt_hdr : args->qry_hdr,
336 args->gt_fname ? args->gt_fname : args->qry_fname);
337 }
338 else if ( args->pair_samples )
339 {
340 int npairs;
341 char **tmp = hts_readlist(args->pair_samples, args->pair_samples_is_file, &npairs);
342 if ( !tmp || !npairs ) error("Failed to parse %s\n", args->pair_samples);
343 if ( !args->pair_samples_is_file && npairs%2 ) error("Expected even number of comma-delimited samples with -p\n");
344 args->npairs = args->pair_samples_is_file ? npairs : npairs/2;
345 args->pairs = (pair_t*) calloc(args->npairs,sizeof(*args->pairs));
346 if ( !args->pair_samples_is_file )
347 {
348 for (i=0; i<args->npairs; i++)
349 {
350 args->pairs[i].iqry = bcf_hdr_id2int(args->qry_hdr, BCF_DT_SAMPLE, tmp[2*i]);
351 args->pairs[i].igt = bcf_hdr_id2int(args->gt_hdr?args->gt_hdr:args->qry_hdr, BCF_DT_SAMPLE, tmp[2*i+1]);
352 if ( args->pairs[i].iqry < 0 ) error("No such sample in %s: [%s]\n",args->qry_fname,tmp[2*i]);
353 if ( args->pairs[i].igt < 0 ) error("No such sample in %s: [%s]\n",args->gt_fname?args->gt_fname:args->qry_fname,tmp[2*i+1]);
354 free(tmp[2*i]);
355 free(tmp[2*i+1]);
356 }
357 }
358 else
359 {
360 for (i=0; i<args->npairs; i++)
361 {
362 char *ptr = tmp[i];
363 while ( *ptr && !isspace(*ptr) ) ptr++;
364 if ( !*ptr ) error("Could not parse %s: %s\n",args->pair_samples,tmp[i]);
365 *ptr = 0;
366 args->pairs[i].iqry = bcf_hdr_id2int(args->qry_hdr, BCF_DT_SAMPLE, tmp[i]);
367 if ( args->pairs[i].iqry < 0 ) error("No such sample in %s: [%s]\n",args->qry_fname,tmp[i]);
368 ptr++;
369 while ( *ptr && isspace(*ptr) ) ptr++;
370 args->pairs[i].igt = bcf_hdr_id2int(args->gt_hdr?args->gt_hdr:args->qry_hdr, BCF_DT_SAMPLE, ptr);
371 if ( args->pairs[i].igt < 0 ) error("No such sample in %s: [%s]\n",args->gt_fname?args->gt_fname:args->qry_fname,ptr);
372 free(tmp[i]);
373 }
374 }
375 free(tmp);
376 qsort(args->pairs,args->npairs,sizeof(*args->pairs),cmp_pair);
377 }
378 else if ( args->gt_hdr )
379 args->ngt_smpl = bcf_hdr_nsamples(args->gt_hdr);
380 if ( !args->ngt_smpl )
381 {
382 args->ngt_smpl = args->nqry_smpl;
383 args->gt_smpl = args->qry_smpl;
384 args->cross_check = 1;
385 }
386
387 // The data arrays
388 if ( !args->npairs ) args->npairs = args->cross_check ? args->nqry_smpl*(args->nqry_smpl+1)/2 : args->ngt_smpl*args->nqry_smpl;
389 if ( !args->pair_samples )
390 {
391 args->qry_dsg = (uint8_t*) malloc(args->nqry_smpl);
392 args->gt_dsg = args->cross_check ? args->qry_dsg : (uint8_t*) malloc(args->ngt_smpl);
393 }
394 if ( args->gt_err )
395 {
396 args->pdiff = (double*) calloc(args->npairs,sizeof(*args->pdiff)); // log probability of pair samples being the same
397 args->qry_prob = (double*) malloc(3*args->nqry_smpl*sizeof(*args->qry_prob));
398 args->gt_prob = args->cross_check ? args->qry_prob : (double*) malloc(3*args->ngt_smpl*sizeof(*args->gt_prob));
399
400 // Convert genotypes to genotype likelihoods given by -E, the probability of reading one allele incorrectly. In this
401 // simple model we have:
402 // - probability of reading an allele incorrectly, eg. 0 as 1 or 1 as 0
403 // P(0|1) = P(1|0) = e
404 // - probability of genotype G={00,01,11} being correct given observed dosage {0,1,2} and the
405 // genotyping error probability e:
406 // P(00|0) = 1 P(00|1) = e P(00|2) = e^2
407 // P(01|0) = e P(01|1) = 1 P(01|2) = e
408 // P(11|0) = e^2 P(11|1) = e P(11|2) = 1
409 //
410 // dsg2prob: the first index is bitmask of 8 possible dsg combinations (only 1<<0,1<<2,1<<3 are set, accessing
411 // anything else indicated an error, this is just to reuse gt_to_dsg(); the second index are the corresponding
412 // probabilities of 0/0, 0/1, and 1/1 genotypes
413 //
414 for (i=0; i<8; i++)
415 for (j=0; j<3; j++)
416 args->dsg2prob[i][j] = HUGE_VAL;
417 double eprob = pow(10,-0.1*args->gt_err); // convert from phred score to probability
418 args->dsg2prob[1][0] = 0; // P(00|0) = 1
419 args->dsg2prob[1][1] = -log(eprob); // P(01|0) = e
420 args->dsg2prob[1][2] = -2*log(eprob); // P(11|0) = e^2
421 args->dsg2prob[2][0] = -log(eprob); // P(00|1) = e
422 args->dsg2prob[2][1] = 0; // P(01|1) = 1
423 args->dsg2prob[2][2] = -log(eprob); // P(11|1) = e
424 args->dsg2prob[4][0] = -2*log(eprob); // P(00|2) = e^2
425 args->dsg2prob[4][1] = -log(eprob); // P(01|2) = e
426 args->dsg2prob[4][2] = 0; // P(11|2) = 1
427
428 // lookup table to avoid exponentiation
429 for (i=0; i<256; i++) args->pl2prob[i] = pow(10,-0.1*i);
430 }
431 else
432 args->ndiff = (uint32_t*) calloc(args->npairs,sizeof(*args->ndiff)); // number of differing genotypes for each pair of samples
433 args->ncnt = (uint32_t*) calloc(args->npairs,sizeof(*args->ncnt)); // number of comparisons performed (non-missing data)
434 if ( !args->ncnt ) error("Error: failed to allocate %.1f Mb\n", args->npairs*sizeof(*args->ncnt)/1e6);
435 if ( args->calc_hwe_prob )
436 {
437 // prob of the observed sequence of matches given site AFs and HWE
438 args->hwe_prob = (double*) calloc(args->npairs,sizeof(*args->hwe_prob));
439 if ( !args->hwe_prob ) error("Error: failed to allocate %.1f Mb. Run with --no-HWE-prob to save some memory.\n", args->npairs*sizeof(*args->hwe_prob)/1e6);
440 args->nmatch = (uint32_t*) calloc(args->npairs,sizeof(*args->ncnt)); // number of matches, used only with calc_hwe_prob
441 if ( !args->nmatch ) error("Error: failed to allocate %.1f Mb.\n", args->npairs*sizeof(*args->ncnt)/1e6);
442 }
443
444 if ( args->distinctive_sites ) diff_sites_init(args);
445
446 args->out_fh = bgzf_open(args->output_fname, args->output_type&FT_GZ ? "wg" : "wu");
447 if ( args->out_fh == NULL )
448 error("[%s] Error: cannot write to %s: %s\n", __func__,args->output_fname ? args->output_fname : "standard output", strerror(errno));
449
450 print_header(args);
451 }
452
453 static void destroy_data(args_t *args)
454 {
455 free(args->kstr.s);
456 if ( args->gt_filter ) filter_destroy(args->gt_filter);
457 if ( args->qry_filter ) filter_destroy(args->qry_filter);
458 if ( args->gt_dsg!=args->qry_dsg ) free(args->gt_dsg);
459 free(args->qry_dsg);
460 if ( args->gt_prob!=args->qry_prob ) free(args->gt_prob);
461 free(args->qry_prob);
462 free(args->es_max_mem);
463 if ( bgzf_close(args->out_fh)!=0 ) error("Error: close failed .. %s\n", args->output_fname?args->output_fname:"bcftools_stdout");
464 if ( args->distinctive_sites ) diff_sites_destroy(args);
465 free(args->hwe_prob);
466 free(args->cwd);
467 free(args->qry_arr);
468 if ( args->gt_hdr ) free(args->gt_arr);
469 free(args->pdiff);
470 free(args->ndiff);
471 free(args->ncnt);
472 free(args->nmatch);
473 free(args->qry_smpl);
474 if ( args->gt_smpl!=args->qry_smpl ) free(args->gt_smpl);
475 free(args->pairs);
476 bcf_sr_destroy(args->files);
477 }
478
479 static inline uint8_t gt_to_dsg(int32_t *ptr)
480 {
481 if ( bcf_gt_is_missing(ptr[0]) || bcf_gt_is_missing(ptr[1]) || ptr[1]==bcf_int32_vector_end ) return 0;
482 uint8_t dsg = (bcf_gt_allele(ptr[0])?1:0) + (bcf_gt_allele(ptr[1])?1:0);
483 return 1<<dsg;
484 }
485 static inline uint8_t pl_to_dsg(int32_t *ptr)
486 {
487 if ( ptr[0]==bcf_int32_missing || ptr[1]==bcf_int32_missing || ptr[2]==bcf_int32_missing ) return 0;
488 if ( ptr[1]==bcf_int32_vector_end || ptr[2]==bcf_int32_vector_end ) return 0;
489 int min_pl = ptr[0]<ptr[1] ? (ptr[0]<ptr[2]?ptr[0]:ptr[2]) : (ptr[1]<ptr[2]?ptr[1]:ptr[2]);
490 uint8_t dsg = 0;
491 if ( ptr[0]==min_pl ) dsg |= 1;
492 if ( ptr[1]==min_pl ) dsg |= 2;
493 if ( ptr[2]==min_pl ) dsg |= 4;
494 return dsg;
495 }
496 static inline uint8_t gt_to_prob(args_t *args, int32_t *ptr, double *prob)
497 {
498 uint8_t dsg = gt_to_dsg(ptr);
499 if ( dsg )
500 {
501 prob[0] = args->dsg2prob[dsg][0];
502 prob[1] = args->dsg2prob[dsg][1];
503 prob[2] = args->dsg2prob[dsg][2];
504 }
505 return dsg;
506 }
507 static inline uint8_t pl_to_prob(args_t *args, int32_t *ptr, double *prob)
508 {
509 uint8_t dsg = pl_to_dsg(ptr);
510 if ( dsg )
511 {
512 prob[0] = (ptr[0]>=0 && ptr[0]<255) ? args->pl2prob[ptr[0]] : args->pl2prob[255];
513 prob[1] = (ptr[1]>=0 && ptr[1]<255) ? args->pl2prob[ptr[1]] : args->pl2prob[255];
514 prob[2] = (ptr[2]>=0 && ptr[2]<255) ? args->pl2prob[ptr[2]] : args->pl2prob[255];
515 double sum = prob[0] + prob[1] + prob[2];
516 prob[0] /= sum;
517 prob[1] /= sum;
518 prob[2] /= sum;
519 prob[0] = -log(prob[0]);
520 prob[1] = -log(prob[1]);
521 prob[2] = -log(prob[2]);
522 }
523 return dsg;
524 }
525 static int set_data(args_t *args, bcf_hdr_t *hdr, bcf1_t *rec, int32_t **arr, int32_t *narr, int *narr1, int *use_GT)
526 {
527 static int warn_dip_GT = 1;
528 static int warn_dip_PL = 1;
529 int i;
530 for (i=0; i<2; i++)
531 {
532 if ( *use_GT )
533 {
534 int ret = bcf_get_genotypes(hdr,rec,arr,narr);
535 if ( ret < 0 )
536 {
537 if ( !i ) { *use_GT = 0; continue; }
538 args->nskip_no_data++;
539 return -1;
540 }
541 if ( ret != 2*bcf_hdr_nsamples(hdr) )
542 {
543 if ( warn_dip_GT )
544 {
545 fprintf(bcftools_stderr,"INFO: skipping %s:%"PRIhts_pos", only diploid FORMAT/GT fields supported. (This is printed only once.)\n", bcf_seqname(hdr,rec),rec->pos+1);
546 warn_dip_GT = 0;
547 }
548 args->nskip_dip_GT++;
549 return -1;
550 }
551 *narr1 = 2;
552 return 0;
553 }
554
555 int ret = bcf_get_format_int32(hdr,rec,"PL",arr,narr);
556 if ( ret < 0 )
557 {
558 if ( !i ) { *use_GT = 1; continue; }
559 args->nskip_no_data++;
560 return -1;
561 }
562 if ( ret != 3*bcf_hdr_nsamples(hdr) )
563 {
564 if ( warn_dip_PL )
565 {
566 fprintf(bcftools_stderr,"INFO: skipping %s:%"PRIhts_pos", only diploid FORMAT/PL fields supported. (This is printed only once.)\n", bcf_seqname(hdr,rec),rec->pos+1);
567 warn_dip_PL = 0;
568 }
569 args->nskip_dip_PL++;
570 return -1;
571 }
572 *narr1 = 3;
573 return 0;
574 }
575 return -1; // should never reach
576 }
577 static void process_line(args_t *args)
578 {
579 int i,j,k, nqry1, ngt1, ret;
580
581 bcf1_t *gt_rec = NULL, *qry_rec = bcf_sr_get_line(args->files,0); // the query file
582 if ( args->qry_filter )
583 {
584 int pass = filter_test(args->qry_filter, qry_rec, NULL);
585 if ( args->qry_filter_logic==FLT_EXCLUDE ) pass = pass ? 0 : 1;
586 if ( !pass ) { args->nskip_filter++; return; }
587 }
588
589 int qry_use_GT = args->qry_use_GT;
590 int gt_use_GT = args->gt_use_GT;
591
592 ret = set_data(args, args->qry_hdr, qry_rec, &args->qry_arr, &args->nqry_arr, &nqry1, &qry_use_GT);
593 if ( ret<0 ) return;
594
595 if ( args->gt_hdr )
596 {
597 gt_rec = bcf_sr_get_line(args->files,1);
598 if ( args->gt_filter )
599 {
600 int pass = filter_test(args->gt_filter, gt_rec, NULL);
601 if ( args->gt_filter_logic==FLT_EXCLUDE ) pass = pass ? 0 : 1;
602 if ( !pass ) { args->nskip_filter++; return; }
603 }
604 ret = set_data(args, args->gt_hdr, gt_rec, &args->gt_arr, &args->ngt_arr, &ngt1, &gt_use_GT);
605 if ( ret<0 ) return;
606 }
607 else
608 {
609 ngt1 = nqry1;
610 args->gt_arr = args->qry_arr;
611 }
612
613 // stats: number of compared sites, and used tags
614 args->ncmp++;
615 args->nused[qry_use_GT][gt_use_GT]++;
616
617 double hwe_dsg[8];
618 if ( args->calc_hwe_prob )
619 {
620 int ac[2];
621 if ( args->gt_hdr )
622 {
623 if ( bcf_calc_ac(args->gt_hdr, gt_rec, ac, BCF_UN_INFO|BCF_UN_FMT)!=1 ) error("todo: bcf_calc_ac() failed\n");
624 }
625 else if ( bcf_calc_ac(args->qry_hdr, qry_rec, ac, BCF_UN_INFO|BCF_UN_FMT)!=1 ) error("todo: bcf_calc_ac() failed\n");
626
627 // Calculate HWE probability for each possible qry+gt dosage combination. The alternate allele dosage
628 // values returned by gt_to_prob() below are 0,1,2,4 (0=missing, 1<<0, 1<<1, 1<<2). We consider only
629 // biallelic sites, therefore we work with eight genotype combinations.
630 //
631 // The array hwe_dsg is accessed with hwe_dsg[qry_dsg & gt_dsg] and is constructed to account for PL uncertainty
632 // when we encounter less informative PL, such as PL=0,0,10, where multiple dosage values are equally
633 // likely. If we allowed complete uncertainty (PL=0,0,0), we'd have up to eight possible genotype
634 // mask combinations: from e.g. 0=(gt_dsg=1<<0 & qry_dsg=1<<1) to 7=(gt_dsg=1<<0|1<<1|1<<2 & qry_dsg=1<<0|1<<1|1<<2).
635 // Note the extreme case of 1|2|4 is skipped, see pl_to_dsg().
636 //
637 // When the dosage is uncertain, we take the minimum of their corresponding HWE value, for example
638 // hwe[0] = 0
639 // hwe[1] = (1-AF)**2
640 // hwe[2] = 2*AF*(1-AF)
641 // hwe[4] = AF**2
642 // hwe[3] = min{hwe[1],hwe[2]}
643
644 double hwe[3]; // while hwe_dsg iterates over dsg bitmasks (0..7), hwe iterates over dsg (0,1,2)
645 double af = ac[0]+ac[1] ? (double)ac[1]/(ac[0]+ac[1]) : 1e-6;
646 hwe[0] = -log((1-af)*(1-af));
647 hwe[1] = -log(2*af*(1-af));
648 hwe[2] = -log(af*af);
649 hwe_dsg[0] = 0;
650 for (i=1; i<8; i++)
651 {
652 hwe_dsg[i] = HUGE_VAL;
653 for (k=0; k<3; k++)
654 {
655 if ( ((1<<k)&i) && hwe_dsg[i] > hwe[k] ) hwe_dsg[i] = hwe[k];
656 }
657 }
658 }
659
660 // The sample pairs were given explicitly via -p/-P options
661 if ( args->pairs )
662 {
663 if ( !args->gt_err )
664 {
665 int ndiff = 0;
666 if ( args->kbs_diff ) diff_sites_reset(args);
667
668 for (i=0; i<args->npairs; i++)
669 {
670 int32_t *ptr;
671 uint8_t qry_dsg, gt_dsg;
672
673 ptr = args->gt_arr + args->pairs[i].igt*ngt1;
674 gt_dsg = gt_use_GT ? gt_to_dsg(ptr) : pl_to_dsg(ptr);
675 if ( !gt_dsg ) continue; // missing value
676 if ( args->hom_only && !(gt_dsg&5) ) continue; // not a hom
677
678 ptr = args->qry_arr + args->pairs[i].iqry*nqry1;
679 qry_dsg = qry_use_GT ? gt_to_dsg(ptr) : pl_to_dsg(ptr);
680 if ( !qry_dsg ) continue; // missing value
681
682 int match = qry_dsg & gt_dsg;
683 if ( !match )
684 {
685 args->ndiff[i]++;
686 if ( args->kbs_diff ) { ndiff++; kbs_insert(args->kbs_diff, i); }
687 }
688 else if ( args->calc_hwe_prob )
689 {
690 args->hwe_prob[i] += hwe_dsg[match];
691 args->nmatch[i]++;
692 }
693 args->ncnt[i]++;
694 }
695
696 if ( ndiff ) diff_sites_push(args, ndiff, qry_rec->rid, qry_rec->pos);
697 }
698 else // gt_err set
699 {
700 for (i=0; i<args->npairs; i++)
701 {
702 int32_t *ptr;
703 double qry_prob[3], gt_prob[3];
704 uint8_t qry_dsg, gt_dsg;
705
706 ptr = args->gt_arr + args->pairs[i].igt*ngt1;
707 gt_dsg = gt_use_GT ? gt_to_prob(args,ptr,gt_prob) : pl_to_prob(args,ptr,gt_prob);
708 if ( !gt_dsg ) continue; // missing value
709 if ( args->hom_only && !(gt_dsg&5) ) continue; // not a hom
710
711 ptr = args->qry_arr + args->pairs[i].iqry*nqry1;
712 qry_dsg = qry_use_GT ? gt_to_prob(args,ptr,qry_prob) : pl_to_prob(args,ptr,qry_prob);
713 if ( !qry_dsg ) continue; // missing value
714
715 double min = qry_prob[0] + gt_prob[0];
716 qry_prob[1] += gt_prob[1];
717 if ( min > qry_prob[1] ) min = qry_prob[1];
718 qry_prob[2] += gt_prob[2];
719 if ( min > qry_prob[2] ) min = qry_prob[2];
720 args->pdiff[i] += min;
721
722 if ( args->calc_hwe_prob )
723 {
724 int match = qry_dsg & gt_dsg;
725 args->hwe_prob[i] += hwe_dsg[match];
726 if ( match ) args->nmatch[i]++;
727 }
728 args->ncnt[i]++;
729 }
730 }
731 return;
732 }
733
734 int idx=0;
735 if ( !args->gt_err )
736 {
737 for (i=0; i<args->nqry_smpl; i++)
738 {
739 int iqry = args->qry_smpl ? args->qry_smpl[i] : i;
740 int32_t *ptr = args->qry_arr + nqry1*iqry;
741 args->qry_dsg[i] = qry_use_GT ? gt_to_dsg(ptr) : pl_to_dsg(ptr);
742 }
743 if ( !args->cross_check ) // in this case gt_dsg points to qry_dsg
744 {
745 for (i=0; i<args->ngt_smpl; i++)
746 {
747 int igt = args->gt_smpl ? args->gt_smpl[i] : i;
748 int32_t *ptr = args->gt_arr + ngt1*igt;
749 args->gt_dsg[i] = gt_use_GT ? gt_to_dsg(ptr) : pl_to_dsg(ptr);
750 if ( args->hom_only && !(args->gt_dsg[i]&5) ) args->gt_dsg[i] = 0; // not a hom, set to a missing value
751 }
752 }
753 for (i=0; i<args->nqry_smpl; i++)
754 {
755 int ngt = args->cross_check ? i : args->ngt_smpl; // two files or a sub-diagonal cross-check mode?
756 if ( !args->qry_dsg[i] ) { idx += ngt; continue; } // missing value
757 for (j=0; j<ngt; j++)
758 {
759 if ( !args->gt_dsg[j] ) { idx++; continue; } // missing value
760 int match = args->qry_dsg[i] & args->gt_dsg[j];
761 if ( !match ) args->ndiff[idx]++;
762 else if ( args->calc_hwe_prob )
763 {
764 args->hwe_prob[idx] += hwe_dsg[match];
765 args->nmatch[idx]++;
766 }
767 args->ncnt[idx]++;
768 idx++;
769 }
770 }
771 }
772 else // gt_err set
773 {
774 for (i=0; i<args->nqry_smpl; i++)
775 {
776 int iqry = args->qry_smpl ? args->qry_smpl[i] : i;
777 int32_t *ptr = args->qry_arr + nqry1*iqry;
778 args->qry_dsg[i] = qry_use_GT ? gt_to_prob(args,ptr,args->qry_prob+i*3) : pl_to_prob(args,ptr,args->qry_prob+i*3);
779 }
780 if ( !args->cross_check ) // in this case gt_dsg points to qry_dsg
781 {
782 for (i=0; i<args->ngt_smpl; i++)
783 {
784 int igt = args->gt_smpl ? args->gt_smpl[i] : i;
785 int32_t *ptr = args->gt_arr + ngt1*igt;
786 args->gt_dsg[i] = gt_use_GT ? gt_to_prob(args,ptr,args->gt_prob+i*3) : pl_to_prob(args,ptr,args->gt_prob+i*3);
787 if ( args->hom_only && !(args->gt_dsg[i]&5) ) args->gt_dsg[i] = 0; // not a hom, set to a missing value
788 }
789 }
790 for (i=0; i<args->nqry_smpl; i++)
791 {
792 int ngt = args->cross_check ? i : args->ngt_smpl; // two files or a sub-diagonal cross-check mode?
793 if ( !args->qry_dsg[i] ) { idx += ngt; continue; } // missing value
794 for (j=0; j<ngt; j++)
795 {
796 if ( !args->gt_dsg[j] ) { idx++; continue; } // missing value
797
798 double min = args->qry_prob[i*3] + args->gt_prob[j*3];
799 if ( min > args->qry_prob[i*3+1] + args->gt_prob[j*3+1] ) min = args->qry_prob[i*3+1] + args->gt_prob[j*3+1];
800 if ( min > args->qry_prob[i*3+2] + args->gt_prob[j*3+2] ) min = args->qry_prob[i*3+2] + args->gt_prob[j*3+2];
801 args->pdiff[idx] += min;
802
803 if ( args->calc_hwe_prob )
804 {
805 int match = args->qry_dsg[i] & args->gt_dsg[j];
806 args->hwe_prob[idx] += hwe_dsg[match];
807 if ( match ) args->nmatch[idx]++;
808 }
809 args->ncnt[idx]++;
810 idx++;
811 }
812 }
813 }
814 }
815
816
817 typedef struct
818 {
819 int ism, idx;
820 double val;
821 }
822 idbl_t;
823 static int cmp_idbl(const void *_a, const void *_b)
824 {
825 idbl_t *a = (idbl_t*)_a;
826 idbl_t *b = (idbl_t*)_b;
827 if ( a->val < b->val ) return -1;
828 if ( a->val > b->val ) return 1;
829 return 0;
830 }
831 static void report_distinctive_sites(args_t *args)
832 {
833 extsort_sort(args->es);
834
835 args->kstr.l = 0;
836 ksprintf(&args->kstr,"# DS, distinctive sites:\n");
837 ksprintf(&args->kstr,"# - chromosome\n");
838 ksprintf(&args->kstr,"# - position\n");
839 ksprintf(&args->kstr,"# - cumulative number of pairs distinguished by this block\n");
840 ksprintf(&args->kstr,"# - block id\n");
841 ksprintf(&args->kstr,"#DS\t[2]Chromosome\t[3]Position\t[4]Cumulative number of distinct pairs\t[5]Block id\n");
842
843 kbitset_t *kbs_blk = kbs_init(args->npairs);
844 kbitset_iter_t itr;
845 int i,ndiff,rid,pos,ndiff_tot = 0, iblock = 0;
846 int ndiff_min = args->distinctive_sites <= args->npairs ? args->distinctive_sites : args->npairs;
847 while ( diff_sites_shift(args,&ndiff,&rid,&pos) )
848 {
849 int ndiff_new = 0, ndiff_dbg = 0;
850 kbs_start(&itr);
851 while ( (i=kbs_next(args->kbs_diff, &itr))>=0 )
852 {
853 ndiff_dbg++;
854 if ( kbs_exists(kbs_blk,i) ) continue; // already set
855 kbs_insert(kbs_blk,i);
856 ndiff_new++;
857 }
858 if ( ndiff_dbg!=ndiff ) error("Corrupted data, fixme: %d vs %d\n",ndiff_dbg,ndiff);
859 if ( !ndiff_new ) continue; // no new pair distinguished by this site
860 ndiff_tot += ndiff_new;
861 args->kstr.l = 0;
862 ksprintf(&args->kstr,"DS\t%s\t%d\t%d\t%d\n",bcf_hdr_id2name(args->qry_hdr,rid),pos+1,ndiff_tot,iblock);
863 if ( bgzf_write(args->out_fh, args->kstr.s, args->kstr.l)!=args->kstr.l ) error("Failed to write to %s\n", args->output_fname);
864 if ( ndiff_tot < ndiff_min ) continue; // fewer than the requested number of pairs can be distinguished at this point
865 iblock++;
866 ndiff_tot = 0;
867 kbs_clear(kbs_blk);
868 }
869 kbs_destroy(kbs_blk);
870 }
871 static void report(args_t *args)
872 {
873 args->kstr.l = 0;
874 ksprintf(&args->kstr,"INFO\tsites-compared\t%u\n",args->ncmp);
875 ksprintf(&args->kstr,"INFO\tsites-skipped-no-match\t%u\n",args->nskip_no_match);
876 ksprintf(&args->kstr,"INFO\tsites-skipped-multiallelic\t%u\n",args->nskip_not_ba);
877 ksprintf(&args->kstr,"INFO\tsites-skipped-monoallelic\t%u\n",args->nskip_mono);
878 ksprintf(&args->kstr,"INFO\tsites-skipped-no-data\t%u\n",args->nskip_no_data);
879 ksprintf(&args->kstr,"INFO\tsites-skipped-GT-not-diploid\t%u\n",args->nskip_dip_GT);
880 ksprintf(&args->kstr,"INFO\tsites-skipped-PL-not-diploid\t%u\n",args->nskip_dip_PL);
881 ksprintf(&args->kstr,"INFO\tsites-skipped-filtering-expression\t%u\n",args->nskip_filter);
882 ksprintf(&args->kstr,"INFO\tsites-used-PL-vs-PL\t%u\n",args->nused[0][0]);
883 ksprintf(&args->kstr,"INFO\tsites-used-PL-vs-GT\t%u\n",args->nused[0][1]);
884 ksprintf(&args->kstr,"INFO\tsites-used-GT-vs-PL\t%u\n",args->nused[1][0]);
885 ksprintf(&args->kstr,"INFO\tsites-used-GT-vs-GT\t%u\n",args->nused[1][1]);
886 ksprintf(&args->kstr,"# DCv2, discordance version 2:\n");
887 ksprintf(&args->kstr,"# - Query sample\n");
888 ksprintf(&args->kstr,"# - Genotyped sample\n");
889 ksprintf(&args->kstr,"# - Discordance, given either as an abstract score or number of mismatches, see the options -E/-u\n"
890 "# in man page for details. Note that samples with high missingness have fewer sites compared,\n"
891 "# which results in lower overall discordance. Therefore it is advisable to use the average score\n"
892 "# per site rather than the absolute value, i.e. divide the value by the number of sites compared\n"
893 "# (smaller value = better match)\n");
894 ksprintf(&args->kstr,"# - Average negative log of HWE probability at matching sites, attempts to quantify the following\n"
895 "# intuition: rare genotype matches are more informative than common genotype matches, hence two\n"
896 "# samples with similar discordance can be further stratified by the HWE score (bigger value = better\n"
897 "# match, the observed concordance was less likely to occur by chance)\n");
898 ksprintf(&args->kstr,"# - Number of sites compared for this pair of samples (bigger = more informative)\n");
899 ksprintf(&args->kstr,"# - Number of matching genotypes\n");
900 ksprintf(&args->kstr,"#DCv2\t[2]Query Sample\t[3]Genotyped Sample\t[4]Discordance\t[5]Average -log P(HWE)\t[6]Number of sites compared\t[7]Number of matching genotypes\n");
901 if ( bgzf_write(args->out_fh, args->kstr.s, args->kstr.l)!=args->kstr.l ) error("Failed to write to %s\n", args->output_fname);
902
903 int trim = args->ntop;
904 if ( !args->pairs )
905 {
906 if ( !args->ngt_smpl && args->nqry_smpl <= args->ntop ) trim = 0;
907 if ( args->ngt_smpl && args->ngt_smpl <= args->ntop ) trim = 0;
908 }
909
910 if ( args->pairs )
911 {
912 int i;
913 for (i=0; i<args->npairs; i++)
914 {
915 args->kstr.l = 0;
916 int iqry = args->pairs[i].iqry;
917 int igt = args->pairs[i].igt;
918 if ( args->ndiff )
919 {
920 ksprintf(&args->kstr,"DCv2\t%s\t%s\t%u\t%e\t%u\t%u\n",
921 args->qry_hdr->samples[iqry],
922 args->gt_hdr?args->gt_hdr->samples[igt]:args->qry_hdr->samples[igt],
923 args->ndiff[i],
924 (args->calc_hwe_prob && args->nmatch[i]) ? args->hwe_prob[i]/args->nmatch[i] : 0,
925 args->ncnt[i],
926 args->nmatch[i]);
927 }
928 else
929 {
930 ksprintf(&args->kstr,"DCv2\t%s\t%s\t%e\t%e\t%u\t%u\n",
931 args->qry_hdr->samples[iqry],
932 args->gt_hdr?args->gt_hdr->samples[igt]:args->qry_hdr->samples[igt],
933 args->pdiff[i],
934 (args->calc_hwe_prob && args->nmatch[i]) ? args->hwe_prob[i]/args->nmatch[i] : 0,
935 args->ncnt[i],
936 args->nmatch[i]);
937 }
938 if ( bgzf_write(args->out_fh, args->kstr.s, args->kstr.l)!=args->kstr.l ) error("Failed to write to %s\n", args->output_fname);
939 }
940 }
941 else if ( !trim )
942 {
943 int i,j,idx=0;
944 for (i=0; i<args->nqry_smpl; i++)
945 {
946 int iqry = args->qry_smpl ? args->qry_smpl[i] : i;
947 int ngt = args->cross_check ? i : args->ngt_smpl;
948 for (j=0; j<ngt; j++)
949 {
950 args->kstr.l = 0;
951 int igt = args->gt_smpl ? args->gt_smpl[j] : j;
952 if ( args->ndiff )
953 {
954 ksprintf(&args->kstr,"DCv2\t%s\t%s\t%u\t%e\t%u\t%u\n",
955 args->qry_hdr->samples[iqry],
956 args->gt_hdr?args->gt_hdr->samples[igt]:args->qry_hdr->samples[igt],
957 args->ndiff[idx],
958 (args->calc_hwe_prob && args->nmatch[idx]) ? args->hwe_prob[idx]/args->nmatch[idx] : 0,
959 args->ncnt[idx],
960 args->calc_hwe_prob ? args->nmatch[idx] : 0);
961 }
962 else
963 {
964 ksprintf(&args->kstr,"DCv2\t%s\t%s\t%e\t%e\t%u\t%u\n",
965 args->qry_hdr->samples[iqry],
966 args->gt_hdr?args->gt_hdr->samples[igt]:args->qry_hdr->samples[igt],
967 args->pdiff[idx],
968 (args->calc_hwe_prob && args->nmatch[idx]) ? args->hwe_prob[idx]/args->nmatch[idx] : 0,
969 args->ncnt[idx],
970 args->calc_hwe_prob ? args->nmatch[idx] : 0);
971 }
972 if ( bgzf_write(args->out_fh, args->kstr.s, args->kstr.l)!=args->kstr.l ) error("Failed to write to %s\n", args->output_fname);
973 idx++;
974 }
975 }
976 }
977 else if ( !args->cross_check )
978 {
979 idbl_t *arr = (idbl_t*)malloc(sizeof(*arr)*args->ngt_smpl);
980 int i,j;
981 for (i=0; i<args->nqry_smpl; i++)
982 {
983 int idx = i*args->ngt_smpl;
984 for (j=0; j<args->ngt_smpl; j++)
985 {
986 if ( args->sort_by_hwe )
987 arr[j].val = args->nmatch[idx] ? -args->hwe_prob[idx]/args->nmatch[idx] : 0; // -args->hwe_prob[idx];
988 else if ( args->ndiff )
989 arr[j].val = args->ncnt[idx] ? (double)args->ndiff[idx]/args->ncnt[idx] : 0;
990 else
991 arr[j].val = args->ncnt[idx] ? args->pdiff[idx]/args->ncnt[idx] : 0;
992 arr[j].ism = j;
993 arr[j].idx = idx;
994 idx++;
995 }
996 qsort(arr, args->ngt_smpl, sizeof(*arr), cmp_idbl);
997 int iqry = args->qry_smpl ? args->qry_smpl[i] : i;
998 for (j=0; j<args->ntop; j++)
999 {
1000 args->kstr.l = 0;
1001 int idx = arr[j].idx;
1002 int igt = args->gt_smpl ? args->gt_smpl[arr[j].ism] : arr[j].ism;
1003 if ( args->ndiff )
1004 {
1005 ksprintf(&args->kstr,"DCv2\t%s\t%s\t%u\t%e\t%u\t%u\n",
1006 args->qry_hdr->samples[iqry],
1007 args->gt_hdr?args->gt_hdr->samples[igt]:args->qry_hdr->samples[igt],
1008 args->ndiff[idx],
1009 (args->calc_hwe_prob && args->nmatch[idx]) ? args->hwe_prob[idx]/args->nmatch[idx] : 0,
1010 args->ncnt[idx],
1011 args->calc_hwe_prob ? args->nmatch[idx] : 0);
1012 }
1013 else
1014 {
1015 ksprintf(&args->kstr,"DCv2\t%s\t%s\t%e\t%e\t%u\t%u\n",
1016 args->qry_hdr->samples[iqry],
1017 args->gt_hdr?args->gt_hdr->samples[igt]:args->qry_hdr->samples[igt],
1018 args->pdiff[idx],
1019 (args->calc_hwe_prob && args->nmatch[idx]) ? args->hwe_prob[idx]/args->nmatch[idx] : 0,
1020 args->ncnt[idx],
1021 args->calc_hwe_prob ? args->nmatch[idx] : 0);
1022 }
1023 if ( bgzf_write(args->out_fh, args->kstr.s, args->kstr.l)!=args->kstr.l ) error("Failed to write to %s\n", args->output_fname);
1024 }
1025 }
1026 free(arr);
1027 }
1028 else
1029 {
1030 int narr = args->nqry_smpl-1;
1031 idbl_t *arr = (idbl_t*)malloc(sizeof(*arr)*narr);
1032 int i,j,k,idx;
1033 for (i=0; i<args->nqry_smpl; i++)
1034 {
1035 k = 0, idx = i*(i-1)/2;
1036 for (j=0; j<i; j++)
1037 {
1038 if ( args->sort_by_hwe )
1039 arr[k].val = args->nmatch[idx] ? -args->hwe_prob[idx]/args->nmatch[idx] : 0;
1040 else if ( args->ndiff )
1041 arr[k].val = args->ncnt[idx] ? (double)args->ndiff[idx]/args->ncnt[idx] : 0;
1042 else
1043 arr[k].val = args->ncnt[idx] ? args->pdiff[idx]/args->ncnt[idx] : 0;
1044 arr[k].ism = j;
1045 arr[k].idx = idx;
1046 idx++;
1047 k++;
1048 }
1049 for (; j<narr; j++)
1050 {
1051 idx = j*(j+1)/2 + i;
1052 if ( args->sort_by_hwe )
1053 arr[k].val = args->nmatch[idx] ? -args->hwe_prob[idx]/args->nmatch[idx] : 0;
1054 else if ( args->ndiff )
1055 arr[k].val = args->ncnt[idx] ? (double)args->ndiff[idx]/args->ncnt[idx] : 0;
1056 else
1057 arr[k].val = args->ncnt[idx] ? args->pdiff[idx]/args->ncnt[idx] : 0;
1058 arr[k].ism = j + 1;
1059 arr[k].idx = idx;
1060 k++;
1061 }
1062 qsort(arr, narr, sizeof(*arr), cmp_idbl);
1063 int iqry = args->qry_smpl ? args->qry_smpl[i] : i;
1064 for (j=0; j<args->ntop; j++)
1065 {
1066 args->kstr.l = 0;
1067 if ( i <= arr[j].ism ) continue;
1068 int idx = arr[j].idx;
1069 int igt = args->qry_smpl ? args->qry_smpl[arr[j].ism] : arr[j].ism;
1070 if ( args->ndiff )
1071 {
1072 ksprintf(&args->kstr,"DCv2\t%s\t%s\t%u\t%e\t%u\t%u\n",
1073 args->qry_hdr->samples[iqry],
1074 args->qry_hdr->samples[igt],
1075 args->ndiff[idx],
1076 (args->calc_hwe_prob && args->nmatch[idx]) ? args->hwe_prob[idx]/args->nmatch[idx] : 0,
1077 args->ncnt[idx],
1078 args->calc_hwe_prob ? args->nmatch[idx] : 0);
1079 }
1080 else
1081 {
1082 ksprintf(&args->kstr,"DCv2\t%s\t%s\t%e\t%e\t%u\t%u\n",
1083 args->qry_hdr->samples[iqry],
1084 args->qry_hdr->samples[igt],
1085 args->pdiff[idx],
1086 (args->calc_hwe_prob && args->nmatch[idx]) ? args->hwe_prob[idx]/args->nmatch[idx] : 0,
1087 args->ncnt[idx],
1088 args->calc_hwe_prob ? args->nmatch[idx] : 0);
1089 }
1090 if ( bgzf_write(args->out_fh, args->kstr.s, args->kstr.l)!=args->kstr.l ) error("Failed to write to %s\n", args->output_fname);
1091 }
1092 }
1093 free(arr);
1094 }
1095 }
1096
1097 static int is_input_okay(args_t *args, int nmatch)
1098 {
1099 int i;
1100 const char *msg;
1101 bcf_hdr_t *hdr;
1102 bcf1_t *rec;
1103 if ( args->gt_hdr && nmatch!=2 )
1104 {
1105 if ( args->nskip_no_match++ ) return 0;
1106 for (i=0; i<2; i++)
1107 {
1108 rec = bcf_sr_get_line(args->files,i);
1109 if ( rec ) break;
1110 }
1111 hdr = bcf_sr_get_header(args->files,i);
1112 fprintf(bcftools_stderr,"INFO: skipping %s:%"PRIhts_pos", no record with matching POS+ALT. (This is printed only once.)\n",
1113 bcf_seqname(hdr,rec),rec->pos+1);
1114 return 0;
1115 }
1116 for (i=0; i<2; i++)
1117 {
1118 hdr = bcf_sr_get_header(args->files,i);
1119 rec = bcf_sr_get_line(args->files,i);
1120 if ( rec->n_allele>2 )
1121 {
1122 if ( args->nskip_not_ba++ ) return 0;
1123 msg = "not a biallelic site, run `bcftools norm -m -` first";
1124 goto not_okay;
1125 }
1126 if ( bcf_get_variant_types(rec)==VCF_REF )
1127 {
1128 if ( args->nskip_mono++ ) return 0;
1129 msg = "monoallelic site";
1130 goto not_okay;
1131 }
1132 if ( !args->gt_hdr ) break;
1133 }
1134 return 1;
1135
1136 not_okay:
1137 fprintf(bcftools_stderr,"INFO: skipping %s:%"PRIhts_pos", %s. (This is printed only once.)\n",
1138 bcf_seqname(hdr,rec),rec->pos+1,msg);
1139 return 0;
1140 }
1141
1142 static void usage(void)
1143 {
1144 fprintf(bcftools_stderr, "\n");
1145 fprintf(bcftools_stderr, "About: Check sample identity. With no -g BCF given, multi-sample cross-check is performed.\n");
1146 fprintf(bcftools_stderr, "Usage: bcftools gtcheck [options] [-g <genotypes.vcf.gz>] <query.vcf.gz>\n");
1147 fprintf(bcftools_stderr, "\n");
1148 fprintf(bcftools_stderr, "Options:\n");
1149 //fprintf(bcftools_stderr, " -a, --all-sites Output comparison for all sites\n");
1150 //fprintf(bcftools_stderr, " -c, --cluster MIN,MAX Min inter- and max intra-sample error [0.23,-0.3]\n");
1151 fprintf(bcftools_stderr, " --distinctive-sites Find sites that can distinguish between at least NUM sample pairs.\n");
1152 fprintf(bcftools_stderr, " NUM[,MEM[,TMP]] If the number is smaller or equal to 1, it is interpreted as the fraction of pairs.\n");
1153 fprintf(bcftools_stderr, " The optional MEM string sets the maximum memory used for in-memory sorting [500M]\n");
1154 #ifdef _WIN32
1155 fprintf(bcftools_stderr, " and TMP is a prefix of temporary files used by external sorting [/bcftools.XXXXXX]\n");
1156 #else
1157 fprintf(bcftools_stderr, " and TMP is a prefix of temporary files used by external sorting [/tmp/bcftools.XXXXXX]\n");
1158 #endif
1159 fprintf(bcftools_stderr, " --dry-run Stop after first record to estimate required time\n");
1160 fprintf(bcftools_stderr, " -E, --error-probability INT Phred-scaled probability of genotyping error, 0 for faster but less accurate results [40]\n");
1161 fprintf(bcftools_stderr, " -e, --exclude [qry|gt]:EXPR Exclude sites for which the expression is true\n");
1162 fprintf(bcftools_stderr, " -g, --genotypes FILE Genotypes to compare against\n");
1163 fprintf(bcftools_stderr, " -H, --homs-only Homozygous genotypes only, useful with low coverage data (requires -g)\n");
1164 fprintf(bcftools_stderr, " -i, --include [qry|gt]:EXPR Include sites for which the expression is true\n");
1165 fprintf(bcftools_stderr, " --n-matches INT Print only top INT matches for each sample (sorted by average score), 0 for unlimited.\n");
1166 fprintf(bcftools_stderr, " Use negative value to sort by HWE probability rather than by discordance [0]\n");
1167 fprintf(bcftools_stderr, " --no-HWE-prob Disable calculation of HWE probability\n");
1168 fprintf(bcftools_stderr, " -o, --output FILE Write output to a file [standard output]\n");
1169 fprintf(bcftools_stderr, " -O, --output-type t|z t: plain tab-delimited text output, z: compressed [t]\n");
1170 fprintf(bcftools_stderr, " -p, --pairs LIST Comma-separated sample pairs to compare (qry,gt[,qry,gt..] with -g or qry,qry[,qry,qry..] w/o)\n");
1171 fprintf(bcftools_stderr, " -P, --pairs-file FILE File with tab-delimited sample pairs to compare (qry,gt with -g or qry,qry w/o)\n");
1172 fprintf(bcftools_stderr, " -r, --regions REGION Restrict to comma-separated list of regions\n");
1173 fprintf(bcftools_stderr, " -R, --regions-file FILE Restrict to regions listed in a file\n");
1174 fprintf(bcftools_stderr, " --regions-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [1]\n");
1175 fprintf(bcftools_stderr, " -s, --samples [qry|gt]:LIST List of query or -g samples, \"-\" to select all samples (by default all samples are compared)\n");
1176 fprintf(bcftools_stderr, " -S, --samples-file [qry|gt]:FILE File with the query or -g samples to compare\n");
1177 fprintf(bcftools_stderr, " -t, --targets REGION Similar to -r but streams rather than index-jumps\n");
1178 fprintf(bcftools_stderr, " -T, --targets-file FILE Similar to -R but streams rather than index-jumps\n");
1179 fprintf(bcftools_stderr, " --targets-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [0]\n");
1180 fprintf(bcftools_stderr, " -u, --use TAG1[,TAG2] Which tag to use in the query file (TAG1) and the -g file (TAG2) [PL,GT]\n");
1181 fprintf(bcftools_stderr, "Examples:\n");
1182 fprintf(bcftools_stderr, " # Check discordance of all samples from B against all samples in A\n");
1183 fprintf(bcftools_stderr, " bcftools gtcheck -g A.bcf B.bcf\n");
1184 fprintf(bcftools_stderr, "\n");
1185 fprintf(bcftools_stderr, " # Limit comparisons to the given list of samples\n");
1186 fprintf(bcftools_stderr, " bcftools gtcheck -s gt:a1,a2,a3 -s qry:b1,b2 -g A.bcf B.bcf\n");
1187 fprintf(bcftools_stderr, "\n");
1188 fprintf(bcftools_stderr, " # Compare only two pairs a1,b1 and a1,b2\n");
1189 fprintf(bcftools_stderr, " bcftools gtcheck -p a1,b1,a1,b2 -g A.bcf B.bcf\n");
1190 fprintf(bcftools_stderr, "\n");
1191 bcftools_exit(1);
1192 }
1193
1194 int main_vcfgtcheck(int argc, char *argv[])
1195 {
1196 int c;
1197 args_t *args = (args_t*) calloc(1,sizeof(args_t));
1198 args->argc = argc; args->argv = argv; set_cwd(args);
1199 args->qry_use_GT = -1;
1200 args->gt_use_GT = -1;
1201 args->calc_hwe_prob = 1;
1202 args->gt_err = 40;
1203 args->regions_overlap = 1;
1204 args->targets_overlap = 0;
1205 args->output_fname = "-";
1206
1207 // external sort for --distinctive-sites
1208 #ifdef _WIN32
1209 args->es_tmp_prefix = NULL;
1210 #else
1211 args->es_tmp_prefix = "/tmp/bcftools-gtcheck";
1212 #endif
1213 args->es_max_mem = strdup("500M");
1214
1215 // In simulated sample swaps the minimum error was 0.3 and maximum intra-sample error was 0.23
1216 // - min_inter: pairs with smaller err value will be considered identical
1217 // - max_intra: pairs with err value bigger than abs(max_intra_err) will be considered
1218 // different. If negative, the cutoff may be heuristically lowered
1219 args->min_inter_err = 0.23;
1220 args->max_intra_err = -0.3;
1221
1222 static struct option loptions[] =
1223 {
1224 {"error-probability",1,0,'E'}, // note this used to be 'e', but can easily auto-detect to assure backward compatibility
1225 {"exclude",required_argument,0,'e'},
1226 {"include",required_argument,0,'i'},
1227 {"output",required_argument,0,'o'},
1228 {"output-type",required_argument,NULL,'O'},
1229 {"use",1,0,'u'},
1230 {"cluster",1,0,'c'},
1231 {"GTs-only",1,0,'G'},
1232 {"all-sites",0,0,'a'},
1233 {"homs-only",0,0,'H'},
1234 {"help",0,0,'h'},
1235 {"genotypes",1,0,'g'},
1236 {"plot",1,0,'p'},
1237 {"samples",1,0,'s'},
1238 {"samples-file",1,0,'S'},
1239 {"n-matches",1,0,2},
1240 {"no-HWE-prob",0,0,3},
1241 {"target-sample",1,0,4},
1242 {"dry-run",0,0,5},
1243 {"distinctive-sites",1,0,6},
1244 {"regions",1,0,'r'},
1245 {"regions-file",1,0,'R'},
1246 {"regions-overlap",required_argument,NULL,7},
1247 {"targets",1,0,'t'},
1248 {"targets-file",1,0,'T'},
1249 {"targets-overlap",required_argument,NULL,8},
1250 {"pairs",1,0,'p'},
1251 {"pairs-file",1,0,'P'},
1252 {0,0,0,0}
1253 };
1254 char *tmp;
1255 while ((c = getopt_long(argc, argv, "hg:p:s:S:p:P:Hr:R:at:T:G:c:u:e:E:i:o:O:",loptions,NULL)) >= 0) {
1256 switch (c) {
1257 case 'o': args->output_fname = optarg; break;
1258 case 'O':
1259 switch (optarg[0]) {
1260 case 't': args->output_type = FT_TAB_TEXT; break;
1261 case 'z': args->output_type = FT_VCF_GZ; break;
1262 default:
1263 {
1264 args->clevel = strtol(optarg,&tmp,10);
1265 if ( *tmp || args->clevel<0 || args->clevel>9 ) error("The output type \"%s\" not recognised\n", optarg);
1266 }
1267 }
1268 if ( optarg[1] )
1269 {
1270 args->clevel = strtol(optarg+1,&tmp,10);
1271 if ( *tmp || args->clevel<0 || args->clevel>9 ) error("Could not parse argument: --output-type %s\n", optarg+1);
1272 }
1273 break;
1274 case 'e':
1275 if ( !strncasecmp("gt:",optarg,3) )
1276 {
1277 if ( args->gt_filter_str ) error("Error: only one -i or -e expression can be given for gt:, and they cannot be combined\n");
1278 args->gt_filter_str = optarg;
1279 args->gt_filter_logic |= FLT_EXCLUDE;
1280 }
1281 else if ( !strncasecmp("qry:",optarg,4) )
1282 {
1283 if ( args->qry_filter_str ) error("Error: only one -i or -e expression can be given for qry:, and they cannot be combined\n");
1284 args->qry_filter_str = optarg;
1285 args->qry_filter_logic |= FLT_EXCLUDE;
1286 }
1287 else
1288 {
1289 // this could be the old -e, --error-probability option
1290 args->gt_err = strtol(optarg,&tmp,10);
1291 if ( !tmp || *tmp )
1292 {
1293 // it is not
1294 args->gt_filter_str = optarg;
1295 args->qry_filter_str = optarg;
1296 args->gt_filter_logic |= FLT_EXCLUDE;
1297 args->qry_filter_logic |= FLT_EXCLUDE;
1298 }
1299 else
1300 {
1301 fprintf(bcftools_stderr,"[warning] auto-detected the old format --error-probability option, please switch from -e to -E.\n");
1302 }
1303 }
1304 break;
1305 case 'i':
1306 if ( !strncasecmp("gt:",optarg,3) )
1307 {
1308 if ( args->gt_filter_str ) error("Error: only one -i or -e expression can be given for gt:, and they cannot be combined\n");
1309 args->gt_filter_str = optarg;
1310 args->gt_filter_logic |= FLT_INCLUDE;
1311 }
1312 else if ( !strncasecmp("qry:",optarg,4) )
1313 {
1314 if ( args->qry_filter_str ) error("Error: only one -i or -e expression can be given for qry:, and they cannot be combined\n");
1315 args->qry_filter_str = optarg;
1316 args->qry_filter_logic |= FLT_INCLUDE;
1317 }
1318 else
1319 {
1320 args->gt_filter_str = optarg;
1321 args->qry_filter_str = optarg;
1322 args->gt_filter_logic |= FLT_INCLUDE;
1323 args->qry_filter_logic |= FLT_INCLUDE;
1324 }
1325 break;
1326 case 'E':
1327 args->gt_err = strtol(optarg,&tmp,10);
1328 if ( !tmp || *tmp ) error("Could not parse: --error-probability %s\n", optarg);
1329 break;
1330 case 'u':
1331 {
1332 int i,nlist;
1333 char **list = hts_readlist(optarg, 0, &nlist);
1334 if ( !list || nlist<=0 || nlist>2 ) error("Failed to parse --use %s\n", optarg);
1335 if ( !strcasecmp("GT",list[0]) ) args->qry_use_GT = 1;
1336 else if ( !strcasecmp("PL",list[0]) ) args->qry_use_GT = 0;
1337 else error("Failed to parse --use %s; only GT and PL are supported\n", optarg);
1338 if ( nlist==2 )
1339 {
1340 if ( !strcasecmp("GT",list[1]) ) args->gt_use_GT = 1;
1341 else if ( !strcasecmp("PL",list[1]) ) args->gt_use_GT = 0;
1342 else error("Failed to parse --use %s; only GT and PL are supported\n", optarg);
1343 }
1344 else args->gt_use_GT = args->qry_use_GT;
1345 for (i=0; i<nlist; i++) free(list[i]);
1346 free(list);
1347 }
1348 break;
1349 case 2 :
1350 args->ntop = strtol(optarg,&tmp,10);
1351 if ( !tmp || *tmp ) error("Could not parse: --n-matches %s\n", optarg);
1352 if ( args->ntop < 0 )
1353 {
1354 args->sort_by_hwe = 1;
1355 args->ntop *= -1;
1356 }
1357 break;
1358 case 3 : args->calc_hwe_prob = 0; break;
1359 case 4 : error("The option -S, --target-sample has been deprecated\n"); break;
1360 case 5 : args->dry_run = 1; break;
1361 case 6 :
1362 args->distinctive_sites = strtod(optarg,&tmp);
1363 if ( *tmp )
1364 {
1365 if ( *tmp!=',' ) error("Could not parse: --distinctive-sites %s\n", optarg);
1366 tmp++;
1367 free(args->es_max_mem);
1368 args->es_max_mem = strdup(tmp);
1369 while ( *tmp && *tmp!=',' ) tmp++;
1370 if ( *tmp ) { *tmp = 0; args->es_tmp_prefix = tmp+1; }
1371 }
1372 args->gt_err = 0;
1373 break;
1374 case 'c':
1375 error("The -c option is to be implemented, please open an issue on github\n");
1376 args->min_inter_err = strtod(optarg,&tmp);
1377 if ( *tmp )
1378 {
1379 if ( *tmp!=',') error("Could not parse: -c %s\n", optarg);
1380 args->max_intra_err = strtod(tmp+1,&tmp);
1381 if ( *tmp ) error("Could not parse: -c %s\n", optarg);
1382 }
1383 break;
1384 case 'G': error("The option -G, --GTs-only has been deprecated\n"); break;
1385 case 'a': args->all_sites = 1; error("The -a option is to be implemented, please open an issue on github\n"); break;
1386 case 'H': args->hom_only = 1; break;
1387 case 'g': args->gt_fname = optarg; break;
1388 // case 'p': args->plot = optarg; break;
1389 case 's':
1390 if ( !strncasecmp("gt:",optarg,3) ) args->gt_samples = optarg+3;
1391 else if ( !strncasecmp("qry:",optarg,4) ) args->qry_samples = optarg+4;
1392 else error("Which one? Query samples (qry:%s) or genotype samples (gt:%s)?\n",optarg,optarg);
1393 break;
1394 case 'S':
1395 if ( !strncasecmp("gt:",optarg,3) ) args->gt_samples = optarg+3, args->gt_samples_is_file = 1;
1396 else if ( !strncasecmp("qry:",optarg,4) ) args->qry_samples = optarg+4, args->qry_samples_is_file = 1;
1397 else error("Which one? Query samples (qry:%s) or genotype samples (gt:%s)?\n",optarg,optarg);
1398 break;
1399 case 'p': args->pair_samples = optarg; break;
1400 case 'P': args->pair_samples = optarg; args->pair_samples_is_file = 1; break;
1401 case 'r': args->regions = optarg; break;
1402 case 'R': args->regions = optarg; args->regions_is_file = 1; break;
1403 case 't': args->targets = optarg; break;
1404 case 'T': args->targets = optarg; args->targets_is_file = 1; break;
1405 case 7 :
1406 args->regions_overlap = parse_overlap_option(optarg);
1407 if ( args->regions_overlap < 0 ) error("Could not parse: --regions-overlap %s\n",optarg);
1408 break;
1409 case 8 :
1410 args->targets_overlap = parse_overlap_option(optarg);
1411 if ( args->targets_overlap < 0 ) error("Could not parse: --targets-overlap %s\n",optarg);
1412 break;
1413 case 'h':
1414 case '?': usage(); break;
1415 default: error("Unknown argument: %s\n", optarg);
1416 }
1417 }
1418 if ( optind==argc )
1419 {
1420 if ( !isatty(fileno((FILE *)stdin)) ) args->qry_fname = "-"; // reading from stdin
1421 else usage(); // no files given
1422 }
1423 else args->qry_fname = argv[optind];
1424 if ( argc>optind+1 ) error("Error: too many files given, run with -h for help\n"); // too many files given
1425 if ( args->pair_samples )
1426 {
1427 if ( args->gt_samples || args->qry_samples ) error("The -p/-P option cannot be combined with -s/-S\n");
1428 if ( args->ntop ) error("The --n-matches option cannot be combined with -p/-P\n");
1429 }
1430 if ( args->distinctive_sites && !args->pair_samples ) error("The experimental option --distinctive-sites requires -p/-P\n");
1431 if ( args->hom_only && !args->gt_fname ) error("The option --homs-only requires --genotypes\n");
1432 if ( args->distinctive_sites && args->gt_err ) error("The option --distinctive-sites cannot be combined with --error-probability\n");
1433
1434 init_data(args);
1435
1436 int ret;
1437 while ( (ret=bcf_sr_next_line(args->files)) )
1438 {
1439 if ( !is_input_okay(args,ret) ) continue;
1440
1441 // time one record to give the user an estimate with very big files
1442 struct timeval t0, t1;
1443 if ( !args->ncmp ) gettimeofday(&t0, NULL);
1444
1445 process_line(args);
1446
1447 if ( args->ncmp==1 )
1448 {
1449 gettimeofday(&t1, NULL);
1450 double delta = (t1.tv_sec - t0.tv_sec) * 1e6 + (t1.tv_usec - t0.tv_usec);
1451 fprintf(bcftools_stderr,"INFO:\tTime required to process one record .. %f seconds\n",delta/1e6);
1452 args->kstr.l = 0;
1453 ksprintf(&args->kstr,"INFO\tTime required to process one record .. %f seconds\n",delta/1e6);
1454 if ( bgzf_write(args->out_fh, args->kstr.s, args->kstr.l)!=args->kstr.l ) error("Failed to write to %s\n", args->output_fname);
1455 if ( args->dry_run ) break;
1456 }
1457 }
1458 if ( !args->dry_run )
1459 {
1460 report(args);
1461 if ( args->distinctive_sites ) report_distinctive_sites(args);
1462 }
1463
1464 destroy_data(args);
1465 free(args);
1466 return 0;
1467 }
1468