Debian Codegraph @

bcftools/vcfgtcheck.c

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