Debian Codegraph @

bcftools/abuf.c.pysam.c

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