Debian Codegraph @

samtools/bam_consensus.c

raw symbols SCIP
1 /* bam_consensus.c -- consensus subcommand.
2
3 Copyright (C) 1998-2001,2003 Medical Research Council (Gap4/5 source)
4 Copyright (C) 2003-2005,2007-2024 Genome Research Ltd.
5
6 Author: James Bonfield <[email protected]>
7
8 The primary work here is GRL since 2021, under an MIT license.
9 Sections derived from Gap5, which include calculate_consensus_gap5()
10 associated functions, are mostly copyright Genome Research Limited from
11 2003 onwards. These were originally under a BSD license, but as GRL is
12 copyright holder these portions can be considered to also be under the
13 same MIT license below:
14
15
16 Permission is hereby granted, free of charge, to any person obtaining a copy
17 of this software and associated documentation files (the "Software"), to deal
18 in the Software without restriction, including without limitation the rights
19 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
20 copies of the Software, and to permit persons to whom the Software is
21 furnished to do so, subject to the following conditions:
22
23 The above copyright notice and this permission notice shall be included in
24 all copies or substantial portions of the Software.
25
26 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
27 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
28 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
29 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
30 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
31 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
32 DEALINGS IN THE SOFTWARE. */
33
34 /*
35 * The Gap5 consensus algorithm was in turn derived from the earlier Gap4
36 * tool, developed by the Medical Research Council as part of the
37 * Staden Package. It is unsure how much of this source code is still
38 * extant, without deep review, but the license used was a compatible
39 * modified BSD license, included below.
40 */
41
42 /*
43 Modified BSD license for any legacy components from the Staden Package:
44
45 Copyright (c) 2003 MEDICAL RESEARCH COUNCIL
46 All rights reserved
47
48 Redistribution and use in source and binary forms, with or without
49 modification, are permitted provided that the following conditions are met:
50
51 . Redistributions of source code must retain the above copyright notice,
52 this list of conditions and the following disclaimer.
53
54 . Redistributions in binary form must reproduce the above copyright notice,
55 this list of conditions and the following disclaimer in the documentation
56 and/or other materials provided with the distribution.
57
58 . Neither the name of the MEDICAL RESEARCH COUNCIL, THE LABORATORY OF
59 MOLECULAR BIOLOGY nor the names of its contributors may be used to endorse or
60 promote products derived from this software without specific prior written
61 permission.
62
63 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
64 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
65 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
66 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
67 ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
68 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
69 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
70 ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
71 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
72 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
73 */
74
75
76 // FIXME: also use strand to spot possible basecalling errors.
77 // Specifically het calls where mods are predominantly on one
78 // strand. So maybe require + and - calls and check concordance
79 // before calling a het as confident. (Still call, but low qual?)
80
81 // TODO: call by kmers rather than individual bases? Or use kmers to skew
82 // quality at least. It can identify variants that are low quality due to
83 // neighbouring edits that aren't consistently correlated.
84
85 // TODO: pileup callback ought to know when it's the last in the region /
86 // chromosome. This means the caller code doesn't have to handle the
87 // termination phase and deduplicates the code. (Changing from
88 // one chr to the next is the same as ending the last.)
89 //
90 // TODO: track which reads contribute to multiple confirmed (HQ) differences
91 // vs which contribute to only one (LQ) difference. Correlated changes
92 // are more likely to be real. Ie consensus more of a path than solely
93 // isolated columns.
94 //
95 // Either that or a dummy "end of data" call is made to signify end to
96 // permit tidying up. Maybe add a "start of data" call too?
97
98 // Eg 50T 20A seems T/A het,
99 // but 30T+ 20T- 18A+ 2A- seems like a consistent A miscall on one strand
100 // only, while T is spread evenly across both strands.
101
102 // TODO: Phasing of long reads.
103 // Long reads offer very strong phasing opportunities for SNPs.
104 // From these, we get strong evidence for accuracy of indels.
105 // Specifically whether the distribution of poly-len within a phases
106 // is significantly different to the distribution of poly len between
107 // phases.
108
109 // TODO end STR trimming. Eg:
110 // REF AAGCTGAAAAGTTAATGTCTTATTTTTTTTTTTTTTTTGAGATGGAGTC
111 // aagctgaaaagttaatgtctta****ttttttttttttgagatggagtc
112 // aagctgaaaagttaatgtcttattttttttt
113 // aagctgaaaagttaatgtctta****ttttttttttttgagatggagtc
114 // Middle seq doesn't validate those initial T alignments.
115 // Qual_train solves this by use of the STR trimmer.
116
117 // TODO add a weight for proximity to homopolymer.
118 // Maybe length/distance? So 3 away from a 12-mer is similar to 1 away
119 // from a 4-mer?
120
121 // TODO: Count number of base types between this point and the nearest
122 // indel or end of read. Eg GATCG<here>AGAGAG*TAGC => 2 (A and G).
123 // adj is nbase/4 * score, or (nbase+1)/5?
124 // Perhaps multiplied by length too, to get local complexity score?
125
126 #include <config.h>
127
128 #include <stdio.h>
129 #include <stdlib.h>
130 #include <strings.h>
131 #include <math.h>
132 #include <limits.h>
133 #include <float.h>
134 #include <ctype.h>
135
136 #include <htslib/sam.h>
137 #include <htslib/hfile.h>
138
139 #include "samtools.h"
140 #include "sam_opts.h"
141 #include "bam_plbuf.h"
142 #include "consensus_pileup.h"
143
144 #ifdef __SSE__
145 # include <xmmintrin.h>
146 #else
147 # define _mm_prefetch(a,b)
148 #endif
149
150 #ifndef MIN
151 # define MIN(a,b) ((a)<(b)?(a):(b))
152 #endif
153 #ifndef MAX
154 # define MAX(a,b) ((a)>(b)?(a):(b))
155 #endif
156
157 // Defines for experiment code which is currently disabled
158
159 // Hardy-Weinberg statistics to check heterozygous sites match allelic
160 // frequencies.
161 //#define DO_HDW
162
163 // Filter bayesian calls by min-depth and min-fract parameters
164 //#define DO_FRACT
165
166 // Checks uniqueness of surrounding bases to adjust scores
167 //#define K2 2
168
169 // Look for strand bias in distribution of homopolymer lengths
170 //#define DO_POLY_DIST
171
172 // Minimum cutoff for storing mod data; => at least 10% chance
173 #define MOD_CUTOFF 0.46
174
175 enum format {
176 FASTQ,
177 FASTA,
178 PILEUP
179 };
180
181 typedef unsigned char uc;
182
183 // Simple recalibration table for substitutions, undercalls and overcalls.
184 // In future, we'll update this to be kmer based too.
185 typedef struct {
186 int smap[101]; // substituion or SNP
187 int umap[101]; // undercall or DEL
188 int omap[101]; // overcall or INS
189 } qcal_t;
190
191 typedef struct {
192 // User options
193 char *reg;
194 int use_qual;
195 int min_qual;
196 int adj_qual;
197 int use_mqual;
198 double scale_mqual;
199 int nm_adjust;
200 int nm_halo;
201 int sc_cost;
202 int low_mqual;
203 int high_mqual;
204 int min_depth;
205 double call_fract;
206 double het_fract;
207 int mode; // One of MODE_* macros below
208 enum format fmt;
209 int cons_cutoff;
210 int ambig;
211 int line_len;
212 int default_qual;
213 int het_only;
214 int all_bases;
215 int show_del;
216 int show_ins;
217 int mark_ins;
218 int excl_flags;
219 int incl_flags;
220 int min_mqual;
221 double P_het;
222 double P_indel;
223 double het_scale;
224 double homopoly_fix;
225 double homopoly_redux;
226 qcal_t qcal;
227
228 // Internal state
229 samFile *fp;
230 FILE *fp_out;
231 sam_hdr_t *h;
232 hts_idx_t *idx;
233 hts_itr_t *iter;
234 kstring_t ks_line;
235 kstring_t ks_ins_seq;
236 kstring_t ks_ins_qual;
237 int last_tid;
238 hts_pos_t last_pos;
239 } consensus_opts;
240
241 /* --------------------------------------------------------------------------
242 * A bayesian consensus algorithm that analyses the data to work out
243 * which hypothesis of pure A/C/G/T/absent and all combinations of two
244 * such bases meets the observations.
245 *
246 * This has its origins in Gap4 (homozygous) -> Gap5 (heterozygous)
247 * -> Crumble (tidied up to use htslib's pileup) -> here.
248 *
249 */
250
251 #define CONS_DISCREP 4
252 #define CONS_ALL 15
253
254 #define CONS_MQUAL 16
255
256 typedef struct {
257 /* the most likely base call - we never call N here */
258 /* A=0, C=1, G=2, T=3, *=4 */
259 int call;
260
261 /* The most likely heterozygous base call */
262 /* Use "ACGT*"[het / 5] vs "ACGT*"[het % 5] for the combination */
263 int het_call;
264
265 /* Log-odds for het_call */
266 int het_logodd;
267
268 /* Single phred style call */
269 int phred;
270
271 /* Sequence depth */
272 int depth;
273
274 /* Discrepancy search score */
275 float discrep;
276 } consensus_t;
277
278 #define P_HET 1e-3
279 #define P_INDEL 2e-4
280 #define P_HOMOPOLY 0.5
281 #define P_HET_SCALE 1.0
282
283 #define LOG10 2.30258509299404568401
284 #define TENOVERLOG10 4.34294481903251827652
285 #define TENLOG2OVERLOG10 3.0103
286
287 #ifdef __GNUC__
288 #define ALIGNED(x) __attribute((aligned(x)))
289 #else
290 #define ALIGNED(x)
291 #endif
292
293 // Initialised once as a global array. This won't work if threaded,
294 // but we'll rewrite if and when that gets added later.
295 static double e_tab_a[1002] ALIGNED(16);
296 static double *e_tab = &e_tab_a[500];
297 static double e_tab2_a[1002] ALIGNED(16);
298 static double *e_tab2 = &e_tab2_a[500];
299 static double e_log[501] ALIGNED(16);
300
301 /* Precomputed matrices for the consensus algorithm */
302 typedef struct {
303 double prior[25] ALIGNED(16); /* Sum to 1.0 */
304 double lprior15[15] ALIGNED(16); /* 15 combinations of {ACGT*} */
305
306 double pMM[101] ALIGNED(16);
307 double p__[101] ALIGNED(16);
308 double p_M[101] ALIGNED(16);
309 double po_[101] ALIGNED(16);
310 double poM[101] ALIGNED(16);
311 double poo[101] ALIGNED(16);
312 double puu[101] ALIGNED(16);
313 double pum[101] ALIGNED(16);
314 double pmm[101] ALIGNED(16);
315
316 // Multiplier on homopolymer length before reducing phred qual
317 double poly_mul;
318 } cons_probs;
319
320 // Two sets of params; recall oriented (gap5) and precision (stf).
321 // We use the former unless MODE_MIXED is set (which is the default
322 // for bayesian consensus mode if P_indel is significant).
323 static cons_probs cons_prob_recall, cons_prob_precise;
324
325 /*
326 * Lots of confusing matrix terms here, so some definitions will help.
327 *
328 * M = match base
329 * m = match pad
330 * _ = mismatch
331 * o = overcall
332 * u = undercall
333 *
334 * We need to distinguish between homozygous columns and heterozygous columns,
335 * done using a flat prior. This is implemented by treating every observation
336 * as coming from one of two alleles, giving us a 2D matrix of possibilities
337 * (the hypotheses) for each and every call (the observation).
338 *
339 * So pMM[] is the chance that given a call 'x' that it came from the
340 * x/x allele combination. Similarly p_o[] is the chance that call
341 * 'x' came from a mismatch (non-x) / overcall (consensus=*) combination.
342 *
343 * Examples with observation (call) C and * follows
344 *
345 * C | A C G T * * | A C G T *
346 * ----------------- -----------------
347 * A | __ _M __ __ o_ A | uu uu uu uu um
348 * C | _M MM _M _M oM C | uu uu uu uu um
349 * G | __ _M __ __ o_ G | uu uu uu uu um
350 * T | __ _M __ __ o_ T | uu uu uu uu um
351 * * | o_ oM o_ o_ oo * | um um um um mm
352 *
353 * In calculation terms, the _M is half __ and half MM, similarly o_ and um.
354 *
355 * Relative weights of substitution vs overcall vs undercall are governed on a
356 * per base basis using the P_OVER and P_UNDER scores (subst is
357 * 1-P_OVER-P_UNDER).
358 *
359 * The heterozygosity weight though is a per column calculation as we're
360 * trying to model whether the column is pure or mixed. Hence this is done
361 * once via a prior and has no affect on the individual matrix cells.
362 *
363 * We have a generic indel probability, but it's a catch all for overcall,
364 * undercall, alignment artifacts, homopolymer issues, etc. So we can set
365 * it considerably higher and just let the QUAL skew do the filtering for
366 * us, albeit no longer well calibrated.
367 */
368
369 // NB: Should _M be MM?
370 // Ie sample really is A/C het, and we observe C. That should be a match,
371 // not half a match.
372
373 #define MODE_SIMPLE 0 // freq counting
374
375 #define MODE_BAYES_116 1 // Samtools 1.16 (no indel param)
376 #define MODE_RECALL 2 // so called as it's the params from Gap5
377 #define MODE_PRECISE 3 // a more precise set; +FN, --FP
378 #define MODE_MIXED 4 // Combination of GAP5/BAYES
379
380 #define QCAL_FLAT 0
381 #define QCAL_HIFI 1
382 #define QCAL_HISEQ 2
383 #define QCAL_ONT_R10_4_SUP 3
384 #define QCAL_ONT_R10_4_DUP 4
385 #define QCAL_ULTIMA 5
386
387 // Calibration tables here don't necessarily reflect the true accuracy.
388 // They have been manually tuned to work in conjunction with other command
389 // line parameters used in the machine profiles. For example reducing one
390 // qual here and increasing sensitivity elsewhere via another parameter.
391 static qcal_t static_qcal[6] = {
392 { // FLAT
393 {0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
394 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
395 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
396 30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
397 40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
398 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
399 60, 61, 62, 63, 64, 65, 66, 67, 68, 69,
400 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
401 80, 81, 82, 83, 84, 85, 86, 87, 88, 89,
402 90, 91, 92, 93, 94, 95, 96, 97, 98, 99},
403 {0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
404 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
405 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
406 30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
407 40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
408 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
409 60, 61, 62, 63, 64, 65, 66, 67, 68, 69,
410 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
411 80, 81, 82, 83, 84, 85, 86, 87, 88, 89,
412 90, 91, 92, 93, 94, 95, 96, 97, 98, 99},
413 {0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
414 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
415 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
416 30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
417 40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
418 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
419 60, 61, 62, 63, 64, 65, 66, 67, 68, 69,
420 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
421 80, 81, 82, 83, 84, 85, 86, 87, 88, 89,
422 90, 91, 92, 93, 94, 95, 96, 97, 98, 99}
423 },
424
425 { // HiFi
426 {10, 11, 11, 12, 13, 14, 15, 16, 18, 19,
427 20, 21, 22, 23, 24, 25, 27, 28, 29, 30,
428 31, 32, 33, 33, 34, 35, 36, 36, 37, 38,
429 38, 39, 39, 40, 40, 41, 41, 41, 41, 42,
430 42, 42, 42, 43, 43, 43, 43, 43, 43, 43,
431 44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
432 44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
433 44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
434 44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
435 44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
436 },
437 { 4, 4, 4, 4, 5, 6, 6, 7, 8, 9,
438 10, 11, 11, 12, 13, 14, 15, 15, 16, 17,
439 18, 19, 19, 20, 20, 21, 22, 23, 23, 24,
440 25, 25, 25, 26, 26, 26, 27, 27, 28, 28,
441 28, 28, 27, 27, 27, 28, 28, 28, 28, 27,
442 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
443 27, 27, 26, 26, 25, 26, 26, 27, 27, 27,
444 26, 26, 26, 26, 26, 26, 26, 26, 27, 27,
445 28, 29, 28, 28, 28, 27, 27, 27, 27, 27,
446 27, 28, 28, 30, 30, 30, 30, 30, 30, 30,
447 },
448 { 8, 8, 8, 8, 9, 10, 11, 12, 13, 14,
449 15, 15, 16, 17, 18, 19, 19, 20, 20, 21,
450 21, 22, 22, 23, 23, 23, 24, 24, 24, 25,
451 25, 25, 25, 25, 25, 26, 26, 26, 26, 27,
452 27, 27, 27, 27, 27, 28, 28, 28, 28, 28,
453 29, 29, 29, 29, 29, 29, 30, 30, 30, 30,
454 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
455 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
456 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
457 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
458 }
459 },
460
461 { // HiSeq
462 { 2, 2, 2, 3, 3, 4, 5, 5, 6, 7,
463 8, 9, 10, 11, 11, 12, 13, 14, 15, 16,
464 17, 17, 18, 19, 20, 21, 22, 22, 23, 24,
465 25, 26, 27, 28, 28, 29, 30, 31, 32, 33,
466 34, 34, 35, 36, 37, 38, 39, 39, 40, 41,
467 42, 43, 44, 45, 45, 46, 47, 48, 49, 50,
468 51, 51, 52, 53, 54, 55, 56, 56, 57, 58,
469 59, 60, 61, 62, 62, 63, 64, 65, 66, 67,
470 68, 68, 69, 70, 71, 72, 73, 73, 74, 75,
471 76, 77, 78, 79, 79, 80, 81, 82, 83, 84,
472 },
473 { 1, 2, 3, 4, 5, 7, 8, 9, 10, 11,
474 13, 14, 15, 16, 17, 19, 20, 21, 22, 23,
475 25, 26, 27, 28, 29, 31, 32, 33, 34, 35,
476 37, 38, 39, 40, 41, 43, 44, 45, 46, 47,
477 49, 50, 51, 52, 53, 55, 56, 57, 58, 59,
478 61, 62, 63, 64, 65, 67, 68, 69, 70, 71,
479 73, 74, 75, 76, 77, 79, 80, 81, 82, 83,
480 85, 86, 87, 88, 89, 91, 92, 93, 94, 95,
481 97, 98, 99, 100, 101, 103, 104, 105, 106, 107,
482 109, 110, 111, 112, 113, 115, 116, 117, 118, 119,
483 },
484 { 1, 2, 3, 4, 5, 7, 8, 9, 10, 11,
485 13, 14, 15, 16, 17, 19, 20, 21, 22, 23,
486 25, 26, 27, 28, 29, 31, 32, 33, 34, 35,
487 37, 38, 39, 40, 41, 43, 44, 45, 46, 47,
488 49, 50, 51, 52, 53, 55, 56, 57, 58, 59,
489 61, 62, 63, 64, 65, 67, 68, 69, 70, 71,
490 73, 74, 75, 76, 77, 79, 80, 81, 82, 83,
491 85, 86, 87, 88, 89, 91, 92, 93, 94, 95,
492 97, 98, 99, 100, 101, 103, 104, 105, 106, 107,
493 109, 110, 111, 112, 113, 115, 116, 117, 118, 119,
494 }
495 },
496 { // ONT R10.4 super
497 { 0, 2, 2, 2, 3, 4, 4, 5, 6, 7,
498 7, 8, 9, 12, 13, 14, 15, 15, 16, 17,
499 18, 19, 20, 22, 24, 25, 26, 27, 28, 29,
500 30, 31, 33, 34, 36, 37, 38, 38, 39, 39,
501 40, 40, 40, 40, 40, 40, 40, 41, 40, 40,
502 41, 41, 40, 40, 40, 40, 41, 40, 40, 40,
503 40, 41, 41, 40, 40, 41, 40, 40, 39, 41,
504 40, 41, 40, 40, 41, 41, 41, 40, 40, 40,
505 40, 40, 40, 40, 40, 40, 40, 40, 40, 40,
506 40, 40, 40, 40, 40, 40, 40, 40, 40, 40,
507 },
508 { 0, 2, 2, 2, 3, 4, 5, 6, 7, 8,
509 8, 9, 9, 10, 10, 10, 11, 12, 12, 13,
510 13, 13, 14, 14, 15, 16, 16, 17, 18, 18,
511 19, 19, 20, 21, 22, 23, 24, 25, 25, 25,
512 25, 25, 25, 25, 25, 25, 26, 26, 26, 26,
513 26, 26, 26, 26, 27, 27, 27, 27, 27, 27,
514 27, 27, 27, 27, 27, 27, 27, 28, 28, 28,
515 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
516 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
517 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
518 },
519 { 0, 4, 6, 6, 6, 7, 7, 8, 9, 9,
520 9, 10, 10, 11, 11, 12, 12, 13, 13, 14,
521 15, 15, 15, 16, 16, 17, 17, 18, 18, 19,
522 19, 20, 20, 21, 22, 22, 23, 23, 24, 24,
523 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
524 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
525 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
526 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
527 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
528 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
529 }
530 },
531 { // ONT R10.4 duplex; just a copy of hifi for now
532 {10, 11, 11, 12, 13, 14, 15, 16, 18, 19,
533 20, 21, 22, 23, 24, 25, 27, 28, 29, 30,
534 31, 32, 33, 33, 34, 35, 36, 36, 37, 38,
535 38, 39, 39, 40, 40, 41, 41, 41, 41, 42,
536 42, 42, 42, 43, 43, 43, 43, 43, 43, 43,
537 44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
538 44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
539 44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
540 44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
541 44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
542 },
543 { 4, 4, 4, 4, 5, 6, 6, 7, 8, 9,
544 10, 11, 11, 12, 13, 14, 15, 15, 16, 17,
545 18, 19, 19, 20, 20, 21, 22, 23, 23, 24,
546 25, 25, 25, 26, 26, 26, 27, 27, 28, 28,
547 28, 28, 27, 27, 27, 28, 28, 28, 28, 27,
548 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
549 27, 27, 26, 26, 25, 26, 26, 27, 27, 27,
550 26, 26, 26, 26, 26, 26, 26, 26, 27, 27,
551 28, 29, 28, 28, 28, 27, 27, 27, 27, 27,
552 27, 28, 28, 30, 30, 30, 30, 30, 30, 30,
553 },
554 { 8, 8, 8, 8, 9, 10, 11, 12, 13, 14,
555 15, 15, 16, 17, 18, 19, 19, 20, 20, 21,
556 21, 22, 22, 23, 23, 23, 24, 24, 24, 25,
557 25, 25, 25, 25, 25, 26, 26, 26, 26, 27,
558 27, 27, 27, 27, 27, 28, 28, 28, 28, 28,
559 29, 29, 29, 29, 29, 29, 30, 30, 30, 30,
560 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
561 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
562 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
563 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
564 }
565 },
566 { // Ultima Genomics
567 { 2, 2, 3, 4, 5, 6, 6, 7, 8, 9,
568 10, 10, 11, 12, 13, 14, 14, 15, 16, 17,
569 18, 18, 19, 21, 22, 23, 23, 24, 25, 26,
570 27, 27, 28, 29, 30, 31, 31, 32, 33, 34,
571 35, 35, 36, 37, 38, 39, 39, 40, 42, 43,
572 44, 44, 45, 46, 47, 48, 48, 49, 50, 51,
573 52, 52, 53, 54, 55, 56, 56, 57, 58, 59,
574 60, 60, 61, 63, 64, 65, 65, 66, 67, 68,
575 69, 69, 70, 71, 72, 73, 73, 74, 75, 76,
576 77, 77, 78, 79, 80, 81, 81, 82, 84, 85,
577 },
578 { 1, 1, 2, 2, 3, 3, 4, 4, 4, 4,
579 5, 5, 6, 6, 7, 7, 8, 8, 9, 10,
580 10, 10, 11, 12, 13, 13, 13, 14, 15, 16,
581 16, 16, 17, 18, 18, 19, 19, 20, 20, 21,
582 21, 22, 22, 22, 22, 23, 23, 24, 24, 25,
583 25, 25, 25, 25, 25, 25, 26, 26, 26, 26,
584 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
585 27, 28, 28, 28, 28, 28, 28, 28, 28, 28,
586 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
587 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
588 },
589 { 1, 1, 2, 2, 3, 3, 4, 4, 4, 4,
590 5, 5, 6, 6, 7, 7, 8, 8, 9, 10,
591 10, 10, 11, 12, 13, 13, 13, 14, 15, 16,
592 16, 16, 17, 18, 18, 19, 19, 20, 20, 21,
593 21, 22, 22, 22, 22, 23, 23, 24, 24, 25,
594 25, 25, 25, 25, 25, 25, 26, 26, 26, 26,
595 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
596 27, 28, 28, 28, 28, 28, 28, 28, 28, 28,
597 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
598 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
599 }
600 }
601 };
602
603 int set_qcal(qcal_t *q, int id) {
604 if (id < 0 || id >= sizeof(static_qcal)/sizeof(*static_qcal))
605 return -1;
606
607 memcpy(q, &static_qcal[id], sizeof(*q));
608 return 0;
609 }
610
611 int load_qcal(qcal_t *q, const char *fn) {
612 int i;
613
614 if (strcmp(fn, ":hifi") == 0)
615 return set_qcal(q, QCAL_HIFI);
616 if (strcmp(fn, ":hiseq") == 0)
617 return set_qcal(q, QCAL_HISEQ);
618 if (strcmp(fn, ":r10.4_sup") == 0)
619 return set_qcal(q, QCAL_ONT_R10_4_SUP);
620 if (strcmp(fn, ":r10.4_dup") == 0)
621 return set_qcal(q, QCAL_ONT_R10_4_DUP);
622 if (strcmp(fn, ":ultima") == 0)
623 return set_qcal(q, QCAL_ULTIMA);
624
625 // default
626 for (i = 0; i < 101; i++)
627 q->smap[i] = q->umap[i] = q->omap[i] = i;
628
629 if (strcmp(fn, ":flat") == 0)
630 return 0;
631
632 hFILE *fp = hopen(fn, "r");
633 if (!fp)
634 return -1;
635
636 kstring_t line = KS_INITIALIZE;
637 int max = 0;
638 int last_qual = 0;
639 while (line.l = 0, kgetline(&line, (kgets_func *)hgets, fp) >= 0) {
640 int v, s, u, o;
641 if (*line.s == '#')
642 continue;
643 if (sscanf(line.s, "QUAL %d %d %d %d", &v, &s, &u, &o) != 4)
644 goto err;
645 while (v > last_qual) {
646 q->smap[last_qual+1] = q->smap[last_qual];
647 q->umap[last_qual+1] = q->umap[last_qual];
648 q->omap[last_qual+1] = q->omap[last_qual];
649 last_qual++;
650 }
651 if (v >= 0 && v < 100) {
652 q->smap[v] = s;
653 q->umap[v] = u;
654 q->omap[v] = o;
655 }
656 if (v < max) {
657 fprintf(stderr, "Qual calibration file is not in ascending order\n");
658 return hclose(fp) ? -2 : -1;
659 }
660 max = v;
661 }
662
663 for (i = max+1; i < 101; i++) {
664 q->smap[i] = q->smap[max];
665 q->umap[i] = q->umap[max];
666 q->omap[i] = q->omap[max];
667 }
668
669 ks_free(&line);
670 return hclose(fp) < 0 ? -2 : 0;
671
672 err:
673 ks_free(&line);
674 return hclose(fp) < 0 ? -2 : -1;
675 }
676
677 static void consensus_init(double p_het, double p_indel, double het_scale,
678 double poly_mul,
679 qcal_t *qcal, int mode, cons_probs *cp) {
680 int i;
681
682 // NB: only need to initialise once, but we do here for now
683 for (i = -500; i <= 500; i++)
684 e_tab[i] = exp(i);
685 for (i = -500; i <= 500; i++)
686 e_tab2[i] = exp(i/10.);
687 for (i = 0; i <= 500; i++)
688 e_log[i] = log(i);
689
690 // EXPERIMENTAL
691 cp->poly_mul = poly_mul;
692
693 // The priors make very little difference, unless shallow data.
694 // ACGT* by ACGT*
695 // So AA=0, CC=6, GG=12, TT=18, **=24
696 for (i = 0; i < 25; i++)
697 cp->prior[i] = p_het / 6; // AC AG AT CG CT GT
698
699 // Flat assumption that it is what we observe, and measure everything else
700 // as relative to this.
701 cp->prior[0]=cp->prior[6]=cp->prior[12]=cp->prior[18]=cp->prior[24] = 1;
702
703 // heterozygous deletion
704 for (i = 4; i < 24; i+=5)
705 cp->prior[i] = p_indel / 6; // /6 to be scaled vs p_het equivalently
706
707 // heterozygous insertion
708 for (i = 20; i < 24; i++)
709 cp->prior[i] = p_indel / 6;
710
711 cp->lprior15[0] = log(cp->prior[0]);
712 cp->lprior15[1] = log(cp->prior[1]);
713 cp->lprior15[2] = log(cp->prior[2]);
714 cp->lprior15[3] = log(cp->prior[3]);
715 cp->lprior15[4] = log(cp->prior[4]);
716 cp->lprior15[5] = log(cp->prior[6]);
717 cp->lprior15[6] = log(cp->prior[7]);
718 cp->lprior15[7] = log(cp->prior[8]);
719 cp->lprior15[8] = log(cp->prior[9]);
720 cp->lprior15[9] = log(cp->prior[12]);
721 cp->lprior15[10] = log(cp->prior[13]);
722 cp->lprior15[11] = log(cp->prior[14]);
723 cp->lprior15[12] = log(cp->prior[18]);
724 cp->lprior15[13] = log(cp->prior[19]);
725 cp->lprior15[14] = log(cp->prior[24]);
726
727 for (i = 1; i < 101; i++) {
728 double prob = 1 - pow(10, -qcal->smap[i] / 10.0);
729
730 // Or is it that prob is 1-p(subst)-p(overcall)?
731 cp->pMM[i] = log(prob);
732
733 //cp->p__[i] = log(1-prob); // Big help to PB-CCS SNPs; unless fudged
734 cp->p__[i] = log((1-prob)/3); // correct? poor on PB-CCS w/o fudge
735
736 // Mixed alleles; just average two likelihoods
737 cp->p_M[i] = log((exp(cp->pMM[i]) + exp(cp->p__[i]))/2);
738
739 // What does this really mean? Can we simulate this by priors?
740 // It reduces the likelihood of calling het sites, which is
741 // maybe compensation for alignment artifacts? I'm unsure,
742 // but it works (to differing degrees) on both PacBio HiFi and
743 // Illumina HiSeq. It (obviously) loses true hets, but
744 // potentially this can be compensated for by tweaking P-het
745 // (which is entirely in the priors).
746 //
747 // Low het_scale reduces false positives by making hets less
748 // likely to be called. In high depth data we normally have
749 // enough evidence to call correctly even with low het_scale,
750 // so it's a good +FN vs --FP tradeoff. However on low depth
751 // data, het_scale can filter out too many true variants.
752 //
753 // TODO: So consider adjusting at the end maybe?
754 // Also consider never changing calls, but changing their
755 // confidence, so the data is what produces the call with the
756 // parameters skewing the quality score distribution.
757 cp->p_M[i] += log(het_scale);
758
759 if (mode == MODE_BAYES_116) {
760 // Compatibility with samtools 1.16
761
762 // This had no differention for indel vs substitution error rates,
763 // so o(vercall) and u(undercall) are subst(_).
764 cp->pmm[i] = cp->pMM[i];
765 cp->poM[i] = cp->p_M[i];
766 cp->pum[i] = cp->p_M[i];
767 cp->po_[i] = cp->p__[i];
768 cp->poo[i] = cp->p__[i];
769 cp->puu[i] = cp->p__[i];
770
771 } else {
772 // When observing A C G T; leads to insertion calls
773 prob = 1 - pow(10, -qcal->omap[i] / 10.0);
774 // /3 for consistency with ACGT rem as relative likelihoods.
775 // Otherwise with flat priors we end up calling all shallow data
776 // as "*", which is illogical.
777 cp->poo[i] = log((1-prob)/3);
778
779 // Ensure pMM is always more likely. (NB: This shouldn't happen
780 // now with the addition of the /3 step above.)
781 if (cp->poo[i] > cp->pMM[i]-.5)
782 cp->poo[i] = cp->pMM[i]-.5;
783
784 cp->po_[i] = log((exp(cp->poo[i]) + exp(cp->p__[i]))/2);
785 cp->poM[i] = log((exp(cp->poo[i]) + exp(cp->pMM[i]))/2);
786
787 // Overcalls should never be twice as likely than mismatches.
788 // Het bases are mix of _M (other) and MM ops (this).
789 // It's fine for _M to be less likely than oM (more likely
790 // to be overcalled than miscalled), but it should never
791 // be stronger when combined with other mixed data.
792 if (cp->poM[i] > cp->p_M[i]+.5)
793 cp->poM[i] = cp->p_M[i]+.5;
794
795 // Note --low-MQ and --scale-MQ have a big impact on
796 // undercall errs. May need to separate these options per
797 // type, but how?
798 // Multiple-calls, as with mixed mode? This feels like a cheat
799
800 prob = 1 - pow(10, -qcal->umap[i] / 10.0);
801 cp->pmm[i] = log(prob);
802 cp->puu[i] = log((1-prob)/3);
803 if (cp->puu[i] > cp->pMM[i]-.5) // MM is -ve
804 cp->puu[i] = cp->pMM[i]-.5;
805
806 cp->pum[i] = log((exp(cp->puu[i]) + exp(cp->pmm[i]))/2);
807 }
808 }
809
810 cp->pMM[0] = cp->pMM[1];
811 cp->p__[0] = cp->p__[1];
812 cp->p_M[0] = cp->p_M[1];
813
814 cp->pmm[0] = cp->pmm[1];
815 cp->poo[0] = cp->poo[1];
816 cp->po_[0] = cp->po_[1];
817 cp->poM[0] = cp->poM[1];
818 cp->puu[0] = cp->puu[1];
819 cp->pum[0] = cp->pum[1];
820 }
821
822 static inline double fast_exp(double y) {
823 if (y >= -50 && y <= 50)
824 return e_tab2[(int)(y*10)];
825
826 if (y < -500)
827 y = -500;
828 if (y > 500)
829 y = 500;
830
831 return e_tab[(int)y];
832 }
833
834 /* Taylor (deg 3) implementation of the log */
835 static inline double fast_log2(double val)
836 {
837 // FP representation is exponent & mantissa, where
838 // value = 2^E * M.
839 // Hence log2(value) = log2(2^E * M)
840 // = log2(2^E)+ log2(M)
841 // = E + log2(M)
842 union { double d; uint64_t x; } u = {val};
843 const int E = ((u.x >> 52) & 2047) - 1024; // exponent E
844 // Initial log2(M) based on mantissa
845 u.x &= ~(2047LL << 52);
846 u.x += 1023LL << 52;
847
848 val = ((-1/3.) * u.d + 2) * u.d - 2/3.;
849
850 return E + val;
851 }
852
853 #define ph_log(x) (-TENLOG2OVERLOG10*fast_log2((x)))
854
855
856 int nins(const bam1_t *b){
857 int i, indel = 0;
858 uint32_t *cig = bam_get_cigar(b);
859 for (i = 0; i < b->core.n_cigar; i++) {
860 int op = bam_cigar_op(cig[i]);
861 if (op == BAM_CINS || op == BAM_CDEL)
862 indel += bam_cigar_oplen(cig[i]);
863 }
864 return indel;
865 }
866
867 /*
868 * Some machines, including 454 and PacBio, store the quality values in
869 * homopolymers with the first or last base always being the low quality
870 * state. This can cause problems when reverse-complementing and aligning,
871 * especially when we left-justify indels.
872 *
873 * Other platforms take the approach of having the middle bases high and
874 * the low confidence spread evenly to both start and end. This means
875 * reverse-complementing doesn't introduce any strand bias.
876 *
877 * We redistribute qualities within homopolymers in this style to fix
878 * naive consensus or variant calling algorithms.
879 */
880 void homopoly_qual_fix(bam1_t *b) {
881 static double ph2err[256] = {0};
882 int i;
883 if (!ph2err[0]) {
884 for (i = 0; i < 256; i++)
885 ph2err[i] = pow(10, i/-10.0);
886 }
887 uint8_t *seq = bam_get_seq(b);
888 uint8_t *qual = bam_get_qual(b);
889 for (i = 0; i < b->core.l_qseq; i++) {
890 int s = i; // start of homopoly
891 int base = bam_seqi(seq, i);
892 while (i+1 < b->core.l_qseq && bam_seqi(seq, i+1) == base)
893 i++;
894 // s..i inclusive is now homopolymer
895
896 if (s == i)
897 continue;
898
899 // Simplest: reverse if end_qual < start_qual
900 // Next: average outer-most two, then next two, etc
901 // Best: fully redistribute so start/end lower qual than centre
902
903 // Middle route of averaging outer pairs is sufficient?
904 int j, k;
905 for (j = s, k = i; j < k; j++,k--) {
906 double e = ph2err[qual[j]] + ph2err[qual[k]];
907 qual[j] = qual[k] = -fast_log2(e/2)*3.0104+.49;
908 }
909 }
910 }
911
912 // Return the local NM figure within halo (+/- HALO) of pos.
913 // This local NM is used as a way to modify MAPQ to get a localised MAPQ
914 // score via an adhoc fashion.
915 double nm_local(const pileup_t *p, const bam1_t *b, hts_pos_t pos) {
916 int *nm = (int *)p->cd;
917 if (!nm)
918 return 0;
919 pos -= b->core.pos;
920 if (pos < 0)
921 return nm[0] & ((1<<24)-1);
922 if (pos >= b->core.l_qseq)
923 return nm[b->core.l_qseq-1] & ((1<<24)-1);
924
925 return (nm[pos] & ((1<<24)-1)) / 10.0;
926 }
927
928 int poly_len(const pileup_t *p, const bam1_t *b, hts_pos_t pos) {
929 int *nm = (int *)p->cd;
930 if (!nm)
931 return 0;
932 pos -= b->core.pos;
933 if (pos >= 0 && pos < b->core.l_qseq)
934 return nm[pos] >> 24;
935 else
936 return 0;
937 }
938
939 /*
940 * Initialise a new sequence appearing in the pileup. We use this to
941 * precompute some metrics that we'll repeatedly use in the consensus
942 * caller; the localised NM score.
943 *
944 * We also directly amend the BAM record (which will be discarded later
945 * anyway) to modify qualities to account for local quality minima.
946 *
947 * Returns 0 (discard) or 1 (keep) on success, -1 on failure.
948 */
949 int nm_init(void *client_data, samFile *fp, sam_hdr_t *h, pileup_t *p) {
950 consensus_opts *opts = (consensus_opts *)client_data;
951 if (!opts->use_mqual)
952 return 1;
953
954 const bam1_t *b = &p->b;
955 int qlen = b->core.l_qseq, i;
956 if (qlen <= 0)
957 return 0;
958 int *local_nm = calloc(qlen, sizeof(*local_nm));
959 if (!local_nm)
960 return -1;
961 p->cd = local_nm;
962
963 double poly_adj = opts->homopoly_fix ? opts->homopoly_fix : 1;
964
965 if (opts->adj_qual) {
966 // Set local_nm based on a function of current qual and the local
967 // minimum qual within the surrounding window.
968 //
969 // Basically if we're in a region of low confidence then we downgrade
970 // higher qual outliers as they may not be as trustworthy as they
971 // claim. This may be because the qualities have been assigned to
972 // the wrong or arbitrary base (very common in homopolymers), or the
973 // surrounding quality (hence also error likelihood) have lead to
974 // misalignments and the base may be contributing to the wrong
975 // pileup column.
976 //
977 // The nm_local() function returns these scores and uses it to bias
978 // the mapping quality, which in turn adjusts base quality.
979 uint8_t *qual = bam_get_qual(b);
980 uint8_t *seq = bam_get_seq(b);
981 const int qhalo = 8; // window size for base qual
982 int qmin = qual[0]; // min qual within qhalo
983 const int qhalop = 2;// window size for homopolymer qual
984 int qminp = qual[0]; // min qual within homopolymer halo
985 int base = bam_seqi(seq, 0), polyl = 0, polyr = 0; // pos, not len
986
987 // Minimum quality of the initial homopolymer
988 for (i = 1; i < qlen; i++) {
989 if (bam_seqi(seq, i) != base)
990 break;
991 if (i < qhalop && qminp > qual[i])
992 qminp = qual[i];
993 }
994
995 // Minimum quality for general bases
996 for (i = 0; i < qlen && i < qhalo; i++) {
997 if (qmin > qual[i])
998 qmin = qual[i];
999 }
1000
1001 for (;i < qlen-qhalo; i++) {
1002 if (opts->homopoly_fix && bam_seqi(seq, i) != base) {
1003 polyl = i;
1004 base = bam_seqi(seq, i);
1005 qminp = qual[i];
1006 int j;
1007 for (j = i+1; j < qlen; j++) {
1008 if (bam_seqi(seq, j) != base)
1009 break;
1010 if (i < qhalop && qminp > qual[j])
1011 qminp = qual[j];
1012 }
1013 polyr = j-1;
1014 } else {
1015 // CHECK: do we want to have opts->homopoly_fix above,
1016 // so when not in use we don't define pl to non-zero?
1017 // Test on SynDip
1018 polyr = polyl;
1019 }
1020 int pl = polyr-polyl;
1021
1022 // Useful for SNPS, as we're judging the variation in
1023 // length as an indicator for base-misalignment.
1024 // Not so useful for indel calling where the longer the indel
1025 // the less confident we are on the len variation being real.
1026 int t = (opts->mode == MODE_BAYES_116)
1027 ? (qual[i] + 5*qmin)/4
1028 : qual[i]/3 + (qminp-pl*2)*poly_adj;
1029
1030
1031 local_nm[i] += t < qual[i] ? qual[i]-t : 0;
1032
1033 // Brute force qminp in polyl to polyr range.
1034 // TODO: optimise this with sliding window
1035 qminp = qual[i];
1036 int k;
1037 for (k = MAX(polyl,i-qhalop); k <= MIN(polyr,i+qhalop); k++)
1038 if (qminp > qual[k])
1039 qminp = qual[k];
1040
1041 if (qmin > qual[i+qhalo])
1042 qmin = qual[i+qhalo];
1043 else if (qmin <= qual[i-qhalo]) {
1044 int j;
1045 qmin = 99;
1046 for (j = i-qhalo+1; j <= i+qhalo; j++)
1047 if (qmin > qual[j])
1048 qmin = qual[j];
1049 }
1050 }
1051 for (; i < qlen; i++) {
1052 int t = (opts->mode == MODE_BAYES_116)
1053 ? (qual[i] + 5*qmin)/4
1054 : qual[i]/3 + qminp*poly_adj;
1055 local_nm[i] += t < qual[i] ? qual[i]-t : 0;
1056 }
1057 }
1058
1059 // Fix e.g. PacBio homopolymer qualities
1060 if (opts->homopoly_fix)
1061 homopoly_qual_fix((bam1_t *)b);
1062
1063 // local_nm[i] & ((1<<24)-1) is for SNP score adjustment.
1064 // We also put some more basic poly-X len in local_nm[i] >> 24.
1065 uint8_t *seq = bam_get_seq(b);
1066 for (i = 0; i < qlen; i++) {
1067 int base = bam_seqi(seq, i);
1068 int poly = 0, j, k;
1069 for (j = i+1; j < qlen; j++)
1070 if (bam_seqi(seq, j) != base)
1071 break;
1072 //printf("%d x %d\n", base, j-i);
1073
1074 poly = j-i-1; if (poly > 100) poly = 100;
1075 const int HALO=0;
1076 for (k = i-HALO; k < j+HALO; k++)
1077 if (k >= 0 && k < qlen)
1078 local_nm[k] = ((MAX(poly, local_nm[k]>>24))<<24)
1079 | (local_nm[k] & ((1<<24)-1));
1080
1081 i = j-1;
1082 }
1083
1084 // Adjust local_nm array by the number of edits within
1085 // a defined region (pos +/- halo).
1086 const int halo = opts->nm_halo;
1087 const uint8_t *md = bam_aux_get(b, "MD");
1088 if (!md)
1089 return 1;
1090 md = (const uint8_t *)bam_aux2Z(md);
1091
1092 // Handle cost of being near a soft-clip
1093 uint32_t *cig = bam_get_cigar(b);
1094 int ncig = b->core.n_cigar;
1095
1096 if ( (cig[0] & BAM_CIGAR_MASK) == BAM_CSOFT_CLIP ||
1097 ((cig[0] & BAM_CIGAR_MASK) == BAM_CHARD_CLIP && ncig > 1 &&
1098 (cig[1] & BAM_CIGAR_MASK) == BAM_CSOFT_CLIP)) {
1099 for (i = 0; i < halo && i < qlen; i++)
1100 local_nm[i]+=opts->sc_cost;
1101 for (; i < halo*2 && i < qlen; i++)
1102 local_nm[i]+=opts->sc_cost>>1;
1103 }
1104 if ( (cig[ncig-1] & BAM_CIGAR_MASK) == BAM_CSOFT_CLIP ||
1105 ((cig[ncig-1] & BAM_CIGAR_MASK) == BAM_CHARD_CLIP && ncig > 1 &&
1106 (cig[ncig-2] & BAM_CIGAR_MASK) == BAM_CSOFT_CLIP)) {
1107 for (i = qlen-1; i >= qlen-halo && i >= 0; i--)
1108 local_nm[i]+=opts->sc_cost;
1109 for (; i >= qlen-halo*2 && i >= 0; i--)
1110 local_nm[i]+=opts->sc_cost>>1;
1111 }
1112
1113 // Now iterate over MD tag
1114 int pos = 0;
1115 while (*md) {
1116 if (isdigit(*md)) {
1117 uint8_t *endptr;
1118 long i = strtol((char *)md, (char **)&endptr, 10);
1119 md = endptr;
1120 pos += i;
1121 continue;
1122 }
1123
1124 // deletion.
1125 // Should we bump local_nm here too? Maybe
1126 if (*md == '^') {
1127 while (*++md && !isdigit(*md))
1128 continue;
1129 continue;
1130 }
1131
1132 // substitution
1133 for (i = pos-halo*2 >= 0 ?pos-halo*2 :0; i < pos-halo && i < qlen; i++)
1134 local_nm[i]+=5;
1135 for (; i < pos+halo && i < qlen; i++)
1136 local_nm[i]+=10;
1137 for (; i < pos+halo*2 && i < qlen; i++)
1138 local_nm[i]+=5;
1139 md++;
1140 }
1141
1142 return 1;
1143 }
1144
1145 void nm_free(void *client_data, samFile *fp, sam_hdr_t *h, pileup_t *p) {
1146 free(p->cd);
1147 p->cd = NULL;
1148 }
1149
1150 #ifdef DO_HDW
1151 /*
1152 * Stirling's formula with a 1/12n correction applied to improve accuracy.
1153 * This seems to hold remarkably true for both low and high numbers too.
1154 */
1155 double lnfact(double n) {
1156 /* Or Gosper's formula...
1157 * return (n*ln(n) - n + ln(2*M_PI*n + M_PI/3) / 2);
1158 */
1159 return ((n+0.5)*log(n) - n + log(2*M_PI)/2) + log(1 + 1/(12.0*n));
1160 /* + log(1 + 1/(288.0*n*n)); */
1161 }
1162
1163 /*
1164 * The binomical coefficient (n,k) for n trials with k successes where
1165 * prob(success) = p.
1166 * k n-k
1167 * P (k|n) = n! / (k! (n-k)!) p (1-p)
1168 * p
1169 *
1170 * The coefficient we are returning here is the n! / (k! (n-k)!) bit.
1171 * We compute it using ln(n!) and then exp() the result back to avoid
1172 * excessively large numbers.
1173 */
1174 double bincoef(int n, double k) {
1175 return exp(lnfact(n) - lnfact(k) - lnfact(n-k));
1176 }
1177
1178 /*
1179 * Given p == 0.5 the binomial expansion simplifies a bit, so we have
1180 * a dedicated function for this.
1181 */
1182 double binprobhalf(int n, double k) {
1183 return bincoef(n, k) * pow(0.5, n);
1184 }
1185
1186 double lnbinprobhalf(int n, double k) {
1187 // ln(binprobhalf) expanded up and simplified
1188 return lnfact(n) - lnfact(k) - lnfact(n-k) - 0.69315*n;
1189 }
1190 #endif
1191
1192 static
1193 int calculate_consensus_gap5(hts_pos_t pos, int flags, int depth,
1194 pileup_t *plp, consensus_opts *opts,
1195 consensus_t *cons, int default_qual,
1196 cons_probs *cp) {
1197 int i, j;
1198 static int init_done =0;
1199 static double q2p[101], mqual_pow[256];
1200 double min_e_exp = DBL_MIN_EXP * log(2) + 1;
1201
1202 double S[15] ALIGNED(16) = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
1203 double sumsC[6] = {0,0,0,0,0,0}; // A C G T * N
1204
1205 // Small hash on seq to check for uniqueness of surrounding bases.
1206 // If it's frequent, then it's more likely to be correctly called than
1207 // if it's rare.
1208 // Helps a bit on deep data, especially with K2=3, but detrimental on
1209 // shallow and (currently) quite a slow down.
1210 #ifdef K2
1211 int hashN[1<<(K2*4+2)] = {0};
1212 int hash1[1<<2] = {0};
1213 #endif
1214
1215 /* Map the 15 possible combinations to 1-base or 2-base encodings */
1216 static int map_sing[15] ALIGNED(16) =
1217 {0, 5, 5, 5, 5,
1218 1, 5, 5, 5,
1219 2, 5, 5,
1220 3, 5,
1221 4};
1222 static int map_het[15] ALIGNED(16) =
1223 {0, 1, 2, 3, 4,
1224 6, 7, 8, 9,
1225 12, 13, 14,
1226 18, 19,
1227 24};
1228
1229 if (!init_done) {
1230 init_done = 1;
1231
1232 for (i = 0; i <= 100; i++) {
1233 q2p[i] = pow(10, -i/10.0);
1234 }
1235
1236 for (i = 0; i < 255; i++) {
1237 //mqual_pow[i] = 1-pow(10, -(i+.01)/10.0);
1238 mqual_pow[i] = 1-pow(10, -(i*.9)/10.0);
1239 //mqual_pow[i] = 1-pow(10, -(i/3+.1)/10.0);
1240 //mqual_pow[i] = 1-pow(10, -(i/2+.05)/10.0);
1241 }
1242 // unknown mqual
1243 mqual_pow[255] = mqual_pow[10];
1244 }
1245
1246 /* Initialise */
1247 int counts[6] = {0};
1248 #ifdef DO_FRACT
1249 int counts2[2][6] = {{0}};
1250 #endif
1251
1252 /* Accumulate */
1253
1254 #ifdef K2
1255 const pileup_t *ptmp = plp;
1256 for (; ptmp; ptmp = ptmp->next) {
1257 const pileup_t *p = ptmp;
1258 if (p->qual < opts->min_qual)
1259 continue;
1260
1261 int hb = 0;
1262 #define _ 0
1263 static int X[16] = {_,0,1,_,2,_,_,_,3,_,_,_,_,_,_,_};
1264 #undef _
1265 uint8_t *seq = bam_get_seq(&p->b);
1266 int i, base1 = X[p->base4];
1267 hash1[base1]++;
1268 for (i = p->seq_offset-K2; i <= p->seq_offset+K2; i++) {
1269 int base = i >= 0 && i < p->b.core.l_qseq ? X[bam_seqi(seq,i)] : _;
1270 hb = (hb<<2)|base;
1271 }
1272 hashN[hb]++;
1273 }
1274 #endif
1275
1276 int td = depth; // original depth
1277 depth = 0;
1278 #ifdef DO_POLY_DIST
1279 int poly_dist[2][100] = {0};
1280 #endif
1281 for (; plp; plp = plp->next) {
1282 pileup_t *p = plp;
1283
1284 if (p->next)
1285 _mm_prefetch(p->next, _MM_HINT_T0);
1286
1287 if (p->qual < opts->min_qual)
1288 continue;
1289
1290 if (p->ref_skip)
1291 continue;
1292
1293 #ifdef K2
1294 int hb = 0;
1295 #define _ 0
1296 static int X[16] = {_,0,1,_,2,_,_,_,3,_,_,_,_,_,_,_};
1297 int i, base1 = X[p->base4];
1298 for (i = p->seq_offset-K2; i <= p->seq_offset+K2; i++) {
1299 int base = i >= 0 && i < p->b.core.l_qseq ? X[bam_seqi(seq,i)] : _;
1300 hb = (hb<<2)|base;
1301 }
1302 #undef _
1303 #endif
1304
1305 const bam1_t *b = &p->b;
1306 uint8_t base = p->base4;
1307 uint8_t *qual_arr = bam_get_qual(b);
1308 uint8_t qual = p->qual;
1309 //qual = qual*qual/40+1;
1310 if (qual == 255 || (qual == 0 && *qual_arr == 255))
1311 qual = default_qual;
1312
1313 #ifdef K2
1314 //qual = qual * hashN[hb] / hash1[base1];
1315 qual -= -TENOVERLOG10*log(hashN[hb] / (hash1[base1]+.1));
1316 if (qual < 1)
1317 qual = 1;
1318 #endif
1319
1320 // =ACM GRSV TWYH KDBN *
1321 static int L[32] = {
1322 5,0,1,5, 2,5,5,5, 3,5,5,5, 5,5,5,5,
1323 4,4,4,4, 4,4,4,4, 4,4,4,4, 4,4,4,4,
1324 };
1325
1326 // convert from sam base to acgt*n order.
1327 base = L[base];
1328
1329 double MM, __, _M, oo, oM, o_, uu, um, mm, qe;
1330
1331 // Correction for mapping quality. Maybe speed up via lookups?
1332 // Cannot nullify mapping quality completely. Lots of (true)
1333 // SNPs means low mapping quality. (Ideally need to know
1334 // hamming distance to next best location.)
1335
1336 if (flags & CONS_MQUAL) {
1337 int mqual = b->core.qual;
1338 if (opts->nm_adjust) {
1339 //mqual /= (nm_local(p, b, pos)+1);
1340 mqual /= (nm_local(p, b, b->core.pos + p->seq_offset+1)+1);
1341 mqual *= 1 + 2*(0.5-(td>30?30:td)/60.0); // depth fudge
1342 }
1343
1344 // higher => call more; +FP, -FN
1345 // lower => call less; -FP, +FN
1346 mqual *= opts->scale_mqual;
1347
1348 // Drop these? They don't seem to ever help.
1349 if (mqual < opts->low_mqual)
1350 mqual = opts->low_mqual;
1351 if (mqual > opts->high_mqual)
1352 mqual = opts->high_mqual;
1353
1354 double _p = 1-q2p[qual];
1355 double _m = mqual_pow[mqual];
1356 qual = ph_log(1-(_m * _p + (1 - _m)/4)); // CURRENT
1357 //qual = ph_log(1-_p*_m); // testing
1358 //qual *= 6/sqrt(td);
1359 }
1360
1361 /* Quality 0 should never be permitted as it breaks the maths */
1362 if (qual < 1)
1363 qual = 1;
1364
1365 double poly = poly_len(p, b, b->core.pos + p->seq_offset+1);
1366 #ifdef DO_POLY_DIST
1367 poly_dist[bam_is_rev(b)][MIN(99,(int)poly)]++;
1368 #endif
1369
1370 // EXPERIMENTAL
1371 // Adjust qual based on homopolymer length.
1372 // Affects different platforms by differing amounts.
1373 // May wish to further separate to qual2 and qual3 for ins and del?
1374 int qual2 = MAX(1, qual-(poly-2)*cp->poly_mul);
1375
1376 /* MM=match _M=half-match __=mismatch */
1377 __ = cp->p__[qual]; // neither match
1378 MM = cp->pMM[qual] - __; // both match
1379 _M = cp->p_M[qual] - __; // one allele only (half match)
1380
1381 /* observation ACGT, but against hypothesis ** or *base */
1382 oo = cp->poo[qual2] - __;
1383 oM = cp->poM[qual2] - __;
1384 o_ = cp->po_[qual2] - __;
1385
1386 /* observation * */
1387 uu = cp->puu[qual2] - __;
1388 um = cp->pum[qual2] - __;
1389 mm = cp->pmm[qual2] - __;
1390
1391 if (flags & CONS_DISCREP) {
1392 qe = q2p[qual];
1393 sumsC[base] += 1 - qe;
1394 }
1395
1396
1397 counts[base]++;
1398 #ifdef DO_FRACT
1399 counts2[bam_is_rev(b)][base]++;
1400 #endif
1401
1402 // oM should never be higher than _M for actual bases! or...
1403 //printf("base %d@%d MM %f _M %f oM %f\n", base, qual, MM, _M, oM);
1404
1405 switch (base) {
1406 case 0: // A
1407 S[0] += MM;
1408 S[1] += _M;
1409 S[2] += _M;
1410 S[3] += _M;
1411 S[4] += oM;
1412 S[8] += o_;
1413 S[11] += o_;
1414 S[13] += o_;
1415 S[14] += oo;
1416 break;
1417
1418 case 1: // C
1419 S[1] += _M;
1420 S[5] += MM;
1421 S[6] += _M;
1422 S[7] += _M;
1423 S[8] += oM;
1424 S[4] += o_;
1425 S[11] += o_;
1426 S[13] += o_;
1427 S[14] += oo;
1428
1429 //fprintf(stderr, "%d %f %f %f\n", qual, MM+__, oo+__, MM-oo);
1430 break;
1431
1432 case 2: // G
1433 S[ 2] += _M;
1434 S[ 6] += _M;
1435 S[ 9] += MM;
1436 S[10] += _M;
1437 S[11] += oM;
1438 S[4] += o_;
1439 S[8] += o_;
1440 S[13] += o_;
1441 S[14] += oo;
1442 break;
1443
1444 case 3: // T
1445 S[ 3] += _M; // _m
1446 S[ 7] += _M;
1447 S[10] += _M;
1448 S[12] += MM; // mm
1449 S[13] += oM;
1450 S[4] += o_;
1451 S[8] += o_;
1452 S[11] += o_;
1453 S[14] += oo;
1454 // S[14] oo
1455
1456 break;
1457
1458 case 4: // *
1459 // under under under under agree-no-base
1460 S[0] += uu; S[1 ]+= uu; S[2 ]+= uu; S[3 ]+= uu; S[4 ]+= um;
1461 S[5 ]+= uu; S[6 ]+= uu; S[7 ]+= uu; S[8 ]+= um;
1462 S[9 ]+= uu; S[10]+= uu; S[11]+= um;
1463 S[12]+= uu; S[13]+= um;
1464 S[14]+= mm;
1465 break;
1466
1467 case 5: /* N => equal weight to all A,C,G,T but not a pad */
1468 S[0] += MM; S[1 ]+= MM; S[2 ]+= MM; S[3 ]+= MM; S[4 ]+= oM;
1469 S[5 ]+= MM; S[6 ]+= MM; S[7 ]+= MM; S[8 ]+= oM;
1470 S[9 ]+= MM; S[10]+= MM; S[11]+= oM;
1471 S[12]+= MM; S[13]+= oM;
1472 S[14]+= oo;
1473 break;
1474 }
1475
1476 depth++;
1477 }
1478
1479 #ifdef DO_POLY_DIST
1480 // Or compute mean and s.d per strand.
1481 // Then compare likelihood of strands coming from the same distribution?
1482 // eg s.d=0.59 vs mean=3.41 sd=0.54... hmm
1483 //
1484 // Or compare ratio of most frequent to next most frequent, for each
1485 // strand.
1486
1487 int d1 = 0, d2 = 0;
1488 double nd1 = 0, nd2 = 0;
1489 int k;
1490 for (k = 0; k < 100; k++) {
1491 if (!poly_dist[0][k] && !poly_dist[1][k])
1492 continue;
1493
1494 // fprintf(stdout, "%ld %d %2d %2d\n", pos, k, poly_dist[0][k], poly_dist[1][k]);
1495 d1 += (k+1)*poly_dist[0][k];
1496 d2 += (k+1)*poly_dist[1][k];
1497 nd1 += poly_dist[0][k];
1498 nd2 += poly_dist[1][k];
1499 }
1500 // printf("Avg = %f / %f %f / %f / %f\n",
1501 // (d1+d2+1)/(nd1+nd2+1.),
1502 // (d1+1)/(nd1+1.), (d2+1)/(nd2+1.),
1503 // (d2+1)/(nd2+1.) - (d1+1)/(nd1+1.),
1504 // ((d2+1)/(nd2+1.) - (d1+1)/(nd1+1.)) / ((d1+d2+1)/(nd1+nd2+1.)));
1505
1506 // Find the top two frequent lengths
1507 int n1 = 0, n2 = 0, l1 = 0, l2 = 0;
1508 for (k = 0; k < 100; k++) {
1509 int poly12 = poly_dist[0][k]+poly_dist[1][k];
1510 if (n1 < poly12) {
1511 n2 = n1; l2 = l1;
1512 n1 = poly12;
1513 l1 = k;
1514 } else if (n2 < poly12) {
1515 n2 = poly12;
1516 l2 = k;
1517 }
1518 }
1519
1520 const double N = 5;
1521 nd1 += 1;
1522 nd2 += 1;
1523
1524 // l1 is most common length
1525 int pn1p = poly_dist[0][l1];
1526 int pn1m = poly_dist[1][l1];
1527 // l2 2nd most common
1528 int pn2p = poly_dist[0][l2];
1529 int pn2m = poly_dist[1][l2];
1530
1531 // ratio if two most common lengths on +
1532 double s1 = (pn1p+N) / (pn2p+N); s1 = s1>1?1/s1:s1;
1533 // ratio if two most common lengths on -
1534 double s2 = (pn1m+N) / (pn2m+N); s2 = s2>1?1/s2:s2;
1535
1536 // ratio of s1 and s2 to identify strand bias
1537 double sbias = s1 / s2; sbias = sbias>1?1/sbias:sbias;
1538
1539 if (pn2p+pn2m > 0 && l1 != l2) {
1540 // printf("len %d,%d + %d,%d - %d,%d\tbias = %f %f, %f %f\t%ld\n",
1541 // l1, l2, pn1p, pn2p, pn1m, pn2m,
1542 // s1, s2, sbias, sqrt(sbias)-1, pos);
1543
1544 // adjust score for het indels
1545 // sbias is close to 0 for strong strand bias, and 1 for none
1546 sbias = 10*log(sbias);//+.5);
1547 S[ 4] += sbias; // A*
1548 S[ 8] += sbias; // C*
1549 S[11] += sbias; // G*
1550 S[13] += sbias; // T*
1551 } else {
1552 sbias = 0;
1553 }
1554 #endif
1555
1556 /* We've accumulated stats, so now we speculate on the consensus call */
1557 double shift, max, max_het, norm[15];
1558 int call = 0, het_call = 0;
1559 double tot1 = 0, tot2 = 0;
1560
1561 /*
1562 * Scale numbers so the maximum score is 0. This shift is essentially
1563 * a multiplication in non-log scale to both numerator and denominator,
1564 * so it cancels out. We do this to avoid calling exp(-large_num) and
1565 * ending up with norm == 0 and hence a 0/0 error.
1566 *
1567 * Can also generate the base-call here too.
1568 */
1569 shift = -DBL_MAX;
1570 max = -DBL_MAX;
1571 max_het = -DBL_MAX;
1572
1573 #ifdef DO_FRACT
1574 // Filter by --min-depth and --het-fract.
1575 // Also add a slight adjustment for strand bias.
1576 for (j = 0; j < 15; j++) {
1577 if (j == 0 || j == 5 || j == 9 || j == 12 || j == 14)
1578 continue;
1579
1580 double c1p = counts2[0][map_het[j]%5];
1581 double c1m = counts2[1][map_het[j]%5];
1582 double c2p = counts2[0][map_het[j]/5];
1583 double c2m = counts2[1][map_het[j]/5];
1584
1585 double c1 = c1p + c1m;
1586 double c2 = c2p + c2m;
1587
1588 if (c1 && c2) {
1589 // Slight decrease in confidence if strong strand bias.
1590 const int N = 10; // avoid low sample size problems
1591 double b1 = 1 - (N+MIN(c1p,c1m))/(N+MAX(c1p,c1m));
1592 double b2 = 1 - (N+MIN(c2p,c2m))/(N+MAX(c2p,c2m));
1593 if (b1 > 0.5) S[j] -= b1;
1594 if (b2 > 0.5) S[j] -= b2;
1595
1596 // Fraction based filtering, via --min-depth and --het-fract opts.
1597 c1 += 1e-5;
1598 c2 += 1e-5;
1599 if (c2 > c1) {
1600 double tmp = c2;
1601 c2 = c1;
1602 c1 = tmp;
1603 }
1604
1605 if (c2 < opts->min_depth)
1606 S[j] -= 100;
1607 if (c2 / (c1+1e-5) <= opts->het_fract)
1608 S[j] -= 100;
1609 }
1610 }
1611 #endif
1612
1613 #ifdef DO_HDW
1614 /*
1615 * Apply Hardy-Weinberg statistics for heterozygous sites.
1616 * This helps, but it also loses sensitivity a little.
1617 */
1618 for (j = 0; j < 15; j++) {
1619 if (j == 0 || j == 5 || j == 9 || j == 12 || j == 14)
1620 continue;
1621
1622 double c1 = counts[map_het[j]%5];
1623 double c2 = counts[map_het[j]/5];
1624
1625 if (c1 && c2) {
1626 c1 += 1e-5;
1627 c2 += 1e-5;
1628 if (c2 > c1) {
1629 double tmp = c2;
1630 c2 = c1;
1631 c1 = tmp;
1632 }
1633
1634 // Limit depth for HW as we'll have an allele freq difference,
1635 // even if it's just caused by alignment reference bias.
1636 double c12 = c1+c2;
1637 if (c12 > 20) {
1638 c2 *= 20/(c12);
1639 c12 = 20;
1640 c1 = 20-c2;
1641 }
1642
1643 // Helps a little, especially reducing FN deletions.
1644 c1+=1;
1645 c2+=1;
1646 c12+=2;
1647 S[j] += lnbinprobhalf(c12, c2) + fast_log2(c12)*0.69+.2;
1648 }
1649 }
1650 #endif
1651
1652 for (j = 0; j < 15; j++) {
1653 S[j] += cp->lprior15[j];
1654 if (shift < S[j])
1655 shift = S[j];
1656
1657 /* Only call pure AA, CC, GG, TT, ** for now */
1658 if (j != 0 && j != 5 && j != 9 && j != 12 && j != 14) {
1659 if (max_het < S[j]) {
1660 max_het = S[j];
1661 het_call = j;
1662 }
1663 continue;
1664 }
1665
1666 if (max < S[j]) {
1667 max = S[j];
1668 call = j;
1669 }
1670 }
1671
1672 /*
1673 * Shift and normalise.
1674 * If call is, say, b we want p = b/(a+b+c+...+n), but then we do
1675 * p/(1-p) later on and this has exceptions when p is very close
1676 * to 1.
1677 *
1678 * Hence we compute b/(a+b+c+...+n - b) and
1679 * rearrange (p/norm) / (1 - (p/norm)) to be p/norm2.
1680 */
1681 for (j = 0; j < 15; j++) {
1682 S[j] -= shift;
1683 double e = fast_exp(S[j]);
1684 S[j] = (S[j] > min_e_exp) ? e : DBL_MIN;
1685 norm[j] = 0;
1686 }
1687
1688 for (j = 0; j < 15; j++) {
1689 norm[j] += tot1;
1690 norm[14-j] += tot2;
1691 tot1 += S[j];
1692 tot2 += S[14-j];
1693 }
1694
1695 /* And store result */
1696 if (!depth || depth == counts[5] /* all N */) {
1697 cons->call = 4; /* N */
1698 cons->het_call = 0;
1699 cons->het_logodd = 0;
1700 cons->phred = 0;
1701 cons->depth = 0;
1702 cons->discrep = 0;
1703 return 0;
1704 }
1705
1706 cons->depth = depth;
1707
1708 /* Call */
1709 if (norm[call] == 0) norm[call] = DBL_MIN;
1710 // Approximation of phred for when S[call] ~= 1 and norm[call]
1711 // is small. Otherwise we need the full calculation.
1712 int ph;
1713 if (S[call] == 1 && norm[call] < .01)
1714 ph = ph_log(norm[call]) + .5;
1715 else
1716 ph = ph_log(1-S[call]/(norm[call]+S[call])) + .5;
1717
1718 cons->call = map_sing[call];
1719 cons->phred = ph < 0 ? 0 : ph;
1720
1721 if (norm[het_call] == 0) norm[het_call] = DBL_MIN;
1722 ph = TENLOG2OVERLOG10 * (fast_log2(S[het_call])
1723 - fast_log2(norm[het_call])) + .5;
1724
1725 cons->het_call = map_het[het_call];
1726 cons->het_logodd = ph;
1727
1728 /* Compute discrepancy score */
1729 if (flags & CONS_DISCREP) {
1730 double m = sumsC[0]+sumsC[1]+sumsC[2]+sumsC[3]+sumsC[4];
1731 double c;
1732 if (cons->het_logodd > 0)
1733 c = sumsC[cons->het_call%5] + sumsC[cons->het_call/5];
1734 else
1735 c = sumsC[cons->call];
1736 cons->discrep = (m-c)/sqrt(m);
1737 }
1738
1739 return 0;
1740 }
1741
1742 // If opts->gap5 is MODE_MIXED then we use two different parameter
1743 // sets, favouring cp_p for precision and cp_r for recall. Otherwise it's
1744 // always cp_r only.
1745 //
1746 // When both calls equal, we return the same result. When they differ,
1747 // we adjust qual based on accurate vs recall profiles.
1748 int calculate_consensus_gap5m(hts_pos_t pos, int flags, int depth,
1749 pileup_t *plp, consensus_opts *opts,
1750 consensus_t *cons, int default_qual,
1751 cons_probs *cp_r, cons_probs *cp_p) {
1752 if (opts->mode != MODE_MIXED)
1753 return calculate_consensus_gap5(pos, flags, depth, plp, opts,
1754 cons, default_qual,
1755 opts->mode == MODE_PRECISE
1756 ? cp_p : cp_r);
1757
1758 // EXPERIMENTAL: mixed mode
1759 consensus_t consP, consR;
1760 // Favours precision
1761 calculate_consensus_gap5(pos, flags, depth, plp, opts,
1762 &consP, default_qual, cp_p);
1763 // Favours recall
1764 calculate_consensus_gap5(pos, flags, depth, plp, opts,
1765 &consR, default_qual, cp_r);
1766
1767 #define MIN(a,b) ((a)<(b)?(a):(b))
1768 #define MAX(a,b) ((a)>(b)?(a):(b))
1769
1770 // Initial starting point is precise mode
1771 memcpy(cons, &consP, sizeof(consP));
1772
1773 if (consP.phred > 0 && consR.phred > 0 && consP.call == consR.call) {
1774 // Both strategies match as HOM
1775 // Boost qual as both in agreement
1776 cons->phred += MIN(20, consR.phred);
1777
1778 } else if (consP.het_logodd >= 0 && consR.het_logodd >= 0 &&
1779 consP.het_call == consR.het_call) {
1780 // Both strategies match as HET
1781 // Boost qual as both in agreement
1782 cons->het_logodd += MIN(20, consR.het_logodd);
1783
1784 } else if (consP.het_logodd >= 0) {
1785 // Accurate method claims heterozygous, so go with it.
1786 // However sensitive method disagrees, so reduce qual a little.
1787 int q2 = MAX(consR.phred, consR.het_logodd);
1788 cons->het_logodd = MAX(1, (cons->het_logodd - q2/2));
1789
1790 } else if (consR.het_logodd >= 70) {
1791 // Accurate is homozygous and consR is het, so we go with it instead
1792 // but at a lower quality value.
1793 // TODO: may wish to check HET is consistent with HOM? Very unlikely
1794 // not to be though.
1795 int q1 = consP.phred;
1796 int q2 = consR.het_logodd;
1797 memcpy(cons, &consR, sizeof(consR));
1798 cons->het_logodd = MIN(15, MAX((q2-q1*2)/2, 1+q2/(q1+1.0)));
1799
1800 } else if (consR.het_logodd >= 0) {
1801 // As above, but low quality
1802 int q1 = consP.phred;
1803 int q2 = consR.het_logodd;
1804 memcpy(cons, &consR, sizeof(consR));
1805 cons->het_logodd = MAX(1,q2 - 0.3*q1)
1806 + 5*(consP.het_call == consR.het_call);
1807 cons->phred = 0;
1808
1809 } else if (consR.het_logodd < 0) {
1810 // Neither are heterozygous, but differing in phred call (V rare).
1811 // Pick highest qual, after some scaling?
1812 consR.phred = consR.phred / 2;
1813 if (consR.phred > consP.phred)
1814 memcpy(cons, &consR, sizeof(consR));
1815 cons->phred = MAX(10, cons->phred);
1816 }
1817
1818 return 0;
1819 }
1820
1821 /* --------------------------------------------------------------------------
1822 * Main processing logic
1823 */
1824
1825 static void dump_fastq(consensus_opts *opts,
1826 const char *name,
1827 const char *seq, size_t seq_l,
1828 const char *qual, size_t qual_l) {
1829 enum format fmt = opts->fmt;
1830 int line_len = opts->line_len;
1831 FILE *fp = opts->fp_out;
1832
1833 fprintf(fp, "%c%s\n", ">@"[fmt==FASTQ], name);
1834 size_t i;
1835 for (i = 0; i < seq_l; i += line_len)
1836 fprintf(fp, "%.*s\n", (int)MIN(line_len, seq_l - i), seq+i);
1837
1838 if (fmt == FASTQ) {
1839 fprintf(fp, "+\n");
1840 for (i = 0; i < seq_l; i += line_len)
1841 fprintf(fp, "%.*s\n", (int)MIN(line_len, seq_l - i), qual+i);
1842 }
1843 }
1844
1845 //---------------------------------------------------------------------------
1846
1847 /*
1848 * Reads a single alignment record, using either the iterator
1849 * or a direct sam_read1 call.
1850 */
1851 static int readaln2(void *dat, samFile *fp, sam_hdr_t *h, bam1_t *b) {
1852 consensus_opts *opts = (consensus_opts *)dat;
1853
1854 for (;;) {
1855 int ret = opts->iter
1856 ? sam_itr_next(fp, opts->iter, b)
1857 : sam_read1(fp, h, b);
1858 if (ret < 0)
1859 return ret;
1860
1861 // Apply hard filters
1862 if (opts->incl_flags && !(b->core.flag & opts->incl_flags))
1863 continue;
1864 if (opts->excl_flags && (b->core.flag & opts->excl_flags))
1865 continue;
1866 if (b->core.qual < opts->min_mqual)
1867 continue;
1868
1869 return ret;
1870 }
1871 }
1872
1873 /* --------------------------------------------------------------------------
1874 * A simple summing algorithm, either pure base frequency, or by
1875 * weighting them according to their quality values.
1876 *
1877 * This is crude, but easy to understand and fits with several
1878 * standard pileup criteria (eg COG-UK / CLIMB Covid-19 seq project).
1879 *
1880 *
1881 * call1 / score1 is the highest scoring allele.
1882 * call2 / score2 is the second highest scoring allele.
1883 *
1884 * Het_fract: score2/score1
1885 * Call_fract: score1 or score1+score2 over total score
1886 * Min_depth: minimum total depth of unfiltered bases (above qual/mqual)
1887 * Min_score: minimum total score of utilised bases (score1+score2)
1888 *
1889 * Eg het_fract 0.66, call_fract 0.75 and min_depth 10.
1890 * 11A, 2C, 2G (14 total depth) is A.
1891 * 9A, 2C, 2G (12 total depth) is N as depth(A) < 10.
1892 * 11A, 5C, 5G (21 total depth) is N as 11/21 < 0.75 (call_fract)
1893 *
1894 *
1895 * 6A, 5G, 1C (12 total depth) is AG het as depth(A)+depth(G) >= 10
1896 * and 5/6 >= 0.66 and 11/12 >= 0.75.
1897 *
1898 * 6A, 5G, 4C (15 total depth) is N as (6+5)/15 < 0.75 (call_fract).
1899 *
1900 *
1901 * Note for the purpose of deletions, a base/del has an ambiguity
1902 * code of lower-case base (otherwise it is uppercase).
1903 */
1904 static int calculate_consensus_simple(const pileup_t *plp,
1905 consensus_opts *opts, int *qual) {
1906 int i, min_qual = opts->min_qual;
1907 int tot_depth = 0;
1908
1909 // Map "seqi" nt16 to A,C,G,T compatibility with weights on pure bases.
1910 // where seqi is A | (C<<1) | (G<<2) | (T<<3)
1911 // * A C M G R S V T W Y H K D B N
1912 static int seqi2A[16] = { 0,8,0,4, 0,4,0,2, 0,4,0,2, 0,2,0,1 };
1913 static int seqi2C[16] = { 0,0,8,4, 0,0,4,2, 0,0,4,2, 0,0,2,1 };
1914 static int seqi2G[16] = { 0,0,0,0, 8,4,4,1, 0,0,0,0, 4,2,2,1 };
1915 static int seqi2T[16] = { 0,0,0,0, 0,0,0,0, 8,4,4,2, 8,2,2,1 };
1916
1917 // Ignore ambiguous bases in seq for now, so we don't treat R, Y, etc
1918 // as part of one base and part another. Based on BAM seqi values.
1919 // We also use freq[16] as "*" for gap.
1920 int freq[17] = {0}; // base frequency, aka depth
1921 uint64_t score[17] = {0}; // summation of base qualities
1922
1923 // Accumulate
1924 for (; plp; plp = plp->next) {
1925 const pileup_t *p = plp;
1926 if (p->next)
1927 _mm_prefetch(p->next, _MM_HINT_T0);
1928
1929 int q = p->qual;
1930 if (q < min_qual)
1931 // Should we still record these in freq[] somewhere so
1932 // we can use them in the fracts?
1933 // Difference between >= X% of high-qual bases calling Y
1934 // and >= X% of all bases are high-quality Y calls.
1935 continue;
1936
1937 //int b = p->is_del ? 16 : bam_seqi(bam_get_seq(&p->b), p->seq_offset);
1938 int b = p->base4;
1939
1940 // Map ambiguity codes to one or more component bases.
1941 if (b < 16) {
1942 int Q = seqi2A[b] * (opts->use_qual ? q : 1);
1943 freq[1] += Q?1:0;
1944 score[1] += Q?Q:0;
1945 Q = seqi2C[b] * (opts->use_qual ? q : 1);
1946 freq[2] += Q?1:0;
1947 score[2] += Q?Q:0;
1948 Q = seqi2G[b] * (opts->use_qual ? q : 1);
1949 freq[4] += Q?1:0;
1950 score[4] += Q?Q:0;
1951 Q = seqi2T[b] * (opts->use_qual ? q : 1);
1952 freq[8] += Q?1:0;
1953 score[8] += Q?Q:0;
1954 } else { /* * */
1955 freq[16] ++;
1956 score[16]+=8 * (opts->use_qual ? q : 1);
1957 }
1958 tot_depth++;
1959 }
1960
1961 // Total usable depth
1962 uint64_t tscore = 0;
1963 for (i = 0; i < 5; i++)
1964 tscore += score[1<<i];
1965
1966 // Best and second best potential calls
1967 int call1 = 15, call2 = 15;
1968 uint64_t score1 = 0, score2 = 0;
1969 for (i = 0; i < 5; i++) {
1970 int c = 1<<i; // A C G T *
1971 if (score1 < score[c]) {
1972 score2 = score1;
1973 call2 = call1;
1974 score1 = score[c];
1975 call1 = c;
1976 } else if (score2 < score[c]) {
1977 score2 = score[c];
1978 call2 = c;
1979 }
1980 }
1981
1982 // Work out which best and second best are usable as a call
1983 uint64_t used_score = score1;
1984 int used_base = call1;
1985 if (score2 >= opts->het_fract * score1 && opts->ambig) {
1986 used_base |= call2;
1987 used_score += score2;
1988 }
1989
1990 // N is too shallow, or insufficient proportion of total
1991 if (tot_depth < opts->min_depth ||
1992 used_score < opts->call_fract * tscore) {
1993 // But note shallow gaps are still called gaps, not N, as
1994 // we're still more confident there is no base than it is
1995 // A, C, G or T.
1996 used_base = call1 == 16 ? 16 : 0; // * or N
1997 }
1998
1999 // Our final call. "?" shouldn't be possible to generate
2000 const char *het =
2001 "NACMGRSVTWYHKDBN"
2002 "*ac?g???t???????";
2003
2004 //printf("%c %d\n", het[used_base], tot_depth);
2005 if (qual)
2006 *qual = used_base ? 100.0 * used_score / tscore : 0;
2007
2008 return het[used_base];
2009 }
2010
2011 static int empty_pileup2(consensus_opts *opts, sam_hdr_t *h, int tid,
2012 hts_pos_t start, hts_pos_t end) {
2013 const char *name = sam_hdr_tid2name(h, tid);
2014 hts_pos_t i;
2015
2016 int err = 0;
2017 for (i = start; i < end; i++)
2018 err |= fprintf(opts->fp_out, "%s\t%"PRIhts_pos"\t0\t0\tN\t0\t*\t*\n", name, i+1) < 0;
2019
2020 return err ? -1 : 0;
2021 }
2022
2023 /*
2024 * Returns 0 on success
2025 * -1 on failure
2026 */
2027 static int basic_pileup(void *cd, samFile *fp, sam_hdr_t *h, pileup_t *p,
2028 int depth, hts_pos_t pos, int nth, int is_insert) {
2029 unsigned char *qp, *cp;
2030 char *rp;
2031 int ref, cb, cq;
2032 consensus_opts *opts = (consensus_opts *)cd;
2033 int tid = p->b.core.tid;
2034
2035 // opts->show_ins=0;
2036 // opts->show_del=1;
2037 if (!opts->show_ins && nth)
2038 return 0;
2039
2040 if (opts->iter) {
2041 if (opts->iter->beg >= pos || opts->iter->end < pos)
2042 return 0;
2043 }
2044
2045 if (opts->all_bases) {
2046 if (tid != opts->last_tid && opts->last_tid >= -1) {
2047 if (opts->last_tid >= 0) {
2048 // remainder of previous ref
2049 hts_pos_t len = sam_hdr_tid2len(opts->h, opts->last_tid);
2050 if (opts->iter)
2051 len = MIN(opts->iter->end, len);
2052 if (empty_pileup2(opts, opts->h, opts->last_tid,
2053 opts->last_pos, len) < 0)
2054 return -1;
2055 }
2056
2057 opts->last_pos = opts->iter ? opts->iter->beg : 0;
2058 }
2059
2060 // Any refs between last_tid and tid
2061 if (!opts->iter && tid > opts->last_tid && opts->all_bases > 1) {
2062 while (++opts->last_tid < tid) {
2063 hts_pos_t len = sam_hdr_tid2len(opts->h, opts->last_tid);
2064 if (empty_pileup2(opts, opts->h, opts->last_tid, 0, len) < 0)
2065 return -1;
2066 }
2067 }
2068
2069 // Any gaps in this ref (same tid) or at start of this new tid
2070 if (opts->last_pos >= 0 && pos > opts->last_pos+1) {
2071 if (empty_pileup2(opts, opts->h, p->b.core.tid, opts->last_pos,
2072 pos-1) < 0)
2073 return -1;
2074 } else if (opts->last_pos < 0) {
2075 if (empty_pileup2(opts, opts->h, p->b.core.tid,
2076 opts->iter ? opts->iter->beg : 0, pos-1) < 0)
2077 return -1;
2078 }
2079 }
2080
2081 if (opts->mode != MODE_SIMPLE) {
2082 consensus_t cons;
2083 calculate_consensus_gap5m(pos, opts->use_mqual ? CONS_MQUAL : 0,
2084 depth, p, opts, &cons, opts->default_qual,
2085 &cons_prob_recall, &cons_prob_precise);
2086 if (cons.depth < opts->min_depth) {
2087 cb = 'N';
2088 cq = 0;
2089 } else if (cons.het_logodd > 0 && opts->ambig) {
2090 cb = "AMRWa" // 5x5 matrix with ACGT* per row / col
2091 "MCSYc"
2092 "RSGKg"
2093 "WYKTt"
2094 "acgt*"[cons.het_call];
2095 cq = cons.het_logodd;
2096 } else{
2097 cb = "ACGT*"[cons.call];
2098 cq = cons.phred;
2099 }
2100 if (cq < opts->cons_cutoff && cb != '*') {
2101 cb = 'N';
2102 cq = 0;
2103 }
2104 } else {
2105 cb = calculate_consensus_simple(p, opts, &cq);
2106 }
2107 if (cb < 0)
2108 return -1;
2109
2110 if (!p)
2111 return 0;
2112
2113 if (!opts->show_del && cb == '*')
2114 return 0;
2115
2116 /* Ref, pos, nth, score, seq, qual */
2117 kstring_t *ks = &opts->ks_line;
2118 ks->l = 0;
2119 ref = p->b.core.tid;
2120 rp = (char *)sam_hdr_tid2name(h, ref);
2121
2122 int err = 0;
2123 err |= kputs(rp, ks) < 0;
2124 err |= kputc_('\t', ks) < 0;
2125 err |= kputw(pos, ks) < 0;
2126 err |= kputc_('\t', ks) < 0;
2127 err |= kputw(nth, ks) < 0;
2128 err |= kputc_('\t', ks) < 0;
2129 err |= kputw(depth, ks) < 0;
2130 err |= kputc_('\t', ks) < 0;
2131 err |= kputc_(cb, ks) < 0;
2132 err |= kputc_('\t', ks) < 0;
2133 err |= kputw(cq, ks) < 0;
2134 err |= kputc_('\t', ks) < 0;
2135 if (err)
2136 return -1;
2137
2138 /* Seq + qual at predetermined offsets */
2139 if (ks_resize(ks, ks->l + depth*2 + 2) < 0)
2140 return -1;
2141
2142 cp = (unsigned char *)ks->s + ks->l;
2143 ks->l += depth*2 + 2;
2144 qp = cp+depth+1;
2145 for (; p; p = p->next) {
2146 // Too tight a loop to help much, but some benefit still
2147 if (p->next && p->next->next)
2148 _mm_prefetch(p->next->next, _MM_HINT_T0);
2149 if (p->b_is_rev) {
2150 *cp++ = p->base == '*' ? '#' : tolower(p->base);
2151 } else {
2152 *cp++ = p->base;
2153 }
2154 *qp++ = MIN(p->qual,93) + '!';
2155 }
2156 *cp++ = '\t';
2157 *qp++ = '\n';
2158 if (fwrite(ks->s, 1, ks->l, opts->fp_out) != ks->l)
2159 return -1;
2160
2161 opts->last_pos = pos;
2162 opts->last_tid = tid;
2163
2164 return 0;
2165 }
2166
2167 static int basic_fasta(void *cd, samFile *fp, sam_hdr_t *h, pileup_t *p,
2168 int depth, hts_pos_t pos, int nth, int is_insert) {
2169 int cb, cq;
2170 consensus_opts *opts = (consensus_opts *)cd;
2171 int tid = p->b.core.tid;
2172 kstring_t *seq = &opts->ks_ins_seq;
2173 kstring_t *qual = &opts->ks_ins_qual;
2174
2175 if (!opts->show_ins && nth)
2176 return 0;
2177
2178 if (opts->iter) {
2179 if (opts->iter->beg >= pos || opts->iter->end < pos)
2180 return 0;
2181 }
2182
2183 next_ref:
2184 if (tid != opts->last_tid) {
2185 if (opts->last_tid != -1) {
2186 if (opts->all_bases) {
2187 // Fill in remainder of previous reference
2188 int i, N;
2189 if (opts->iter) {
2190 opts->last_pos = MAX(opts->last_pos, opts->iter->beg-1);
2191 N = opts->iter->end;
2192 } else {
2193 N = INT_MAX;
2194 }
2195 N = MIN(N, sam_hdr_tid2len(opts->h, opts->last_tid))
2196 - opts->last_pos;
2197 if (N > 0) {
2198 if (ks_expand(seq, N+1) < 0)
2199 return -1;
2200 if (ks_expand(qual, N+1) < 0)
2201 return -1;
2202 for (i = 0; i < N; i++) {
2203 seq->s[seq->l++] = 'N';
2204 qual->s[qual->l++] = '!';
2205 }
2206 seq->s[seq->l] = 0;
2207 qual->s[qual->l] = 0;
2208 }
2209 }
2210 dump_fastq(opts, sam_hdr_tid2name(opts->h, opts->last_tid),
2211 seq->s, seq->l, qual->s, qual->l);
2212 }
2213
2214 seq->l = 0; qual->l = 0;
2215
2216 if (!opts->iter && opts->all_bases > 1 && ++opts->last_tid < tid) {
2217 opts->last_pos = 0;
2218 goto next_ref;
2219 }
2220
2221 opts->last_tid = tid;
2222 if (opts->iter)
2223 opts->last_pos = opts->iter->beg;
2224 else
2225 opts->last_pos = opts->all_bases ? 0 : pos-1;
2226 }
2227
2228 // share this with basic_pileup
2229 if (opts->mode != MODE_SIMPLE) {
2230 consensus_t cons;
2231 calculate_consensus_gap5m(pos, opts->use_mqual ? CONS_MQUAL : 0,
2232 depth, p, opts, &cons, opts->default_qual,
2233 &cons_prob_recall, &cons_prob_precise);
2234 if (cons.depth < opts->min_depth) {
2235 cb = 'N';
2236 cq = 0;
2237 } else if (cons.het_logodd > 0 && opts->ambig) {
2238 cb = "AMRWa" // 5x5 matrix with ACGT* per row / col
2239 "MCSYc"
2240 "RSGKg"
2241 "WYKTt"
2242 "acgt*"[cons.het_call];
2243 cq = cons.het_logodd;
2244 } else {
2245 cb = "ACGT*"[cons.call];
2246 cq = cons.phred;
2247 }
2248 if (cq < opts->cons_cutoff && cb != '*' &&
2249 cons.het_call % 5 != 4 && cons.het_call / 5 != 4) {
2250 // het base/* keeps base or * as most likely pure call, else N.
2251 // This is because we don't have a traditional way of representing
2252 // base or not-base ambiguity.
2253 cb = 'N';
2254 cq = 0;
2255 }
2256 } else {
2257 cb = calculate_consensus_simple(p, opts, &cq);
2258 }
2259 if (cb < 0)
2260 return -1;
2261
2262 if (!p)
2263 return 0;
2264
2265 if (!opts->show_del && cb == '*') {
2266 opts->last_pos = pos;
2267 opts->last_tid = tid;
2268 return 0;
2269 }
2270 if (opts->mark_ins && nth && cb != '*') {
2271 kputc('_', seq);
2272 kputc('_', qual);
2273 }
2274
2275 // end of share
2276
2277 // Append consensus base/qual to seqs
2278 if (pos > opts->last_pos) {
2279 if (opts->last_pos >= 0 || opts->all_bases) {
2280 // FIXME: don't expand qual if fasta
2281 if (ks_expand(seq, pos - opts->last_pos) < 0 ||
2282 ks_expand(qual, pos - opts->last_pos) < 0)
2283 return -1;
2284 memset(seq->s + seq->l, 'N', pos - (opts->last_pos+1));
2285 memset(qual->s + qual->l, '!', pos - (opts->last_pos+1));
2286 seq->l += pos - (opts->last_pos+1);
2287 qual->l += pos - (opts->last_pos+1);
2288 }
2289 }
2290 if ((nth && opts->show_ins && cb != '*')
2291 || cb != '*' || (pos > opts->last_pos && opts->show_del)) {
2292 int err = 0;
2293 err |= kputc(cb, seq) < 0;
2294 err |= kputc(MIN(cq, '~'-'!')+'!', qual) < 0;
2295 if (err)
2296 return -1;
2297 }
2298
2299 opts->last_pos = pos;
2300 opts->last_tid = tid;
2301
2302 return 0;
2303 }
2304
2305 // END OF NEW PILEUP
2306 //---------------------------------------------------------------------------
2307
2308 static void usage_exit(FILE *fp, int exit_status) {
2309 fprintf(fp, "Usage: samtools consensus [options] <in.bam>\n");
2310 fprintf(fp, "\nOptions:\n");
2311 fprintf(fp, " -r, --region REG Limit query to REG. Requires an index\n");
2312 fprintf(fp, " -f, --format FMT Output in format FASTA, FASTQ or PILEUP [FASTA]\n");
2313 fprintf(fp, " -l, --line-len INT Wrap FASTA/Q at line length INT [70]\n");
2314 fprintf(fp, " -o, --output FILE Output consensus to FILE\n");
2315 fprintf(fp, " -m, --mode STR Switch consensus mode to \"simple\"/\"bayesian\" [bayesian]\n");
2316 fprintf(fp, " -a Output all bases (start/end of reference)\n");
2317 fprintf(fp, " --rf, --incl-flags STR|INT\n");
2318 fprintf(fp, " Only include reads with any flag bit set [0]\n");
2319 fprintf(fp, " --ff, --excl-flags STR|INT\n");
2320 fprintf(fp, " Exclude reads with any flag bit set\n");
2321 fprintf(fp, " [UNMAP,SECONDARY,QCFAIL,DUP]\n");
2322 fprintf(fp, " --min-MQ INT Exclude reads with mapping quality below INT [0]\n");
2323 fprintf(fp, " --min-BQ INT Exclude reads with base quality below INT [0]\n");
2324 fprintf(fp, " --show-del yes/no Whether to show deletion as \"*\" [no]\n");
2325 fprintf(fp, " --show-ins yes/no Whether to show insertions [yes]\n");
2326 fprintf(fp, " --mark-ins Add '+' before every inserted base/qual [off]\n");
2327 fprintf(fp, " -A, --ambig Enable IUPAC ambiguity codes [off]\n");
2328 fprintf(fp, " -d, --min-depth INT Minimum depth of INT [1]\n");
2329 fprintf(fp, "\nFor simple consensus mode:\n");
2330 fprintf(fp, " -q, --(no-)use-qual Use quality values in calculation [off]\n");
2331 fprintf(fp, " -c, --call-fract INT At least INT portion of bases must agree [0.75]\n");
2332 fprintf(fp, " -H, --het-fract INT Minimum fraction of 2nd-most to most common base [0.15]\n");
2333 fprintf(fp, "\nFor default \"Bayesian\" consensus mode:\n");
2334 fprintf(fp, " -C, --cutoff C Consensus cutoff quality C [10]\n");
2335 fprintf(fp, " --(no-)adj-qual Modify quality with local minima [on]\n");
2336 fprintf(fp, " --(no-)use-MQ Use mapping quality in calculation [on]\n");
2337 fprintf(fp, " --(no-)adj-MQ Modify mapping quality by local NM [on]\n");
2338 fprintf(fp, " --NM-halo INT Size of window for NM count in --adj-MQ [50]\n");
2339 fprintf(fp, " --scale-MQ FLOAT Scale mapping quality by FLOAT [1.00]\n");
2340 fprintf(fp, " --low-MQ INT Cap minimum mapping quality [1]\n");
2341 fprintf(fp, " --high-MQ INT Cap maximum mapping quality [60]\n");
2342 fprintf(fp, " --P-het FLOAT Probability of heterozygous site[%.1e]\n",
2343 P_HET);
2344 fprintf(fp, " --P-indel FLOAT Probability of indel sites[%.1e]\n",
2345 P_INDEL);
2346 fprintf(fp, " --het-scale FLOAT Heterozygous SNP probability multiplier[%.1e]\n",
2347 P_HET_SCALE);
2348 fprintf(fp, " -p, --homopoly-fix Spread low-qual bases to both ends of homopolymers\n");
2349 fprintf(fp, " --homopoly-score FLOAT\n"
2350 " Qual fraction adjustment for -p option [%g]\n", P_HOMOPOLY);
2351 fprintf(fp, " -t, --qual-calibration FILE / :config (see man page)\n");
2352 fprintf(fp, " Load quality calibration file\n");
2353 fprintf(fp, "\n");
2354 fprintf(fp, " -X, --config STR Use pre-defined configuration set. STR from:\n");
2355 fprintf(fp, " hiseq, hifi, r10.4_sup, r10.4_dup and ultima\n");
2356
2357 fprintf(fp, "\nGlobal options:\n");
2358 sam_global_opt_help(fp, "-.---@-.");
2359 exit(exit_status);
2360 }
2361
2362 int main_consensus(int argc, char **argv) {
2363 int c, ret = 1;
2364
2365 consensus_opts opts = {
2366 // User options
2367 .mode = MODE_RECALL,
2368 .use_qual = 0,
2369 .min_qual = 0,
2370 .adj_qual = 1,
2371 .use_mqual = 1,
2372 .scale_mqual = 1.00,
2373 .nm_adjust = 1,
2374 .nm_halo = 50,
2375 .sc_cost = 60,
2376 .low_mqual = 1,
2377 .high_mqual = 60,
2378 .min_depth = 1,
2379 .call_fract = 0.75,
2380 .het_fract = 0.5,
2381 .het_only = 0,
2382 .fmt = FASTA,
2383 .cons_cutoff = 10,
2384 .ambig = 0,
2385 .line_len = 70,
2386 .default_qual = 10,
2387 .all_bases = 0,
2388 .show_del = 0,
2389 .show_ins = 1,
2390 .mark_ins = 0,
2391 .incl_flags = 0,
2392 .excl_flags = BAM_FUNMAP | BAM_FSECONDARY | BAM_FQCFAIL | BAM_FDUP,
2393 .min_mqual = 0,
2394 .P_het = P_HET,
2395 .P_indel = P_INDEL,
2396 .het_scale = P_HET_SCALE,
2397 .homopoly_fix = 0,
2398 .homopoly_redux = 0.01,
2399
2400 // Internal state
2401 .ks_line = {0,0},
2402 .ks_ins_seq = {0,0},
2403 .ks_ins_qual = {0,0},
2404 .fp = NULL,
2405 .fp_out = stdout,
2406 .iter = NULL,
2407 .idx = NULL,
2408 .last_tid = -1,
2409 .last_pos = -1,
2410 };
2411
2412 set_qcal(&opts.qcal, QCAL_FLAT);
2413
2414 sam_global_args ga = SAM_GLOBAL_ARGS_INIT;
2415 static const struct option lopts[] = {
2416 SAM_OPT_GLOBAL_OPTIONS('-', 0, 'O', '-', '-', '@'),
2417 {"use-qual", no_argument, NULL, 'q'},
2418 {"no-use-qual", no_argument, NULL, 'q'+1000},
2419 {"adj-qual", no_argument, NULL, 'q'+100},
2420 {"no-adj-qual", no_argument, NULL, 'q'+101},
2421 {"use-MQ", no_argument, NULL, 'm'+1000},
2422 {"no-use-MQ", no_argument, NULL, 'm'+1001},
2423 {"adj-MQ", no_argument, NULL, 'm'+100},
2424 {"no-adj-MQ", no_argument, NULL, 'm'+101},
2425 {"NM-halo", required_argument, NULL, 'h'+100},
2426 {"SC-cost", required_argument, NULL, 'h'+101},
2427 {"scale-MQ", required_argument, NULL, 14},
2428 {"low-MQ" , required_argument, NULL, 9},
2429 {"high-MQ", required_argument, NULL, 10},
2430 {"min-depth", required_argument, NULL, 'd'},
2431 {"call-fract", required_argument, NULL, 'c'},
2432 {"het-fract", required_argument, NULL, 'H'},
2433 {"region", required_argument, NULL, 'r'},
2434 {"format", required_argument, NULL, 'f'},
2435 {"cutoff", required_argument, NULL, 'C'},
2436 {"ambig", no_argument, NULL, 'A'},
2437 {"line-len", required_argument, NULL, 'l'},
2438 {"default-qual", required_argument, NULL, 1},
2439 {"het-only", no_argument, NULL, 6},
2440 {"show-del", required_argument, NULL, 7},
2441 {"show-ins", required_argument, NULL, 8},
2442 {"mark-ins", no_argument, NULL, 18},
2443 {"output", required_argument, NULL, 'o'},
2444 {"incl-flags", required_argument, NULL, 11},
2445 {"rf", required_argument, NULL, 11},
2446 {"excl-flags", required_argument, NULL, 12},
2447 {"ff", required_argument, NULL, 12},
2448 {"min-MQ", required_argument, NULL, 13},
2449 {"min-BQ", required_argument, NULL, 16},
2450 {"P-het", required_argument, NULL, 15},
2451 {"P-indel", required_argument, NULL, 17},
2452 {"het-scale", required_argument, NULL, 19},
2453 {"mode", required_argument, NULL, 'm'},
2454 {"homopoly-fix", no_argument, NULL, 'p'},
2455 {"homopoly-score", required_argument, NULL, 'p'+100},
2456 {"homopoly-redux", required_argument, NULL, 'p'+200},
2457 {"qual-calibration", required_argument, NULL, 't'},
2458 {"config", required_argument, NULL, 'X'},
2459 {NULL, 0, NULL, 0}
2460 };
2461
2462 while ((c = getopt_long(argc, argv, "@:qd:c:H:r:5f:C:aAl:o:m:pt:X:",
2463 lopts, NULL)) >= 0) {
2464 switch (c) {
2465 case 'a': opts.all_bases++; break;
2466 case 'q': opts.use_qual=1; break;
2467 case 'q'+1000: opts.use_qual=0; break;
2468 case 'm'+1000: opts.use_mqual=1; break;
2469 case 'm'+1001: opts.use_mqual=0; break;
2470 case 14: opts.scale_mqual = atof(optarg); break;
2471 case 9: opts.low_mqual = atoi(optarg); break;
2472 case 10: opts.high_mqual = atoi(optarg); break;
2473 case 'd': opts.min_depth = atoi(optarg); break;
2474 case 'c': opts.call_fract = atof(optarg); break;
2475 case 'H': opts.het_fract = atof(optarg); break;
2476 case 'r': opts.reg = optarg; break;
2477 case 'C': opts.cons_cutoff = atoi(optarg); break;
2478 case 'A': opts.ambig = 1; break;
2479 case 'p': opts.homopoly_fix = P_HOMOPOLY; break;
2480 case 'p'+100: opts.homopoly_fix = atof(optarg); break;
2481 case 'p'+200:
2482 // EXPERIMENTAL
2483 opts.homopoly_redux = atof(optarg); break;
2484 case 1: opts.default_qual = atoi(optarg); break;
2485 case 6: opts.het_only = 1; break;
2486 case 7: opts.show_del = (*optarg == 'y' || *optarg == 'Y'); break;
2487 case 8: opts.show_ins = (*optarg == 'y' || *optarg == 'Y'); break;
2488 case 18: opts.mark_ins = 1; break;
2489 case 13: opts.min_mqual = atoi(optarg); break;
2490 case 16: opts.min_qual = atoi(optarg); break;
2491 case 15: opts.P_het = atof(optarg); break;
2492 case 17: opts.P_indel = atof(optarg); break;
2493 case 19: opts.het_scale = atof(optarg); break;
2494 case 'q'+100: opts.adj_qual = 1; break;
2495 case 'q'+101: opts.adj_qual = 0; break;
2496 case 'm'+100: opts.nm_adjust = 1; break;
2497 case 'm'+101: opts.nm_adjust = 0; break;
2498 case 'h'+100: opts.nm_halo = atoi(optarg); break;
2499 case 'h'+101: opts.sc_cost = atoi(optarg); break;
2500
2501 case 'm': // mode
2502 if (strcasecmp(optarg, "simple") == 0) {
2503 opts.mode = MODE_SIMPLE;
2504 } else if (strcasecmp(optarg, "bayesian_m") == 0) {
2505 // EXPERIMENTAL:
2506 // A mixture of modified precise/recall params and a
2507 // blending of the two. Sometimes helps a bit.
2508 opts.mode = MODE_MIXED;
2509 } else if (strcasecmp(optarg, "bayesian_p") == 0) {
2510 // EXPERIMENTAL:
2511 // favours precision
2512 opts.mode = MODE_PRECISE;
2513 } else if (strcasecmp(optarg, "bayesian_r") == 0 ||
2514 strcasecmp(optarg, "bayesian") == 0) {
2515 // favours recall; the default
2516 opts.mode = MODE_RECALL;
2517 } else if (strcasecmp(optarg, "bayesian_116") == 0) {
2518 opts.mode = MODE_BAYES_116;
2519 } else {
2520 fprintf(stderr, "Unknown mode %s\n", optarg);
2521 return 1;
2522 }
2523 break;
2524
2525 case 'l':
2526 if ((opts.line_len = atoi(optarg)) <= 0)
2527 opts.line_len = INT_MAX;
2528 break;
2529
2530 case 'f':
2531 if (strcasecmp(optarg, "fasta") == 0) {
2532 opts.fmt = FASTA;
2533 } else if (strcasecmp(optarg, "fastq") == 0) {
2534 opts.fmt = FASTQ;
2535 } else if (strcasecmp(optarg, "pileup") == 0) {
2536 opts.fmt = PILEUP;
2537 } else {
2538 fprintf(stderr, "Unknown format %s\n", optarg);
2539 return 1;
2540 }
2541 break;
2542
2543 case 'o':
2544 if (!(opts.fp_out = fopen(optarg, "w"))) {
2545 perror(optarg);
2546 return 1;
2547 }
2548 break;
2549
2550 case 'X':
2551 if (strcasecmp(optarg, "hifi") == 0) {
2552 set_qcal(&opts.qcal, QCAL_HIFI);
2553 opts.mode = MODE_RECALL;
2554 opts.homopoly_fix = 0.3;
2555 opts.homopoly_redux = 0.01;
2556 opts.low_mqual = 5;
2557 opts.scale_mqual = 1.5;
2558 opts.het_scale = 0.37;
2559 } else if (strcasecmp(optarg, "hiseq") == 0) {
2560 opts.mode = MODE_RECALL;
2561 set_qcal(&opts.qcal, QCAL_HISEQ);
2562 opts.homopoly_redux = 0.01;
2563 } else if (strcasecmp(optarg, "r10.4_sup") == 0) {
2564 // Same as HiFi params, but ONT calibration table.
2565 // At higher depth, hifi params work well for ONT
2566 // when combined with ONT calibration chart.
2567 //
2568 // At lower depth we gain a bit from increasing homopoly_redux
2569 set_qcal(&opts.qcal, QCAL_ONT_R10_4_SUP);
2570 opts.mode = MODE_RECALL;
2571 opts.homopoly_fix = 0.3;
2572 opts.homopoly_redux = 0.01;
2573 opts.low_mqual = 5;
2574 opts.scale_mqual = 1.5;
2575 opts.het_scale = 0.37;
2576
2577 // Also consider, for lower depth:
2578 // opts.homopoly_redux = 1;
2579 // opts.scale_mqual = 1;
2580 // opts.het_scale = 0.45;
2581 } else if (strcasecmp(optarg, "r10.4_dup") == 0) {
2582 // Just a copy of of HiFi for duplex currently until
2583 // we get a good truth set for calibration.
2584 set_qcal(&opts.qcal, QCAL_ONT_R10_4_DUP);
2585 opts.mode = MODE_RECALL;
2586 opts.homopoly_fix = 0.3;
2587 opts.homopoly_redux = 0.01;
2588 opts.low_mqual = 5;
2589 opts.scale_mqual = 1.5;
2590 opts.het_scale = 0.37;
2591 } else if (strcasecmp(optarg, "ultima") == 0) {
2592 // Very similar to HiFi, but with own calibration table
2593 opts.mode = MODE_RECALL;
2594 set_qcal(&opts.qcal, QCAL_ULTIMA);
2595 opts.homopoly_fix = 0.3;
2596 opts.homopoly_redux = 0.01;
2597 opts.het_scale = 0.37;
2598 opts.scale_mqual = 2;
2599 opts.low_mqual = 10;
2600 } else {
2601 // NB consider defaults that are a mixture of all above.
2602 // Options are all similar for all bar Illumina.
2603 // Unsure what :flat calibration table does to each of
2604 // these though.
2605 fprintf(stderr, "Unrecognised configuration name: \"%s\"\n",
2606 optarg);
2607 return 1;
2608 }
2609 break;
2610
2611 case 11:
2612 if ((opts.incl_flags = bam_str2flag(optarg)) < 0) {
2613 print_error("consensus", "could not parse --rf %s", optarg);
2614 return 1;
2615 }
2616 break;
2617 case 12:
2618 if ((opts.excl_flags = bam_str2flag(optarg)) < 0) {
2619 print_error("consensus", "could not parse --ff %s", optarg);
2620 return 1;
2621 }
2622 break;
2623
2624 case 't': // --qual-calibration
2625 if (load_qcal(&opts.qcal, optarg) < 0) {
2626 print_error("consensus",
2627 "failed to load quality calibration '%s'",
2628 optarg);
2629 return -1;
2630 }
2631 break;
2632
2633 default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break;
2634 /* else fall-through */
2635 case '?':
2636 usage_exit(stderr, EXIT_FAILURE);
2637 }
2638 }
2639
2640 #if 0
2641 // Dump out the qcal table. Useful for copying into the code above.
2642 int i;
2643 qcal_t *q = &opts.qcal;
2644 fprintf(stderr, "{");
2645 for (i = 0; i < 100; i++)
2646 fprintf(stderr, "%2d,%s", q->smap[i],(i+1)%10?" ":"\n");
2647 fprintf(stderr, "},\n{");
2648 for (i = 0; i < 100; i++)
2649 fprintf(stderr, "%2d,%s", q->umap[i],(i+1)%10?" ":"\n");
2650 fprintf(stderr, "},\n{");
2651 for (i = 0; i < 100; i++)
2652 fprintf(stderr, "%2d,%s", q->omap[i],(i+1)%10?" ":"\n");
2653 fprintf(stderr, "}\n");
2654 #endif
2655
2656 if (opts.mode != MODE_SIMPLE) {
2657 if (opts.mode == MODE_PRECISE)
2658 // More accuracy / precision, but a significant drop
2659 // in recall.
2660 consensus_init(opts.P_het, opts.P_indel,
2661 0.3 * opts.het_scale, opts.homopoly_redux,
2662 &opts.qcal, MODE_PRECISE, &cons_prob_precise);
2663
2664 if (opts.mode == MODE_MIXED)
2665 // Blend these in when running in mixed mode, so we can
2666 // keep sensitivity but have a better joint quality to
2667 // reduce the FP rate.
2668 consensus_init(pow(opts.P_het, 0.7), pow(opts.P_indel, 0.7),
2669 0.3 * opts.het_scale, opts.homopoly_redux,
2670 &opts.qcal, MODE_PRECISE, &cons_prob_precise);
2671
2672 // Better recall, at a cost of some accuracy (false positives)
2673 consensus_init(opts.P_het, opts.P_indel, opts.het_scale,
2674 opts.mode == MODE_RECALL ? opts.homopoly_redux : 0.01,
2675 &opts.qcal, MODE_RECALL, &cons_prob_recall);
2676 }
2677
2678 if (argc != optind+1) {
2679 if (argc == optind) usage_exit(stdout, EXIT_SUCCESS);
2680 else usage_exit(stderr, EXIT_FAILURE);
2681 }
2682 opts.fp = sam_open_format(argv[optind], "r", &ga.in);
2683 if (opts.fp == NULL) {
2684 print_error_errno("consensus", "Cannot open input file \"%s\"",
2685 argv[optind]);
2686 goto err;
2687 }
2688 if (ga.nthreads > 0)
2689 hts_set_threads(opts.fp, ga.nthreads);
2690
2691 if (hts_set_opt(opts.fp, CRAM_OPT_DECODE_MD, 0)) {
2692 fprintf(stderr, "Failed to set CRAM_OPT_DECODE_MD value\n");
2693 goto err;
2694 }
2695
2696 if (!(opts.h = sam_hdr_read(opts.fp))) {
2697 fprintf(stderr, "Failed to read header for \"%s\"\n", argv[optind]);
2698 goto err;
2699 }
2700
2701 if (opts.reg) {
2702 opts.idx = sam_index_load(opts.fp, argv[optind]);
2703 if (!opts.idx) {
2704 print_error("consensus", "Cannot load index for input file \"%s\"",
2705 argv[optind]);
2706 goto err;
2707 }
2708 opts.iter = sam_itr_querys(opts.idx, opts.h, opts.reg);
2709 if (!opts.iter) {
2710 print_error("consensus", "Failed to parse region \"%s\"",
2711 opts.reg);
2712 goto err;
2713 }
2714 }
2715
2716 if (opts.fmt == PILEUP) {
2717 if (pileup_loop(opts.fp, opts.h, readaln2,
2718 opts.mode != MODE_SIMPLE ? nm_init : NULL,
2719 basic_pileup,
2720 opts.mode != MODE_SIMPLE ? nm_free : NULL,
2721 &opts) < 0)
2722 goto err;
2723
2724 if (opts.all_bases) {
2725 int tid = opts.iter ? opts.iter->tid : opts.last_tid;
2726 int len = sam_hdr_tid2len(opts.h, tid);
2727 int pos = opts.last_pos;
2728 if (opts.iter) {
2729 len = MIN(opts.iter->end, len);
2730 pos = MAX(opts.iter->beg, pos);
2731 }
2732 if (empty_pileup2(&opts, opts.h, tid, pos, len) < 0)
2733 goto err;
2734 }
2735 while (!opts.iter && opts.all_bases > 1 &&
2736 ++opts.last_tid < opts.h->n_targets) {
2737 int len = sam_hdr_tid2len(opts.h, opts.last_tid);
2738 if (empty_pileup2(&opts, opts.h, opts.last_tid, 0, len) < 0)
2739 goto err;
2740 }
2741
2742 } else {
2743 if (pileup_loop(opts.fp, opts.h, readaln2,
2744 opts.mode != MODE_SIMPLE ? nm_init : NULL,
2745 basic_fasta,
2746 opts.mode != MODE_SIMPLE ? nm_free : NULL,
2747 &opts) < 0)
2748 goto err;
2749
2750 next_ref_q:
2751 if (opts.all_bases) {
2752 // fill out terminator
2753 int tid = opts.iter ? opts.iter->tid : opts.last_tid;
2754 int len = sam_hdr_tid2len(opts.h, tid);
2755 int pos = opts.last_pos;
2756 if (opts.iter) {
2757 len = MIN(opts.iter->end, len);
2758 pos = MAX(opts.iter->beg, pos);
2759 opts.last_tid = opts.iter->tid;
2760 }
2761 if (pos < len) {
2762 if (ks_expand(&opts.ks_ins_seq, len-pos+1) < 0)
2763 goto err;
2764 if (ks_expand(&opts.ks_ins_qual, len-pos+1) < 0)
2765 goto err;
2766 while (pos++ < len) {
2767 opts.ks_ins_seq.s [opts.ks_ins_seq.l++] = 'N';
2768 opts.ks_ins_qual.s[opts.ks_ins_qual.l++] = '!';
2769 }
2770 opts.ks_ins_seq.s [opts.ks_ins_seq.l] = 0;
2771 opts.ks_ins_qual.s[opts.ks_ins_qual.l] = 0;
2772 }
2773 }
2774 if (opts.last_tid >= 0)
2775 dump_fastq(&opts, sam_hdr_tid2name(opts.h, opts.last_tid),
2776 opts.ks_ins_seq.s, opts.ks_ins_seq.l,
2777 opts.ks_ins_qual.s, opts.ks_ins_qual.l);
2778
2779 if (!opts.iter && opts.all_bases > 1 &&
2780 ++opts.last_tid < opts.h->n_targets) {
2781 opts.last_pos = 0;
2782 opts.ks_ins_seq.l = opts.ks_ins_qual.l = 0;
2783 goto next_ref_q;
2784 }
2785 // if (consensus_loop(&opts) < 0) {
2786 // print_error_errno("consensus", "Failed");
2787 // goto err;
2788 // }
2789 }
2790
2791 ret = 0;
2792
2793 err:
2794 if (opts.iter)
2795 hts_itr_destroy(opts.iter);
2796 if (opts.idx)
2797 hts_idx_destroy(opts.idx);
2798
2799 if (opts.fp && sam_close(opts.fp) < 0) {
2800 print_error_errno("consensus", "Closing input file \"%s\"",
2801 argv[optind]);
2802 ret = 1;
2803 }
2804
2805 if (opts.h)
2806 sam_hdr_destroy(opts.h);
2807 sam_global_args_free(&ga);
2808
2809 if (opts.fp_out && opts.fp_out != stdout)
2810 ret |= fclose(opts.fp_out) != 0;
2811 else
2812 ret |= fflush(stdout) != 0;
2813
2814 ks_free(&opts.ks_line);
2815 ks_free(&opts.ks_ins_seq);
2816 ks_free(&opts.ks_ins_qual);
2817
2818 if (ret)
2819 print_error("consensus", "failed");
2820
2821 return ret;
2822 }