forked from samtools/samtools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bam_consensus.c
2816 lines (2484 loc) · 97.4 KB
/
bam_consensus.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* bam_consensus.c -- consensus subcommand.
Copyright (C) 1998-2001,2003 Medical Research Council (Gap4/5 source)
Copyright (C) 2003-2005,2007-2023 Genome Research Ltd.
Author: James Bonfield <[email protected]>
The primary work here is GRL since 2021, under an MIT license.
Sections derived from Gap5, which include calculate_consensus_gap5()
associated functions, are mostly copyright Genome Research Limited from
2003 onwards. These were originally under a BSD license, but as GRL is
copyright holder these portions can be considered to also be under the
same MIT license below:
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE. */
/*
* The Gap5 consensus algorithm was in turn derived from the earlier Gap4
* tool, developed by the Medical Research Council as part of the
* Staden Package. It is unsure how much of this source code is still
* extant, without deep review, but the license used was a compatible
* modified BSD license, included below.
*/
/*
Modified BSD license for any legacy components from the Staden Package:
Copyright (c) 2003 MEDICAL RESEARCH COUNCIL
All rights reserved
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
. Neither the name of the MEDICAL RESEARCH COUNCIL, THE LABORATORY OF
MOLECULAR BIOLOGY nor the names of its contributors may be used to endorse or
promote products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// FIXME: also use strand to spot possible basecalling errors.
// Specifically het calls where mods are predominantly on one
// strand. So maybe require + and - calls and check concordance
// before calling a het as confident. (Still call, but low qual?)
// TODO: call by kmers rather than individual bases? Or use kmers to skew
// quality at least. It can identify variants that are low quality due to
// neighbouring edits that aren't consistently correlated.
// TODO: pileup callback ought to know when it's the last in the region /
// chromosome. This means the caller code doesn't have to handle the
// termination phase and deduplicates the code. (Changing from
// one chr to the next is the same as ending the last.)
//
// TODO: track which reads contribute to multiple confirmed (HQ) differences
// vs which contribute to only one (LQ) difference. Correlated changes
// are more likely to be real. Ie consensus more of a path than solely
// isolated columns.
//
// Either that or a dummy "end of data" call is made to signify end to
// permit tidying up. Maybe add a "start of data" call too?
// Eg 50T 20A seems T/A het,
// but 30T+ 20T- 18A+ 2A- seems like a consistent A miscall on one strand
// only, while T is spread evenly across both strands.
// TODO: Phasing of long reads.
// Long reads offer very strong phasing opportunities for SNPs.
// From these, we get strong evidence for accuracy of indels.
// Specifically whether the distribution of poly-len within a phases
// is significantly different to the distribution of poly len between
// phases.
// TODO end STR trimming. Eg:
// REF AAGCTGAAAAGTTAATGTCTTATTTTTTTTTTTTTTTTGAGATGGAGTC
// aagctgaaaagttaatgtctta****ttttttttttttgagatggagtc
// aagctgaaaagttaatgtcttattttttttt
// aagctgaaaagttaatgtctta****ttttttttttttgagatggagtc
// Middle seq doesn't validate those initial T alignments.
// Qual_train solves this by use of the STR trimmer.
// TODO add a weight for proximity to homopolymer.
// Maybe length/distance? So 3 away from a 12-mer is similar to 1 away
// from a 4-mer?
// TODO: Count number of base types between this point and the nearest
// indel or end of read. Eg GATCG<here>AGAGAG*TAGC => 2 (A and G).
// adj is nbase/4 * score, or (nbase+1)/5?
// Perhaps multiplied by length too, to get local complexity score?
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <math.h>
#include <limits.h>
#include <float.h>
#include <ctype.h>
#include <htslib/sam.h>
#include <htslib/hfile.h>
#include "samtools.h"
#include "sam_opts.h"
#include "bam_plbuf.h"
#include "consensus_pileup.h"
#ifdef __SSE__
# include <xmmintrin.h>
#else
# define _mm_prefetch(a,b)
#endif
#ifndef MIN
# define MIN(a,b) ((a)<(b)?(a):(b))
#endif
#ifndef MAX
# define MAX(a,b) ((a)>(b)?(a):(b))
#endif
// Defines for experiment code which is currently disabled
// Hardy-Weinberg statistics to check heterozygous sites match allelic
// frequencies.
//#define DO_HDW
// Filter bayesian calls by min-depth and min-fract parameters
//#define DO_FRACT
// Checks uniqueness of surrounding bases to adjust scores
//#define K2 2
// Look for strand bias in distribution of homopolymer lengths
//#define DO_POLY_DIST
// Minimum cutoff for storing mod data; => at least 10% chance
#define MOD_CUTOFF 0.46
enum format {
FASTQ,
FASTA,
PILEUP
};
typedef unsigned char uc;
// Simple recalibration table for substitutions, undercalls and overcalls.
// In future, we'll update this to be kmer based too.
typedef struct {
int smap[101]; // substituion or SNP
int umap[101]; // undercall or DEL
int omap[101]; // overcall or INS
} qcal_t;
typedef struct {
// User options
char *reg;
int use_qual;
int min_qual;
int adj_qual;
int use_mqual;
double scale_mqual;
int nm_adjust;
int nm_halo;
int sc_cost;
int low_mqual;
int high_mqual;
int min_depth;
double call_fract;
double het_fract;
int mode; // One of MODE_* macros below
enum format fmt;
int cons_cutoff;
int ambig;
int line_len;
int default_qual;
int het_only;
int all_bases;
int show_del;
int show_ins;
int mark_ins;
int excl_flags;
int incl_flags;
int min_mqual;
double P_het;
double P_indel;
double het_scale;
double homopoly_fix;
double homopoly_redux;
qcal_t qcal;
// Internal state
samFile *fp;
FILE *fp_out;
sam_hdr_t *h;
hts_idx_t *idx;
hts_itr_t *iter;
kstring_t ks_line;
kstring_t ks_ins_seq;
kstring_t ks_ins_qual;
int last_tid;
hts_pos_t last_pos;
} consensus_opts;
/* --------------------------------------------------------------------------
* A bayesian consensus algorithm that analyses the data to work out
* which hypothesis of pure A/C/G/T/absent and all combinations of two
* such bases meets the observations.
*
* This has its origins in Gap4 (homozygous) -> Gap5 (heterozygous)
* -> Crumble (tidied up to use htslib's pileup) -> here.
*
*/
#define CONS_DISCREP 4
#define CONS_ALL 15
#define CONS_MQUAL 16
typedef struct {
/* the most likely base call - we never call N here */
/* A=0, C=1, G=2, T=3, *=4 */
int call;
/* The most likely heterozygous base call */
/* Use "ACGT*"[het / 5] vs "ACGT*"[het % 5] for the combination */
int het_call;
/* Log-odds for het_call */
int het_logodd;
/* Single phred style call */
int phred;
/* Sequence depth */
int depth;
/* Discrepancy search score */
float discrep;
} consensus_t;
#define P_HET 1e-3
#define P_INDEL 2e-4
#define P_HOMOPOLY 0.5
#define P_HET_SCALE 1.0
#define LOG10 2.30258509299404568401
#define TENOVERLOG10 4.34294481903251827652
#define TENLOG2OVERLOG10 3.0103
#ifdef __GNUC__
#define ALIGNED(x) __attribute((aligned(x)))
#else
#define ALIGNED(x)
#endif
// Initialised once as a global array. This won't work if threaded,
// but we'll rewrite if and when that gets added later.
static double e_tab_a[1002] ALIGNED(16);
static double *e_tab = &e_tab_a[500];
static double e_tab2_a[1002] ALIGNED(16);
static double *e_tab2 = &e_tab2_a[500];
static double e_log[501] ALIGNED(16);
/* Precomputed matrices for the consensus algorithm */
typedef struct {
double prior[25] ALIGNED(16); /* Sum to 1.0 */
double lprior15[15] ALIGNED(16); /* 15 combinations of {ACGT*} */
double pMM[101] ALIGNED(16);
double p__[101] ALIGNED(16);
double p_M[101] ALIGNED(16);
double po_[101] ALIGNED(16);
double poM[101] ALIGNED(16);
double poo[101] ALIGNED(16);
double puu[101] ALIGNED(16);
double pum[101] ALIGNED(16);
double pmm[101] ALIGNED(16);
// Multiplier on homopolymer length before reducing phred qual
double poly_mul;
} cons_probs;
// Two sets of params; recall oriented (gap5) and precision (stf).
// We use the former unless MODE_MIXED is set (which is the default
// for bayesian consensus mode if P_indel is significant).
static cons_probs cons_prob_recall, cons_prob_precise;
/*
* Lots of confusing matrix terms here, so some definitions will help.
*
* M = match base
* m = match pad
* _ = mismatch
* o = overcall
* u = undercall
*
* We need to distinguish between homozygous columns and heterozygous columns,
* done using a flat prior. This is implemented by treating every observation
* as coming from one of two alleles, giving us a 2D matrix of possibilities
* (the hypotheses) for each and every call (the observation).
*
* So pMM[] is the chance that given a call 'x' that it came from the
* x/x allele combination. Similarly p_o[] is the chance that call
* 'x' came from a mismatch (non-x) / overcall (consensus=*) combination.
*
* Examples with observation (call) C and * follows
*
* C | A C G T * * | A C G T *
* ----------------- -----------------
* A | __ _M __ __ o_ A | uu uu uu uu um
* C | _M MM _M _M oM C | uu uu uu uu um
* G | __ _M __ __ o_ G | uu uu uu uu um
* T | __ _M __ __ o_ T | uu uu uu uu um
* * | o_ oM o_ o_ oo * | um um um um mm
*
* In calculation terms, the _M is half __ and half MM, similarly o_ and um.
*
* Relative weights of substitution vs overcall vs undercall are governed on a
* per base basis using the P_OVER and P_UNDER scores (subst is
* 1-P_OVER-P_UNDER).
*
* The heterozygosity weight though is a per column calculation as we're
* trying to model whether the column is pure or mixed. Hence this is done
* once via a prior and has no affect on the individual matrix cells.
*
* We have a generic indel probability, but it's a catch all for overcall,
* undercall, alignment artifacts, homopolymer issues, etc. So we can set
* it considerably higher and just let the QUAL skew do the filtering for
* us, albeit no longer well calibrated.
*/
// NB: Should _M be MM?
// Ie sample really is A/C het, and we observe C. That should be a match,
// not half a match.
#define MODE_SIMPLE 0 // freq counting
#define MODE_BAYES_116 1 // Samtools 1.16 (no indel param)
#define MODE_RECALL 2 // so called as it's the params from Gap5
#define MODE_PRECISE 3 // a more precise set; +FN, --FP
#define MODE_MIXED 4 // Combination of GAP5/BAYES
#define QCAL_FLAT 0
#define QCAL_HIFI 1
#define QCAL_HISEQ 2
#define QCAL_ONT_R10_4_SUP 3
#define QCAL_ONT_R10_4_DUP 4
#define QCAL_ULTIMA 5
// Calibration tables here don't necessarily reflect the true accuracy.
// They have been manually tuned to work in conjunction with other command
// line parameters used in the machine profiles. For example reducing one
// qual here and increasing sensitivity elsewhere via another parameter.
static qcal_t static_qcal[6] = {
{ // FLAT
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
60, 61, 62, 63, 64, 65, 66, 67, 68, 69,
70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 84, 85, 86, 87, 88, 89,
90, 91, 92, 93, 94, 95, 96, 97, 98, 99},
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
60, 61, 62, 63, 64, 65, 66, 67, 68, 69,
70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 84, 85, 86, 87, 88, 89,
90, 91, 92, 93, 94, 95, 96, 97, 98, 99},
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
60, 61, 62, 63, 64, 65, 66, 67, 68, 69,
70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 84, 85, 86, 87, 88, 89,
90, 91, 92, 93, 94, 95, 96, 97, 98, 99}
},
{ // HiFi
{10, 11, 11, 12, 13, 14, 15, 16, 18, 19,
20, 21, 22, 23, 24, 25, 27, 28, 29, 30,
31, 32, 33, 33, 34, 35, 36, 36, 37, 38,
38, 39, 39, 40, 40, 41, 41, 41, 41, 42,
42, 42, 42, 43, 43, 43, 43, 43, 43, 43,
44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
},
{ 4, 4, 4, 4, 5, 6, 6, 7, 8, 9,
10, 11, 11, 12, 13, 14, 15, 15, 16, 17,
18, 19, 19, 20, 20, 21, 22, 23, 23, 24,
25, 25, 25, 26, 26, 26, 27, 27, 28, 28,
28, 28, 27, 27, 27, 28, 28, 28, 28, 27,
27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 26, 26, 25, 26, 26, 27, 27, 27,
26, 26, 26, 26, 26, 26, 26, 26, 27, 27,
28, 29, 28, 28, 28, 27, 27, 27, 27, 27,
27, 28, 28, 30, 30, 30, 30, 30, 30, 30,
},
{ 8, 8, 8, 8, 9, 10, 11, 12, 13, 14,
15, 15, 16, 17, 18, 19, 19, 20, 20, 21,
21, 22, 22, 23, 23, 23, 24, 24, 24, 25,
25, 25, 25, 25, 25, 26, 26, 26, 26, 27,
27, 27, 27, 27, 27, 28, 28, 28, 28, 28,
29, 29, 29, 29, 29, 29, 30, 30, 30, 30,
30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
}
},
{ // HiSeq
{ 2, 2, 2, 3, 3, 4, 5, 5, 6, 7,
8, 9, 10, 11, 11, 12, 13, 14, 15, 16,
17, 17, 18, 19, 20, 21, 22, 22, 23, 24,
25, 26, 27, 28, 28, 29, 30, 31, 32, 33,
34, 34, 35, 36, 37, 38, 39, 39, 40, 41,
42, 43, 44, 45, 45, 46, 47, 48, 49, 50,
51, 51, 52, 53, 54, 55, 56, 56, 57, 58,
59, 60, 61, 62, 62, 63, 64, 65, 66, 67,
68, 68, 69, 70, 71, 72, 73, 73, 74, 75,
76, 77, 78, 79, 79, 80, 81, 82, 83, 84,
},
{ 1, 2, 3, 4, 5, 7, 8, 9, 10, 11,
13, 14, 15, 16, 17, 19, 20, 21, 22, 23,
25, 26, 27, 28, 29, 31, 32, 33, 34, 35,
37, 38, 39, 40, 41, 43, 44, 45, 46, 47,
49, 50, 51, 52, 53, 55, 56, 57, 58, 59,
61, 62, 63, 64, 65, 67, 68, 69, 70, 71,
73, 74, 75, 76, 77, 79, 80, 81, 82, 83,
85, 86, 87, 88, 89, 91, 92, 93, 94, 95,
97, 98, 99, 100, 101, 103, 104, 105, 106, 107,
109, 110, 111, 112, 113, 115, 116, 117, 118, 119,
},
{ 1, 2, 3, 4, 5, 7, 8, 9, 10, 11,
13, 14, 15, 16, 17, 19, 20, 21, 22, 23,
25, 26, 27, 28, 29, 31, 32, 33, 34, 35,
37, 38, 39, 40, 41, 43, 44, 45, 46, 47,
49, 50, 51, 52, 53, 55, 56, 57, 58, 59,
61, 62, 63, 64, 65, 67, 68, 69, 70, 71,
73, 74, 75, 76, 77, 79, 80, 81, 82, 83,
85, 86, 87, 88, 89, 91, 92, 93, 94, 95,
97, 98, 99, 100, 101, 103, 104, 105, 106, 107,
109, 110, 111, 112, 113, 115, 116, 117, 118, 119,
}
},
{ // ONT R10.4 super
{ 0, 2, 2, 2, 3, 4, 4, 5, 6, 7,
7, 8, 9, 12, 13, 14, 15, 15, 16, 17,
18, 19, 20, 22, 24, 25, 26, 27, 28, 29,
30, 31, 33, 34, 36, 37, 38, 38, 39, 39,
40, 40, 40, 40, 40, 40, 40, 41, 40, 40,
41, 41, 40, 40, 40, 40, 41, 40, 40, 40,
40, 41, 41, 40, 40, 41, 40, 40, 39, 41,
40, 41, 40, 40, 41, 41, 41, 40, 40, 40,
40, 40, 40, 40, 40, 40, 40, 40, 40, 40,
40, 40, 40, 40, 40, 40, 40, 40, 40, 40,
},
{ 0, 2, 2, 2, 3, 4, 5, 6, 7, 8,
8, 9, 9, 10, 10, 10, 11, 12, 12, 13,
13, 13, 14, 14, 15, 16, 16, 17, 18, 18,
19, 19, 20, 21, 22, 23, 24, 25, 25, 25,
25, 25, 25, 25, 25, 25, 26, 26, 26, 26,
26, 26, 26, 26, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
},
{ 0, 4, 6, 6, 6, 7, 7, 8, 9, 9,
9, 10, 10, 11, 11, 12, 12, 13, 13, 14,
15, 15, 15, 16, 16, 17, 17, 18, 18, 19,
19, 20, 20, 21, 22, 22, 23, 23, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
}
},
{ // ONT R10.4 duplex; just a copy of hifi for now
{10, 11, 11, 12, 13, 14, 15, 16, 18, 19,
20, 21, 22, 23, 24, 25, 27, 28, 29, 30,
31, 32, 33, 33, 34, 35, 36, 36, 37, 38,
38, 39, 39, 40, 40, 41, 41, 41, 41, 42,
42, 42, 42, 43, 43, 43, 43, 43, 43, 43,
44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
},
{ 4, 4, 4, 4, 5, 6, 6, 7, 8, 9,
10, 11, 11, 12, 13, 14, 15, 15, 16, 17,
18, 19, 19, 20, 20, 21, 22, 23, 23, 24,
25, 25, 25, 26, 26, 26, 27, 27, 28, 28,
28, 28, 27, 27, 27, 28, 28, 28, 28, 27,
27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 26, 26, 25, 26, 26, 27, 27, 27,
26, 26, 26, 26, 26, 26, 26, 26, 27, 27,
28, 29, 28, 28, 28, 27, 27, 27, 27, 27,
27, 28, 28, 30, 30, 30, 30, 30, 30, 30,
},
{ 8, 8, 8, 8, 9, 10, 11, 12, 13, 14,
15, 15, 16, 17, 18, 19, 19, 20, 20, 21,
21, 22, 22, 23, 23, 23, 24, 24, 24, 25,
25, 25, 25, 25, 25, 26, 26, 26, 26, 27,
27, 27, 27, 27, 27, 28, 28, 28, 28, 28,
29, 29, 29, 29, 29, 29, 30, 30, 30, 30,
30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
}
},
{ // Ultima Genomics
{ 2, 2, 3, 4, 5, 6, 6, 7, 8, 9,
10, 10, 11, 12, 13, 14, 14, 15, 16, 17,
18, 18, 19, 21, 22, 23, 23, 24, 25, 26,
27, 27, 28, 29, 30, 31, 31, 32, 33, 34,
35, 35, 36, 37, 38, 39, 39, 40, 42, 43,
44, 44, 45, 46, 47, 48, 48, 49, 50, 51,
52, 52, 53, 54, 55, 56, 56, 57, 58, 59,
60, 60, 61, 63, 64, 65, 65, 66, 67, 68,
69, 69, 70, 71, 72, 73, 73, 74, 75, 76,
77, 77, 78, 79, 80, 81, 81, 82, 84, 85,
},
{ 1, 1, 2, 2, 3, 3, 4, 4, 4, 4,
5, 5, 6, 6, 7, 7, 8, 8, 9, 10,
10, 10, 11, 12, 13, 13, 13, 14, 15, 16,
16, 16, 17, 18, 18, 19, 19, 20, 20, 21,
21, 22, 22, 22, 22, 23, 23, 24, 24, 25,
25, 25, 25, 25, 25, 25, 26, 26, 26, 26,
26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
27, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
},
{ 1, 1, 2, 2, 3, 3, 4, 4, 4, 4,
5, 5, 6, 6, 7, 7, 8, 8, 9, 10,
10, 10, 11, 12, 13, 13, 13, 14, 15, 16,
16, 16, 17, 18, 18, 19, 19, 20, 20, 21,
21, 22, 22, 22, 22, 23, 23, 24, 24, 25,
25, 25, 25, 25, 25, 25, 26, 26, 26, 26,
26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
27, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
}
}
};
int set_qcal(qcal_t *q, int id) {
if (id < 0 || id >= sizeof(static_qcal)/sizeof(*static_qcal))
return -1;
memcpy(q, &static_qcal[id], sizeof(*q));
return 0;
}
int load_qcal(qcal_t *q, const char *fn) {
int i;
if (strcmp(fn, ":hifi") == 0)
return set_qcal(q, QCAL_HIFI);
if (strcmp(fn, ":hiseq") == 0)
return set_qcal(q, QCAL_HISEQ);
if (strcmp(fn, ":r10.4_sup") == 0)
return set_qcal(q, QCAL_ONT_R10_4_SUP);
if (strcmp(fn, ":r10.4_dup") == 0)
return set_qcal(q, QCAL_ONT_R10_4_DUP);
if (strcmp(fn, ":ultima") == 0)
return set_qcal(q, QCAL_ULTIMA);
// default
for (i = 0; i < 101; i++)
q->smap[i] = q->umap[i] = q->omap[i] = i;
if (strcmp(fn, ":flat") == 0)
return 0;
hFILE *fp = hopen(fn, "r");
if (!fp)
return -1;
kstring_t line = KS_INITIALIZE;
int max = 0;
int last_qual = 0;
while (line.l = 0, kgetline(&line, (kgets_func *)hgets, fp) >= 0) {
int v, s, u, o;
if (*line.s == '#')
continue;
if (sscanf(line.s, "QUAL %d %d %d %d", &v, &s, &u, &o) != 4)
goto err;
while (v > last_qual) {
q->smap[last_qual+1] = q->smap[last_qual];
q->umap[last_qual+1] = q->umap[last_qual];
q->omap[last_qual+1] = q->omap[last_qual];
last_qual++;
}
if (v >= 0 && v < 100) {
q->smap[v] = s;
q->umap[v] = u;
q->omap[v] = o;
}
if (v < max) {
fprintf(stderr, "Qual calibration file is not in ascending order\n");
return hclose(fp) ? -2 : -1;
}
max = v;
}
for (i = max+1; i < 101; i++) {
q->smap[i] = q->smap[max];
q->umap[i] = q->umap[max];
q->omap[i] = q->omap[max];
}
ks_free(&line);
return hclose(fp) < 0 ? -2 : 0;
err:
ks_free(&line);
return hclose(fp) < 0 ? -2 : -1;
}
static void consensus_init(double p_het, double p_indel, double het_scale,
double poly_mul,
qcal_t *qcal, int mode, cons_probs *cp) {
int i;
// NB: only need to initialise once, but we do here for now
for (i = -500; i <= 500; i++)
e_tab[i] = exp(i);
for (i = -500; i <= 500; i++)
e_tab2[i] = exp(i/10.);
for (i = 0; i <= 500; i++)
e_log[i] = log(i);
// EXPERIMENTAL
cp->poly_mul = poly_mul;
// The priors make very little difference, unless shallow data.
// ACGT* by ACGT*
// So AA=0, CC=6, GG=12, TT=18, **=24
for (i = 0; i < 25; i++)
cp->prior[i] = p_het / 6; // AC AG AT CG CT GT
// Flat assumption that it is what we observe, and measure everything else
// as relative to this.
cp->prior[0]=cp->prior[6]=cp->prior[12]=cp->prior[18]=cp->prior[24] = 1;
// heterozygous deletion
for (i = 4; i < 24; i+=5)
cp->prior[i] = p_indel / 6; // /6 to be scaled vs p_het equivalently
// heterozygous insertion
for (i = 20; i < 24; i++)
cp->prior[i] = p_indel / 6;
cp->lprior15[0] = log(cp->prior[0]);
cp->lprior15[1] = log(cp->prior[1]);
cp->lprior15[2] = log(cp->prior[2]);
cp->lprior15[3] = log(cp->prior[3]);
cp->lprior15[4] = log(cp->prior[4]);
cp->lprior15[5] = log(cp->prior[6]);
cp->lprior15[6] = log(cp->prior[7]);
cp->lprior15[7] = log(cp->prior[8]);
cp->lprior15[8] = log(cp->prior[9]);
cp->lprior15[9] = log(cp->prior[12]);
cp->lprior15[10] = log(cp->prior[13]);
cp->lprior15[11] = log(cp->prior[14]);
cp->lprior15[12] = log(cp->prior[18]);
cp->lprior15[13] = log(cp->prior[19]);
cp->lprior15[14] = log(cp->prior[24]);
for (i = 1; i < 101; i++) {
double prob = 1 - pow(10, -qcal->smap[i] / 10.0);
// Or is it that prob is 1-p(subst)-p(overcall)?
cp->pMM[i] = log(prob);
//cp->p__[i] = log(1-prob); // Big help to PB-CCS SNPs; unless fudged
cp->p__[i] = log((1-prob)/3); // correct? poor on PB-CCS w/o fudge
// Mixed alleles; just average two likelihoods
cp->p_M[i] = log((exp(cp->pMM[i]) + exp(cp->p__[i]))/2);
// What does this really mean? Can we simulate this by priors?
// It reduces the likelihood of calling het sites, which is
// maybe compensation for alignment artifacts? I'm unsure,
// but it works (to differing degrees) on both PacBio HiFi and
// Illumina HiSeq. It (obviously) loses true hets, but
// potentially this can be compensated for by tweaking P-het
// (which is entirely in the priors).
//
// Low het_scale reduces false positives by making hets less
// likely to be called. In high depth data we normally have
// enough evidence to call correctly even with low het_scale,
// so it's a good +FN vs --FP tradeoff. However on low depth
// data, het_scale can filter out too many true variants.
//
// TODO: So consider adjusting at the end maybe?
// Also consider never changing calls, but changing their
// confidence, so the data is what produces the call with the
// parameters skewing the quality score distribution.
cp->p_M[i] += log(het_scale);
if (mode == MODE_BAYES_116) {
// Compatibility with samtools 1.16
// This had no differention for indel vs substitution error rates,
// so o(vercall) and u(undercall) are subst(_).
cp->pmm[i] = cp->pMM[i];
cp->poM[i] = cp->p_M[i];
cp->pum[i] = cp->p_M[i];
cp->po_[i] = cp->p__[i];
cp->poo[i] = cp->p__[i];
cp->puu[i] = cp->p__[i];
} else {
// When observing A C G T; leads to insertion calls
prob = 1 - pow(10, -qcal->omap[i] / 10.0);
// /3 for consistency with ACGT rem as relative likelihoods.
// Otherwise with flat priors we end up calling all shallow data
// as "*", which is illogical.
cp->poo[i] = log((1-prob)/3);
// Ensure pMM is always more likely. (NB: This shouldn't happen
// now with the addition of the /3 step above.)
if (cp->poo[i] > cp->pMM[i]-.5)
cp->poo[i] = cp->pMM[i]-.5;
cp->po_[i] = log((exp(cp->poo[i]) + exp(cp->p__[i]))/2);
cp->poM[i] = log((exp(cp->poo[i]) + exp(cp->pMM[i]))/2);
// Overcalls should never be twice as likely than mismatches.
// Het bases are mix of _M (other) and MM ops (this).
// It's fine for _M to be less likely than oM (more likely
// to be overcalled than miscalled), but it should never
// be stronger when combined with other mixed data.
if (cp->poM[i] > cp->p_M[i]+.5)
cp->poM[i] = cp->p_M[i]+.5;
// Note --low-MQ and --scale-MQ have a big impact on
// undercall errs. May need to separate these options per
// type, but how?
// Multiple-calls, as with mixed mode? This feels like a cheat
prob = 1 - pow(10, -qcal->umap[i] / 10.0);
cp->pmm[i] = log(prob);
cp->puu[i] = log((1-prob)/3);
if (cp->puu[i] > cp->pMM[i]-.5) // MM is -ve
cp->puu[i] = cp->pMM[i]-.5;
cp->pum[i] = log((exp(cp->puu[i]) + exp(cp->pmm[i]))/2);
}
}
cp->pMM[0] = cp->pMM[1];
cp->p__[0] = cp->p__[1];
cp->p_M[0] = cp->p_M[1];
cp->pmm[0] = cp->pmm[1];
cp->poo[0] = cp->poo[1];
cp->po_[0] = cp->po_[1];
cp->poM[0] = cp->poM[1];
cp->puu[0] = cp->puu[1];
cp->pum[0] = cp->pum[1];
}
static inline double fast_exp(double y) {
if (y >= -50 && y <= 50)
return e_tab2[(int)(y*10)];
if (y < -500)
y = -500;
if (y > 500)
y = 500;
return e_tab[(int)y];
}
/* Taylor (deg 3) implementation of the log */
static inline double fast_log2(double val)
{
// FP representation is exponent & mantissa, where
// value = 2^E * M.
// Hence log2(value) = log2(2^E * M)
// = log2(2^E)+ log2(M)
// = E + log2(M)
union { double d; uint64_t x; } u = {val};
const int E = ((u.x >> 52) & 2047) - 1024; // exponent E
// Initial log2(M) based on mantissa
u.x &= ~(2047LL << 52);
u.x += 1023LL << 52;
val = ((-1/3.) * u.d + 2) * u.d - 2/3.;
return E + val;
}
#define ph_log(x) (-TENLOG2OVERLOG10*fast_log2((x)))
int nins(const bam1_t *b){
int i, indel = 0;
uint32_t *cig = bam_get_cigar(b);
for (i = 0; i < b->core.n_cigar; i++) {
int op = bam_cigar_op(cig[i]);
if (op == BAM_CINS || op == BAM_CDEL)
indel += bam_cigar_oplen(cig[i]);
}
return indel;
}
/*
* Some machines, including 454 and PacBio, store the quality values in
* homopolymers with the first or last base always being the low quality
* state. This can cause problems when reverse-complementing and aligning,
* especially when we left-justify indels.
*
* Other platforms take the approach of having the middle bases high and
* the low confidence spread evenly to both start and end. This means
* reverse-complementing doesn't introduce any strand bias.
*
* We redistribute qualities within homopolymers in this style to fix
* naive consensus or variant calling algorithms.
*/
void homopoly_qual_fix(bam1_t *b) {
static double ph2err[256] = {0};
int i;
if (!ph2err[0]) {
for (i = 0; i < 256; i++)
ph2err[i] = pow(10, i/-10.0);
}
uint8_t *seq = bam_get_seq(b);
uint8_t *qual = bam_get_qual(b);
for (i = 0; i < b->core.l_qseq; i++) {
int s = i; // start of homopoly
int base = bam_seqi(seq, i);
while (i+1 < b->core.l_qseq && bam_seqi(seq, i+1) == base)
i++;
// s..i inclusive is now homopolymer
if (s == i)
continue;
// Simplest: reverse if end_qual < start_qual
// Next: average outer-most two, then next two, etc
// Best: fully redistribute so start/end lower qual than centre
// Middle route of averaging outer pairs is sufficient?
int j, k;
for (j = s, k = i; j < k; j++,k--) {
double e = ph2err[qual[j]] + ph2err[qual[k]];
qual[j] = qual[k] = -fast_log2(e/2)*3.0104+.49;
}
}
}
// Return the local NM figure within halo (+/- HALO) of pos.
// This local NM is used as a way to modify MAPQ to get a localised MAPQ
// score via an adhoc fashion.
double nm_local(const pileup_t *p, const bam1_t *b, hts_pos_t pos) {
int *nm = (int *)p->cd;
if (!nm)
return 0;
pos -= b->core.pos;
if (pos < 0)
return nm[0] & ((1<<24)-1);
if (pos >= b->core.l_qseq)
return nm[b->core.l_qseq-1] & ((1<<24)-1);
return (nm[pos] & ((1<<24)-1)) / 10.0;
}
int poly_len(const pileup_t *p, const bam1_t *b, hts_pos_t pos) {
int *nm = (int *)p->cd;
if (!nm)
return 0;
pos -= b->core.pos;
if (pos >= 0 && pos < b->core.l_qseq)
return nm[pos] >> 24;
else
return 0;
}
/*
* Initialise a new sequence appearing in the pileup. We use this to
* precompute some metrics that we'll repeatedly use in the consensus
* caller; the localised NM score.
*
* We also directly amend the BAM record (which will be discarded later
* anyway) to modify qualities to account for local quality minima.
*
* Returns 0 (discard) or 1 (keep) on success, -1 on failure.
*/
int nm_init(void *client_data, samFile *fp, sam_hdr_t *h, pileup_t *p) {
consensus_opts *opts = (consensus_opts *)client_data;
if (!opts->use_mqual)
return 1;
const bam1_t *b = &p->b;
int qlen = b->core.l_qseq, i;
if (qlen <= 0)
return 0;
int *local_nm = calloc(qlen, sizeof(*local_nm));
if (!local_nm)
return -1;
p->cd = local_nm;
double poly_adj = opts->homopoly_fix ? opts->homopoly_fix : 1;
if (opts->adj_qual) {
// Set local_nm based on a function of current qual and the local
// minimum qual within the surrounding window.
//
// Basically if we're in a region of low confidence then we downgrade
// higher qual outliers as they may not be as trustworthy as they
// claim. This may be because the qualities have been assigned to
// the wrong or arbitrary base (very common in homopolymers), or the
// surrounding quality (hence also error likelihood) have lead to
// misalignments and the base may be contributing to the wrong
// pileup column.
//
// The nm_local() function returns these scores and uses it to bias
// the mapping quality, which in turn adjusts base quality.
uint8_t *qual = bam_get_qual(b);
uint8_t *seq = bam_get_seq(b);
const int qhalo = 8; // window size for base qual
int qmin = qual[0]; // min qual within qhalo
const int qhalop = 2;// window size for homopolymer qual
int qminp = qual[0]; // min qual within homopolymer halo
int base = bam_seqi(seq, 0), polyl = 0, polyr = 0; // pos, not len
// Minimum quality of the initial homopolymer
for (i = 1; i < qlen; i++) {
if (bam_seqi(seq, i) != base)
break;
if (i < qhalop && qminp > qual[i])
qminp = qual[i];
}
// Minimum quality for general bases
for (i = 0; i < qlen && i < qhalo; i++) {
if (qmin > qual[i])
qmin = qual[i];
}