Debian Codegraph @

bcftools/abuf.c

raw symbols SCIP
1 /* The MIT License
2
3 Copyright (c) 2021-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 <ctype.h>
31 #include "bcftools.h"
32 #include "abuf.h"
33 #include "rbuf.h"
34
35 typedef enum
36 {
37 M_FIRST, M_SUM
38 }
39 merge_rule_t;
40
41 typedef struct
42 {
43 kstring_t ref, alt;
44 int ial; // the index of the original ALT allele, 1-based
45 int beg, end; // 0-based inclusive offsets to ref,alt
46 int plen; // the ref,alt prefix length, eg plen=1 for C>CA
47 }
48 atom_t;
49
50 typedef struct
51 {
52 bcf1_t *rec;
53 int nori, nout; // number of ALTs in the input, and VCF rows on output
54 uint8_t *tbl; // nori columns, nout rows; indicates allele contribution to output rows, see "The atomization works as follows" below
55 uint8_t *overlaps; // is the star allele needed for this variant?
56 atom_t **atoms;
57 int matoms, mtbl, moverlaps;
58 char *info_tag;
59 }
60 split_t;
61
62 struct _abuf_t
63 {
64 abuf_opt_t mode;
65 split_t split;
66 atom_t *atoms;
67 int natoms, matoms;
68 const bcf_hdr_t *hdr;
69 bcf_hdr_t *out_hdr;
70 bcf1_t **vcf; // dimensions stored in rbuf
71 rbuf_t rbuf;
72
73 kstring_t tmps;
74 void *tmp, *tmp2;
75 int32_t *gt, *tmpi;
76 int ngt, mgt, ntmpi, mtmpi, mtmp, mtmp2;
77 int star_allele;
78 };
79
80 abuf_t *abuf_init(const bcf_hdr_t *hdr, abuf_opt_t mode)
81 {
82 if ( mode!=SPLIT ) error("todo\n");
83 abuf_t *buf = (abuf_t*) calloc(1,sizeof(abuf_t));
84 buf->hdr = hdr;
85 buf->out_hdr = (bcf_hdr_t*) hdr;
86 buf->mode = mode;
87 buf->star_allele = 1;
88 rbuf_init(&buf->rbuf, 0);
89 return buf;
90 }
91
92 void abuf_destroy(abuf_t *buf)
93 {
94 int i;
95 for (i=0; i<buf->matoms; i++)
96 {
97 free(buf->atoms[i].ref.s);
98 free(buf->atoms[i].alt.s);
99 }
100 free(buf->atoms);
101 free(buf->split.atoms);
102 free(buf->split.overlaps);
103 free(buf->split.tbl);
104 for (i=0; i<buf->rbuf.m; i++)
105 if ( buf->vcf[i] ) bcf_destroy(buf->vcf[i]);
106 free(buf->vcf);
107 free(buf->gt);
108 free(buf->tmpi);
109 free(buf->tmp);
110 free(buf->tmp2);
111 free(buf->tmps.s);
112 free(buf);
113 }
114
115 void abuf_set(abuf_t *buf, abuf_opt_t key, void *value)
116 {
117 if ( key==BCF_HDR ) { buf->out_hdr = *((bcf_hdr_t**)value); return; }
118 if ( key==INFO_TAG )
119 {
120 buf->split.info_tag = *((char**)value);
121 bcf_hdr_printf(buf->out_hdr,"##INFO=<ID=%s,Number=1,Type=String,Description=\"Original variant. Format: CHR|POS|REF|ALT|USED_ALT_IDX\">",buf->split.info_tag);
122 return;
123 }
124 if ( key==STAR_ALLELE ) { buf->star_allele = *((int*)value); return; }
125 }
126
127 /*
128 Split alleles into primitivs, e.g.
129 CC>TT becomes C>T,C>T
130 GCGT>GTGA becomes C>T,T>A
131
132 There is no sequence alignment, just trimming and hungry matching
133 from left side.
134 */
135 static void _atomize_allele(abuf_t *buf, bcf1_t *rec, int ial)
136 {
137 // Trim identical sequence from right
138 char *ref = rec->d.allele[0];
139 char *alt = rec->d.allele[ial];
140 int rlen = strlen(ref);
141 int alen = strlen(alt);
142 while ( rlen>1 && alen>1 && ref[rlen-1]==alt[alen-1] ) rlen--, alen--;
143 int Mlen = rlen > alen ? rlen : alen;
144
145 atom_t *atom = NULL;
146 int i;
147 for (i=0; i<Mlen; i++)
148 {
149 char refb = i<rlen ? ref[i] : '-';
150 char altb = i<alen ? alt[i] : '-';
151 if ( refb!=altb )
152 {
153 if ( refb=='-' || altb=='-' )
154 {
155 assert(atom);
156 if ( altb!='-' ) kputc(altb, &atom->alt);
157 if ( refb!='-' ) { kputc(refb, &atom->ref); atom->end++; }
158 continue;
159 }
160 buf->natoms++;
161 hts_expand0(atom_t,buf->natoms,buf->matoms,buf->atoms);
162 atom = &buf->atoms[buf->natoms-1];
163 atom->ref.l = 0;
164 atom->alt.l = 0;
165 kputc(refb, &atom->ref);
166 kputc(altb, &atom->alt);
167 atom->beg = atom->end = i;
168 atom->ial = ial;
169
170 if ( rlen!=alen && (i+1>=rlen || i+1>=alen) ) // the next base is an indel combined with SNV, e.g. C>GGG?
171 {
172 buf->natoms++;
173 hts_expand0(atom_t,buf->natoms,buf->matoms,buf->atoms);
174 atom = &buf->atoms[buf->natoms-1];
175 atom->ref.l = 0;
176 atom->alt.l = 0;
177 kputc(refb, &atom->ref);
178 kputc(refb, &atom->alt);
179 atom->beg = atom->end = i;
180 atom->ial = ial;
181 atom->plen = 1;
182 }
183 continue;
184 }
185 if ( i+1>=rlen || i+1>=alen ) // is the next base an indel?
186 {
187 buf->natoms++;
188 hts_expand0(atom_t,buf->natoms,buf->matoms,buf->atoms);
189 atom = &buf->atoms[buf->natoms-1];
190 atom->ref.l = 0;
191 atom->alt.l = 0;
192 kputc(refb, &atom->ref);
193 kputc(altb, &atom->alt);
194 atom->beg = atom->end = i;
195 atom->ial = ial;
196 }
197 }
198 }
199 static int _atoms_inconsistent(const atom_t *a, const atom_t *b)
200 {
201 if ( a->beg < b->beg ) return -1;
202 if ( a->beg > b->beg ) return 1;
203 int rcmp = strcasecmp(a->ref.s,b->ref.s);
204 if ( rcmp ) return rcmp;
205 return strcasecmp(a->alt.s,b->alt.s);
206 }
207
208 // returns
209 // 0 .. identical beg,ref,alt
210 // 1 .. non-overlapping variants, but record may overlap (A>AT vs A>C)
211 // 2 .. overlapping (conflicting) variants
212 static int _atoms_overlap(const atom_t *a, const atom_t *b)
213 {
214 if ( a->beg < b->beg ) return 2;
215 if ( a->beg > b->beg ) return 2;
216
217 // consider SNV followed by DEL as not overlapping
218 // CC > C a.plen=1 (ref,alt prefix len=1)
219 // C > T b.plen=0 (ref,alt prefix len=0)
220 if ( a->plen && a->plen >= b->ref.l ) return 1;
221 if ( b->plen && b->plen >= a->ref.l ) return 1;
222
223 int rcmp = strcasecmp(a->ref.s,b->ref.s);
224 if ( rcmp ) return 2;
225
226 // consider SNV followed by INS as not overlapping
227 // A > AT a.plen=1 (ref,alt prefix len=1)
228 // A > C b.plen=0 (ref,alt prefix len=0)
229 if ( a->plen && a->plen >= b->alt.l ) return 1;
230 if ( b->plen && b->plen >= a->alt.l ) return 1;
231
232 rcmp = strcasecmp(a->alt.s,b->alt.s);
233 if ( rcmp ) return 2;
234 return 0;
235 }
236 /*
237 For reproducibility of tests on different platforms, we need to guarantee the same order of identical
238 atoms originating from different source ALTs. Even though they are consistent, different values can be
239 picked for VCF annotations as currently the values from the one that comes first are used.
240 */
241 static int _cmp_atoms(const void *aptr, const void *bptr)
242 {
243 const atom_t *a = (const atom_t*) aptr;
244 const atom_t *b = (const atom_t*) bptr;
245 int rcmp = _atoms_inconsistent(a,b);
246 if ( rcmp ) return rcmp;
247 if ( a->ial < b->ial ) return -1;
248 if ( a->ial > b->ial ) return 1;
249 return 0;
250 }
251 static void _split_table_init(abuf_t *buf, bcf1_t *rec, int natoms)
252 {
253 buf->split.rec = rec;
254 buf->split.nori = rec->n_allele - 1;
255 buf->split.nout = 0;
256 hts_expand(uint8_t,buf->split.nori*natoms,buf->split.mtbl,buf->split.tbl);
257 hts_expand(atom_t*,natoms,buf->split.matoms,buf->split.atoms);
258 hts_expand(uint8_t,natoms,buf->split.moverlaps,buf->split.overlaps);
259 memset(buf->split.overlaps,0,sizeof(*buf->split.overlaps)*natoms);
260 }
261 static void _split_table_new(abuf_t *buf, atom_t *atom)
262 {
263 int i, iout = buf->split.nout++;
264 buf->split.atoms[iout] = atom;
265 uint8_t *ptr = buf->split.tbl + iout*buf->split.nori;
266 for (i=0; i<buf->split.nori; i++) ptr[i] = 0;
267 ptr[atom->ial-1] = 1;
268 }
269 static void _split_table_overlap(abuf_t *buf, int iout, atom_t *atom)
270 {
271 uint8_t *ptr = buf->split.tbl + iout*buf->split.nori;
272 int olap = _atoms_overlap(atom,buf->split.atoms[iout]);
273 ptr[atom->ial-1] = olap > 1 ? 2 : 1;
274
275 // The test test/atomize.split.5.vcf shows why we sometimes can and sometimes
276 // cannot remove the star allele like this
277 // buf->split.overlaps[iout] = olap > 1 ? 1 : 0;
278 // I forgot the details of the code, so don't immediately see
279 // if this could be made smarter
280 buf->split.overlaps[iout] = 1;
281 }
282 #if 0
283 static void _split_table_print(abuf_t *buf)
284 {
285 int i,j;
286 for (i=0; i<buf->split.nout; i++)
287 {
288 atom_t *atom = buf->split.atoms[i];
289 uint8_t *ptr = buf->split.tbl + i*buf->split.nori;
290 fprintf(stderr,"%d\t%s\t%s",(int)buf->split.rec->pos+1+atom->beg,atom->ref.s,atom->alt.s);
291 for (j=0; j<buf->split.nori; j++) fprintf(stderr,"\t%d",(int)ptr[j]);
292 fprintf(stderr,"\n");
293 }
294 }
295 static void _split_table_print_atoms(abuf_t *buf)
296 {
297 int i;
298 for (i=0; i<buf->natoms; i++)
299 {
300 atom_t *atom = &buf->atoms[i];
301 fprintf(stderr,"atom%d %p: ialt=%d %s>%s %d-%d\n",i,atom,atom->ial,atom->ref.s,atom->alt.s,atom->beg,atom->end);
302 }
303 }
304 #endif
305 static inline uint8_t _has_star_allele(abuf_t *buf, int iout)
306 {
307 if ( !buf->star_allele ) return 0;
308 return buf->split.overlaps[iout];
309 }
310 static inline int _split_table_get_ial(abuf_t *buf, int irow, int ial)
311 {
312 if ( !ial ) return ial;
313 return buf->split.tbl[irow*buf->split.nori + ial - 1];
314 }
315 static void _split_table_set_chrom_qual(abuf_t *buf)
316 {
317 int iout,j;
318 bcf1_t *rec = buf->split.rec;
319 for (iout=0; iout<buf->split.nout; iout++)
320 {
321 rbuf_expand0(&buf->rbuf, bcf1_t*, buf->rbuf.n+1, buf->vcf);
322 j = rbuf_append(&buf->rbuf);
323 if ( !buf->vcf[j] ) buf->vcf[j] = bcf_init1();
324 bcf1_t *out = buf->vcf[j];
325 bcf_clear1(out);
326
327 atom_t *atom = buf->split.atoms[iout];
328 out->rid = rec->rid;
329 out->pos = rec->pos + atom->beg;
330 bcf_update_id(buf->out_hdr, out, rec->d.id);
331
332 const char *als[3];
333 als[0] = atom->ref.s;
334 als[1] = atom->alt.s;
335 als[2] = "*";
336 int nals = _has_star_allele(buf,iout) ? 3 : 2;
337 bcf_update_alleles(buf->out_hdr, out, als, nals);
338
339 if ( bcf_float_is_missing(rec->qual) )
340 bcf_float_set_missing(out->qual);
341 else
342 out->qual = rec->qual;
343
344 bcf_update_filter(buf->out_hdr, out, rec->d.flt, rec->d.n_flt);
345 }
346 }
347 int copy_string_field(char *src, int isrc, int src_len, kstring_t *dst, int idst);
348 static void _split_table_set_info(abuf_t *buf, bcf_info_t *info, merge_rule_t mode)
349 {
350 const char *tag = bcf_hdr_int2id(buf->hdr,BCF_DT_ID,info->key);
351 int type = bcf_hdr_id2type(buf->hdr,BCF_HL_INFO,info->key);
352 int len = bcf_hdr_id2length(buf->hdr,BCF_HL_INFO,info->key);
353 if ( len==BCF_VL_G ) return; // todo: Number=G INFO tags
354 if ( type==BCF_HT_LONG ) return; // todo: 64bit integers
355
356 bcf1_t *rec = buf->split.rec;
357 int mtmp = ( type==BCF_HT_INT || type==BCF_HT_REAL ) ? buf->mtmp/4 : buf->mtmp;
358 int nval = bcf_get_info_values(buf->hdr,rec,tag,&buf->tmp,&mtmp,type);
359 if ( type==BCF_HT_INT || type==BCF_HT_REAL ) buf->mtmp = mtmp*4;
360
361 // Check for incorrect number of values. Note this check does not consider all values missing
362 // and will remove annotations that don't pass.
363 if ( type==BCF_HT_INT || type==BCF_HT_REAL )
364 {
365 if ( (len==BCF_VL_A && nval != rec->n_allele - 1) || (len==BCF_VL_R && nval != rec->n_allele) ) return;
366 }
367
368 if ( buf->mtmp2 < buf->mtmp )
369 {
370 buf->tmp2 = realloc(buf->tmp2, buf->mtmp);
371 if ( !buf->tmp2 ) error("Failed to alloc %d bytes\n", buf->mtmp);
372 buf->mtmp2 = buf->mtmp;
373 }
374
375 const int num_size = 4;
376 assert( num_size==sizeof(int32_t) && num_size==sizeof(float) );
377 int32_t missing = bcf_int32_missing;
378 void *missing_ptr = (void*)&missing;
379 if ( type==BCF_HT_REAL ) bcf_float_set_missing(*((float*)missing_ptr));
380 int32_t vector_end = bcf_int32_vector_end;
381 void *vector_end_ptr = (void*)&vector_end;
382 if ( type==BCF_HT_REAL ) bcf_float_set_vector_end(*((float*)vector_end_ptr));
383
384 int iout,i;
385 for (iout=0; iout<buf->split.nout; iout++)
386 {
387 bcf1_t *out = buf->vcf[rbuf_kth(&buf->rbuf,iout)];
388 int star_allele = _has_star_allele(buf,iout);
389 int ret = 0;
390 if ( len==BCF_VL_FIXED || len==BCF_VL_VAR )
391 ret = bcf_update_info(buf->out_hdr, out, tag, type==BCF_HT_FLAG ? NULL : buf->tmp, nval, type);
392 else if ( len==BCF_VL_A && type!=BCF_HT_STR )
393 {
394 int iori = buf->split.atoms[iout]->ial - 1;
395 assert( iori<nval );
396 if ( !memcmp(vector_end_ptr,buf->tmp+num_size*iori,num_size) )
397 memcpy(buf->tmp2,missing_ptr,num_size);
398 else
399 memcpy(buf->tmp2,buf->tmp+num_size*iori,num_size);
400 if ( star_allele )
401 memcpy(buf->tmp2+num_size,missing_ptr,num_size);
402 ret = bcf_update_info(buf->out_hdr, out, tag, buf->tmp2, 1 + star_allele, type);
403 }
404 else if ( len==BCF_VL_A && type==BCF_HT_STR )
405 {
406 int iori = buf->split.atoms[iout]->ial - 1;
407 kstring_t dst;
408 dst.l = 0; dst.m = buf->mtmp2; dst.s = (char*)buf->tmp2;
409 kputc('.',&dst);
410 if ( star_allele ) kputs(",.",&dst);
411 copy_string_field(buf->tmp, iori, nval, &dst, 0);
412 if ( star_allele ) copy_string_field(".", 0, 1, &dst, 1);
413 buf->mtmp2 = dst.m;
414 buf->tmp2 = dst.s;
415 ret = bcf_update_info(buf->out_hdr, out, tag, buf->tmp2, dst.l, type);
416 }
417 else if ( len==BCF_VL_R && type!=BCF_HT_STR )
418 {
419 memcpy(buf->tmp2,buf->tmp,num_size); // REF contributes to all records
420 int iori = buf->split.atoms[iout]->ial;
421 assert( iori<nval && iori<=buf->split.nori );
422 if ( !memcmp(vector_end_ptr,buf->tmp+num_size*iori,num_size) )
423 memcpy(buf->tmp2+num_size,missing_ptr,num_size);
424 else
425 memcpy(buf->tmp2+num_size,buf->tmp+num_size*iori,num_size);
426 if ( type==BCF_HT_INT && mode==M_SUM )
427 {
428 uint8_t *tbl = buf->split.tbl + iout*buf->split.nori;
429 for (i=iori; i<buf->split.nori; i++)
430 {
431 if ( tbl[i]==1 ) ((int32_t*)buf->tmp2)[1] += ((int32_t*)buf->tmp)[i+1];
432 }
433 }
434 if ( star_allele )
435 memcpy(buf->tmp2+2*num_size,missing_ptr,num_size);
436 ret = bcf_update_info(buf->out_hdr, out, tag, buf->tmp2, 2 + star_allele, type);
437 }
438 else if ( len==BCF_VL_R && type==BCF_HT_STR )
439 {
440 int iori = buf->split.atoms[iout]->ial - 1;
441 kstring_t dst;
442 dst.l = 0; dst.m = buf->mtmp2; dst.s = (char*)buf->tmp2;
443 kputs(".,.",&dst);
444 if ( star_allele ) kputs(",.",&dst);
445 copy_string_field(buf->tmp, 0, nval, &dst, 0);
446 copy_string_field(buf->tmp, iori+1, nval, &dst, 1);
447 if ( star_allele ) copy_string_field(".", 0, 1, &dst, 2);
448 buf->mtmp2 = dst.m;
449 buf->tmp2 = dst.s;
450 ret = bcf_update_info(buf->out_hdr, out, tag, buf->tmp2, dst.l, type);
451 }
452 if ( ret!=0 ) error("An error occurred while updating INFO/%s (errcode=%d)\n",tag,ret);
453 }
454 }
455 static void _split_table_set_history(abuf_t *buf)
456 {
457 int i,j,ret;
458 bcf1_t *rec = buf->split.rec;
459
460 // Don't update if the tag already exists. This is to prevent -a from overwriting -m
461 int m = 0;
462 char *tmp = NULL;
463 ret = bcf_get_info_string(buf->hdr,rec,buf->split.info_tag,&tmp,&m);
464 free(tmp);
465 if ( ret>0 ) return;
466
467 buf->tmps.l = 0;
468 ksprintf(&buf->tmps,"%s|%"PRIhts_pos"|%s|",bcf_seqname(buf->hdr,rec),rec->pos+1,rec->d.allele[0]);
469 for (i=1; i<rec->n_allele; i++)
470 {
471 kputs(rec->d.allele[i],&buf->tmps);
472 if ( i+1<rec->n_allele ) kputc(',',&buf->tmps);
473 else kputc(',',&buf->tmps);
474 }
475 int len = buf->tmps.l;
476 buf->tmps.s[buf->tmps.l-1] = '|';
477
478 for (i=0; i<buf->split.nout; i++)
479 {
480 buf->tmps.l = len;
481 bcf1_t *out = buf->vcf[rbuf_kth(&buf->rbuf,i)];
482 uint8_t *ptr = buf->split.tbl + i*buf->split.nori;
483 for (j=0; j<buf->split.nori; j++)
484 {
485 if ( ptr[j]!=1 ) continue;
486 kputw(j+1,&buf->tmps);
487 kputc(',',&buf->tmps);
488 }
489 buf->tmps.s[--buf->tmps.l] = 0;
490 if ( (ret=bcf_update_info_string(buf->out_hdr, out, buf->split.info_tag, buf->tmps.s))!=0 )
491 error("An error occurred while updating INFO/%s (errcode=%d)\n",buf->split.info_tag,ret);
492 }
493 }
494 static void _split_table_set_gt(abuf_t *buf)
495 {
496 int nsmpl = bcf_hdr_nsamples(buf->hdr);
497 if ( !nsmpl ) return;
498
499 bcf1_t *rec = buf->split.rec;
500 buf->ngt = bcf_get_genotypes(buf->hdr, rec, &buf->gt, &buf->mgt);
501 if ( buf->ngt<=0 ) return;
502 else
503 hts_expand(int32_t,buf->ngt,buf->mtmpi,buf->tmpi);
504
505 int iout,i,j;
506 for (iout=0; iout<buf->split.nout; iout++)
507 {
508 bcf1_t *out = buf->vcf[rbuf_kth(&buf->rbuf,iout)];
509 int star_allele = _has_star_allele(buf,iout);
510 int max_ploidy = buf->ngt/nsmpl;
511 int32_t *src = buf->gt, *dst = buf->tmpi;
512 for (i=0; i<nsmpl; i++)
513 {
514 for (j=0; j<max_ploidy; j++)
515 {
516 if ( src[j]==bcf_int32_vector_end || bcf_gt_is_missing(src[j]) )
517 {
518 dst[j] = src[j];
519 continue;
520 }
521 int iori = bcf_gt_allele(src[j]);
522 if ( iori<0 || iori>=rec->n_allele )
523 error("Out-of-bounds genotypes at %s:%"PRIhts_pos"\n",bcf_seqname(buf->hdr,rec),rec->pos+1);
524 int ial = _split_table_get_ial(buf,iout,iori);
525 if ( ial==2 && !star_allele )
526 {
527 dst[j] = bcf_gt_missing;
528 if ( bcf_gt_is_phased(src[j]) ) dst[j] |= 1;
529 }
530 else
531 dst[j] = bcf_gt_is_phased(src[j]) ? bcf_gt_phased(ial) : bcf_gt_unphased(ial);
532 }
533 src += max_ploidy;
534 dst += max_ploidy;
535 }
536 bcf_update_genotypes(buf->out_hdr,out,buf->tmpi,buf->ngt);
537 }
538 }
539 static void _split_table_set_format(abuf_t *buf, bcf_fmt_t *fmt, merge_rule_t mode)
540 {
541 int nsmpl = bcf_hdr_nsamples(buf->hdr);
542 if ( !nsmpl ) return;
543
544 const char *tag = bcf_hdr_int2id(buf->hdr,BCF_DT_ID,fmt->id);
545 if ( tag[0]=='G' && tag[1]=='T' && !tag[2] ) // FORMAT/GT
546 {
547 _split_table_set_gt(buf);
548 return;
549 }
550
551 int type = bcf_hdr_id2type(buf->hdr,BCF_HL_FMT,fmt->id);
552 int len = bcf_hdr_id2length(buf->hdr,BCF_HL_FMT,fmt->id);
553 if ( type==BCF_HT_STR && len==BCF_VL_G ) return; // possible todo: Number=G for strings
554 if ( type==BCF_HT_LONG ) return; // todo: 64bit integers
555
556 const int num_size = 4;
557 assert( num_size==sizeof(int32_t) && num_size==sizeof(float) );
558 int32_t missing = bcf_int32_missing;
559 void *missing_ptr = (void*)&missing;
560 if ( type==BCF_HT_REAL ) bcf_float_set_missing(*((float*)missing_ptr));
561 int32_t vector_end = bcf_int32_vector_end;
562 void *vector_end_ptr = (void*)&vector_end;
563 if ( type==BCF_HT_REAL ) bcf_float_set_vector_end(*((float*)vector_end_ptr));
564
565 bcf1_t *rec = buf->split.rec;
566 int mtmp = ( type==BCF_HT_INT || type==BCF_HT_REAL ) ? buf->mtmp/num_size : buf->mtmp; // number of items
567 int nval = bcf_get_format_values(buf->hdr,rec,tag,&buf->tmp,&mtmp,type);
568 if ( type==BCF_HT_INT || type==BCF_HT_REAL ) buf->mtmp = mtmp*num_size; // number of bytes
569
570 if ( type==BCF_HT_INT || type==BCF_HT_REAL )
571 {
572 if ( len==BCF_VL_G && nval!=nsmpl*rec->n_allele && nval!=nsmpl*rec->n_allele*(rec->n_allele+1)/2 ) return; // not haploid nor diploid
573
574 // Check for incorrect number of values. Note this check does not consider all values missing
575 // and will remove annotations that don't pass.
576 if ( (len==BCF_VL_A && nval != nsmpl*(rec->n_allele - 1)) || (len==BCF_VL_R && nval != nsmpl*rec->n_allele) ) return;
577 }
578
579 // Increase buffer size to accommodate star allele
580 int nval1 = nval / nsmpl;
581 mtmp = buf->mtmp;
582 if ( type==BCF_HT_INT || type==BCF_HT_REAL )
583 {
584 if ( (len==BCF_VL_A || len==BCF_VL_R) && mtmp < num_size*nsmpl*(nval1+1) ) mtmp = num_size*nsmpl*(nval1+1); // +1 for the possibility of the star allele
585 else if ( len==BCF_VL_G && mtmp < num_size*nsmpl*(nval1+3) ) mtmp = num_size*nsmpl*(nval1+3);
586 }
587 else if ( type==BCF_HT_STR )
588 {
589 if ( (len==BCF_VL_A || len==BCF_VL_R) && mtmp < nsmpl*(nval1+2) ) mtmp = nsmpl*(nval1+2); // +2 for the possibility of the star allele, ",."
590 else if ( len==BCF_VL_G && mtmp < nsmpl*(nval1+6) ) mtmp = nsmpl*(nval1+6);
591 }
592
593 if ( buf->mtmp2 < mtmp )
594 {
595 buf->tmp2 = realloc(buf->tmp2, mtmp);
596 if ( !buf->tmp2 ) error("Failed to alloc %d bytes\n", mtmp);
597 buf->mtmp2 = mtmp;
598 }
599
600 int iout, i, j;
601 for (iout=0; iout<buf->split.nout; iout++)
602 {
603 int star_allele = _has_star_allele(buf,iout);
604 bcf1_t *out = buf->vcf[rbuf_kth(&buf->rbuf,iout)];
605 int ret = 0;
606 if ( len==BCF_VL_FIXED || len==BCF_VL_VAR )
607 ret = bcf_update_format(buf->out_hdr, out, tag, buf->tmp, nval, type);
608 else if ( len==BCF_VL_A && type!=BCF_HT_STR )
609 {
610 int iori = buf->split.atoms[iout]->ial - 1;
611 assert( iori<nval );
612 for (i=0; i<nsmpl; i++)
613 {
614 void *src = buf->tmp + nval1*num_size*i;
615 void *dst = buf->tmp2 + num_size*i*(star_allele+1);
616 if ( !memcmp(vector_end_ptr,src+iori*num_size,num_size) )
617 memcpy(dst,missing_ptr,num_size);
618 else
619 memcpy(dst,src+iori*num_size,num_size);
620 if ( star_allele )
621 memcpy(dst+num_size,missing_ptr,num_size);
622 }
623 ret = bcf_update_format(buf->out_hdr, out, tag, buf->tmp2, nsmpl*(star_allele+1), type);
624 }
625 else if ( (len==BCF_VL_A || len==BCF_VL_R) && type==BCF_HT_STR )
626 {
627 int ioff = len==BCF_VL_R ? 1 : 0;
628 int iori = buf->split.atoms[iout]->ial - 1;
629 int nval1_dst = star_allele ? nval1 + 2 : nval1;
630 memset(buf->tmp2,0,nval1_dst*nsmpl);
631 for (i=0; i<nsmpl; i++)
632 {
633 kstring_t dst;
634 dst.l = 0; dst.m = nval1_dst; dst.s = (char*)buf->tmp2 + nval1_dst*i;
635 kputc_('.',&dst);
636 if ( star_allele ) kputsn_(",.",2,&dst);
637 if ( len==BCF_VL_R )
638 {
639 kputsn_(",.",2,&dst);
640 copy_string_field(buf->tmp+nval1*i, 0, nval1, &dst, 0);
641 }
642 copy_string_field(buf->tmp+nval1*i, iori+ioff, nval1, &dst, 0+ioff);
643 if ( star_allele ) copy_string_field(".", 0, 1, &dst, 1+ioff);
644 }
645 ret = bcf_update_format(buf->out_hdr, out, tag, buf->tmp2, nval1_dst*nsmpl, type);
646 }
647 else if ( len==BCF_VL_R && type!=BCF_HT_STR )
648 {
649 int iori = buf->split.atoms[iout]->ial;
650 assert( iori<=nval );
651 for (i=0; i<nsmpl; i++)
652 {
653 void *src = buf->tmp + nval1*num_size*i;
654 void *dst = buf->tmp2 + num_size*i*(star_allele+2);
655 memcpy(dst,src,num_size);
656 memcpy(dst+num_size,src+iori*num_size,num_size);
657 if ( type==BCF_HT_INT && mode==M_SUM )
658 {
659 uint8_t *tbl = buf->split.tbl + iout*buf->split.nori;
660 for (j=iori; j<buf->split.nori; j++)
661 if ( tbl[j]==1 ) ((int32_t*)dst)[1] += ((int32_t*)src)[j+1];
662 }
663 if ( star_allele )
664 memcpy(dst+num_size*2,missing_ptr,num_size);
665 }
666 ret = bcf_update_format(buf->out_hdr, out, tag, buf->tmp2, nsmpl*(star_allele+2), type);
667 }
668 else if ( len==BCF_VL_G && type!=BCF_HT_STR )
669 {
670 int iori = buf->split.atoms[iout]->ial;
671 int i01 = bcf_alleles2gt(0,iori);
672 int i11 = bcf_alleles2gt(iori,iori);
673 assert( iori<nval );
674 #define BRANCH(type_t, is_missing, is_vector_end, set_missing, set_vector_end) { \
675 for (i=0; i<nsmpl; i++) \
676 { \
677 type_t *src = (type_t*)buf->tmp + i*nval1; \
678 type_t *dst = (type_t*)buf->tmp2 + i*3*(1+star_allele); \
679 int n=0; /* determine ploidy of this genotype */ \
680 while ( n<nval1 && !(is_vector_end) ) { n++; src++; } \
681 src = (type_t*)buf->tmp + i*nval1; \
682 memcpy(dst++,src,sizeof(type)); \
683 int nmiss = 0, nend = 0; \
684 if ( n==rec->n_allele ) /* haploid */ \
685 { \
686 memcpy(dst++,src+iori,sizeof(type)); \
687 if ( star_allele ) { nmiss = 1; nend = 3; } \
688 else nend = 1; \
689 } \
690 else if ( n==nval1 ) \
691 { \
692 memcpy(dst++,src+i01,sizeof(type)); \
693 memcpy(dst++,src+i11,sizeof(type)); \
694 if ( star_allele ) nmiss = 3; \
695 } \
696 else if ( n==1 && is_missing ) \
697 { \
698 if ( star_allele ) nend = 5; \
699 else nend = 2; \
700 } \
701 else \
702 error("Incorrect number of values at %s:%"PRIhts_pos" .. tag=FORMAT/%s Number=G nAlleles=%d nValues=%d, %d-th sample\n", \
703 bcf_seqname(buf->hdr,rec),rec->pos+1,tag,rec->n_allele,n,i+1); \
704 for (j=0; j<nmiss; j++) { set_missing; dst++; } \
705 for (j=0; j<nend; j++) { set_vector_end; dst++; } \
706 } \
707 }
708 switch (type)
709 {
710 case BCF_HT_INT: BRANCH(int32_t, *src==bcf_int32_missing, *src==bcf_int32_vector_end, *dst=bcf_int32_missing, *dst=bcf_int32_vector_end); break;
711 case BCF_HT_REAL: BRANCH(float, bcf_float_is_missing(*src), bcf_float_is_vector_end(*src), bcf_float_set_missing(*dst), bcf_float_set_vector_end(*dst)); break;
712 default: error("Unexpected case: %d\n", type);
713 }
714 #undef BRANCH
715 ret = bcf_update_format(buf->out_hdr, out, tag, buf->tmp2, 3*(1+star_allele)*nsmpl, type);
716 }
717 if ( ret!=0 ) error("An error occurred while updating FORMAT/%s (errcode=%d)\n",tag,ret);
718 }
719 }
720 static inline int _is_acgtn(char *seq)
721 {
722 while ( *seq )
723 {
724 char c = toupper(*seq);
725 if ( c!='A' && c!='C' && c!='G' && c!='T' && c!='N' ) return 0;
726 seq++;
727 }
728 return 1;
729 }
730 /*
731 The atomization works as follows:
732 - Atomize each alternate allele separately by leaving out sequence identical to the reference. No
733 alignment is performed, just greedy trimming of the end, then from left. This operation returns
734 a list of atoms (atom_t) which carry fragments of REF,ALT and their positions as 0-based offsets
735 to the original REF allele
736 - Sort atoms by POS, REF and ALT. Each unique atom (POS+REF+ALT) forms a new VCF record, each
737 with a single ALT.
738 - For each new VCF record determine how to translate the original allele index (iori) to this new
739 record:
740 - 1: the original allele matches the atom
741 - 0: the original allele does not overlap this atom or the overlapping part matches the REF
742 allele
743 - 2 (or equivalently "."): there is a mismatch between the original allele and the atom
744 The mapping is encoded in a table with columns corresponding to the original ALTs and rows
745 to the new POS+ALTs (atoms). The table is initialized to 0, then we set 1's for matching
746 atoms and 2's for overlapping mismatching atoms.
747
748 Note that different ALT alleles can result in the same atom (the same output line) and this code
749 does not know how to reconcile possibly conflicting VCF annotations. This could be improved
750 and merge logic provided, similarly to `merge -l`. For example, the allelic depths (AD) should
751 be summed for the same atomized output allele. However, this level of complexity is not addressed
752 in this initial draft. Higher priority for now is to provide the inverse "join" operation.
753
754 Update 2021-04-09:
755 Tags QS,AD are now automatically incremented as they should be, for both INFO and FORMAT.
756 Note that the code will fail on missing values (todo) and it needs to be generalized and
757 made customizable.
758 */
759 void _abuf_split(abuf_t *buf, bcf1_t *rec)
760 {
761 int i,j;
762 if ( rec->n_allele < 2 )
763 {
764 rbuf_expand0(&buf->rbuf, bcf1_t*, buf->rbuf.n+1, buf->vcf);
765 int j = rbuf_append(&buf->rbuf);
766 if ( buf->vcf[j] ) bcf_destroy(buf->vcf[j]);
767 buf->vcf[j] = bcf_dup(rec);
768 return;
769 }
770 for (i=0; i<rec->n_allele; i++)
771 {
772 if ( _is_acgtn(rec->d.allele[i]) ) continue;
773 rbuf_expand0(&buf->rbuf, bcf1_t*, buf->rbuf.n+1, buf->vcf);
774 int j = rbuf_append(&buf->rbuf);
775 if ( buf->vcf[j] ) bcf_destroy(buf->vcf[j]);
776 buf->vcf[j] = bcf_dup(rec);
777 return;
778 }
779
780 buf->natoms = 0;
781 for (i=1; i<rec->n_allele; i++) _atomize_allele(buf,rec,i);
782 qsort(buf->atoms,buf->natoms,sizeof(*buf->atoms),_cmp_atoms);
783 _split_table_init(buf,rec,buf->natoms);
784 for (i=0; i<buf->natoms; i++)
785 {
786 if ( i && _atoms_inconsistent(&buf->atoms[i-1],&buf->atoms[i])==0 ) continue;
787 _split_table_new(buf, &buf->atoms[i]); // add a new unique output atom
788 }
789 for (i=0; i<buf->natoms; i++)
790 {
791 // Looping over sorted list of all atoms with possible duplicates from different source ALT alleles
792 atom_t *atom = &buf->atoms[i];
793 for (j=0; j<buf->split.nout; j++)
794 {
795 atom_t *out = buf->split.atoms[j];
796 if ( atom == out ) continue; // table already set to 1
797 if ( atom->beg > out->end ) continue; // cannot overlap this output atom
798 if ( atom->end < out->beg ) break; // this atom is ahead of all subsequent output records
799 _split_table_overlap(buf, j, atom);
800 }
801 }
802 // _split_table_print(buf);
803 // _split_table_print_atoms(buf);
804 assert( !buf->rbuf.n ); // all records should be flushed first in the SPLIT mode
805
806 // Create the output records, transferring all annotations:
807 // CHROM-QUAL
808 _split_table_set_chrom_qual(buf);
809
810 // INFO
811 for (i=0; i<rec->n_info; i++)
812 {
813 // this implementation of merging rules is temporary: generalize and made customizable through the API
814 merge_rule_t mode = M_FIRST;
815 const char *tag = bcf_hdr_int2id(buf->hdr,BCF_DT_ID,rec->d.info[i].key);
816 if ( !strcmp(tag,"QS") || !strcmp(tag,"AD") ) mode = M_SUM;
817
818 _split_table_set_info(buf, &rec->d.info[i], mode);
819 }
820
821 // Set INFO tag showing the original record
822 if ( buf->split.info_tag )
823 _split_table_set_history(buf);
824
825 // FORMAT
826 for (i=0; i<rec->n_fmt; i++)
827 {
828 // this implementation of merging rules is temporary: generalize and made customizable through the API
829 merge_rule_t mode = M_FIRST;
830 const char *tag = bcf_hdr_int2id(buf->hdr,BCF_DT_ID,rec->d.fmt[i].id);
831 if ( !strcmp(tag,"QS") || !strcmp(tag,"AD") ) mode = M_SUM;
832
833 _split_table_set_format(buf, &rec->d.fmt[i], mode);
834 }
835
836 // Check that at least one FORMAT field was added, if not, the number of samples must be set manually
837 for (i=0; i<buf->split.nout; i++)
838 {
839 bcf1_t *out = buf->vcf[rbuf_kth(&buf->rbuf,i)];
840 if ( !out->n_sample ) out->n_sample = rec->n_sample;
841 }
842 }
843
844 void abuf_push(abuf_t *buf, bcf1_t *rec)
845 {
846 bcf_unpack(rec, BCF_UN_ALL);
847 if ( buf->mode==SPLIT ) _abuf_split(buf,rec);
848 }
849
850 bcf1_t *abuf_flush(abuf_t *buf, int flush_all)
851 {
852 int i;
853
854 if ( buf->rbuf.n==0 ) return NULL;
855 if ( flush_all ) goto ret;
856
857 ret:
858 i = rbuf_shift(&buf->rbuf);
859 return buf->vcf[i];
860 }
861