Debian Codegraph @

bcftools/vcfbuf.c.pysam.c

raw symbols SCIP
1 #include "bcftools.pysam.h"
2
3 /* The MIT License
4
5 Copyright (c) 2016-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 */
28
29 #include <assert.h>
30 #include <strings.h>
31 #include <htslib/vcf.h>
32 #include <htslib/vcfutils.h>
33 #include <htslib/hts_os.h>
34 #include <htslib/kbitset.h>
35 #include "bcftools.h"
36 #include "vcfbuf.h"
37 #include "rbuf.h"
38
39 typedef struct
40 {
41 double max[VCFBUF_LD_N];
42 int rand_missing, filter1;
43 }
44 ld_t;
45
46 typedef struct
47 {
48 bcf1_t *rec;
49 double af;
50 unsigned int af_set:1, filter:1, idx:30;
51 }
52 vcfrec_t;
53
54 #define PRUNE_MODE_MAX_AF 1
55 #define PRUNE_MODE_1ST 2
56 #define PRUNE_MODE_RAND 3
57 typedef struct
58 {
59 int max_sites, mvrec, mac, mfarr, mode;
60 int *ac, *idx;
61 float *farr;
62 char *af_tag;
63 vcfrec_t **vrec;
64 }
65 prune_t;
66
67
68 #define MARK_OVERLAP 1
69 #define MARK_DUP 2
70 #define MARK_EXPR 3
71
72 #define MARK_MISSING_SCALAR 0 // actual value to use
73 #define MARK_MISSING_MAX_DP 1 // max overlap_t.value scaled by INFO/DP
74
75 // temporary internal structure for iterative overlap removal by mark_t.expr
76 typedef struct
77 {
78 double value; // the sort value
79 int rmme, idx; // mark for removal, index in vcfbuf_t.rbuf
80 int dp; // with MARK_MISSING_MAX_DP, INFO/DP is used extrapolate missing QUAL
81 kbitset_t *bset; // mark which records it overlaps with, given as 0-based indexes to vcfbuf_t.rbuf
82 bcf1_t *rec;
83 }
84 overlap_t;
85 typedef struct
86 {
87 // modes
88 int mode;
89 char *expr;
90
91 // sites marked according to expr, returned to the caller via vcfbuf_get()
92 rbuf_t rbuf;
93 uint8_t *mark;
94 int last;
95
96 // MARK_OVERLAP
97 int overlap_rid, overlap_end;
98
99 // MARK_EXPR
100 int nbuf;
101 overlap_t *buf, **buf_ptr;
102 int missing_expr; // the value to use when min(QUAL) encounters a missing value
103 float missing_value; // the default missing value
104 float max_qual; // with MARK_MISSING_MAX_DP
105 int max_qual_dp; //
106 int ntmpi; // temporary int array and the allocated memory
107 int32_t *tmpi;
108 }
109 mark_t;
110
111 struct _vcfbuf_t
112 {
113 int win, // maximum number of sites in the buffer, either number of sites (<0) or bp (<0)
114 dummy; // the caller maintains the buffer via push/peek/flush
115 bcf_hdr_t *hdr;
116 vcfrec_t *vcf;
117 rbuf_t rbuf;
118 ld_t ld;
119 prune_t prune;
120 mark_t mark;
121 enum { clean, dirty } status;
122 };
123
124 vcfbuf_t *vcfbuf_init(bcf_hdr_t *hdr, int win)
125 {
126 vcfbuf_t *buf = (vcfbuf_t*) calloc(1,sizeof(vcfbuf_t));
127 buf->hdr = hdr;
128 buf->win = win;
129 buf->status = clean;
130 buf->mark.overlap_rid = -1;
131 int i;
132 for (i=0; i<VCFBUF_LD_N; i++) buf->ld.max[i] = HUGE_VAL;
133 rbuf_init(&buf->rbuf, 0);
134 return buf;
135 }
136
137 void vcfbuf_destroy(vcfbuf_t *buf)
138 {
139 int i;
140 for (i=0; i<buf->rbuf.m; i++)
141 if ( buf->vcf[i].rec ) bcf_destroy(buf->vcf[i].rec);
142 free(buf->vcf);
143 free(buf->prune.farr);
144 free(buf->prune.vrec);
145 free(buf->prune.ac);
146 free(buf->prune.af_tag);
147 free(buf->prune.idx);
148 free(buf->mark.mark);
149 free(buf->mark.expr);
150 for (i=0; i<buf->mark.nbuf; i++) kbs_destroy(buf->mark.buf[i].bset);
151 free(buf->mark.buf);
152 free(buf->mark.buf_ptr);
153 free(buf->mark.tmpi);
154 free(buf);
155 }
156
157 int vcfbuf_set(vcfbuf_t *buf, vcfbuf_opt_t key, ...)
158 {
159 va_list args;
160 switch (key)
161 {
162 case LD_FILTER1:
163 va_start(args, key);
164 buf->ld.filter1 = va_arg(args,int);
165 va_end(args);
166 return 0;
167
168 case LD_RAND_MISSING:
169 va_start(args, key);
170 buf->ld.rand_missing = va_arg(args,int);
171 va_end(args);
172 return 0;
173
174 case LD_MAX_R2:
175 va_start(args, key);
176 buf->ld.max[VCFBUF_LD_IDX_R2] = va_arg(args,double);
177 va_end(args);
178 return 0;
179
180 case LD_MAX_LD:
181 va_start(args, key);
182 buf->ld.max[VCFBUF_LD_IDX_LD] = va_arg(args,double);
183 va_end(args);
184 return 0;
185
186 case LD_MAX_HD:
187 va_start(args, key);
188 buf->ld.max[VCFBUF_LD_IDX_HD] = va_arg(args,double);
189 va_end(args);
190 return 0;
191
192 case VCFBUF_DUMMY:
193 va_start(args, key);
194 buf->dummy = va_arg(args,int);
195 va_end(args);
196 return 0;
197
198 case PRUNE_NSITES:
199 va_start(args, key);
200 buf->prune.max_sites = va_arg(args,int);
201 if ( !buf->prune.mode ) buf->prune.mode = PRUNE_MODE_MAX_AF;
202 va_end(args);
203 return 0;
204
205 case PRUNE_NSITES_MODE:
206 va_start(args, key);
207 char *mode = va_arg(args,char*);
208 va_end(args);
209 if ( !strcasecmp(mode,"maxAF") ) buf->prune.mode = PRUNE_MODE_MAX_AF;
210 else if ( !strcasecmp(mode,"1st") ) buf->prune.mode = PRUNE_MODE_1ST;
211 else if ( !strcasecmp(mode,"rand") ) buf->prune.mode = PRUNE_MODE_RAND;
212 else error("The mode \"%s\" is not recognised\n",mode);
213 return 0;
214
215 case PRUNE_AF_TAG:
216 va_start(args, key);
217 buf->prune.af_tag = strdup(va_arg(args,char*));
218 va_end(args);
219 return 0;
220
221 case MARK:
222 va_start(args, key);
223 buf->mark.expr = strdup(va_arg(args,char*));
224 if ( !strcasecmp(buf->mark.expr,"overlap") ) buf->mark.mode = MARK_OVERLAP;
225 else if ( !strcasecmp(buf->mark.expr,"dup") ) buf->mark.mode = MARK_DUP;
226 else buf->mark.mode = MARK_EXPR;
227 va_end(args);
228 return 0;
229
230 case MARK_MISSING_EXPR:
231 va_start(args, key);
232 char *expr = va_arg(args,char*);
233 if ( !strcasecmp(expr,"0") )
234 {
235 buf->mark.missing_expr = MARK_MISSING_SCALAR;
236 buf->mark.missing_value = 0;
237 }
238 else if ( !strcasecmp(expr,"DP") )
239 {
240 if ( buf->mark.mode!=MARK_EXPR ) error("Only the combination of --mark 'min(QUAL)' with --missing DP is currently supported\n");
241 buf->mark.missing_expr = MARK_MISSING_MAX_DP;
242 }
243 else
244 error("todo: MARK_MISSING_EXPR=%s\n",expr);
245 va_end(args);
246 return 0;
247 }
248 return 0;
249 }
250
251 void *vcfbuf_get(vcfbuf_t *buf, vcfbuf_opt_t key, ...)
252 {
253 va_list args;
254 va_start(args, key);
255 if ( key==MARK )
256 return &buf->mark.last;
257 va_end(args);
258 return NULL;
259 }
260
261 int vcfbuf_nsites(vcfbuf_t *buf)
262 {
263 return buf->rbuf.n;
264 }
265
266 bcf1_t *vcfbuf_push(vcfbuf_t *buf, bcf1_t *rec)
267 {
268 // make sure the caller is using the buffer correctly and calls vcfbuf_flush()
269 // before placing next vcfbuf_push() call
270 assert(buf->status!=dirty);
271 if ( !buf->dummy ) buf->status = dirty;
272
273 rbuf_expand0(&buf->rbuf, vcfrec_t, buf->rbuf.n+1, buf->vcf);
274 int i = rbuf_append(&buf->rbuf);
275 if ( !buf->vcf[i].rec ) buf->vcf[i].rec = bcf_init1();
276
277 bcf1_t *ret = buf->vcf[i].rec;
278 buf->vcf[i].rec = rec;
279 buf->vcf[i].af_set = 0;
280 buf->vcf[i].filter = buf->ld.filter1;
281 buf->ld.filter1 = 0;
282
283 return ret;
284 }
285
286 bcf1_t *vcfbuf_peek(vcfbuf_t *buf, int idx)
287 {
288 buf->status = clean;
289 int i = rbuf_kth(&buf->rbuf, idx);
290 return i<0 ? NULL : buf->vcf[i].rec;
291 }
292
293 bcf1_t *vcfbuf_remove(vcfbuf_t *buf, int idx)
294 {
295 int i = rbuf_kth(&buf->rbuf, idx);
296 if ( i<0 ) return NULL;
297 bcf1_t *rec = buf->vcf[i].rec;
298 rbuf_remove_kth(&buf->rbuf, vcfrec_t, idx, buf->vcf);
299 return rec;
300 }
301
302 static int cmpvrec(const void *_a, const void *_b)
303 {
304 vcfrec_t *a = *((vcfrec_t**) _a);
305 vcfrec_t *b = *((vcfrec_t**) _b);
306 if ( a->af < b->af ) return -1;
307 if ( a->af == b->af ) return 0;
308 return 1;
309 }
310 static int cmpint_desc(const void *_a, const void *_b)
311 {
312 int a = *((int*)_a);
313 int b = *((int*)_b);
314 if ( a < b ) return 1;
315 if ( a == b ) return 0;
316 return -1;
317 }
318
319 static void _prune_sites(vcfbuf_t *buf, int flush_all)
320 {
321
322 int nbuf = flush_all ? buf->rbuf.n : buf->rbuf.n - 1;
323
324 int nprune = nbuf - buf->prune.max_sites;
325 int i,k,irec = 0;
326 if ( buf->prune.mode==PRUNE_MODE_1ST )
327 {
328 int eoff = flush_all ? 1 : 2;
329 for (i=0; i<nprune; i++)
330 rbuf_remove_kth(&buf->rbuf, vcfrec_t, buf->rbuf.n - eoff, buf->vcf);
331 return;
332 }
333 if ( buf->prune.mode==PRUNE_MODE_RAND )
334 {
335 int eoff = flush_all ? 0 : 1;
336 for (i=0; i<nprune; i++)
337 {
338 int j = (buf->rbuf.n - eoff) * hts_drand48();
339 rbuf_remove_kth(&buf->rbuf, vcfrec_t, j, buf->vcf);
340 }
341 return;
342 }
343
344 if ( nbuf > buf->prune.mvrec )
345 {
346 buf->prune.idx = (int*) realloc(buf->prune.idx, nbuf*sizeof(int));
347 buf->prune.vrec = (vcfrec_t**) realloc(buf->prune.vrec, nbuf*sizeof(vcfrec_t*));
348 buf->prune.mvrec = nbuf;
349 }
350
351 // set allele frequency and prepare buffer for sorting
352 for (i=-1; rbuf_next(&buf->rbuf,&i) && irec<nbuf; )
353 {
354 bcf1_t *line = buf->vcf[i].rec;
355 if ( line->n_allele > buf->prune.mac )
356 {
357 buf->prune.ac = (int*) realloc(buf->prune.ac, line->n_allele*sizeof(*buf->prune.ac));
358 buf->prune.mac = line->n_allele;
359 }
360 if ( !buf->vcf[i].af_set )
361 {
362 buf->vcf[i].af = 0;
363 if ( buf->prune.af_tag )
364 {
365 if ( bcf_get_info_float(buf->hdr,line,buf->prune.af_tag,&buf->prune.farr, &buf->prune.mfarr) > 0 ) buf->vcf[i].af = buf->prune.farr[0];
366 }
367 else if ( bcf_calc_ac(buf->hdr, line, buf->prune.ac, BCF_UN_INFO|BCF_UN_FMT) )
368 {
369 int ntot = buf->prune.ac[0], nalt = 0;
370 for (k=1; k<line->n_allele; k++) nalt += buf->prune.ac[k];
371 buf->vcf[i].af = ntot ? (float)nalt/ntot : 0;
372 }
373 buf->vcf[i].af_set = 1;
374 }
375 buf->vcf[i].idx = irec;
376 buf->prune.vrec[irec++] = &buf->vcf[i];
377 }
378
379 // sort by allele frequency, low AF will be removed preferentially
380 qsort(buf->prune.vrec, nbuf, sizeof(*buf->prune.vrec), cmpvrec);
381
382 // sort the rbuf indexes to be pruned descendently so that j-th rbuf index
383 // is removed before i-th index if i<j
384 for (i=0; i<nprune; i++)
385 buf->prune.idx[i] = buf->prune.vrec[i]->idx;
386
387 qsort(buf->prune.idx, nprune, sizeof(int), cmpint_desc);
388
389 for (i=0; i<nprune; i++)
390 rbuf_remove_kth(&buf->rbuf, vcfrec_t, buf->prune.idx[i], buf->vcf);
391 }
392
393 static int mark_dup_can_flush_(vcfbuf_t *buf, int flush_all)
394 {
395 int flush = flush_all;
396 mark_t *mark = &buf->mark;
397 if ( buf->status==dirty )
398 {
399 // a new site was just added by vcfbuf_push()
400 rbuf_expand0(&mark->rbuf, uint8_t, buf->rbuf.n, mark->mark);
401 int i = rbuf_append(&mark->rbuf);
402 mark->mark[i] = 0;
403
404 if ( buf->rbuf.n==1 ) goto flush;
405
406 // there is at least one previous site, check if it's a duplicate
407 int k1 = rbuf_kth(&buf->rbuf, -1);
408 int k2 = rbuf_kth(&buf->rbuf, -2);
409 vcfrec_t *rec1 = &buf->vcf[k1];
410 vcfrec_t *rec2 = &buf->vcf[k2];
411
412 int is_dup = 1;
413 if ( rec1->rec->rid!=rec2->rec->rid ) is_dup = 0;
414 else if ( rec1->rec->pos!=rec2->rec->pos ) is_dup = 0;
415
416 if ( is_dup )
417 {
418 // it is, mark the last two sites as duplicates
419 int k1 = rbuf_kth(&mark->rbuf, -1);
420 int k2 = rbuf_kth(&mark->rbuf, -2);
421 mark->mark[k1] = 1;
422 mark->mark[k2] = 1;
423 goto flush;
424 }
425
426 // the last site is not a duplicate with the previous, all sites but the last one can be flushed
427 flush = 1;
428 }
429 else if ( buf->rbuf.n > 1 ) flush = 1;
430
431 flush:
432 if ( !flush ) return 0;
433
434 int i = rbuf_shift(&mark->rbuf);
435 mark->last = mark->mark[i];
436 return 1;
437 }
438
439 static int mark_overlap_helper_(vcfbuf_t *buf, int flush_all)
440 {
441 if ( buf->status!=dirty ) return flush_all;
442
443 int flush = flush_all;
444 mark_t *mark = &buf->mark;
445
446 // a new site was just added by vcfbuf_push()
447 buf->status = clean;
448
449 rbuf_expand0(&mark->rbuf, uint8_t, buf->rbuf.n, mark->mark);
450 int i = rbuf_append(&mark->rbuf);
451 mark->mark[i] = 0;
452
453 // determine beg and end of the last record that was just added
454 i = rbuf_last(&buf->rbuf);
455 vcfrec_t *last = &buf->vcf[i];
456 if ( mark->overlap_rid != last->rec->rid ) mark->overlap_end = 0;
457 int beg_pos = last->rec->pos;
458 int end_pos = last->rec->pos + last->rec->rlen - 1;
459
460 // Assuming left-aligned indels. In case it is a deletion, the real variant
461 // starts one base after. If an insertion, the overlap with previous is zero
462 int imin = last->rec->rlen;
463 for (i=0; i<last->rec->n_allele; i++)
464 {
465 char *ref = last->rec->d.allele[0];
466 char *alt = last->rec->d.allele[i];
467 if ( *alt == '<' ) continue; // ignore symbolic alleles
468 while ( *ref && *alt && nt_to_upper(*ref)==nt_to_upper(*alt) ) { ref++; alt++; }
469 if ( imin > ref - last->rec->d.allele[0] ) imin = ref - last->rec->d.allele[0];
470 }
471 if ( beg_pos <= mark->overlap_end )
472 {
473 // the new site overlaps with the previous
474 beg_pos += imin;
475 if ( beg_pos > end_pos ) end_pos = beg_pos;
476 }
477 if ( buf->rbuf.n==1 )
478 {
479 mark->overlap_rid = last->rec->rid;
480 mark->overlap_end = end_pos;
481 return flush;
482 }
483 if ( beg_pos <= mark->overlap_end )
484 {
485 if ( mark->overlap_end < end_pos ) mark->overlap_end = end_pos;
486 int k1 = rbuf_kth(&mark->rbuf, -1);
487 int k2 = rbuf_kth(&mark->rbuf, -2);
488 mark->mark[k1] = 1;
489 mark->mark[k2] = 1;
490 }
491 else
492 {
493 if ( mark->overlap_end < end_pos ) mark->overlap_end = end_pos;
494 flush = 1;
495 }
496 return flush;
497 }
498
499
500 static int mark_overlap_can_flush_(vcfbuf_t *buf, int flush_all)
501 {
502 int flush = flush_all;
503 if ( buf->status==dirty ) flush = mark_overlap_helper_(buf,flush_all);
504 else if ( buf->rbuf.n > 1 ) flush = 1;
505 if ( !flush ) return 0;
506
507 mark_t *mark = &buf->mark;
508 int i = rbuf_shift(&mark->rbuf);
509 mark->last = mark->mark[i];
510 return 1;
511 }
512
513
514 static int records_overlap(bcf1_t *a, bcf1_t *b)
515 {
516 if ( a->rid != b->rid ) return 0;
517 if ( a->pos + a->rlen - 1 < b->pos ) return 0;
518 return 1;
519 }
520
521 static int cmp_overlap_ptr_asc(const void *aptr, const void *bptr)
522 {
523 overlap_t *a = *((overlap_t**)aptr);
524 overlap_t *b = *((overlap_t**)bptr);
525 if ( a->value < b->value ) return -1;
526 if ( a->value > b->value ) return 1;
527 return 0;
528 }
529 static void mark_expr_missing_reset_(vcfbuf_t *buf)
530 {
531 buf->mark.max_qual = 0;
532 buf->mark.max_qual_dp = 0;
533 }
534 static void mark_expr_missing_prep_(vcfbuf_t *buf, overlap_t *olap)
535 {
536 int nval = bcf_get_info_int32(buf->hdr,olap->rec,"DP",&buf->mark.tmpi,&buf->mark.ntmpi);
537 if ( nval!=1 ) return;
538
539 olap->dp = buf->mark.tmpi[0];
540 if ( bcf_float_is_missing(olap->rec->qual) ) return;
541 if ( buf->mark.max_qual < olap->rec->qual )
542 {
543 buf->mark.max_qual = olap->rec->qual;
544 buf->mark.max_qual_dp = olap->dp;
545 }
546 }
547 static void mark_expr_missing_set_(vcfbuf_t *buf, overlap_t *olap)
548 {
549 if ( !bcf_float_is_missing(olap->rec->qual) ) return;
550 if ( !buf->mark.max_qual_dp ) return;
551
552 // scale QUAL of the most confident variant in the overlap proportionally to the coverage
553 // and use that to prioritize the records
554 olap->value = buf->mark.max_qual * olap->dp / buf->mark.max_qual_dp;
555 }
556 static int mark_expr_can_flush_(vcfbuf_t *buf, int flush_all)
557 {
558 mark_t *mark = &buf->mark;
559 if ( strcasecmp("min(QUAL)",mark->expr) ) error("Todo; at this time only min(QUAL) is supported\n");
560
561 int flush = flush_all;
562 if ( buf->status==dirty )
563 {
564 flush = mark_overlap_helper_(buf,flush_all);
565 if ( !flush ) return 0;
566
567 if ( mark->missing_expr==MARK_MISSING_MAX_DP ) mark_expr_missing_reset_(buf);
568
569 // init overlaps, each overlap_t structure keeps a list of overlapping records, symmetrical
570 size_t nori = mark->nbuf;
571 hts_resize(overlap_t, buf->rbuf.n, &mark->nbuf, &mark->buf, HTS_RESIZE_CLEAR);
572 hts_resize(overlap_t*, buf->rbuf.n, &nori, &mark->buf_ptr, HTS_RESIZE_CLEAR);
573 int i;
574 for (i=0; i<buf->rbuf.n; i++)
575 {
576 overlap_t *oi = &mark->buf[i];
577 int j = rbuf_kth(&buf->rbuf, i);
578 assert(j>=0);
579 bcf1_t *rec = buf->vcf[j].rec;
580 assert(rec);
581 oi->rec = rec;
582
583 // todo: other than QUAL values
584 oi->value = bcf_float_is_missing(rec->qual) ? mark->missing_value : rec->qual;
585 if ( mark->missing_expr==MARK_MISSING_MAX_DP ) mark_expr_missing_prep_(buf,oi);
586 if ( oi->bset )
587 {
588 kbs_resize(&oi->bset,buf->rbuf.n);
589 kbs_clear(oi->bset);
590 }
591 else
592 oi->bset = kbs_init(buf->rbuf.n);
593 oi->idx = i;
594 mark->buf_ptr[i] = oi;
595 mark->mark[oi->idx] = 0;
596 }
597 int nolap = 0;
598 for (i=0; i<buf->rbuf.n; i++)
599 {
600 overlap_t *oi = &mark->buf[i];
601 if ( mark->missing_expr==MARK_MISSING_MAX_DP ) mark_expr_missing_set_(buf,oi);
602 int j;
603 for (j=i+1; j<buf->rbuf.n; j++)
604 {
605 overlap_t *oj = &mark->buf[j];
606 if ( !records_overlap(oi->rec,oj->rec) ) continue;
607 kbs_insert(oi->bset,j);
608 kbs_insert(oj->bset,i);
609 nolap++;
610 }
611 }
612
613 // sort according to the requested criteria, currently only min(QUAL)
614 qsort(mark->buf_ptr,buf->rbuf.n,sizeof(*mark->buf_ptr),cmp_overlap_ptr_asc); // todo: other than min()
615
616 // go through the list sorted by overlap_t.value, eg QUAL
617 for (i=0; nolap && i<buf->rbuf.n; i++)
618 {
619 kbitset_iter_t itr;
620 overlap_t *oi = mark->buf_ptr[i];
621 kbs_start(&itr);
622 int j;
623 while ((j=kbs_next(oi->bset, &itr)) >= 0)
624 {
625 kbs_delete(oi->bset,j);
626 assert(nolap);
627 assert(kbs_exists(mark->buf[j].bset,oi->idx));
628 kbs_delete(mark->buf[j].bset,oi->idx);
629 nolap--;
630 }
631 j = rbuf_kth(&mark->rbuf,oi->idx);
632 mark->mark[j] = 1;
633 }
634 }
635 else if ( buf->rbuf.n > 1 ) flush = 1;
636 if ( !flush ) return 0;
637
638 int i = rbuf_shift(&mark->rbuf);
639 mark->last = mark->mark[i];
640 return 1;
641 }
642
643 bcf1_t *vcfbuf_flush(vcfbuf_t *buf, int flush_all)
644 {
645 int i,j;
646
647 // nothing to do, no lines in the buffer
648 if ( buf->rbuf.n==0 ) return NULL;
649
650 // dummy mode, always flushing
651 if ( buf->dummy ) goto ret;
652
653 // pruning mode
654 if ( buf->win )
655 {
656 int can_flush = flush_all;
657 i = rbuf_kth(&buf->rbuf, 0); // first
658 j = rbuf_last(&buf->rbuf); // last
659 if ( buf->vcf[i].rec->rid != buf->vcf[j].rec->rid ) can_flush = 1;
660 else if ( buf->win > 0 )
661 {
662 if ( buf->rbuf.n > buf->win ) can_flush = 1;
663 }
664 else if ( buf->win < 0 )
665 {
666 if ( !(buf->vcf[i].rec->pos - buf->vcf[j].rec->pos > buf->win) ) can_flush = 1;
667 }
668 buf->status = clean;
669 if ( !can_flush ) return NULL;
670 if ( buf->prune.max_sites && buf->prune.max_sites < buf->rbuf.n ) _prune_sites(buf, flush_all);
671 goto ret;
672 }
673
674 // overlaps and duplicates
675 if ( buf->mark.mode )
676 {
677 int can_flush = 0;
678 if ( buf->mark.mode==MARK_OVERLAP )
679 {
680 if ( mark_overlap_can_flush_(buf,flush_all) ) can_flush = 1;
681 }
682 else if ( buf->mark.mode==MARK_DUP )
683 {
684 if ( mark_dup_can_flush_(buf,flush_all) ) can_flush = 1;
685 }
686 if ( buf->mark.mode==MARK_EXPR )
687 {
688 if ( mark_expr_can_flush_(buf,flush_all) ) can_flush = 1;
689 }
690 buf->status = clean;
691 if ( !can_flush ) return NULL;
692 goto ret;
693 }
694
695 ret:
696 buf->status = clean;
697 i = rbuf_shift(&buf->rbuf);
698 return buf->vcf[i].rec;
699 }
700
701 static double _estimate_af(int8_t *ptr, int size, int nvals, int nsamples)
702 {
703 int i,j, nref = 0, nalt = 0;
704 for (i=0; i<nsamples; i++)
705 {
706 for (j=0; j<nvals; j++)
707 {
708 if ( ptr[j]==bcf_gt_missing ) break;
709 if ( ptr[j]==bcf_int8_vector_end ) break;
710 if ( bcf_gt_allele(ptr[j]) ) nalt++;
711 else nref++;
712 }
713 ptr += size;
714 }
715 if ( nref+nalt == 0 ) return 0;
716 return (double)nalt/(nref+nalt);
717 }
718
719 /*
720 The `ld` is set to D approximated as suggested in https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2710162/
721 D =~ (GT correlation) * sqrt(Pa*(1-Pa)*Pb*(1-Pb))
722
723 and `hd` as proposed in Ragsdale, A. P., & Gravel, S. (2019). Unbiased estimation of linkage
724 disequilibrium from unphased data. Molecular Biology and Evolution. doi:10.1093/molbev/msz265
725
726 \hat{D} = 1/[n*(n+1)]*[
727 (n1 + n2/2 + n4/2 + n5/4)*(n5/4 + n6/2 + n8/2 + n9)
728 -(n2/2 + n3 + n5/4 + n6/2)*(n4/2 + n5/4 + n7 + n8/2)
729 ]
730 where n1,n2,..n9 are counts of RR/RR,RR/RA,..,AA/AA genotypes.
731
732 Returns 0 on success, -1 if the values could not be determined (missing genotypes)
733 */
734 static int _calc_r2_ld(vcfbuf_t *buf, bcf1_t *arec, bcf1_t *brec, vcfbuf_ld_t *ld)
735 {
736 if ( arec->n_sample!=brec->n_sample ) error("Different number of samples: %d vs %d\n",arec->n_sample,brec->n_sample);
737 assert( arec->n_sample );
738
739 int i,j,igt = bcf_hdr_id2int(buf->hdr, BCF_DT_ID, "GT");
740 bcf_unpack(arec, BCF_UN_FMT);
741 bcf_unpack(brec, BCF_UN_FMT);
742 bcf_fmt_t *afmt = NULL, *bfmt = NULL;
743 for (i=0; i<arec->n_fmt; i++)
744 if ( arec->d.fmt[i].id==igt ) { afmt = &arec->d.fmt[i]; break; }
745 if ( !afmt ) return -1; // no GT tag
746 for (i=0; i<brec->n_fmt; i++)
747 if ( brec->d.fmt[i].id==igt ) { bfmt = &brec->d.fmt[i]; break; }
748 if ( !bfmt ) return -1; // no GT tag
749
750 if ( afmt->n==0 ) return -1; // empty?!
751 if ( bfmt->n==0 ) return -1; // empty?!
752 if ( afmt->type!=BCF_BT_INT8 ) error("TODO: the GT fmt_type is not int8!\n");
753 if ( bfmt->type!=BCF_BT_INT8 ) error("TODO: the GT fmt_type is not int8!\n");
754
755 // Determine allele frequencies, this is to sample randomly missing genotypes
756 double aaf = 0, baf = 0;
757 if ( buf->ld.rand_missing )
758 {
759 aaf = _estimate_af((int8_t*)afmt->p, afmt->size, afmt->n, arec->n_sample);
760 baf = _estimate_af((int8_t*)bfmt->p, bfmt->size, bfmt->n, brec->n_sample);
761 }
762
763 // Calculate r2, lf, hd
764 double nhd[] = {0,0,0,0,0,0,0,0,0};
765 double ab = 0, aa = 0, bb = 0, a = 0, b = 0;
766 int nab = 0, ndiff = 0;
767 int an_tot = 0, bn_tot = 0;
768 for (i=0; i<arec->n_sample; i++)
769 {
770 int8_t *aptr = (int8_t*) (afmt->p + i*afmt->size);
771 int8_t *bptr = (int8_t*) (bfmt->p + i*bfmt->size);
772 int adsg = 0, bdsg = 0; // dosages (0,1,2) at sites (a,b)
773 int an = 0, bn = 0; // number of alleles at sites (a,b)
774 for (j=0; j<afmt->n; j++)
775 {
776 if ( aptr[j]==bcf_int8_vector_end ) break;
777 if ( aptr[j]==bcf_gt_missing )
778 {
779 if ( !buf->ld.rand_missing ) break;
780 if ( hts_drand48() >= aaf ) adsg += 1;
781 }
782 else if ( bcf_gt_allele(aptr[j]) ) adsg += 1;
783 an++;
784 }
785 for (j=0; j<bfmt->n; j++)
786 {
787 if ( bptr[j]==bcf_int8_vector_end ) break;
788 if ( bptr[j]==bcf_gt_missing )
789 {
790 if ( !buf->ld.rand_missing ) break;
791 if ( hts_drand48() >= baf ) bdsg += 1;
792 }
793 else if ( bcf_gt_allele(bptr[j]) ) bdsg += 1;
794 bn++;
795 }
796 if ( an && bn )
797 {
798 an_tot += an;
799 aa += adsg*adsg;
800 a += adsg;
801
802 bn_tot += bn;
803 bb += bdsg*bdsg;
804 b += bdsg;
805
806 if ( adsg!=bdsg ) ndiff++;
807 ab += adsg*bdsg;
808 nab++;
809 }
810 if ( an==2 && bn==2 ) // for now only diploid genotypes
811 {
812 assert( adsg<=2 && bdsg<=2 );
813 nhd[ bdsg*3 + adsg ]++;
814 }
815 }
816 if ( !nab ) return -1; // no data in common for the two sites
817
818 double pa = a/an_tot;
819 double pb = b/bn_tot;
820 double cor;
821 if ( !ndiff ) cor = 1;
822 else
823 {
824 if ( aa == a*a/nab || bb == b*b/nab ) // zero variance, add small noise
825 {
826 aa += 1e-4;
827 bb += 1e-4;
828 ab += 1e-4;
829 a += 1e-2;
830 b += 1e-2;
831 nab++;
832 }
833 cor = (ab - a*b/nab) / sqrt(aa - a*a/nab) / sqrt(bb - b*b/nab);
834 }
835
836 ld->val[VCFBUF_LD_IDX_R2] = cor * cor;
837
838 // Lewontin's normalization of D. Also we cap at 1 as the calculation
839 // can result in values bigger than 1 for high AFs.
840 ld->val[VCFBUF_LD_IDX_LD] = cor * sqrt(pa*(1-pa)*pb*(1-pb));
841 double norm;
842 if ( ld->val[VCFBUF_LD_IDX_LD] < 0 )
843 norm = -pa*pb > -(1-pa)*(1-pb) ? -pa*pb : -(1-pa)*(1-pb);
844 else
845 norm = pa*(1-pb) > (1-pa)*pb ? pa*(1-pb) : (1-pa)*pb;
846 if ( norm )
847 ld->val[VCFBUF_LD_IDX_LD] = fabs(norm) > fabs(ld->val[VCFBUF_LD_IDX_LD]) ? ld->val[VCFBUF_LD_IDX_LD]/norm : 1;
848 if ( !ld->val[VCFBUF_LD_IDX_LD] )
849 ld->val[VCFBUF_LD_IDX_LD] = fabs(ld->val[VCFBUF_LD_IDX_LD]); // avoid "-0" on output
850
851 ld->val[VCFBUF_LD_IDX_HD] =
852 (nhd[0] + nhd[1]/2. + nhd[3]/2. + nhd[4]/4.)*(nhd[4]/4. + nhd[5]/2. + nhd[7]/2. + nhd[8])
853 - (nhd[1]/2. + nhd[2] + nhd[4]/4. + nhd[5]/2.)*(nhd[3]/2. + nhd[4]/4. + nhd[6] + nhd[7]/2.);
854 ld->val[VCFBUF_LD_IDX_HD] /= nab;
855 ld->val[VCFBUF_LD_IDX_HD] /= nab+1;
856
857 return 0;
858 }
859
860 int vcfbuf_ld(vcfbuf_t *buf, bcf1_t *rec, vcfbuf_ld_t *ld)
861 {
862 int ret = -1;
863 if ( !buf->rbuf.n ) return ret;
864
865 int j, i = buf->rbuf.f;
866
867 // Relying on vcfbuf being properly flushed - all sites in the buffer
868 // must come from the same chromosome
869 if ( buf->vcf[i].rec->rid != rec->rid ) return ret;
870
871 vcfbuf_ld_t tmp;
872 for (j=0; j<VCFBUF_LD_N; j++)
873 {
874 ld->val[j] = -HUGE_VAL;
875 ld->rec[j] = NULL;
876 }
877
878 for (i=-1; rbuf_next(&buf->rbuf,&i); )
879 {
880 if ( buf->vcf[i].filter ) continue;
881 if ( _calc_r2_ld(buf, buf->vcf[i].rec, rec, &tmp) < 0 ) continue; // missing genotypes
882
883 int done = 0;
884 for (j=0; j<VCFBUF_LD_N; j++)
885 {
886 if ( ld->val[j] < tmp.val[j] )
887 {
888 ld->val[j] = tmp.val[j];
889 ld->rec[j] = buf->vcf[i].rec;
890 }
891 if ( buf->ld.max[j] < tmp.val[j] ) done = 1;
892 ret = 0;
893 }
894 if ( done ) return ret;
895 }
896 return ret;
897 }
898
899