-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsnp_score.c
2677 lines (2297 loc) · 75.3 KB
/
snp_score.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
// Various extra heuristics for storing qualities. The general rule
// of thumb is that if we think the alignment is suspect in some way
// then we need to keep all the qualities so that it can be remapped
// to a new place. Consider migration from GRCh37 to h38 - even if it
// has high mapping quality in GRCh37, if we can detect something
// suspicious then we preserve our accuracy when we subsequently
// remap.
//
// Additionally we may be able to generate a bed file showing regions
// that shouldn't be considered as high quality for snp/indel
// calling.
// TODO: excessive depth => mismapped. (keep quals) Eg
// 16:46393052
// TODO: More than 2 haplotypes for 1 single sample.
// 1:142537663 (Also extra deep)
// 1:8404952
// 17:22251551
// TODO: Prevelance of lots of low mapping quality may mean other
// high quality reads should also be considered low mapping quality?
// (But perhaps only if they're not softclipped.) Lack of
// soft-clipping implies collapsed repeat, so casts doubt on all data.
// DONE: need to test
// 1:8404952
// TODO: Concordant soft-clip detection
// Regions with lots of soft-clip that aligns well against each other
// indicate a large insertion or possibly an expanded repeat. These
// sometimes give rise to fake SNPs.
// [Less complex solution, count %age of reads with clip-point larger
// than a specific length at a specific site. If > X then preserve all
// reads with a clip point at that site (regardless of length). Or
// all reads, not just those with soft-clip?]
// 1:231337816
// 18:312676
// X:104252683
// TODO: Insertion concordance.
// This is hard to do with samtools pileup as we only get ref by ref
// rather than consensus by consensus, but if there is a lot of
// variance between the inserted bases then it implies we have suspect
// alignments.
// DONE: Trivial implementation is simply length concordance; if there
// are many different lengths then it's probably suspect.
// TODO: Per type parameters, so one set for SNPs and another set for Indels.
// TODO: Generalised "somatic" option that is like -k(eep) but for any value
// at or above a specific qual?
//#define DEBUG
#define CRUMBLE_VERSION "0.9.1"
/*
* Prunes quality based on snp calling score.
*
* Bi-allelic consensus is computed (possibly as hom).
* If call has high confidence, then bin to 2 qualities.
* - high if base is one of the 1-2 consensus calls.
* - low otherwise.
*
* Exceptions.
* - Within 'D' bases of any read indel.
* - Within 'D' bases of a soft-clip (possible clipped indel).
* - Any sequence with mapping quality of <= M.
* - Any column with high discrepancy, implying possibly tri-allelic.
*
*/
/*
* TODO: Het indels may mean we quantise the indel but not the
* non-indel. This gives a bias. Need to treat both the same.
*
* Identify low complexity regions. If we're preserving confidence
* then it needs to be for all bases in that low-complexity section so
* that local realignment doesn't change qualities.
*
* Consider using STR method for detecting start/end range of bases to
* keep for SNPs as well as indels, particularly when the sequence is
* soft-clipped during an STR. (Possibility of misaligned bases
* then.) Or just a low complexity filter? Or concordant soft-clips?
*
* For indels, consider the soft-clip adjustment on reads ending in
* STR adjacent to indels as these bases don't confirm the count.
*/
// Default params
#define MAX_DEPTH 20000
#define QL 5
#define QM 25 // below => QL, else QH
#define QH 40
#define QCAP 60 // useful in PacBio CCS
// If mapping qual <= MIN_MQUAL we preserve all quality values.
#define MIN_MQUAL 0
// Whether to allow quality reduction on mismatching bases (ie QL)
#define REDUCE_QUAL 1
#define BINARY_QUAL 0
// Fraction of reads with an indel before we attempt STR scoring
#define INDEL_FRACT 0.
// Standard gap5 algorithm; set MIN_QUAL_A to 0 to disable
#define MIN_QUAL_A 0
#define MIN_INDEL_A 50
#define MIN_DISCREP_A 2.0
// With mqual adjustment; set MIN_QUAL_B to 0 to disable
#define MIN_QUAL_B 70
#define MIN_INDEL_B 125
#define MIN_DISCREP_B 1.5
//#define MIN_QUAL_B 50
//#define MIN_INDEL_B 100
//#define MIN_DISCREP_B 1.5
// Extra growth to expand indel qual region.
// New region = old_region +/- (region_len*STR_MUL + STR_ADD)
#define S_STR_MUL 0.0
#define S_STR_ADD 0
#define I_STR_MUL 1.0
#define I_STR_ADD 2
// Prevalence of low mapping quality, > PERC => store all
// Lower => larger files
#define LOW_MQUAL_PERC 1.0
// Amount of variable sized insertion
#define INS_LEN_PERC 1.0
// Percentage of seqs with large soft-clips
#define CLIP_PERC 0.2
// Amount of over-depth to consider this as as suspect region
#define OVER_DEPTH 999.0
// Percentage of reads spanning indel.
#define INDEL_OVERLAP_PERC 0.0
#define PBLOCK 8
#define BED_DIST 50
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <assert.h>
#include <math.h>
#include <float.h>
#include <getopt.h>
#include <inttypes.h>
#include <unistd.h>
#include <htslib/sam.h>
#include <htslib/cram.h>
#include <htslib/khash.h>
#include "str_finder.h"
#include "tree.h"
#include "bed.h"
#ifndef MIN
#define MIN(a,b) ((a)<(b)?(a):(b))
#endif
#ifndef MAX
#define MAX(a,b) ((a)>(b)?(a):(b))
#endif
#ifndef ABS
#define ABS(a) ((a)>=0?(a):-(a))
#endif
KHASH_SET_INIT_INT(aux_exists)
typedef khash_t(aux_exists) *auxhash_t;
typedef struct {
int reduce_qual, binary_qual;
int iSTR_add, sSTR_add;
double iSTR_mul, sSTR_mul;
int qlow, qcutoff, qhigh, qcap;
int min_mqual;
char *region;
char *bed_fn;
bed_reg *bed;
int nbed;
double indel_fract;
// Standard gap5 algorithm
int min_qual_A;
int min_indel_A;
double min_discrep_A;
// Mqual adjusted algorithm
int min_qual_B;
int min_indel_B;
double min_discrep_B;
// Tag white/black lists
auxhash_t aux_whitelist;
auxhash_t aux_blacklist;
double low_mqual_perc;
double clip_perc;
double ins_len_perc;
double over_depth;
double indel_ov_perc;
FILE *bed_fp;
int verbose;
int pblock;
int softclip;
int noPG;
int perfect_col;
// For BD/BI tag adjustments
int BD_low, BD_mid, BD_high;
int BI_low, BI_mid, BI_high;
} cram_lossy_params;
//-----------------------------------------------------------------------------
// Binning
static int bin2[256];
static uint8_t preserve_qual[256] = {0};
void init_bins(cram_lossy_params *p) {
int i;
// Binary mode - just high/low
for (i = 0; i < p->qcutoff; i++)
bin2[i] = p->qlow;
for (; i < 256; i++)
bin2[i] = p->qhigh;
// Except for any explicit values we wish to preserve
for (i = 0; i < 256; i++)
if (preserve_qual[i] > 1) // really presever
bin2[i] = i;
}
//-----------------------------------------------------------------------------
// Bits ripped out of gap5's consensus algorithm; an interim solution
#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_phred;
/* Single phred style call */
unsigned char phred;
/* Sequence depth */
int depth;
/* Discrepancy search score */
float discrep;
/* Bit field of bases with qualities in the preserve_qual array */
/* A=1, C=2, G=4, T=8, *=16, N=32 */
int call_preserve;
} consensus_t;
#define P_HET 1e-6
#define LOG10 2.30258509299404568401
#define TENOVERLOG10 4.34294481903251827652
#define TENLOG2OVERLOG10 3.0103
/* Sequencing technologies for seq_t.seq_tech; 5 bits, so max=31 */
#define STECH_UNKNOWN 0
#define STECH_SANGER 1
#define STECH_SOLEXA 2
#define STECH_SOLID 3
#define STECH_454 4
#define STECH_HELICOS 5
#define STECH_IONTORRENT 6
#define STECH_PACBIO 7
#define STECH_ONT 8
#define STECH_LAST 8 // highest value
double tech_undercall[] = {
1.00, // unknown
1.00, // sanger
1.00, // solexa/illumina
1.00, // solid
1.00, // 454
1.00, // helicos
1.00, // iontorrent
1.00, // pacbio
1.63, // ont
};
#ifdef __GNUC__
#define ALIGNED(x) __attribute((aligned(x)))
#else
#define ALIGNED(x)
#endif
static double prior[25] ALIGNED(16); /* Sum to 1.0 */
static double lprior15[15] ALIGNED(16); /* 15 combinations of {ACGT*} */
/* Precomputed matrices for the consensus algorithm */
static double pMM[9][101] ALIGNED(16);
static double p__[9][101] ALIGNED(16);
static double p_M[9][101] ALIGNED(16);
static double po_[9][101] ALIGNED(16);
static double poM[9][101] ALIGNED(16);
static double poo[9][101] ALIGNED(16);
static double puu[9][101] ALIGNED(16);
static double pum[9][101] ALIGNED(16);
static double pmm[9][101] ALIGNED(16);
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);
/*
* 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.
*/
static void consensus_init(double p_het) {
int i, t;
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);
// Heterozygous locations
for (i = 0; i < 25; i++)
prior[i] = p_het / 20;
prior[0] = prior[6] = prior[12] = prior[18] = prior[24] = (1-p_het)/5;
lprior15[0] = log(prior[0]);
lprior15[1] = log(prior[1]*2);
lprior15[2] = log(prior[2]*2);
lprior15[3] = log(prior[3]*2);
lprior15[4] = log(prior[4]*2);
lprior15[5] = log(prior[6]);
lprior15[6] = log(prior[7]*2);
lprior15[7] = log(prior[8]*2);
lprior15[8] = log(prior[9]*2);
lprior15[9] = log(prior[12]);
lprior15[10] = log(prior[13]*2);
lprior15[11] = log(prior[14]*2);
lprior15[12] = log(prior[18]);
lprior15[13] = log(prior[19]*2);
lprior15[14] = log(prior[24]);
// Rewrite as new form
for (t = STECH_UNKNOWN; t <= STECH_LAST; t++) {
for (i = 1; i < 101; i++) {
double prob = 1 - pow(10, -i / 10.0);
// if (t == STECH_ONT)
// prob = 0.85; // Fake FIXED prob for now
// May want to multiply all these by 5 so pMM[i] becomes close
// to -0 for most data. This makes the sums increment very slowly,
// keeping bit precision in the accumulator.
#if 0
double p_overcall[] = {
0.001, // unknown
0.010, // sanger
0.001, // solexa/illumina
0.001, // solid
0.010, // 454
0.010, // helicos
0.010, // iontorrent
0.010, // pacbio
0.050, // ont
};
double p_undercall[] = {
0.001, // unknown
0.010, // sanger
0.001, // solexa/illumina
0.001, // solid
0.010, // 454
0.010, // helicos
0.010, // iontorrent
0.010, // pacbio
0.280, // ont
};
double norm = (1-p_overcall[t])*prob + 3*((1-p_overcall[t])*(1-prob)/3)
+ p_overcall[t]*(1-prob);
pMM[t][i] = log((1-p_overcall[t]) * prob /norm);
p__[t][i] = log((1-p_overcall[t]) * (1-prob)/3 /norm);
poo[t][i] = log((p_overcall[t]*(1-prob)) /norm);
p_M[t][i] = log((exp(pMM[t][i]) + exp(p__[t][i]))/2);
po_[t][i] = log((exp(p__[t][i]) + exp(poo[t][i]))/2);
poM[t][i] = log((exp(pMM[t][i]) + exp(poo[t][i]))/2);
// [t]* observation vs base
norm = p_undercall[t]*(1-prob)*4 + (1-p_undercall[t])*prob;
puu[t][i] = log((p_undercall[t] * (1-prob)) /norm);
pmm[t][i] = log((1-p_undercall[t])*prob /norm);
pum[t][i] = log((exp(puu[t][i]) + exp(pmm[t][i]))/2);
#else
//prob = 1-(1-prob)*2; if (prob < 0.1) prob = 0.1; // Fudge
pMM[t][i] = log(prob/5);
p__[t][i] = log((1-prob)/20);
p_M[t][i] = log((exp(pMM[t][i]) + exp(p__[t][i]))/2);
puu[t][i] = p__[t][i];
poM[t][i] = p_M[t][i] *= tech_undercall[t];
po_[t][i] = p__[t][i] *= tech_undercall[t];
poo[t][i] = p__[t][i] *= tech_undercall[t];
pum[t][i] = p_M[t][i] *= tech_undercall[t];
pmm[t][i] = pMM[t][i] *= tech_undercall[t];
#endif
}
pMM[t][0] = pMM[t][1];
p__[t][0] = p__[t][1];
p_M[t][0] = p_M[t][1];
pmm[t][0] = pmm[t][1];
poo[t][0] = poo[t][1];
po_[t][0] = po_[t][1];
poM[t][0] = poM[t][1];
puu[t][0] = puu[t][1];
pum[t][0] = pum[t][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;
// printf("%f => %g %g\n", y, exp(y), e_tab[(int)y]);
return e_tab[(int)y];
}
/*Taylor (deg 3) implementation of the log: http://www.flipcode.com/cgi-bin/fcarticles.cgi?show=63828*/
static inline double fast_log2 (double val)
{
register int64_t *const exp_ptr = ((int64_t*)&val);
register int64_t x = *exp_ptr;
register const int log_2 = ((x >> 52) & 2047) - 1024;
x &= ~(2047LL << 52);
x += 1023LL << 52;
*exp_ptr = x;
val = ((-1.0f/3) * val + 2) * val - 2.0f/3;
return val + log_2;
}
static inline double fast_log (double val) {
return fast_log2(val)*0.69314718;
}
//#define fast_exp exp
//#define fast_log log
#define ph_log(x) (-TENLOG2OVERLOG10*fast_log2((x)))
/*
* As per calculate_consensus_bit_het but for a single pileup column.
*/
int calculate_consensus_pileup(int flags,
const bam_pileup1_t *p,
int np,
consensus_t *cons) {
int i, j;
static int init_done =0;
static double q2p[101], mqual_pow[256];
double min_e_exp = DBL_MIN_EXP * log(2) + 1;
double S[15] ALIGNED(16) = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
double sumsC[6] = {0,0,0,0,0,0}, sumsE = 0;
int depth = 0;
/* Map the 15 possible combinations to 1-base or 2-base encodings */
static int map_sing[15] ALIGNED(16) =
{0, 5, 5, 5, 5,
1, 5, 5, 5,
2, 5, 5,
3, 5,
4};
static int map_het[15] ALIGNED(16) =
{0, 1, 2, 3, 4,
6, 7, 8, 9,
12, 13, 14,
18, 19,
24};
if (!init_done) {
init_done = 1;
consensus_init(P_HET);
for (i = 0; i <= 100; i++) {
q2p[i] = pow(10, -i/10.0);
}
for (i = 0; i < 255; i++) {
//mqual_pow[i] = 1-pow(10, -(i+.01)/10.0);
//mqual_pow[i] = 1-pow(10, -(i/3+.1)/10.0);
mqual_pow[i] = 1-pow(10, -(i/2+.05)/10.0);
}
// unknown mqual
mqual_pow[255] = mqual_pow[10];
}
/* Initialise */
int counts[6] = {0};
/* Accumulate */
int n;
//printf("-----\n");
// FIXME: also seed with unknown alleles so low coverage data is
// less confident.
cons->call_preserve = 0;
for (n = 0; n < np; n++) {
if (p[n].is_refskip)
continue;
bam1_t *b = p[n].b;
if (!b->core.l_qseq)
continue;
uint8_t base = bam_seqi(bam_get_seq(b), p[n].qpos);
uint8_t *qptr = &bam_get_qual(b)[p[n].qpos];
uint8_t qual = *qptr;
const int stech = STECH_SOLEXA;
// =ACM GRSV TWYH KDBN
static int L[16] = {
5,0,1,5, 2,5,5,5, 3,5,5,5, 5,5,5,5
};
// convert from sam base to acgt*n order.
base = L[base];
if (p[n].is_del) base = 4;
if (preserve_qual[qual]) // basic preservation count
cons->call_preserve |= 1<<base;
if (preserve_qual[qual] > 1) // MUST preserve count
cons->call_preserve |= (1<<base)<<8;
if (p[n].indel > 0) {
int ins;
for (ins = 0; ins < p[n].indel; ins++)
if (preserve_qual[*++qptr])
// Not really a "*", but an indel to a consensus
// which may well be "*" if this is a single indel case.
cons->call_preserve |= 1<<4;
}
double MM, __, _M, qe;
// Correction for mapping quality. Maybe speed up via lookups?
// Cannot nullify mapping quality completely. Lots of (true)
// SNPs means low mapping quality. (Ideally need to know
// hamming distance to next best location.)
if (flags & CONS_MQUAL) {
double _p = mqual_pow[qual];
double _m = mqual_pow[b->core.qual];
//printf("%c %d -> %d, %f %f\n", "ACGT*N"[base], qual, (int)(-TENOVERLOG10 * log(1-(_m * _p + (1 - _m)/4))), _p, _m);
qual = ph_log(1-(_m * _p + (1 - _m)/4));
}
/* Quality 0 should never be permitted as it breaks the math */
if (qual < 1)
qual = 1;
__ = p__[stech][qual];
MM = pMM[stech][qual] - __;
_M = p_M[stech][qual] - __;
if (flags & CONS_DISCREP) {
qe = q2p[qual];
sumsE += qe;
sumsC[base] += 1 - qe;
}
counts[base]++;
switch (base) {
case 0:
S[0] += MM; S[1 ]+= _M; S[2 ]+= _M; S[3 ]+= _M; S[4 ]+= _M;
break;
case 1:
S[1 ]+= _M; S[5 ]+= MM; S[6 ]+= _M; S[7 ]+= _M; S[8 ]+= _M;
break;
case 2:
S[2 ]+= _M; S[6 ]+= _M; S[9 ]+= MM; S[10]+= _M; S[11]+= _M;
break;
case 3:
S[3 ]+= _M; S[7 ]+= _M; S[10]+= _M; S[12]+= MM; S[13]+= _M;
break;
case 4:
S[4 ]+= _M; S[8 ]+= _M; S[11]+= _M; S[13]+= _M; S[14]+= MM;
break;
case 5: /* N => equal weight to all A,C,G,T but not a pad */
S[0] += MM; S[1 ]+= MM; S[2 ]+= MM; S[3 ]+= MM; S[4 ]+= _M;
S[5 ]+= MM; S[6 ]+= MM; S[7 ]+= MM; S[8 ]+= _M;
S[9 ]+= MM; S[10]+= MM; S[11]+= _M;
S[12]+= MM; S[13]+= _M;
break;
}
depth++;
}
/* and speculate */
{
double shift, max, max_het, norm[15];
int call = 0, het_call = 0, ph;
double tot1, tot2;
/*
* Scale numbers so the maximum score is 0. This shift is essentially
* a multiplication in non-log scale to both numerator and denominator,
* so it cancels out. We do this to avoid calling exp(-large_num) and
* ending up with norm == 0 and hence a 0/0 error.
*
* Can also generate the base-call here too.
*/
shift = -DBL_MAX;
max = -DBL_MAX;
max_het = -DBL_MAX;
for (j = 0; j < 15; j++) {
S[j] += lprior15[j];
if (shift < S[j])
shift = S[j];
/* Only call pure AA, CC, GG, TT, ** for now */
if (j != 0 && j != 5 && j != 9 && j != 12 && j != 14) {
if (max_het < S[j]) {
max_het = S[j];
het_call = j;
}
continue;
}
if (max < S[j]) {
max = S[j];
call = j;
}
}
/*
* Shift and normalise.
* If call is, say, b we want p = b/(a+b+c+...+n), but then we do
* p/(1-p) later on and this has exceptions when p is very close
* to 1.
*
* Hence we compute b/(a+b+c+...+n - b) and
* rearrange (p/norm) / (1 - (p/norm)) to be p/norm2.
*/
for (j = 0; j < 15; j++) {
S[j] -= shift;
double e = fast_exp(S[j]);
S[j] = (S[j] > min_e_exp) ? e : DBL_MIN;
norm[j] = 0;
}
tot1 = tot2 = 0;
for (j = 0; j < 15; j++) {
norm[j] += tot1;
norm[14-j] += tot2;
tot1 += S[j];
tot2 += S[14-j];
}
/* And store result */
if (depth && depth != counts[5] /* all N */) {
double m;
cons->depth = depth;
cons->call = map_sing[call];
if (norm[call] == 0) norm[call] = DBL_MIN;
ph = ph_log(norm[call]) + .5;
cons->phred = ph > 255 ? 255 : (ph < 0 ? 0 : ph);
//cons->call_prob1 = norm[call]; // p = 1 - call_prob1
cons->het_call = map_het[het_call];
//cons->call_preserve = bit2het[cons->call_preserve & 31];
if (norm[het_call] == 0) norm[het_call] = DBL_MIN;
ph = TENLOG2OVERLOG10 * (fast_log2(S[het_call]) - fast_log2(norm[het_call])) + .5;
cons->het_phred = ph;
//cons->het_prob_n = S[het_call]; // p = prob_n / prob_d
//cons->het_prob_d = norm[het_call];
/* Compute discrepancy score */
if (flags & CONS_DISCREP) {
m = sumsC[0]+sumsC[1]+sumsC[2]+sumsC[3]+sumsC[4];
double c;
if (cons->het_phred > 0)
c = sumsC[cons->het_call%5] + sumsC[cons->het_call/5];
else
c = sumsC[cons->call];;
cons->discrep = (m-c)/sqrt(m);
// printf("Discrep = %f, %f %f %f %f %f\n", cons->discrep,
// sumsC[0], sumsC[1], sumsC[2], sumsC[3], sumsC[4]);
// if (cons->discrep > 1)
// printf("XYZZY\n");
}
} else {
cons->call = 5; /* N */
cons->het_call = 0;
cons->het_phred = 0;
cons->phred = 0;
cons->depth = 0;
cons->discrep = 0;
}
}
return 0;
}
// Applies a basic P-block algorithm to a string of quality values.
// All blocks of qualities within +/- level get replaced by a representative
// value such that the delta is within 'level'.
// The original paper had a more complex method, but this is just (min+max)/2.
void pblock(bam1_t *b, int level, int qcap) {
if (!b)
return;
int len = b->core.l_qseq, i, j, qmin = INT_MAX, qmax = INT_MIN;
int last_qmin = 0, last_qmax = 0, mid;
uint8_t *qual = bam_get_qual(b);
level *= 2;
for (i = j = 0; i < len; i++) {
if (qmin > qual[i])
qmin = qual[i];
if (qmax < qual[i])
qmax = qual[i];
if (qmax - qmin > level || preserve_qual[qual[i]]) {
mid = (last_qmin + last_qmax) / 2;
if (mid > qcap)
mid = qcap;
memset(qual+j, mid, i-j);
while (i < len && preserve_qual[qual[i]])
i++;
qmin = qmax = qual[i];
j = i;
}
last_qmin = qmin;
last_qmax = qmax;
}
mid = (last_qmin + last_qmax) / 2;
memset(qual+j, mid, i-j);
}
// // Quantise qualities by bin[] array. Alternative to pblock above
// void qblock(bam1_t *b) {
// if (!b)
// return;
//
// int len = b->core.l_qseq, i;
// uint8_t *qual = bam_get_qual(b);
//
// for (i = 0; i < len; i++)
// qual[i] = bin[qual[i]];
// }
//-----------------------------------------------------------------------------
// Tree of bam objects, sorted by chromosome & position
typedef struct bam_sorted_item {
RB_ENTRY(bam_sorted_item) link;
bam1_t *b;
uint64_t id;
int end_pos;
int keep_qual;
} bam_sorted_item;
RB_HEAD(bam_sort, bam_sorted_item);
typedef struct bam_sort bam_sorted_list;
static int bam_item_cmp(bam_sorted_item *b1, bam_sorted_item *b2) {
int d;
if (b2->b->core.tid == -1)
return -1;
if ((d = b1->b->core.tid - b2->b->core.tid))
return d;
if ((d = b1->b->core.pos - b2->b->core.pos))
return d;
return b1->id - b2->id;
}
RB_PROTOTYPE(bam_sort, bam_sorted_item, link, bam_item_cmp);
RB_GENERATE(bam_sort, bam_sorted_item, link, bam_item_cmp);
bam_sorted_list *bam_sorted_list_new(void) {
bam_sorted_list *bl = calloc(1, sizeof(bam_sorted_list));
if (!bl)
return NULL;
RB_INIT(bl);
return bl;
}
void bam_sorted_list_destroy(bam_sorted_list *bl) {
bam_sorted_item *node, *next;
if (!bl)
return;
for (node = RB_MIN(bam_sort, bl); node; node = next) {
next = RB_NEXT(bam_sort, bl, node);
RB_REMOVE(bam_sort, bl, node);
free(node);
}
free(bl);
}
bam_sorted_item *bam_sorted_item_new(void) {
return calloc(1, sizeof(bam_sorted_item));
}
/*
* Inserts a bam structure into the bam_sorted_list, in positional
* order.
*
* Returns the newly created bam_sorted_list element on success.
* NULL on failure.
*/
bam_sorted_item *insert_bam_list2(bam_sorted_list *bl, bam_sorted_item *ele) {
RB_INSERT(bam_sort, bl, ele);
return ele;
}
bam_sorted_item *insert_bam_list_id(bam_sorted_list *bl, bam1_t *b, uint64_t id) {
bam_sorted_item *ele = bam_sorted_item_new();
if (!ele)
return NULL;
ele->b = b;
ele->id = id;
ele->end_pos = bam_endpos(ele->b);
return insert_bam_list2(bl, ele);
}
static uint64_t global_id = 0;
bam_sorted_item *insert_bam_list(bam_sorted_list *bl, bam1_t *b) {
return insert_bam_list_id(bl, b, global_id++);
}
/*
* Removes an item from the bam_sorted_list.
*/
void remove_bam_list(bam_sorted_list *bl, bam_sorted_item *ele) {
RB_REMOVE(bam_sort, bl, ele);
free(ele);
}
//-----------------------------------------------------------------------------
// Copied from htslib/sam.c.
// TODO: we need a proper interface to find the length of an aux tag,
// or at the very make exportable versions of these in htslib.
static inline int aux_type2size(uint8_t type)
{
switch (type) {
case 'A': case 'c': case 'C':
return 1;
case 's': case 'S':
return 2;
case 'i': case 'I': case 'f':
return 4;
case 'd':
return 8;
case 'Z': case 'H': case 'B':
return type;
default:
return 0;
}
}
// Copied from htslib/sam.c.
static inline uint8_t *skip_aux(uint8_t *s)
{
int size = aux_type2size(*s); ++s; // skip type
uint32_t n;
switch (size) {
case 'Z':
case 'H':
while (*s) ++s;
return s + 1;
case 'B':
size = aux_type2size(*s); ++s;
memcpy(&n, s, 4); s += 4;
return s + size * n;
case 0:
abort();
break;
default:
return s + size;
}
}
void purge_tags(cram_lossy_params *settings, bam1_t *b) {
if (settings->aux_whitelist) {
uint8_t *s_from, *s_to;
auxhash_t h = settings->aux_whitelist;
s_from = s_to = bam_get_aux(b);
while (s_from < b->data + b->l_data) {
int x = (int)s_from[0]<<8 | s_from[1];
uint8_t *s = skip_aux(s_from+2);
if (kh_get(aux_exists, h, x) != kh_end(h) ) {
if (s_to != s_from) memmove(s_to, s_from, s - s_from);