Debian Codegraph @

bcftools/vcfbuf.c

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