Debian Codegraph @

bcftools/mcall.c.pysam.c

raw symbols SCIP
1 #include "bcftools.pysam.h"
2
3 /* mcall.c -- multiallelic and rare variant calling.
4
5 Copyright (C) 2012-2022 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 #include <assert.h>
28 #include <math.h>
29 #include <inttypes.h>
30 #include <ctype.h>
31 #include <htslib/kfunc.h>
32 #include <htslib/khash_str2int.h>
33 #include "call.h"
34 #include "prob1.h"
35
36 // Using priors for GTs does not seem to be mathematically justified. Although
37 // it seems effective in removing false calls, it also flips a significant
38 // proportion of HET genotypes. Better is to filter by FORMAT/GQ using
39 // `bcftools filter`.
40 #define USE_PRIOR_FOR_GTS 0
41
42 // Go with uniform PLs for samples with no coverage. If unset, missing
43 // genotypes is reported instead.
44 #define FLAT_PDG_FOR_MISSING 0
45
46 int test16(float *anno16, anno16_t *a);
47
48 void qcall_init(call_t *call) { return; }
49 void qcall_destroy(call_t *call) { return; }
50 int qcall(call_t *call, bcf1_t *rec)
51 {
52 // QCall format:
53 // chromosome, position, reference allele, depth, mapping quality, 0, ..
54 error("TODO: qcall output\n");
55 return 0;
56 }
57
58 void call_init_pl2p(call_t *call)
59 {
60 int i;
61 for (i=0; i<256; i++)
62 call->pl2p[i] = pow(10., -i/10.);
63 }
64
65 // Macros for accessing call->trio and call->ntrio
66 #define FTYPE_222 0 // family type: all diploid
67 #define FTYPE_121 1 // chrX, the child is a boy
68 #define FTYPE_122 2 // chrX, a girl
69 #define FTYPE_101 3 // chrY, boy
70 #define FTYPE_100 4 // chrY, girl
71
72 #define GT_SKIP 0xf // empty genotype (chrY in females)
73
74 #define IS_POW2(x) (!((x) & ((x) - 1))) // zero is permitted
75 #define IS_HOM(x) IS_POW2(x)
76
77 // Pkij = P(k|i,j) tells how likely it is to be a het if the parents
78 // are homs etc. The consistency of i,j,k has been already checked.
79 // Parameters are alleles and ploidy of father, mother, kid
80 // Returns 2/Pkij.
81 int calc_Pkij(int fals, int mals, int kals, int fpl, int mpl, int kpl)
82 {
83 int als = fals|mals|kals;
84 if ( IS_HOM(als) ) return 2; // all are the same: child must be a HOM, P=1
85
86 if ( fpl==1 )
87 {
88 if ( kpl==1 ) // chr X, the child is a boy, the copy is inherited from the mother
89 {
90 if ( IS_HOM(mals) ) return 2; // 0 11 -> P(1) = 1
91 return 4; // 0 01 -> P(0) = P(1) = 1/2
92 }
93 // chr X, the child is a girl
94 if ( IS_HOM(mals) ) return 2; // 0 11 -> P(01) = 1
95 return 4; // 0 01 -> P(00) = P(01) = 1/2
96 }
97
98 if ( IS_HOM(fals) && IS_HOM(mals) ) return 2; // 00 11 01, the child must be a HET, P=1
99 if ( !IS_HOM(fals) && !IS_HOM(mals) )
100 {
101 if ( IS_HOM(kals) ) return 8; // 01 01 00 or 01 01 11, P(k=HOM) = 1/4
102 return 4; // 01 01 01, P(k=HET) = 1/2
103 }
104 return 4; // 00 01, P(k=HET) = P(k=HOM) = 1/2
105 }
106
107 // Initialize ntrio and trio: ntrio lists the number of possible
108 // genotypes given combination of haploid/diploid genomes and the
109 // number of alleles. trio lists allowed genotype combinations:
110 // 4bit: 2/Pkij, 4: father, 4: mother, 4: child
111 // See also mcall_call_trio_genotypes()
112 //
113 static void mcall_init_trios(call_t *call)
114 {
115 if ( call->prior_AN )
116 {
117 int id = bcf_hdr_id2int(call->hdr,BCF_DT_ID,call->prior_AN);
118 if ( id==-1 ) error("No such tag \"%s\"\n", call->prior_AN);
119 if ( !bcf_hdr_idinfo_exists(call->hdr,BCF_HL_FMT,id) ) error("No such FORMAT tag \"%s\"\n", call->prior_AN);
120 id = bcf_hdr_id2int(call->hdr,BCF_DT_ID,call->prior_AC);
121 if ( id==-1 ) error("No such tag \"%s\"\n", call->prior_AC);
122 if ( !bcf_hdr_idinfo_exists(call->hdr,BCF_HL_FMT,id) ) error("No such FORMAT tag \"%s\"\n", call->prior_AC);
123 }
124
125 // 23, 138, 478 possible diploid trio genotypes with 2, 3, 4 alleles
126 call->ntrio[FTYPE_222][2] = 15; call->ntrio[FTYPE_222][3] = 78; call->ntrio[FTYPE_222][4] = 250;
127 call->ntrio[FTYPE_121][2] = 8; call->ntrio[FTYPE_121][3] = 27; call->ntrio[FTYPE_121][4] = 64;
128 call->ntrio[FTYPE_122][2] = 8; call->ntrio[FTYPE_122][3] = 27; call->ntrio[FTYPE_122][4] = 64;
129 call->ntrio[FTYPE_101][2] = 2; call->ntrio[FTYPE_101][3] = 3; call->ntrio[FTYPE_101][4] = 4;
130 call->ntrio[FTYPE_100][2] = 2; call->ntrio[FTYPE_100][3] = 3; call->ntrio[FTYPE_100][4] = 4;
131
132 int nals, itype;
133 for (itype=0; itype<=4; itype++)
134 {
135 for (nals=2; nals<=4; nals++)
136 call->trio[itype][nals] = (uint16_t*) malloc(sizeof(uint16_t)*call->ntrio[itype][nals]);
137 }
138
139 // max 10 possible diploid genotypes
140 int gts[10];
141 for (nals=2; nals<=4; nals++)
142 {
143 int i,j,k, n = 0, ngts = 0;
144 for (i=0; i<nals; i++)
145 for (j=0; j<=i; j++)
146 gts[ngts++] = 1<<i | 1<<j;
147
148 // 222: all diploid
149 // i,j,k: father, mother, child
150 for (i=0; i<ngts; i++)
151 for (j=0; j<ngts; j++)
152 for (k=0; k<ngts; k++)
153 {
154 if ( ((gts[i]|gts[j])&gts[k]) != gts[k] ) continue; // k not present in neither i nor j
155 if ( !(gts[i] & gts[k]) || !(gts[j] & gts[k]) ) continue; // one copy from father, one from mother
156 int Pkij = calc_Pkij(gts[i],gts[j],gts[k], 2,2,2);
157 call->trio[FTYPE_222][nals][n++] = Pkij<<12 | i<<8 | j<<4 | k; // father, mother, child
158 }
159 assert( n==call->ntrio[FTYPE_222][nals] );
160
161 // 121: chrX, boy
162 n = 0;
163 for (i=0; i<ngts; i++)
164 for (j=0; j<ngts; j++)
165 for (k=0; k<ngts; k++)
166 {
167 if ( !IS_HOM(gts[i]) || !IS_HOM(gts[k]) ) continue; // father nor boy can be diploid
168 if ( ((gts[i]|gts[j])&gts[k]) != gts[k] ) continue;
169 if ( !(gts[j] & gts[k]) ) continue; // boy must inherit the copy from mother
170 int Pkij = calc_Pkij(gts[i],gts[j],gts[k], 1,2,1);
171 call->trio[FTYPE_121][nals][n++] = Pkij<<12 | i<<8 | j<<4 | k;
172 }
173 assert( n==call->ntrio[FTYPE_121][nals] );
174
175 // 122: chrX, girl
176 n = 0;
177 for (i=0; i<ngts; i++)
178 for (j=0; j<ngts; j++)
179 for (k=0; k<ngts; k++)
180 {
181 if ( !IS_HOM(gts[i]) ) continue;
182 if ( ((gts[i]|gts[j])&gts[k]) != gts[k] ) continue;
183 if ( !(gts[i] & gts[k]) ) continue; // girl must inherit one copy from the father and one from the mother
184 if ( !(gts[j] & gts[k]) ) continue;
185 int Pkij = calc_Pkij(gts[i],gts[j],gts[k], 1,2,2);
186 call->trio[FTYPE_122][nals][n++] = Pkij<<12 | i<<8 | j<<4 | k;
187 }
188 assert( n==call->ntrio[FTYPE_122][nals] );
189
190 // 101: chrY, boy
191 n = 0;
192 for (i=0; i<ngts; i++)
193 for (k=0; k<ngts; k++)
194 {
195 if ( !IS_HOM(gts[i]) || !IS_HOM(gts[k]) ) continue;
196 if ( (gts[i]&gts[k]) != gts[k] ) continue;
197 call->trio[FTYPE_101][nals][n++] = 1<<12 | i<<8 | GT_SKIP<<4 | k;
198 }
199 assert( n==call->ntrio[FTYPE_101][nals] );
200
201 // 100: chrY, girl
202 n = 0;
203 for (i=0; i<ngts; i++)
204 {
205 if ( !IS_POW2(gts[i]) ) continue;
206 call->trio[FTYPE_100][nals][n++] = 1<<12 | i<<8 | GT_SKIP<<4 | GT_SKIP;
207 }
208 assert( n==call->ntrio[FTYPE_100][nals] );
209
210 }
211 call->GLs = (double*) calloc(bcf_hdr_nsamples(call->hdr)*10,sizeof(double));
212
213 int i, j;
214 for (i=0; i<call->nfams; i++)
215 {
216 family_t *fam = &call->fams[i];
217 int ploidy[3];
218 for (j=0; j<3; j++)
219 ploidy[j] = call->ploidy[fam->sample[j]];
220
221 if ( ploidy[FATHER]==2 ) // not X, not Y
222 {
223 if ( ploidy[MOTHER]!=2 || ploidy[CHILD]!=2 )
224 error("Incorrect ploidy: %d %d %d\n", ploidy[FATHER],ploidy[MOTHER],ploidy[CHILD]);
225 fam->type = FTYPE_222;
226 continue;
227 }
228 if ( ploidy[FATHER]!=1 || ploidy[MOTHER]==1 )
229 error("Incorrect ploidy: %d %d %d\n", ploidy[FATHER],ploidy[MOTHER],ploidy[CHILD]);
230 if ( ploidy[MOTHER]==2 ) // X
231 {
232 if ( ploidy[CHILD]==0 )
233 error("Incorrect ploidy: %d %d %d\n", ploidy[FATHER],ploidy[MOTHER],ploidy[CHILD]);
234 fam->type = ploidy[CHILD]==2 ? FTYPE_122 : FTYPE_121; // a girl or a boy
235 }
236 else // Y
237 {
238 if ( ploidy[CHILD]==2 )
239 error("Incorrect ploidy: %d %d %d\n", ploidy[FATHER],ploidy[MOTHER],ploidy[CHILD]);
240 fam->type = ploidy[CHILD]==0 ? FTYPE_100 : FTYPE_101; // a girl or a boy
241 }
242 }
243 }
244 static void mcall_destroy_trios(call_t *call)
245 {
246 int i, j;
247 for (i=2; i<=4; i++)
248 for (j=0; j<=4; j++)
249 free(call->trio[j][i]);
250 }
251
252 static void init_sample_groups(call_t *call)
253 {
254 int i, nsmpl = bcf_hdr_nsamples(call->hdr);
255 if ( !call->sample_groups )
256 {
257 // standard pooled calling, all samples in the same group
258 call->nsmpl_grp = 1;
259 call->smpl_grp = (smpl_grp_t*)calloc(1,sizeof(*call->smpl_grp));
260 call->smpl_grp[0].nsmpl = nsmpl;
261 call->smpl_grp[0].smpl = (uint32_t*)calloc(call->smpl_grp[0].nsmpl,sizeof(uint32_t));
262 for (i=0; i<nsmpl; i++)
263 call->smpl_grp[0].smpl[i] = i;
264 return;
265 }
266
267 if ( call->sample_groups_tag )
268 {
269 // Is the tag defined in the header?
270 int tag_id = bcf_hdr_id2int(call->hdr,BCF_DT_ID,call->sample_groups_tag);
271 if ( tag_id==-1 ) error("No such tag \"%s\"\n",call->sample_groups_tag);
272 if ( !bcf_hdr_idinfo_exists(call->hdr,BCF_HL_FMT,tag_id) ) error("No such FORMAT tag \"%s\"\n", call->sample_groups_tag);
273 }
274 else
275 {
276 int tag_id = bcf_hdr_id2int(call->hdr,BCF_DT_ID,"QS");
277 if ( tag_id >= 0 && bcf_hdr_idinfo_exists(call->hdr,BCF_HL_FMT,tag_id) ) call->sample_groups_tag = "QS";
278 else
279 {
280 tag_id = bcf_hdr_id2int(call->hdr,BCF_DT_ID,"AD");
281 if ( tag_id >= 0 && bcf_hdr_idinfo_exists(call->hdr,BCF_HL_FMT,tag_id) ) call->sample_groups_tag = "AD";
282 else error("Error: neither \"AD\" nor \"QS\" FORMAT tag exists and no alternative given with -G\n");
283 }
284 }
285
286 // Read samples/groups
287 if ( !strcmp("-",call->sample_groups) )
288 {
289 // single-sample calling, each sample creates its own group
290 call->nsmpl_grp = nsmpl;
291 call->smpl_grp = (smpl_grp_t*)calloc(nsmpl,sizeof(*call->smpl_grp));
292 for (i=0; i<nsmpl; i++)
293 {
294 call->smpl_grp[i].nsmpl = 1;
295 call->smpl_grp[i].smpl = (uint32_t*)calloc(call->smpl_grp[i].nsmpl,sizeof(uint32_t));
296 call->smpl_grp[i].smpl[0] = i;
297 }
298 }
299 else
300 {
301 int nlines;
302 char **lines = hts_readlist(call->sample_groups, 1, &nlines);
303 if ( !lines ) error("Could not read the file: %s\n", call->sample_groups);
304
305 uint32_t *smpl2grp = (uint32_t*)calloc(nsmpl,sizeof(uint32_t));
306 uint32_t *grp2n = (uint32_t*)calloc(nsmpl,sizeof(uint32_t));
307 void *grp2idx = khash_str2int_init();
308
309 call->nsmpl_grp = 0;
310 for (i=0; i<nlines; i++)
311 {
312 char *ptr = lines[i];
313 while ( *ptr && !isspace(*ptr) ) ptr++;
314 if ( !*ptr ) error("Could not parse the line in %s, expected a sample name followed by tab and a population name: %s\n",call->sample_groups,lines[i]);
315 char *tmp = ptr;
316 while ( *ptr && isspace(*ptr) ) ptr++;
317 if ( !*ptr ) error("Could not parse the line in %s, expected a sample name followed by tab and a population name: %s\n",call->sample_groups,lines[i]);
318 *tmp = 0;
319 int ismpl = bcf_hdr_id2int(call->hdr, BCF_DT_SAMPLE, lines[i]);
320 if ( ismpl<0 ) continue;
321 if ( smpl2grp[ismpl] ) error("Error: the sample \"%s\" is listed twice in %s\n", lines[i],call->sample_groups);
322 if ( !khash_str2int_has_key(grp2idx,ptr+1) )
323 {
324 khash_str2int_set(grp2idx, ptr+1, call->nsmpl_grp);
325 call->nsmpl_grp++;
326 }
327 int igrp = -1;
328 if ( khash_str2int_get(grp2idx, ptr+1, &igrp)!=0 )
329 error("This should not happen, fixme: %s\n",ptr+1);
330 grp2n[igrp]++;
331 smpl2grp[ismpl] = igrp+1; // +1 to distinguish unlisted samples
332 }
333 khash_str2int_destroy(grp2idx);
334 if ( !call->nsmpl_grp ) error("Could not parse the file, no matching samples found: %s\n", call->sample_groups);
335
336 call->smpl_grp = (smpl_grp_t*)calloc(call->nsmpl_grp,sizeof(*call->smpl_grp));
337 for (i=0; i<nsmpl; i++)
338 {
339 if ( !smpl2grp[i] ) error("Error: The sample \"%s\" is not listed in %s\n",call->hdr->samples[i],call->sample_groups);
340 int igrp = smpl2grp[i] - 1;
341 if ( !call->smpl_grp[igrp].nsmpl )
342 call->smpl_grp[igrp].smpl = (uint32_t*)calloc(grp2n[igrp],sizeof(uint32_t));
343 call->smpl_grp[igrp].smpl[call->smpl_grp[igrp].nsmpl] = i;
344 call->smpl_grp[igrp].nsmpl++;
345 }
346 free(smpl2grp);
347 free(grp2n);
348 for (i=0; i<nlines; i++) free(lines[i]);
349 free(lines);
350 }
351 }
352 static void destroy_sample_groups(call_t *call)
353 {
354 int i;
355 for (i=0; i<call->nsmpl_grp; i++)
356 {
357 free(call->smpl_grp[i].qsum);
358 free(call->smpl_grp[i].smpl);
359 }
360 free(call->smpl_grp);
361 }
362
363 void mcall_init(call_t *call)
364 {
365 init_sample_groups(call);
366 call_init_pl2p(call);
367
368 call->nals_map = 5;
369 call->als_map = (int*) malloc(sizeof(int)*call->nals_map);
370 call->npl_map = 5*(5+1)/2; // will be expanded later if necessary
371 call->pl_map = (int*) malloc(sizeof(int)*call->npl_map);
372 call->gts = (int32_t*) calloc(bcf_hdr_nsamples(call->hdr)*2,sizeof(int32_t)); // assuming at most diploid everywhere
373
374 if ( call->flag & CALL_CONSTR_TRIO )
375 {
376 call->cgts = (int32_t*) calloc(bcf_hdr_nsamples(call->hdr),sizeof(int32_t));
377 call->ugts = (int32_t*) calloc(bcf_hdr_nsamples(call->hdr),sizeof(int32_t));
378 mcall_init_trios(call);
379 bcf_hdr_append(call->hdr,"##FORMAT=<ID=CGT,Number=1,Type=Integer,Description=\"Constrained Genotype (0-based index to Number=G ordering).\">");
380 bcf_hdr_append(call->hdr,"##FORMAT=<ID=UGT,Number=1,Type=Integer,Description=\"Unconstrained Genotype (0-based index to Number=G ordering).\">");
381 }
382 if ( call->flag & CALL_CONSTR_ALLELES ) call->vcmp = vcmp_init();
383
384 bcf_hdr_append(call->hdr,"##FORMAT=<ID=GT,Number=1,Type=String,Description=\"Genotype\">");
385 if ( call->output_tags & CALL_FMT_GQ )
386 bcf_hdr_append(call->hdr,"##FORMAT=<ID=GQ,Number=1,Type=Integer,Description=\"Phred-scaled Genotype Quality\">");
387 if ( call->output_tags & CALL_FMT_GP )
388 bcf_hdr_append(call->hdr,"##FORMAT=<ID=GP,Number=G,Type=Float,Description=\"Genotype posterior probabilities in the range 0 to 1\">");
389 if ( call->output_tags & (CALL_FMT_GQ|CALL_FMT_GP) )
390 call->GQs = (int32_t*) malloc(sizeof(int32_t)*bcf_hdr_nsamples(call->hdr));
391 bcf_hdr_append(call->hdr,"##INFO=<ID=AC,Number=A,Type=Integer,Description=\"Allele count in genotypes for each ALT allele, in the same order as listed\">");
392 bcf_hdr_append(call->hdr,"##INFO=<ID=AN,Number=1,Type=Integer,Description=\"Total number of alleles in called genotypes\">");
393 bcf_hdr_append(call->hdr,"##INFO=<ID=DP4,Number=4,Type=Integer,Description=\"Number of high-quality ref-forward , ref-reverse, alt-forward and alt-reverse bases\">");
394 bcf_hdr_append(call->hdr,"##INFO=<ID=MQ,Number=1,Type=Integer,Description=\"Average mapping quality\">");
395 if ( call->output_tags & CALL_FMT_PV4 )
396 bcf_hdr_append(call->hdr,"##INFO=<ID=PV4,Number=4,Type=Float,Description=\"P-values for strand bias, baseQ bias, mapQ bias and tail distance bias\">\n");
397
398 // init the prior
399 if ( call->theta>0 )
400 {
401 int i, n = 0;
402 if ( !call->ploidy ) n = 2*bcf_hdr_nsamples(call->hdr); // all are diploid
403 else
404 {
405 for (i=0; i<bcf_hdr_nsamples(call->hdr); i++)
406 n += call->ploidy[i];
407 }
408 // Watterson factor, here aM_1 = aM_2 = 1
409 double aM = 1;
410 for (i=2; i<n; i++) aM += 1./i;
411 call->theta *= aM;
412 if ( call->theta >= 1 )
413 {
414 fprintf(bcftools_stderr,"The prior is too big (theta*aM=%.2f), going with 0.99\n", call->theta);
415 call->theta = 0.99;
416 }
417 call->theta = log(call->theta);
418 }
419 }
420
421 void mcall_destroy(call_t *call)
422 {
423 destroy_sample_groups(call);
424 if (call->vcmp) vcmp_destroy(call->vcmp);
425 free(call->itmp);
426 mcall_destroy_trios(call);
427 free(call->GPs);
428 free(call->ADs);
429 free(call->GLs);
430 free(call->GQs);
431 free(call->anno16);
432 free(call->PLs);
433 free(call->als_map);
434 free(call->pl_map);
435 free(call->gts); free(call->cgts); free(call->ugts);
436 free(call->pdg);
437 free(call->als);
438 free(call->ac);
439 return;
440 }
441
442
443 // Inits P(D|G): convert PLs from log space and normalize. In case of zero
444 // depth, missing PLs are all zero. In this case, pdg's are set to 0
445 // so that the corresponding genotypes can be set as missing and the
446 // qual calculation is not affected.
447 // Missing values are replaced by generic likelihoods when X (unseen allele) is
448 // present.
449 // NB: While the -m calling model uses the pdgs in canonical order,
450 // the original samtools -c calling code uses pdgs in reverse order (AA comes
451 // first, RR last).
452 // NB: Ploidy is not taken into account here, which is incorrect.
453 void set_pdg(double *pl2p, int *PLs, double *pdg, int n_smpl, int n_gt, int unseen)
454 {
455 int i, j, nals;
456
457 // find out the number of alleles, expecting diploid genotype likelihoods
458 bcf_gt2alleles(n_gt-1, &i, &nals);
459 assert( i==nals );
460 nals++;
461
462 for (i=0; i<n_smpl; i++)
463 {
464 double sum = 0;
465 for (j=0; j<n_gt; j++)
466 {
467 if ( PLs[j]==bcf_int32_vector_end )
468 {
469 // We expect diploid genotype likelihoods. If not diploid, treat as missing
470 j = 0;
471 break;
472 }
473 if ( PLs[j]==bcf_int32_missing ) break;
474 pdg[j] = PLs[j] < 256 ? pl2p[PLs[j]] : pow(10., -PLs[j]/10.);
475 sum += pdg[j];
476 }
477
478 if ( j==0 )
479 {
480 // First value is missing (LK of RR), this indicates that
481 // all values are missing.
482 j = sum = n_gt;
483 }
484 else if ( j<n_gt && unseen<0 )
485 {
486 // Some of the values are missing and the unseen allele LK is not
487 // available. In such a case, we set LK to a very small value.
488 sum = 0;
489 for (j=0; j<n_gt; j++)
490 {
491 assert( PLs[j]!=bcf_int32_vector_end );
492 if ( PLs[j]==bcf_int32_missing ) PLs[j] = 255;
493 pdg[j] = PLs[j] < 256 ? pl2p[PLs[j]] : pow(10., -PLs[j]/10.);
494 sum += pdg[j];
495 }
496 }
497 if ( j<n_gt )
498 {
499 // Missing values present, fill with unseen allele LK. This can be only
500 // as good as the merge was.
501 int ia,ib, k;
502 j = 0;
503 sum = 0;
504 for (ia=0; ia<nals; ia++)
505 {
506 for (ib=0; ib<=ia; ib++)
507 {
508 if ( PLs[j]==bcf_int32_missing )
509 {
510 k = bcf_alleles2gt(ia,unseen);
511 if ( PLs[k]==bcf_int32_missing ) k = bcf_alleles2gt(ib,unseen);
512 if ( PLs[k]==bcf_int32_missing ) k = bcf_alleles2gt(unseen,unseen);
513 if ( PLs[k]==bcf_int32_missing )
514 {
515 // The PLs for unseen allele X are not present as well as for ia, ib.
516 // This can happen with incremental calling, when one of the merged
517 // files had all alleles A,C,G,T, in such a case, X was not present.
518 // Use a very small value instead.
519 PLs[j] = 255;
520 }
521 else
522 PLs[j] = PLs[k];
523 }
524 pdg[j] = pl2p[ PLs[j] ];
525 sum += pdg[j];
526 j++;
527 }
528 }
529 }
530 // Normalize: sum_i pdg_i = 1
531 if ( sum==n_gt )
532 {
533 // all missing
534 #if FLAT_PDG_FOR_MISSING
535 for (j=0; j<n_gt; j++) pdg[j] = 1./n_gt;
536 #else
537 for (j=0; j<n_gt; j++) pdg[j] = 0;
538 #endif
539 }
540 else
541 for (j=0; j<n_gt; j++) pdg[j] /= sum;
542
543 PLs += n_gt;
544 pdg += n_gt;
545 }
546 }
547
548 // Create mapping between old and new (trimmed) alleles
549 void init_allele_trimming_maps(call_t *call, int nals_ori, int als_out)
550 {
551 int i, j, nout = 0;
552
553 // als_map: old(i) -> new(j)
554 for (i=0; i<nals_ori; i++)
555 {
556 if ( als_out & (1<<i) ) call->als_map[i] = nout++;
557 else call->als_map[i] = -1;
558 }
559
560 if ( !call->pl_map ) return;
561
562 // pl_map: new(k) -> old(l)
563 int k = 0, l = 0;
564 for (i=0; i<nals_ori; i++)
565 {
566 for (j=0; j<=i; j++)
567 {
568 if ( (als_out & (1<<i)) && (als_out & (1<<j)) ) call->pl_map[k++] = l;
569 l++;
570 }
571 }
572 }
573
574 /** log(exp(a)+exp(b)) */
575 static inline double logsumexp2(double a, double b)
576 {
577 if ( a>b )
578 return log(1 + exp(b-a)) + a;
579 else
580 return log(1 + exp(a-b)) + b;
581 }
582
583 // Macro to set the most likely alleles
584 #define UPDATE_MAX_LKs(als,sum) { \
585 if ( max_lk<lk_tot && lk_tot_set ) { max_lk = lk_tot; max_als = (als); } \
586 if ( sum ) lk_sum = logsumexp2(lk_tot,lk_sum); \
587 }
588
589 #define SWAP(type_t,x,y) {type_t tmp; tmp = x; x = y; y = tmp; }
590
591 // Determine the most likely combination of alleles. In this implementation,
592 // at most tri-allelic sites are considered. Returns the number of alleles.
593 static int mcall_find_best_alleles(call_t *call, int nals, smpl_grp_t *grp)
594 {
595 int ia,ib,ic; // iterators over up to three alleles
596 int max_als=0; // most likely combination of alleles
597 double ref_lk = -HUGE_VAL, max_lk = -HUGE_VAL; // likelihood of the reference and of most likely combination of alleles
598 double lk_sum = -HUGE_VAL; // for normalizing the likelihoods
599 int nsmpl = grp->nsmpl;
600 int ngts = nals*(nals+1)/2;
601
602 // Single allele
603 for (ia=0; ia<nals; ia++)
604 {
605 double lk_tot = 0;
606 int lk_tot_set = 0;
607 int iaa = (ia+1)*(ia+2)/2-1; // index in PL which corresponds to the homozygous "ia/ia" genotype
608 int ismpl;
609 for (ismpl=0; ismpl<nsmpl; ismpl++)
610 {
611 double *pdg = call->pdg + grp->smpl[ismpl]*ngts + iaa;
612 if ( *pdg ) { lk_tot += log(*pdg); lk_tot_set = 1; }
613 }
614 if ( ia==0 ) ref_lk = lk_tot; // likelihood of 0/0 for all samples
615 else lk_tot += call->theta; // the prior
616 UPDATE_MAX_LKs(1<<ia, ia>0 && lk_tot_set);
617 }
618
619 // Two alleles
620 if ( nals>1 )
621 {
622 for (ia=0; ia<nals; ia++)
623 {
624 if ( grp->qsum[ia]==0 ) continue;
625 int iaa = (ia+1)*(ia+2)/2-1;
626 for (ib=0; ib<ia; ib++)
627 {
628 if ( grp->qsum[ib]==0 ) continue;
629 double lk_tot = 0;
630 int lk_tot_set = 0;
631 double fa = grp->qsum[ia]/(grp->qsum[ia] + grp->qsum[ib]);
632 double fb = grp->qsum[ib]/(grp->qsum[ia] + grp->qsum[ib]);
633 double fa2 = fa*fa;
634 double fb2 = fb*fb;
635 double fab = 2*fa*fb;
636 int is, ibb = (ib+1)*(ib+2)/2-1, iab = iaa - ia + ib;
637 for (is=0; is<nsmpl; is++)
638 {
639 int ismpl = grp->smpl[is];
640 double *pdg = call->pdg + ismpl*ngts;
641 double val = 0;
642 if ( !call->ploidy || call->ploidy[ismpl]==2 )
643 val = fa2*pdg[iaa] + fb2*pdg[ibb] + fab*pdg[iab];
644 else if ( call->ploidy && call->ploidy[ismpl]==1 )
645 val = fa*pdg[iaa] + fb*pdg[ibb];
646 if ( val ) { lk_tot += log(val); lk_tot_set = 1; }
647 }
648 if ( ia!=0 ) lk_tot += call->theta; // the prior
649 if ( ib!=0 ) lk_tot += call->theta;
650 UPDATE_MAX_LKs(1<<ia|1<<ib, lk_tot_set);
651 }
652 }
653 }
654
655 // Three alleles
656 if ( nals>2 )
657 {
658 for (ia=0; ia<nals; ia++)
659 {
660 if ( grp->qsum[ia]==0 ) continue;
661 int iaa = (ia+1)*(ia+2)/2-1;
662 for (ib=0; ib<ia; ib++)
663 {
664 if ( grp->qsum[ib]==0 ) continue;
665 int ibb = (ib+1)*(ib+2)/2-1;
666 int iab = iaa - ia + ib;
667 for (ic=0; ic<ib; ic++)
668 {
669 if ( grp->qsum[ic]==0 ) continue;
670 double lk_tot = 0;
671 int lk_tot_set = 0;
672
673 double fa = grp->qsum[ia]/(grp->qsum[ia] + grp->qsum[ib] + grp->qsum[ic]);
674 double fb = grp->qsum[ib]/(grp->qsum[ia] + grp->qsum[ib] + grp->qsum[ic]);
675 double fc = grp->qsum[ic]/(grp->qsum[ia] + grp->qsum[ib] + grp->qsum[ic]);
676 double fa2 = fa*fa;
677 double fb2 = fb*fb;
678 double fc2 = fc*fc;
679 double fab = 2*fa*fb, fac = 2*fa*fc, fbc = 2*fb*fc;
680 int is, icc = (ic+1)*(ic+2)/2-1;
681 int iac = iaa - ia + ic, ibc = ibb - ib + ic;
682 for (is=0; is<nsmpl; is++)
683 {
684 int ismpl = grp->smpl[is];
685 double *pdg = call->pdg + ismpl*ngts;
686 double val = 0;
687 if ( !call->ploidy || call->ploidy[ismpl]==2 )
688 val = fa2*pdg[iaa] + fb2*pdg[ibb] + fc2*pdg[icc] + fab*pdg[iab] + fac*pdg[iac] + fbc*pdg[ibc];
689 else if ( call->ploidy && call->ploidy[ismpl]==1 )
690 val = fa*pdg[iaa] + fb*pdg[ibb] + fc*pdg[icc];
691 if ( val ) { lk_tot += log(val); lk_tot_set = 1; }
692 }
693 if ( ia!=0 ) lk_tot += call->theta; // the prior
694 if ( ib!=0 ) lk_tot += call->theta; // the prior
695 if ( ic!=0 ) lk_tot += call->theta; // the prior
696 UPDATE_MAX_LKs(1<<ia|1<<ib|1<<ic, lk_tot_set);
697 }
698 }
699 }
700 }
701
702 int i, n = 0;
703 for (i=0; i<nals; i++) if ( max_als & 1<<i) n++;
704
705 grp->max_lk = max_lk;
706 grp->ref_lk = ref_lk;
707 grp->lk_sum = lk_sum;
708 grp->als = max_als;
709 grp->nals = n;
710
711 return n;
712 }
713
714 // Sets GT=0/0 or GT=. if PL=0,0,0
715 static void mcall_set_ref_genotypes(call_t *call, int nals_ori)
716 {
717 int i;
718 int ngts = nals_ori*(nals_ori+1)/2; // need this to distinguish between GT=0/0 vs GT=.
719 int nsmpl = bcf_hdr_nsamples(call->hdr);
720
721 for (i=0; i<nals_ori; i++) call->ac[i] = 0; // nals_new<=nals_ori, never mind setting extra 0's
722
723 // Set all genotypes to 0/0 or 0
724 int *gts = call->gts;
725 double *pdg = call->pdg;
726 int isample;
727 for (isample = 0; isample < nsmpl; isample++)
728 {
729 int ploidy = call->ploidy ? call->ploidy[isample] : 2;
730 for (i=0; i<ngts; i++) if ( pdg[i]!=0.0 ) break;
731 if ( i==ngts || !ploidy )
732 {
733 gts[0] = bcf_gt_missing;
734 gts[1] = ploidy==2 ? bcf_gt_missing : bcf_int32_vector_end;
735 }
736 else
737 {
738 gts[0] = bcf_gt_unphased(0);
739 gts[1] = ploidy==2 ? bcf_gt_unphased(0) : bcf_int32_vector_end;
740 call->ac[0] += ploidy;
741 }
742 gts += 2;
743 pdg += ngts;
744 }
745 }
746
747 static void mcall_call_genotypes(call_t *call, int nals_ori, smpl_grp_t *grp)
748 {
749 int ia, ib, i;
750 int ngts_ori = nals_ori*(nals_ori+1)/2;
751 int ngts_new = call->nals_new*(call->nals_new+1)/2;
752 int nsmpl = grp->nsmpl;
753
754 #if USE_PRIOR_FOR_GTS
755 float prior = exp(call->theta);
756 #endif
757
758 int is;
759 for (is = 0; is < nsmpl; is++)
760 {
761 int ismpl = grp->smpl[is];
762 double *pdg = call->pdg + ismpl*ngts_ori;
763 float *gps = call->GPs + ismpl*ngts_new;
764 int *gts = call->gts + ismpl*2;
765
766 int ploidy = call->ploidy ? call->ploidy[ismpl] : 2;
767 assert( ploidy>=0 && ploidy<=2 );
768
769 if ( !ploidy )
770 {
771 gts[0] = bcf_gt_missing;
772 gts[1] = bcf_int32_vector_end;
773 gps[0] = -1;
774 continue;
775 }
776
777 #if !FLAT_PDG_FOR_MISSING
778 // Skip samples with zero depth, they have all pdg's equal to 0
779 for (i=0; i<ngts_ori; i++) if ( pdg[i]!=0.0 ) break;
780 if ( i==ngts_ori )
781 {
782 gts[0] = bcf_gt_missing;
783 gts[1] = ploidy==2 ? bcf_gt_missing : bcf_int32_vector_end;
784 gps[0] = -1;
785 continue;
786 }
787 #endif
788
789 // Default fallback for the case all LKs are the same
790 gts[0] = bcf_gt_unphased(0);
791 gts[1] = ploidy==2 ? bcf_gt_unphased(0) : bcf_int32_vector_end;
792
793 // Non-zero depth, determine the most likely genotype
794 double best_lk = 0;
795 for (ia=0; ia<nals_ori; ia++)
796 {
797 if ( !(grp->als & 1<<ia) ) continue; // ia-th allele not in the final selection, skip
798 int iaa = (ia+1)*(ia+2)/2-1; // PL index of the ia/ia genotype
799 double lk = ploidy==2 ? pdg[iaa]*grp->qsum[ia]*grp->qsum[ia] : pdg[iaa]*grp->qsum[ia];
800 #if USE_PRIOR_FOR_GTS
801 if ( ia!=0 ) lk *= prior;
802 #endif
803 int igt = ploidy==2 ? bcf_alleles2gt(call->als_map[ia],call->als_map[ia]) : call->als_map[ia];
804 gps[igt] = lk;
805 if ( best_lk < lk )
806 {
807 best_lk = lk;
808 gts[0] = bcf_gt_unphased(call->als_map[ia]);
809 }
810 }
811 if ( ploidy==2 )
812 {
813 gts[1] = gts[0];
814 for (ia=0; ia<nals_ori; ia++)
815 {
816 if ( !(grp->als & 1<<ia) ) continue;
817 int iaa = (ia+1)*(ia+2)/2-1;
818 for (ib=0; ib<ia; ib++)
819 {
820 if ( !(grp->als & 1<<ib) ) continue;
821 int iab = iaa - ia + ib;
822 double lk = 2*pdg[iab]*grp->qsum[ia]*grp->qsum[ib];
823 #if USE_PRIOR_FOR_GTS
824 if ( ia!=0 ) lk *= prior;
825 if ( ib!=0 ) lk *= prior;
826 #endif
827 int igt = bcf_alleles2gt(call->als_map[ia],call->als_map[ib]);
828 gps[igt] = lk;
829 if ( best_lk < lk )
830 {
831 best_lk = lk;
832 gts[0] = bcf_gt_unphased(call->als_map[ib]);
833 gts[1] = bcf_gt_unphased(call->als_map[ia]);
834 }
835 }
836 }
837 }
838 else
839 gts[1] = bcf_int32_vector_end;
840
841 call->ac[ bcf_gt_allele(gts[0]) ]++;
842 if ( gts[1]!=bcf_int32_vector_end ) call->ac[ bcf_gt_allele(gts[1]) ]++;
843 }
844 if ( !(call->output_tags & (CALL_FMT_GQ|CALL_FMT_GP)) ) return;
845 double max, sum;
846 for (is=0; is<nsmpl; is++)
847 {
848 int ismpl = grp->smpl[is];
849 float *gps = call->GPs + ismpl*ngts_new;
850
851 int nmax;
852 if ( call->ploidy )
853 {
854 if ( call->ploidy[ismpl]==2 ) nmax = ngts_new;
855 else if ( call->ploidy[ismpl]==1 ) nmax = grp->nals;
856 else nmax = 0;
857 }
858 else nmax = ngts_new;
859
860 max = gps[0];
861 if ( max<0 || nmax==0 )
862 {
863 // no call
864 if ( call->output_tags & CALL_FMT_GP )
865 {
866 for (i=0; i<nmax; i++) gps[i] = 0;
867 if ( nmax==0 ) { bcf_float_set_missing(gps[i]); nmax++; }
868 if ( nmax < ngts_new ) bcf_float_set_vector_end(gps[nmax]);
869 }
870 call->GQs[ismpl] = 0;
871 continue;
872 }
873 sum = gps[0];
874 for (i=1; i<nmax; i++)
875 {
876 if ( max < gps[i] ) max = gps[i];
877 sum += gps[i];
878 }
879 max = -4.34294*log(1 - max/sum);
880 call->GQs[ismpl] = max<=INT8_MAX ? max : INT8_MAX;
881 if ( call->output_tags & CALL_FMT_GP )
882 {
883 assert( max );
884 for (i=0; i<nmax; i++) gps[i] = gps[i]/sum;
885 for (; i<ngts_new; i++) bcf_float_set_vector_end(gps[i]);
886 }
887 }
888 }
889
890
891 /**
892 Pm = P(mendelian) .. parameter to vary, 1-Pm is the probability of novel mutation.
893 When trio_Pm_ins is negative, Pm is calculated dynamically
894 according to indel length. For simplicity, only the
895 first ALT is considered.
896 Pkij = P(k|i,j) .. probability that the genotype combination i,j,k is consistent
897 with mendelian inheritance (the likelihood that offspring
898 of two HETs is a HOM is smaller than it being a HET)
899
900 P_uc(F=i,M=j,K=k) = P(F=i) . P(M=j) . P(K=k) .. unconstrained P
901 P_c(F=i,M=j,K=k) = P_uc . Pkij .. constrained P
902 P(F=i,M=j,K=k) = P_uc . (1 - Pm) + P_c . Pm
903 = P_uc . [1 - Pm + Pkij . Pm]
904
905 We choose genotype combination i,j,k which maximizes P(F=i,M=j,K=k). This
906 probability gives the quality GQ(Trio).
907 Individual qualities are calculated as
908 GQ(F=i,M=j,K=k) = P(F=i,M=j,K=k) / \sum_{x,y} P(F=i,M=x,K=y)
909 */
910 #if 0
911 static void mcall_call_trio_genotypes(call_t *call, bcf1_t *rec, int nals, int nals_new, int als_new)
912 {
913 int ia, ib, i;
914 int nsmpl = bcf_hdr_nsamples(call->hdr);
915 int ngts = nals*(nals+1)/2;
916 int nout_gts = nals_new*(nals_new+1)/2;
917 double *gls = call->GLs - nout_gts;
918 double *pdg = call->pdg - ngts;
919
920 // Calculate individuals' genotype likelihoods P(X=i)
921 int isample;
922 for (isample = 0; isample < nsmpl; isample++)
923 {
924 int ploidy = call->ploidy ? call->ploidy[isample] : 2;
925 int32_t *gts = call->ugts + isample;
926
927 gls += nout_gts;
928 pdg += ngts;
929
930 // Skip samples with all pdg's equal to 1. These have zero depth.
931 for (i=0; i<ngts; i++) if ( pdg[i]!=0.0 ) break;
932 if ( i==ngts || !ploidy )
933 {
934 gts[0] = -1;
935 gls[0] = 1;
936 continue;
937 }
938
939 for (i=0; i<nout_gts; i++) gls[i] = -HUGE_VAL;
940
941 grp1_t *grp = &call->smpl_grp.grp[call->smpl_grp.smpl2grp[isample]];
942 double sum_lk = 0;
943 double best_lk = 0;
944 for (ia=0; ia<nals; ia++)
945 {
946 if ( !(als_new & 1<<ia) ) continue; // ia-th allele not in the final selection, skip
947 int iaa = bcf_alleles2gt(ia,ia); // PL index of the ia/ia genotype
948 int idx = bcf_alleles2gt(call->als_map[ia],call->als_map[ia]);
949 double lk = ploidy==2 ? pdg[iaa]*grp->qsum[ia]*grp->qsum[ia] : pdg[iaa]*grp->qsum[ia];
950 sum_lk += lk;
951 gls[idx] = lk;
952 if ( best_lk < lk )
953 {
954 best_lk = lk;
955 gts[0] = bcf_alleles2gt(call->als_map[ia],call->als_map[ia]);
956 }
957 }
958 if ( ploidy==2 )
959 {
960 for (ia=0; ia<nals; ia++)
961 {
962 if ( !(als_new & 1<<ia) ) continue;
963 for (ib=0; ib<ia; ib++)
964 {
965 if ( !(als_new & 1<<ib) ) continue;
966 int iab = bcf_alleles2gt(ia,ib);
967 int idx = bcf_alleles2gt(call->als_map[ia],call->als_map[ib]);
968 double lk = 2*pdg[iab]*grp->qsum[ia]*grp->qsum[ib];
969 sum_lk += lk;
970 gls[idx] = lk;
971 if ( best_lk < lk )
972 {
973 best_lk = lk;
974 gts[0] = bcf_alleles2gt(call->als_map[ib],call->als_map[ia]);
975 }
976 }
977 }
978 }
979 for (i=0; i<nout_gts; i++)
980 if ( gls[i]!=-HUGE_VAL ) gls[i] = log(gls[i]/sum_lk);
981 }
982
983 // Set novel mutation rate for this site: using first ALT allele for simplicity.
984 double trio_Pm;
985 if ( call->trio_Pm_ins<0 && call->trio_Pm_del<0 ) trio_Pm = call->trio_Pm_SNPs; // the same Pm for indels and SNPs requested
986 else
987 {
988 int ret = bcf_get_variant_types(rec);
989 if ( !(ret & VCF_INDEL) ) trio_Pm = call->trio_Pm_SNPs;
990 else
991 {
992 if ( call->trio_Pm_ins<0 ) // dynamic calculation, trio_Pm_del holds the scaling factor
993 {
994 trio_Pm = rec->d.var[1].n<0 ? -21.9313 - 0.2856*rec->d.var[1].n : -22.8689 + 0.2994*rec->d.var[1].n;
995 trio_Pm = 1 - call->trio_Pm_del * exp(trio_Pm);
996 }
997 else // snps and indels set explicitly
998 {
999 trio_Pm = rec->d.var[1].n<0 ? call->trio_Pm_del : call->trio_Pm_ins;
1000 }
1001 }
1002 }
1003
1004 // Calculate constrained likelihoods and determine genotypes
1005 int ifm;
1006 for (ifm=0; ifm<call->nfams; ifm++)
1007 {
1008 family_t *fam = &call->fams[ifm];
1009 int ntrio = call->ntrio[fam->type][nals_new];
1010 uint16_t *trio = call->trio[fam->type][nals_new];
1011
1012 // Unconstrained likelihood
1013 int uc_itr = 0;
1014 double uc_lk = 0;
1015 for (i=0; i<3; i++) // for father, mother, child
1016 {
1017 int ismpl = fam->sample[i];
1018 double *gl = call->GLs + nout_gts*ismpl;
1019 if ( gl[0]==1 ) continue;
1020 int j, jmax = 0;
1021 double max = gl[0];
1022 for (j=1; j<nout_gts; j++)
1023 if ( max < gl[j] ) { max = gl[j]; jmax = j; }
1024 uc_lk += max;
1025 uc_itr |= jmax << ((2-i)*4);
1026 }
1027
1028 // Best constrained likelihood
1029 int c_itr = -1, itr, uc_is_mendelian = 0;
1030 double c_lk = -HUGE_VAL;
1031 for (itr=0; itr<ntrio; itr++) // for each trio genotype combination
1032 {
1033 double lk = 0;
1034 int npresent = 0;
1035 for (i=0; i<3; i++) // for father, mother, child
1036 {
1037 int ismpl = fam->sample[i];
1038 double *gl = call->GLs + nout_gts*ismpl;
1039 if ( gl[0]==1 ) continue;
1040 int igt = trio[itr]>>((2-i)*4) & 0xf;
1041 assert( !call->ploidy || call->ploidy[ismpl]>0 );
1042 if ( igt==GT_SKIP ) continue;
1043 lk += gl[igt];
1044 npresent++;
1045 // fprintf(bcftools_stderr," %e", gl[igt]);
1046 }
1047 // fprintf(bcftools_stderr,"\t\t");
1048 double Pkij = npresent==3 ? (double)2/(trio[itr]>>12) : 1; // with missing genotypes Pkij's are different
1049 lk += log(1 - trio_Pm * (1 - Pkij));
1050 // fprintf(bcftools_stderr,"%d%d%d\t%e\t%.2f\n", trio[itr]>>8&0xf,trio[itr]>>4&0xf,trio[itr]&0xf, lk, Pkij);
1051 if ( c_lk < lk ) { c_lk = lk; c_itr = trio[itr]; }
1052 if ( uc_itr==trio[itr] ) uc_is_mendelian = 1;
1053 }
1054
1055 if ( !uc_is_mendelian )
1056 {
1057 uc_lk += log(1 - trio_Pm);
1058 // fprintf(bcftools_stderr,"c_lk=%e uc_lk=%e c_itr=%d%d%d uc_itr=%d%d%d\n", c_lk,uc_lk,c_itr>>8&0xf,c_itr>>4&0xf,c_itr&0xf,uc_itr>>8&0xf,uc_itr>>4&0xf,uc_itr&0xf);
1059 if ( c_lk < uc_lk ) { c_lk = uc_lk; c_itr = uc_itr; }
1060 }
1061 // fprintf(bcftools_stderr,"best_lk=%e best_itr=%d%d%d uc_itr=%d%d%d\n", c_lk,c_itr>>8&0xf,c_itr>>4&0xf,c_itr&0xf,uc_itr>>8&0xf,uc_itr>>4&0xf,uc_itr&0xf);
1062
1063 // Set genotypes for father, mother, child and calculate genotype qualities
1064 for (i=0; i<3; i++)
1065 {
1066 // GT
1067 int ismpl = fam->sample[i];
1068 int igt = c_itr>>((2-i)*4) & 0xf;
1069 double *gl = call->GLs + nout_gts*ismpl;
1070 int32_t *gts = call->cgts + ismpl;
1071 if ( gl[0]==1 || igt==GT_SKIP ) // zero depth, set missing genotypes
1072 {
1073 gts[0] = -1;
1074 // bcf_float_set_missing(call->GQs[ismpl]);
1075 continue;
1076 }
1077 gts[0] = igt;
1078
1079 #if 0
1080 // todo: Genotype Qualities
1081 //
1082 // GQ: for each family member i sum over all genotypes j,k keeping igt fixed
1083 double lk_sum = 0;
1084 for (itr=0; itr<ntrio; itr++)
1085 {
1086 if ( igt != (trio[itr]>>((2-i)*4) & 0xf) ) continue;
1087 double lk = 0;
1088 int j;
1089 for (j=0; j<3; j++)
1090 {
1091 int jsmpl = fam->sample[j];
1092 double *gl = call->GLs + ngts*jsmpl;
1093 if ( gl[0]==1 ) continue;
1094 int jgt = trio[itr]>>((2-j)*4) & 0xf;
1095 if ( jgt==GT_SKIP ) continue;
1096 lk += gl[jgt];
1097 }
1098 double Pkij = (double)2/(trio[itr]>>12);
1099 lk += log(1 - trio_Pm * (1 - Pkij));
1100 lk_sum = logsumexp2(lk_sum, lk);
1101 }
1102 if ( !uc_is_mendelian && (best_itr>>((2-i)*4)&0xf)==(uc_itr>>((2-i)*4)&0xf) ) lk_sum = logsumexp2(lk_sum,uc_lk);
1103 call->GQs[ismpl] = -4.3429*(best_lk - lk_sum);
1104 #endif
1105 }
1106 }
1107
1108 for (i=0; i<4; i++) call->ac[i] = 0;
1109 call->nhets = 0;
1110 call->ndiploid = 0;
1111
1112 // Test if CGT,UGT are needed
1113 int ucgts_needed = 0;
1114 int32_t *cgts = call->cgts - 1;
1115 int32_t *ugts = call->ugts - 1;
1116 int32_t *gts = call->gts - 2;
1117 for (isample = 0; isample < nsmpl; isample++)
1118 {
1119 int ploidy = call->ploidy ? call->ploidy[isample] : 2;
1120 cgts++;
1121 ugts++;
1122 gts += 2;
1123 if ( ugts[0]==-1 )
1124 {
1125 gts[0] = bcf_gt_missing;
1126 gts[1] = ploidy==2 ? bcf_gt_missing : bcf_int32_vector_end;
1127 continue;
1128 }
1129 int a,b;
1130 if ( cgts[0]!=ugts[0] )
1131 {
1132 bcf_gt2alleles(cgts[0], &a, &b);
1133 gts[0] = bcf_gt_unphased(a);
1134 gts[1] = ploidy==1 ? bcf_int32_vector_end : bcf_gt_unphased(b);
1135 }
1136 else
1137 {
1138 bcf_gt2alleles(ugts[0], &a, &b);
1139 gts[0] = bcf_gt_unphased(a);
1140 gts[1] = ploidy==1 ? bcf_int32_vector_end : bcf_gt_unphased(b);
1141 }
1142 if ( cgts[0]!=ugts[0] ) ucgts_needed = 1;
1143 call->ac[a]++;
1144 if ( ploidy==2 )
1145 {
1146 call->ac[b]++;
1147 call->ndiploid++;
1148 if ( a!=b ) call->nhets++;
1149 }
1150 }
1151 if ( ucgts_needed )
1152 {
1153 // Some GTs are different
1154 bcf_update_format_int32(call->hdr,rec,"UGT",call->ugts,nsmpl);
1155 bcf_update_format_int32(call->hdr,rec,"CGT",call->cgts,nsmpl);
1156 }
1157 }
1158 #endif
1159
1160 static void mcall_trim_and_update_PLs(call_t *call, bcf1_t *rec, int nals_ori, int nals_new)
1161 {
1162 int npls_src = nals_ori*(nals_ori+1)/2;
1163 int npls_dst = nals_new*(nals_new+1)/2; // number of PL values in diploid samples, ori and new
1164 if ( call->all_diploid && npls_src == npls_dst ) return;
1165
1166 int *pls_src = call->PLs, *pls_dst = call->PLs;
1167
1168 int nsmpl = bcf_hdr_nsamples(call->hdr);
1169 int isample, ia;
1170 for (isample = 0; isample < nsmpl; isample++)
1171 {
1172 int ploidy = call->ploidy ? call->ploidy[isample] : 2;
1173 if ( ploidy==2 )
1174 {
1175 for (ia=0; ia<npls_dst; ia++)
1176 pls_dst[ia] = pls_src[ call->pl_map[ia] ];
1177 }
1178 else if ( ploidy==1 )
1179 {
1180 for (ia=0; ia<nals_new; ia++)
1181 {
1182 int isrc = (ia+1)*(ia+2)/2-1;
1183 pls_dst[ia] = pls_src[ call->pl_map[isrc] ];
1184 }
1185 if ( ia<npls_dst ) pls_dst[ia] = bcf_int32_vector_end;
1186 }
1187 else
1188 {
1189 pls_dst[0] = bcf_int32_missing;
1190 pls_dst[1] = bcf_int32_vector_end; // relying on nals_new>1 in mcall()
1191 }
1192 pls_src += npls_src;
1193 pls_dst += npls_dst;
1194 }
1195 bcf_update_format_int32(call->hdr, rec, "PL", call->PLs, npls_dst*nsmpl);
1196 }
1197
1198 void mcall_trim_and_update_numberR(call_t *call, bcf1_t *rec, int nals_ori, int nals_new)
1199 {
1200 if ( nals_ori==nals_new ) return;
1201
1202 int i,j, nret, size = sizeof(float);
1203
1204 void *tmp_ori = call->itmp, *tmp_new = call->PLs; // reusing PLs storage which is not used at this point
1205 int ntmp_ori = call->n_itmp, ntmp_new = call->mPLs;
1206
1207 // INFO fields
1208 for (i=0; i<rec->n_info; i++)
1209 {
1210 bcf_info_t *info = &rec->d.info[i];
1211 int vlen = bcf_hdr_id2length(call->hdr,BCF_HL_INFO,info->key);
1212 if ( vlen!=BCF_VL_R ) continue; // not a Number=R tag
1213
1214 int type = bcf_hdr_id2type(call->hdr,BCF_HL_INFO,info->key);
1215 const char *key = bcf_hdr_int2id(call->hdr,BCF_DT_ID,info->key);
1216 nret = bcf_get_info_values(call->hdr, rec, key, &tmp_ori, &ntmp_ori, type);
1217 if ( nret<=0 ) continue;
1218
1219 if ( nals_new==1 )
1220 bcf_update_info_int32(call->hdr, rec, key, tmp_ori, 1); // has to be the REF, the order could not change
1221 else
1222 {
1223 for (j=0; j<nals_ori; j++)
1224 {
1225 int k = call->als_map[j];
1226 if ( k==-1 ) continue; // to be dropped
1227 memcpy((char *)tmp_new+size*k, (char *)tmp_ori+size*j, size);
1228 }
1229 bcf_update_info_int32(call->hdr, rec, key, tmp_new, nals_new);
1230 }
1231 }
1232
1233 // FORMAT fields
1234 for (i=0; i<rec->n_fmt; i++)
1235 {
1236 bcf_fmt_t *fmt = &rec->d.fmt[i];
1237 int vlen = bcf_hdr_id2length(call->hdr,BCF_HL_FMT,fmt->id);
1238 if ( vlen!=BCF_VL_R ) continue; // not a Number=R tag
1239
1240 int type = bcf_hdr_id2type(call->hdr,BCF_HL_FMT,fmt->id);
1241 const char *key = bcf_hdr_int2id(call->hdr,BCF_DT_ID,fmt->id);
1242 nret = bcf_get_format_values(call->hdr, rec, key, &tmp_ori, &ntmp_ori, type);
1243 if (nret<=0) continue;
1244 int nsmpl = bcf_hdr_nsamples(call->hdr);
1245
1246 assert( nret==nals_ori*nsmpl );
1247
1248 for (j=0; j<nsmpl; j++)
1249 {
1250 char *ptr_src = (char *)tmp_ori + j*nals_ori*size;
1251 char *ptr_dst = (char *)tmp_new + j*nals_new*size;
1252 int k;
1253 for (k=0; k<nals_ori; k++)
1254 {
1255 int l = call->als_map[k];
1256 if ( l==-1 ) continue; // to be dropped
1257 memcpy(ptr_dst+size*l, ptr_src+size*k, size);
1258 }
1259 }
1260 bcf_update_format_int32(call->hdr, rec, key, tmp_new, nals_new*nsmpl);
1261 }
1262
1263 call->PLs = (int32_t*) tmp_new;
1264 call->mPLs = ntmp_new;
1265 call->itmp = (int32_t*) tmp_ori;
1266 call->n_itmp = ntmp_ori;
1267 }
1268
1269
1270 // NB: in this function we temporarily use calls->als_map for a different
1271 // purpose to store mapping from new (target) alleles to original alleles.
1272 //
1273 static int mcall_constrain_alleles(call_t *call, bcf1_t *rec, int *unseen)
1274 {
1275 assert( call->tgt_als->n );
1276 hts_expand(char*,call->tgt_als->n+1,call->nals,call->als);
1277 hts_expand(int,call->tgt_als->n+1,call->nals_map,call->als_map);
1278 hts_expand(int,(call->tgt_als->n+1)*(call->tgt_als->n+2)/2,call->npl_map,call->pl_map);
1279
1280 int has_new = 0;
1281
1282 int i, j, nals = 1;
1283 for (i=1; i<call->nals_map; i++) call->als_map[i] = -1;
1284
1285 if ( vcmp_set_ref(call->vcmp, rec->d.allele[0], call->tgt_als->allele[0]) < 0 )
1286 error("The reference alleles are not compatible at %s:%d .. %s vs %s\n", call->hdr->id[BCF_DT_CTG][rec->rid].key,rec->pos+1,call->tgt_als->allele[0],rec->d.allele[0]);
1287
1288 // create mapping from new to old alleles
1289 call->als[0] = call->tgt_als->allele[0];
1290 call->als_map[0] = 0;
1291
1292 for (i=1; i<call->tgt_als->n; i++)
1293 {
1294 call->als[nals] = call->tgt_als->allele[i];
1295 j = vcmp_find_allele(call->vcmp, rec->d.allele+1, rec->n_allele - 1, call->tgt_als->allele[i]);
1296 if ( j>=0 )
1297 {
1298 // existing allele
1299 call->als_map[nals] = j+1;
1300 }
1301 else
1302 {
1303 // There is a new allele in targets which is not present in VCF.
1304 // We use the X allele to estimate PLs. Note that X may not be
1305 // present at multiallelic indels sites. In that case we use the
1306 // last allele anyway, because the least likely allele comes last
1307 // in mpileup's ALT output.
1308 call->als_map[nals] = (*unseen)>=0 ? *unseen : rec->n_allele - 1;
1309 has_new = 1;
1310 }
1311 nals++;
1312 }
1313 if ( *unseen )
1314 {
1315 call->als_map[nals] = *unseen;
1316 call->als[nals] = rec->d.allele[*unseen];
1317 nals++;
1318 }
1319
1320 if ( !has_new && nals==rec->n_allele ) return 0;
1321 bcf_update_alleles(call->hdr, rec, (const char**)call->als, nals);
1322
1323 // create mapping from new PL to old PL
1324 int k = 0;
1325 for (i=0; i<nals; i++)
1326 {
1327 for (j=0; j<=i; j++)
1328 {
1329 int a = call->als_map[i], b = call->als_map[j];
1330 call->pl_map[k++] = a>b ? a*(a+1)/2 + b : b*(b+1)/2 + a;
1331 }
1332 }
1333
1334 // update PL
1335 call->nPLs = bcf_get_format_int32(call->hdr, rec, "PL", &call->PLs, &call->mPLs);
1336 int nsmpl = bcf_hdr_nsamples(call->hdr);
1337 int npls_ori = call->nPLs / nsmpl;
1338 int npls_new = k;
1339 hts_expand(int32_t,npls_new*nsmpl,call->n_itmp,call->itmp);
1340 int *ori_pl = call->PLs, *new_pl = call->itmp;
1341 for (i=0; i<nsmpl; i++)
1342 {
1343 for (k=0; k<npls_new; k++)
1344 {
1345 new_pl[k] = ori_pl[call->pl_map[k]];
1346 if ( new_pl[k]==bcf_int32_missing && *unseen>=0 )
1347 {
1348 // missing value, and there is an unseen allele: identify the
1349 // alleles and use the lk of either AX or XX
1350 int k_ori = call->pl_map[k], ia, ib;
1351 bcf_gt2alleles(k_ori, &ia, &ib);
1352 k_ori = bcf_alleles2gt(ia,*unseen);
1353 if ( ori_pl[k_ori]==bcf_int32_missing ) k_ori = bcf_alleles2gt(ib,*unseen);
1354 if ( ori_pl[k_ori]==bcf_int32_missing ) k_ori = bcf_alleles2gt(*unseen,*unseen);
1355 new_pl[k] = ori_pl[k_ori];
1356 }
1357 if ( !k && new_pl[k]==bcf_int32_vector_end ) new_pl[k]=bcf_int32_missing;
1358 }
1359 ori_pl += npls_ori;
1360 new_pl += npls_new;
1361 }
1362 bcf_update_format_int32(call->hdr, rec, "PL", call->itmp, npls_new*nsmpl);
1363
1364 // update QS, use temporarily call->GPs to store the values
1365 int nqs = bcf_get_info_float(call->hdr, rec, "QS", &call->smpl_grp[0].qsum, &call->smpl_grp[0].nqsum);
1366 hts_expand(float,nals,call->nGPs,call->GPs);
1367 for (i=0; i<nals; i++)
1368 call->GPs[i] = call->als_map[i]<nqs ? call->smpl_grp[0].qsum[call->als_map[i]] : 0;
1369 bcf_update_info_float(call->hdr, rec, "QS", call->GPs, nals);
1370
1371 // update any Number=R tags
1372 void *tmp_ori = call->itmp, *tmp_new = call->PLs; // reusing PLs storage which is not used at this point
1373 int ntmp_ori = call->n_itmp, ntmp_new = call->mPLs;
1374 for (i=0; i<rec->n_fmt; i++)
1375 {
1376 bcf_fmt_t *fmt = &rec->d.fmt[i];
1377 int vlen = bcf_hdr_id2length(call->hdr,BCF_HL_FMT,fmt->id);
1378 if ( vlen!=BCF_VL_R ) continue; // not a Number=R tag
1379
1380 // NB:works only for BCF_HT_INT and BCF_HT_REAL
1381 int type = bcf_hdr_id2type(call->hdr,BCF_HL_FMT,fmt->id);
1382 assert( type==BCF_HT_INT || type==BCF_HT_REAL );
1383 assert( sizeof(float)==sizeof(int32_t) );
1384
1385 const char *key = bcf_hdr_int2id(call->hdr,BCF_DT_ID,fmt->id);
1386 int nret = bcf_get_format_values(call->hdr, rec, key, &tmp_ori, &ntmp_ori, type);
1387 if (nret<=0) continue;
1388 int nsmpl = bcf_hdr_nsamples(call->hdr);
1389 int size1 = sizeof(float);
1390 hts_expand(float, nsmpl * nals, ntmp_new, tmp_new);
1391 for (j=0; j<nsmpl; j++)
1392 {
1393 uint8_t *ptr_ori = (uint8_t *) tmp_ori + j*size1*fmt->n;
1394 uint8_t *ptr_new = (uint8_t *) tmp_new + j*nals*size1;
1395 for (k=0; k<nals; k++)
1396 {
1397 uint8_t *dst = ptr_new + size1*k;
1398 uint8_t *src = ptr_ori + size1*call->als_map[k];
1399 memcpy(dst,src,size1);
1400 }
1401 }
1402 nret = bcf_update_format(call->hdr, rec, key, tmp_new, nsmpl*nals, type);
1403 assert( nret==0 );
1404 }
1405 call->PLs = (int32_t*) tmp_new;
1406 call->mPLs = ntmp_new;
1407 call->itmp = (int32_t*) tmp_ori;
1408 call->n_itmp = ntmp_ori;
1409
1410 if ( *unseen ) *unseen = nals-1;
1411 return 0;
1412 }
1413
1414
1415 /**
1416 * This function implements the multiallelic calling model. It has two major parts:
1417 * 1) determine the most likely set of alleles and calculate the quality of ref/non-ref site
1418 * 2) determine and set the genotypes
1419 * In various places in between, the BCF record gets updated.
1420 */
1421 int mcall(call_t *call, bcf1_t *rec)
1422 {
1423 int i,j, unseen = call->unseen;
1424
1425 // Force alleles when calling genotypes given alleles was requested
1426 if ( call->flag & CALL_CONSTR_ALLELES && mcall_constrain_alleles(call, rec, &unseen)!=0 ) return -2;
1427
1428 int nsmpl = bcf_hdr_nsamples(call->hdr);
1429 int nals_ori = rec->n_allele;
1430 hts_expand(int,nals_ori,call->nac,call->ac);
1431 hts_expand(int,nals_ori,call->nals_map,call->als_map);
1432 hts_expand(int,nals_ori*(nals_ori+1)/2,call->npl_map,call->pl_map);
1433
1434 // Get the genotype likelihoods
1435 call->nPLs = bcf_get_format_int32(call->hdr, rec, "PL", &call->PLs, &call->mPLs);
1436 if ( call->nPLs!=nsmpl*nals_ori*(nals_ori+1)/2 && call->nPLs!=nsmpl*nals_ori ) // a mixture of diploid and haploid or haploid only
1437 error("Wrong number of PL fields? nals=%d npl=%d\n", nals_ori,call->nPLs);
1438
1439 // Convert PLs to probabilities
1440 int ngts_ori = nals_ori*(nals_ori+1)/2;
1441 hts_expand(double, call->nPLs, call->npdg, call->pdg);
1442 set_pdg(call->pl2p, call->PLs, call->pdg, nsmpl, ngts_ori, unseen);
1443
1444 // Get sum of qualities, serves as an AF estimate, f_x = QS/N in Eq. 1 in call-m math notes.
1445 if ( call->nsmpl_grp == 1 )
1446 {
1447 int nqs = bcf_get_info_float(call->hdr, rec, "QS", &call->smpl_grp[0].qsum, &call->smpl_grp[0].nqsum);
1448 if ( nqs<=0 ) error("The QS annotation not present at %s:%d\n", bcf_seqname(call->hdr,rec),rec->pos+1);
1449 if ( nqs < nals_ori )
1450 {
1451 // Some of the listed alleles do not have the corresponding QS field. This is
1452 // typically ref-only site with <*> in ALT.
1453 hts_expand(float,nals_ori,call->smpl_grp[0].nqsum,call->smpl_grp[0].qsum);
1454 for (i=nqs; i<nals_ori; i++) call->smpl_grp[0].qsum[i] = 0;
1455 }
1456 }
1457 else
1458 {
1459 for (j=0; j<call->nsmpl_grp; j++)
1460 {
1461 hts_expand(float,nals_ori,call->smpl_grp[j].nqsum,call->smpl_grp[j].qsum);
1462 memset(call->smpl_grp[j].qsum, 0, sizeof(float)*nals_ori);
1463 }
1464
1465 // Use FORMAT/AD or FORMAT/QS
1466 int nad = bcf_get_format_int32(call->hdr, rec, call->sample_groups_tag, &call->ADs, &call->nADs);
1467 if ( nad<1 ) error("Error: FORMAT/%s is required with the -G option, mpileup must be run with \"-a AD\" or \"-a QS\"\n",call->sample_groups_tag);
1468 nad /= bcf_hdr_nsamples(call->hdr);
1469 for (i=0; i<call->nsmpl_grp; i++)
1470 {
1471 int is;
1472 smpl_grp_t *grp = &call->smpl_grp[i];
1473 hts_expand(float,nals_ori,grp->nqsum,grp->qsum);
1474 for (j=0; j<nals_ori; j++) grp->qsum[j] = 0;
1475 for (is=0; is<grp->nsmpl; is++)
1476 {
1477 int ismpl = grp->smpl[is];
1478 int32_t *ptr = call->ADs + ismpl*nad;
1479 float sum = 0;
1480 for (j=0; j<nad; j++)
1481 {
1482 if ( ptr[j]==bcf_int32_vector_end ) break;
1483 if ( ptr[j]!=bcf_int32_missing ) sum += ptr[j];
1484 }
1485 if ( sum )
1486 {
1487 for (j=0; j<nad; j++)
1488 {
1489 if ( ptr[j]==bcf_int32_vector_end ) break;
1490 if ( ptr[j]!=bcf_int32_missing ) grp->qsum[j] += ptr[j]/sum;
1491 }
1492 }
1493 }
1494 }
1495 }
1496
1497 // If available, take into account reference panel AFs
1498 if ( call->prior_AN && bcf_get_info_int32(call->hdr, rec, call->prior_AN ,&call->ac, &call->nac)==1 )
1499 {
1500 int an = call->ac[0]; // number of alleles total, proceed only if not zero; reuse call->ac
1501 if ( an > 0 && bcf_get_info_int32(call->hdr, rec, call->prior_AC ,&call->ac, &call->nac)==nals_ori-1 ) // number of ALT alleles
1502 {
1503 int ac0 = an; // this will become the number of REFs
1504 for (i=0; i<nals_ori-1; i++)
1505 {
1506 if ( call->ac[i]==bcf_int32_vector_end ) break;
1507 if ( call->ac[i]==bcf_int32_missing ) continue;
1508 ac0 -= call->ac[i];
1509
1510 // here an*0.5 is the number of samples in the populatio and ac*0.5 is the AF weighted by the number of samples
1511 for (j=0; j<call->nsmpl_grp; j++)
1512 call->smpl_grp[j].qsum[i+1] = (call->smpl_grp[j].qsum[i+1] + 0.5*call->ac[i]) / (call->smpl_grp[j].nsmpl + 0.5*an);
1513 }
1514 if ( ac0<0 ) error("Incorrect %s,%s values at %s:%d\n", call->prior_AN,call->prior_AC,bcf_seqname(call->hdr,rec),rec->pos+1);
1515 for (j=0; j<call->nsmpl_grp; j++)
1516 call->smpl_grp[j].qsum[0] = (call->smpl_grp[j].qsum[0] + 0.5*ac0) / (call->smpl_grp[j].nsmpl + 0.5*an);
1517 }
1518 }
1519
1520 // normalize so that QS sums to 1 for each group
1521 for (j=0; j<call->nsmpl_grp; j++)
1522 {
1523 float sum = 0;
1524 for (i=0; i<nals_ori; i++) sum += call->smpl_grp[j].qsum[i];
1525 if ( sum ) for (i=0; i<nals_ori; i++) call->smpl_grp[j].qsum[i] /= sum;
1526 }
1527
1528 bcf_update_info_int32(call->hdr, rec, "QS", NULL, 0); // remove QS tag
1529
1530 if ( nals_ori > 8*sizeof(call->als_new) )
1531 {
1532 fprintf(bcftools_stderr,"Too many alleles at %s:%"PRId64", skipping.\n", bcf_seqname(call->hdr,rec),(int64_t) rec->pos+1);
1533 return 0;
1534 }
1535
1536 // For each group find the best combination of alleles
1537 call->als_new = 0;
1538 double ref_lk = -HUGE_VAL, lk_sum = -HUGE_VAL, max_qual = -HUGE_VAL;
1539 for (j=0; j<call->nsmpl_grp; j++)
1540 {
1541 smpl_grp_t *grp = &call->smpl_grp[j];
1542 mcall_find_best_alleles(call, nals_ori, grp);
1543 call->als_new |= grp->als;
1544 if ( grp->max_lk==-HUGE_VAL ) continue;
1545 double qual = -4.343*(grp->ref_lk - logsumexp2(grp->lk_sum,grp->ref_lk));
1546 if ( max_qual < qual )
1547 {
1548 max_qual = qual;
1549 lk_sum = grp->lk_sum;
1550 ref_lk = grp->ref_lk;
1551 }
1552 }
1553
1554 // Make sure the REF allele is always present
1555 if ( !(call->als_new&1) ) call->als_new |= 1;
1556
1557 int is_variant = call->als_new==1 ? 0 : 1;
1558 if ( call->flag & CALL_VARONLY && !is_variant ) return 0;
1559
1560 call->nals_new = 0;
1561 for (i=0; i<nals_ori; i++)
1562 {
1563 if ( (call->flag&CALL_KEEP_UNSEEN) && i==unseen && call->nals_new==1 )
1564 {
1565 call->nals_new++;
1566 call->als_new |= 1<<i;
1567 }
1568 if ( i>0 && i==unseen ) continue;
1569 if ( call->flag & CALL_KEEPALT ) call->als_new |= 1<<i;
1570 if ( call->als_new & (1<<i) ) call->nals_new++;
1571 }
1572
1573 init_allele_trimming_maps(call,nals_ori,call->als_new);
1574
1575 int nAC = 0;
1576 if ( call->als_new==1 ) // only REF allele on output
1577 {
1578 mcall_set_ref_genotypes(call,nals_ori);
1579 bcf_update_format_int32(call->hdr, rec, "PL", NULL, 0); // remove PL, useless now
1580 }
1581 else if ( !is_variant )
1582 {
1583 mcall_set_ref_genotypes(call,nals_ori); // running with -A, prevent mcall_call_genotypes from putting some ALT back
1584 mcall_trim_and_update_PLs(call, rec, nals_ori, call->nals_new);
1585 }
1586 else
1587 {
1588 // The most likely set of alleles includes non-reference allele (or was enforced), call genotypes.
1589 // Note that it is a valid outcome if the called genotypes exclude some of the ALTs.
1590 int ngts_new = call->nals_new*(call->nals_new+1)/2;
1591 hts_expand(float,ngts_new*nsmpl,call->nGPs,call->GPs);
1592 for (i=0; i<call->nals_new; i++) call->ac[i] = 0;
1593
1594 if ( call->flag & CALL_CONSTR_TRIO && call->nals_new>4 )
1595 {
1596 fprintf(bcftools_stderr,"Too many alleles at %s:%"PRId64", skipping.\n", bcf_seqname(call->hdr,rec),(int64_t) rec->pos+1);
1597 return 0;
1598 }
1599 if ( call->output_tags & (CALL_FMT_GQ|CALL_FMT_GP) )
1600 {
1601 memset(call->GPs,0,nsmpl*ngts_new*sizeof(*call->GPs));
1602 memset(call->GQs,0,nsmpl*sizeof(*call->GQs));
1603 }
1604 for (i=0; i<call->nsmpl_grp; i++)
1605 {
1606 if ( call->flag & CALL_CONSTR_TRIO )
1607 error("todo: constrained trio calling temporarily disabled\n"); //mcall_call_trio_genotypes(call,rec,nals,&call->smpl_grp[i]);
1608 else
1609 mcall_call_genotypes(call,nals_ori,&call->smpl_grp[i]);
1610 }
1611
1612 // Skip the site if all samples are 0/0. This can happen occasionally.
1613 for (i=1; i<call->nals_new; i++) nAC += call->ac[i];
1614 if ( !nAC && call->flag & CALL_VARONLY ) return 0;
1615
1616 if ( call->output_tags & CALL_FMT_GP )
1617 bcf_update_format_float(call->hdr, rec, "GP", call->GPs, nsmpl*ngts_new);
1618 if ( call->output_tags & CALL_FMT_GQ )
1619 bcf_update_format_int32(call->hdr, rec, "GQ", call->GQs, nsmpl);
1620
1621 mcall_trim_and_update_PLs(call,rec,nals_ori,call->nals_new);
1622 }
1623 if ( nals_ori!=call->nals_new )
1624 mcall_trim_and_update_numberR(call,rec,nals_ori,call->nals_new);
1625
1626 // Set QUAL
1627 if ( nAC )
1628 {
1629 // Quality of a variant site. fabs() to avoid negative zeros in VCF output when CALL_KEEPALT is set
1630 rec->qual = max_qual;
1631 }
1632 else
1633 {
1634 // Set the quality of a REF site
1635 if ( lk_sum!=-HUGE_VAL ) // no support from (high quality) reads, so QUAL=1-prior
1636 rec->qual = -4.343*(lk_sum - logsumexp2(lk_sum,ref_lk));
1637 else if ( call->ac[0] )
1638 rec->qual = call->theta ? -4.343*call->theta : 0;
1639 else
1640 bcf_float_set_missing(rec->qual);
1641 }
1642
1643 // AC, AN
1644 if ( call->nals_new>1 ) bcf_update_info_int32(call->hdr, rec, "AC", call->ac+1, call->nals_new-1);
1645 nAC += call->ac[0];
1646 bcf_update_info_int32(call->hdr, rec, "AN", &nAC, 1);
1647
1648 // Remove unused alleles
1649 hts_expand(char*,call->nals_new,call->nals,call->als);
1650 for (i=0; i<nals_ori; i++)
1651 if ( call->als_map[i]>=0 ) call->als[call->als_map[i]] = rec->d.allele[i];
1652 bcf_update_alleles(call->hdr, rec, (const char**)call->als, call->nals_new);
1653 bcf_update_genotypes(call->hdr, rec, call->gts, nsmpl*2);
1654
1655 // DP4 and PV4 tags
1656 if ( bcf_get_info_float(call->hdr, rec, "I16", &call->anno16, &call->n16)==16 )
1657 {
1658 int32_t dp[4]; dp[0] = call->anno16[0]; dp[1] = call->anno16[1]; dp[2] = call->anno16[2]; dp[3] = call->anno16[3];
1659 bcf_update_info_int32(call->hdr, rec, "DP4", dp, 4);
1660
1661 int32_t mq = (call->anno16[8]+call->anno16[10])/(call->anno16[0]+call->anno16[1]+call->anno16[2]+call->anno16[3]);
1662 bcf_update_info_int32(call->hdr, rec, "MQ", &mq, 1);
1663
1664 if ( call->output_tags & CALL_FMT_PV4 )
1665 {
1666 anno16_t a;
1667 float tmpf[4];
1668 int is_tested = test16(call->anno16, &a) >= 0 && a.is_tested ? 1 : 0;
1669 if ( is_tested )
1670 {
1671 for (i=0; i<4; i++) tmpf[i] = a.p[i];
1672 bcf_update_info_float(call->hdr, rec, "PV4", tmpf, 4);
1673 }
1674 }
1675 }
1676
1677 bcf_update_info_int32(call->hdr, rec, "I16", NULL, 0); // remove I16 tag
1678
1679 return is_variant ? call->nals_new : 1;
1680 }
1681