Debian Codegraph @

samtools/bam_consensus.c.pysam.c

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