forked from samtools/samtools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stats.c
2617 lines (2344 loc) · 106 KB
/
stats.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
/* stats.c -- This is the former bamcheck integrated into samtools/htslib.
Copyright (C) 2012-2022 Genome Research Ltd.
Author: Petr Danecek <[email protected]>
Author: Sam Nicholls <[email protected]>
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. */
/* Assumptions, approximations and other issues:
- GC-depth graph does not split reads, the starting position determines which bin is incremented.
There are small overlaps between bins (max readlen-1). However, the bins are big (20k).
- coverage distribution ignores softclips and deletions
- some stats require sorted BAMs
- GC content graph can have an untidy, step-like pattern when BAM contains multiple read lengths.
- 'bases mapped' (stats->nbases_mapped) is calculated from read lengths given by BAM (core.l_qseq)
- With the -t option, the whole reads are used. Except for the number of mapped bases (cigar)
counts, no splicing is done, no indels or soft clips are considered, even small overlap is
good enough to include the read in the stats.
- GC content of reads not calculated for "=" sequences
*/
#include <config.h>
#include <unistd.h> // for isatty()
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
#include <inttypes.h>
#include <getopt.h>
#include <errno.h>
#include <assert.h>
#include <zlib.h> // for crc32
#include <htslib/faidx.h>
#include <htslib/sam.h>
#include <htslib/hts.h>
#include <htslib/hts_defs.h>
#include "samtools.h"
#include <htslib/khash.h>
#include <htslib/kstring.h>
#include "stats_isize.h"
#include "sam_opts.h"
#include "bedidx.h"
#define BWA_MIN_RDLEN 35
#define DEFAULT_CHUNK_NO 8
#define DEFAULT_PAIR_MAX 10000
#define ERROR_LIMIT 200
// From the spec
// If 0x4 is set, no assumptions can be made about RNAME, POS, CIGAR, MAPQ, bits 0x2, 0x10, 0x100 and 0x800, and the bit 0x20 of the previous read in the template.
#define IS_PAIRED(bam) ((bam)->core.flag&BAM_FPAIRED)
#define IS_PAIRED_AND_MAPPED(bam) (((bam)->core.flag&BAM_FPAIRED) && !((bam)->core.flag&BAM_FUNMAP) && !((bam)->core.flag&BAM_FMUNMAP))
#define IS_PROPERLYPAIRED(bam) (((bam)->core.flag&(BAM_FPAIRED|BAM_FPROPER_PAIR)) == (BAM_FPAIRED|BAM_FPROPER_PAIR) && !((bam)->core.flag&BAM_FUNMAP))
#define IS_UNMAPPED(bam) ((bam)->core.flag&BAM_FUNMAP)
#define IS_REVERSE(bam) ((bam)->core.flag&BAM_FREVERSE)
#define IS_MATE_REVERSE(bam) ((bam)->core.flag&BAM_FMREVERSE)
#define IS_READ1(bam) ((bam)->core.flag&BAM_FREAD1)
#define IS_READ2(bam) ((bam)->core.flag&BAM_FREAD2)
#define IS_DUP(bam) ((bam)->core.flag&BAM_FDUP)
#define IS_ORIGINAL(bam) (((bam)->core.flag&(BAM_FSECONDARY|BAM_FSUPPLEMENTARY)) == 0)
#define READ_ORDER_NONE 0
#define READ_ORDER_FIRST 1
#define READ_ORDER_LAST 2
#define READ_ORDER_MIDDLE 3
#define REG_INC 100
#define POS_INC 1000
// The GC-depth graph works as follows: split the reference sequence into
// segments and calculate GC content and depth in each bin. Then sort
// these segments by their GC and plot the depth distribution by means
// of 10th, 25th, etc. depth percentiles.
typedef struct
{
float gc;
uint32_t depth;
}
gc_depth_t;
// For coverage distribution, a simple pileup
typedef struct
{
hts_pos_t pos;
int size, start;
int *buffer;
}
round_buffer_t;
typedef struct
{
int npos, mpos, cpos;
hts_pair_pos_t *pos;
}
regions_t;
typedef struct
{
uint64_t a;
uint64_t c;
uint64_t g;
uint64_t t;
uint64_t n;
uint64_t other;
}
acgtno_count_t;
typedef struct
{
char tag_name[3];
char qual_name[3];
uint32_t nbases;
int32_t tag_sep; // Index of the separator (if present)
int32_t max_qual;
uint32_t offset; // Where the tag stats info is located in the allocated memory
}
barcode_info_t;
typedef struct
{
// Auxiliary data
int flag_require, flag_filter;
faidx_t *fai; // Reference sequence for GC-depth graph
int argc; // Command line arguments to be printed on the output
char **argv;
int gcd_bin_size; // The size of GC-depth bin
int nisize; // The maximum insert size that the allocated array can hold - 0 indicates no limit
int trim_qual; // bwa trim quality
float isize_main_bulk; // There are always some unrealistically big insert sizes, report only the main part
int cov_min,cov_max,cov_step; // Minimum, maximum coverage and size of the coverage bins
samFile* sam;
sam_hdr_t* sam_header;
// Filters
int filter_readlen;
// Misc
char *split_tag; // Tag on which to perform stats splitting
char *split_prefix; // Path or string prefix for filenames created when splitting
int remove_overlaps;
int cov_threshold;
}
stats_info_t;
typedef struct
{
// Dimensions of the quality histogram holder (quals_1st,quals_2nd), GC content holder (gc_1st,gc_2nd),
// insert size histogram holder
int nquals; // The number of quality bins
int nbases; // The maximum sequence length the allocated array can hold
int ngc; // The size of gc_1st and gc_2nd
int nindels; // The maximum indel length for indel distribution
// Arrays for the histogram data
uint64_t *quals_1st, *quals_2nd;
uint64_t *gc_1st, *gc_2nd;
acgtno_count_t *acgtno_cycles_1st, *acgtno_cycles_2nd;
acgtno_count_t *acgtno_revcomp;
uint64_t *read_lengths, *read_lengths_1st, *read_lengths_2nd;
uint64_t *insertions, *deletions;
uint64_t *ins_cycles_1st, *ins_cycles_2nd, *del_cycles_1st, *del_cycles_2nd;
isize_t *isize;
uint64_t* mapping_qualities;
// The extremes encountered
int max_len; // Maximum read length
int max_len_1st; // Maximum read length for forward reads
int max_len_2nd; // Maximum read length for reverse reads
int max_qual; // Maximum quality
int is_sorted;
// Summary numbers
uint64_t total_len;
uint64_t total_len_1st;
uint64_t total_len_2nd;
uint64_t total_len_dup;
uint64_t nreads_1st;
uint64_t nreads_2nd;
uint64_t nreads_other;
uint64_t nreads_filtered;
uint64_t nreads_dup;
uint64_t nreads_unmapped;
uint64_t nreads_single_mapped;
uint64_t nreads_paired_and_mapped;
uint64_t nreads_properly_paired;
uint64_t nreads_paired_tech;
uint64_t nreads_anomalous;
uint64_t nreads_mq0;
uint64_t nbases_mapped;
uint64_t nbases_mapped_cigar;
uint64_t nbases_trimmed; // bwa trimmed bases
uint64_t nmismatches;
uint64_t nreads_QCfailed, nreads_secondary, nreads_supplementary;
struct {
uint32_t names, reads, quals;
} checksum;
// GC-depth related data
uint32_t ngcd, igcd; // The maximum number of GC depth bins and index of the current bin
gc_depth_t *gcd; // The GC-depth bins holder
int32_t tid; // Position of the current bin
hts_pos_t gcd_pos, pos; // Position of the last read
// Coverage distribution related data
int ncov; // The number of coverage bins
uint64_t *cov; // The coverage frequencies
round_buffer_t cov_rbuf; // Pileup round buffer
// Mismatches by read cycle
uint8_t *rseq_buf; // A buffer for reference sequence to check the mismatches against
int mrseq_buf; // The size of the buffer
hts_pos_t rseq_pos; // The coordinate of the first base in the buffer
int64_t nrseq_buf; // The used part of the buffer
uint64_t *mpc_buf; // Mismatches per cycle
// Target regions
int nregions;
hts_pos_t reg_from, reg_to;
regions_t *regions;
// Auxiliary data
double sum_qual; // For calculating average quality value
void *rg_hash; // Read groups to include, the array is null-terminated
// Split
char* split_name;
stats_info_t* info; // Pointer to options and settings struct
hts_pair_pos_t *chunks;
uint32_t nchunks;
uint32_t pair_count; // Number of active pairs in the pairing hash table
uint64_t target_count; // Number of bases covered by the target file
uint32_t last_pair_tid;
uint32_t last_read_flush;
// Barcode statistics
acgtno_count_t *acgtno_barcode;
uint64_t *quals_barcode;
barcode_info_t *tags_barcode;
uint32_t ntags;
uint32_t error_number;
}
stats_t;
KHASH_MAP_INIT_STR(c2stats, stats_t*)
typedef struct {
uint32_t first; // 1 - first read, 2 - second read
uint32_t n, m; // number of chunks, allocated chunks
hts_pair_pos_t *chunks; // chunk array of size m
} pair_t;
KHASH_MAP_INIT_STR(qn2pair, pair_t*)
KHASH_SET_INIT_STR(rg)
static void HTS_NORETURN error(const char *format, ...);
int is_in_regions(bam1_t *bam_line, stats_t *stats);
void realloc_buffers(stats_t *stats, int seq_len);
static int regions_lt(const void *r1, const void *r2) {
int64_t from_diff = ((hts_pair_pos_t *)r1)->beg - ((hts_pair_pos_t *)r2)->beg;
int64_t to_diff = ((hts_pair_pos_t *)r1)->end - ((hts_pair_pos_t *)r2)->end;
return from_diff > 0 ? 1 : from_diff < 0 ? -1 : to_diff > 0 ? 1 : to_diff < 0 ? -1 : 0;
}
// Coverage distribution methods
static inline int coverage_idx(int min, int max, int n, int step, int depth)
{
if ( depth < min )
return 0;
if ( depth > max )
return n-1;
return 1 + (depth - min) / step;
}
static inline int round_buffer_lidx2ridx(int offset, int size, hts_pos_t refpos, hts_pos_t pos)
{
return (offset + (pos-refpos) % size) % size;
}
void round_buffer_flush(stats_t *stats, hts_pos_t pos)
{
int ibuf,idp;
if ( pos==stats->cov_rbuf.pos )
return;
hts_pos_t new_pos = pos;
if ( pos==-1 || pos - stats->cov_rbuf.pos >= stats->cov_rbuf.size )
{
// Flush the whole buffer, but in sequential order,
pos = stats->cov_rbuf.pos + stats->cov_rbuf.size - 1;
}
if ( pos < stats->cov_rbuf.pos )
error("Expected coordinates in ascending order, got %"PRIhts_pos" after %"PRIhts_pos"\n", pos, stats->cov_rbuf.pos);
int ifrom = stats->cov_rbuf.start;
int ito = round_buffer_lidx2ridx(stats->cov_rbuf.start, stats->cov_rbuf.size, stats->cov_rbuf.pos, pos-1);
if ( ifrom>ito )
{
for (ibuf=ifrom; ibuf<stats->cov_rbuf.size; ibuf++)
{
if ( !stats->cov_rbuf.buffer[ibuf] )
continue;
idp = coverage_idx(stats->info->cov_min,stats->info->cov_max,stats->ncov,stats->info->cov_step,stats->cov_rbuf.buffer[ibuf]);
stats->cov[idp]++;
stats->cov_rbuf.buffer[ibuf] = 0;
}
ifrom = 0;
}
for (ibuf=ifrom; ibuf<=ito; ibuf++)
{
if ( !stats->cov_rbuf.buffer[ibuf] )
continue;
idp = coverage_idx(stats->info->cov_min,stats->info->cov_max,stats->ncov,stats->info->cov_step,stats->cov_rbuf.buffer[ibuf]);
stats->cov[idp]++;
stats->cov_rbuf.buffer[ibuf] = 0;
}
stats->cov_rbuf.start = (new_pos==-1) ? 0 : round_buffer_lidx2ridx(stats->cov_rbuf.start, stats->cov_rbuf.size, stats->cov_rbuf.pos, pos);
stats->cov_rbuf.pos = new_pos;
}
/**
* [from, to) - 0 based half-open
*/
static void round_buffer_insert_read(round_buffer_t *rbuf, hts_pos_t from, hts_pos_t to)
{
if ( to-from > rbuf->size )
error("The read length too big (%"PRIhts_pos"), please increase the buffer length (currently %d)\n", to-from, rbuf->size);
if ( from < rbuf->pos )
error("The reads are not sorted (%"PRIhts_pos" comes after %"PRIhts_pos").\n", from, rbuf->pos);
int ifrom, ito, ibuf;
ifrom = round_buffer_lidx2ridx(rbuf->start, rbuf->size, rbuf->pos, from);
ito = round_buffer_lidx2ridx(rbuf->start, rbuf->size, rbuf->pos, to);
if ( ifrom>ito )
{
for (ibuf=ifrom; ibuf<rbuf->size; ibuf++)
rbuf->buffer[ibuf]++;
ifrom = 0;
}
for (ibuf=ifrom; ibuf<ito; ibuf++)
rbuf->buffer[ibuf]++;
}
// Calculate the number of bases in the read trimmed by BWA
int bwa_trim_read(int trim_qual, uint8_t *quals, int len, int reverse)
{
if ( len<BWA_MIN_RDLEN ) return 0;
// Although the name implies that the read cannot be trimmed to more than BWA_MIN_RDLEN,
// the calculation can in fact trim it to (BWA_MIN_RDLEN-1). (bwa_trim_read in bwa/bwaseqio.c).
int max_trimmed = len - BWA_MIN_RDLEN + 1;
int l, sum=0, max_sum=0, max_l=0;
for (l=0; l<max_trimmed; l++)
{
sum += trim_qual - quals[ reverse ? l : len-1-l ];
if ( sum<0 ) break;
if ( sum>max_sum )
{
max_sum = sum;
// This is the correct way, but bwa clips from some reason one base less
// max_l = l+1;
max_l = l;
}
}
return max_l;
}
void count_indels(stats_t *stats,bam1_t *bam_line)
{
int is_fwd = IS_REVERSE(bam_line) ? 0 : 1;
uint32_t order = IS_PAIRED(bam_line) ? (IS_READ1(bam_line) ? READ_ORDER_FIRST : 0) + (IS_READ2(bam_line) ? READ_ORDER_LAST : 0) : READ_ORDER_FIRST;
int icig;
int icycle = 0;
int read_len = bam_line->core.l_qseq;
for (icig=0; icig<bam_line->core.n_cigar; icig++)
{
int cig = bam_cigar_op(bam_get_cigar(bam_line)[icig]);
int ncig = bam_cigar_oplen(bam_get_cigar(bam_line)[icig]);
if ( !ncig ) continue; // curiously, this can happen: 0D
if ( cig==BAM_CINS )
{
int idx = is_fwd ? icycle : read_len-icycle-ncig;
if ( idx<0 )
error("FIXME: read_len=%d vs icycle=%d\n", read_len,icycle);
if ( idx >= stats->nbases || idx<0 ) error("FIXME: %d vs %d, %s:%"PRIhts_pos" %s\n", idx, stats->nbases, sam_hdr_tid2name(stats->info->sam_header, bam_line->core.tid), bam_line->core.pos+1, bam_get_qname(bam_line));
if ( order == READ_ORDER_FIRST )
stats->ins_cycles_1st[idx]++;
if ( order == READ_ORDER_LAST )
stats->ins_cycles_2nd[idx]++;
icycle += ncig;
if ( ncig<=stats->nindels )
stats->insertions[ncig-1]++;
continue;
}
if ( cig==BAM_CDEL )
{
int idx = is_fwd ? icycle-1 : read_len-icycle-1;
if ( idx<0 ) continue; // discard meaningless deletions
if ( idx >= stats->nbases ) error("FIXME: %d vs %d\n", idx,stats->nbases);
if ( order == READ_ORDER_FIRST )
stats->del_cycles_1st[idx]++;
if ( order == READ_ORDER_LAST )
stats->del_cycles_2nd[idx]++;
if ( ncig<=stats->nindels )
stats->deletions[ncig-1]++;
continue;
}
if ( cig!=BAM_CREF_SKIP && cig!=BAM_CHARD_CLIP && cig!=BAM_CPAD )
icycle += ncig;
}
}
int unclipped_length(bam1_t *bam_line)
{
int icig, read_len = bam_line->core.l_qseq;
for (icig=0; icig<bam_line->core.n_cigar; icig++)
{
int cig = bam_cigar_op(bam_get_cigar(bam_line)[icig]);
if ( cig==BAM_CHARD_CLIP )
read_len += bam_cigar_oplen(bam_get_cigar(bam_line)[icig]);
}
return read_len;
}
void count_mismatches_per_cycle(stats_t *stats, bam1_t *bam_line, int read_len)
{
int is_fwd = IS_REVERSE(bam_line) ? 0 : 1;
int icig, iread=0, icycle=0;
hts_pos_t iref = bam_line->core.pos - stats->rseq_pos;
uint8_t *read = bam_get_seq(bam_line);
uint8_t *quals = bam_get_qual(bam_line);
uint64_t *mpc_buf = stats->mpc_buf;
for (icig=0; icig<bam_line->core.n_cigar; icig++)
{
int cig = bam_cigar_op(bam_get_cigar(bam_line)[icig]);
int ncig = bam_cigar_oplen(bam_get_cigar(bam_line)[icig]);
if ( cig==BAM_CINS )
{
iread += ncig;
icycle += ncig;
continue;
}
if ( cig==BAM_CDEL )
{
iref += ncig;
continue;
}
if ( cig==BAM_CSOFT_CLIP )
{
icycle += ncig;
// Soft-clips are present in the sequence, but the position of the read marks a start of the sequence after clipping
// iref += ncig;
iread += ncig;
continue;
}
if ( cig==BAM_CHARD_CLIP )
{
icycle += ncig;
continue;
}
// Ignore H and N CIGARs. The letter are inserted e.g. by TopHat and often require very large
// chunk of refseq in memory. Not very frequent and not noticeable in the stats.
if ( cig==BAM_CREF_SKIP || cig==BAM_CHARD_CLIP || cig==BAM_CPAD ) continue;
if ( cig!=BAM_CMATCH && cig!=BAM_CEQUAL && cig!=BAM_CDIFF ) // not relying on precalculated diffs
error("TODO: cigar %d, %s:%"PRIhts_pos" %s\n", cig, sam_hdr_tid2name(stats->info->sam_header, bam_line->core.tid), bam_line->core.pos+1, bam_get_qname(bam_line));
if ( ncig+iref > stats->nrseq_buf )
error("FIXME: %d+%"PRIhts_pos" > %"PRId64", %s, %s:%"PRIhts_pos"\n", ncig, iref, stats->nrseq_buf, bam_get_qname(bam_line), sam_hdr_tid2name(stats->info->sam_header, bam_line->core.tid), bam_line->core.pos+1);
int im;
for (im=0; im<ncig; im++)
{
uint8_t cread = bam_seqi(read,iread);
uint8_t cref = stats->rseq_buf[iref];
// ---------------15
// =ACMGRSVTWYHKDBN
if ( cread==15 )
{
int idx = is_fwd ? icycle : read_len-icycle-1;
if ( idx>stats->max_len )
error("mpc: %d>%d\n",idx,stats->max_len);
idx = idx*stats->nquals;
if ( idx>=stats->nquals*stats->nbases )
error("FIXME: mpc_buf overflow\n");
mpc_buf[idx]++;
}
else if ( cref && cread && cref!=cread )
{
uint8_t qual = quals[iread] + 1;
if ( qual>=stats->nquals )
error("TODO: quality too high %d>=%d (%s %"PRIhts_pos" %s)\n", qual, stats->nquals, sam_hdr_tid2name(stats->info->sam_header, bam_line->core.tid), bam_line->core.pos+1, bam_get_qname(bam_line));
int idx = is_fwd ? icycle : read_len-icycle-1;
if ( idx>stats->max_len )
error("mpc: %d>%d (%s %"PRIhts_pos" %s)\n", idx, stats->max_len, sam_hdr_tid2name(stats->info->sam_header, bam_line->core.tid), bam_line->core.pos+1, bam_get_qname(bam_line));
idx = idx*stats->nquals + qual;
if ( idx>=stats->nquals*stats->nbases )
error("FIXME: mpc_buf overflow\n");
mpc_buf[idx]++;
}
iref++;
iread++;
icycle++;
}
}
}
void read_ref_seq(stats_t *stats, int32_t tid, hts_pos_t pos, hts_pos_t end)
{
int i;
hts_pos_t fai_ref_len;
char *fai_ref;
if (end < pos+stats->mrseq_buf-1)
end = pos+stats->mrseq_buf-1;
else if (stats->mrseq_buf < end - pos) {
size_t sz = end - pos;
uint8_t *new_rseq = realloc(stats->rseq_buf, sz);
if (!new_rseq)
error("Couldn't expand the reference sequence buffer\n");
stats->rseq_buf = new_rseq;
stats->mrseq_buf = sz;
}
fai_ref = faidx_fetch_seq64(stats->info->fai, sam_hdr_tid2name(stats->info->sam_header, tid), pos, pos+stats->mrseq_buf-1, &fai_ref_len);
if ( fai_ref_len < 0 ) error("Failed to fetch the sequence \"%s\"\n", sam_hdr_tid2name(stats->info->sam_header, tid));
uint8_t *ptr = stats->rseq_buf;
for (i=0; i<fai_ref_len; i++)
{
// Conversion between uint8_t coding and ACGT
// -12-4---8-------
// =ACMGRSVTWYHKDBN
switch (fai_ref[i])
{
case 'A':
case 'a': *ptr = 1; break;
case 'C':
case 'c': *ptr = 2; break;
case 'G':
case 'g': *ptr = 4; break;
case 'T':
case 't': *ptr = 8; break;
default: *ptr = 0; break;
}
ptr++;
}
free(fai_ref);
if ( fai_ref_len < stats->mrseq_buf ) memset(ptr,0, stats->mrseq_buf - fai_ref_len);
stats->nrseq_buf = fai_ref_len;
stats->rseq_pos = pos;
stats->tid = tid;
}
float fai_gc_content(stats_t *stats, hts_pos_t pos, int len)
{
uint32_t gc,count,c;
hts_pos_t i = pos - stats->rseq_pos, ito = i + len;
assert( i>=0 );
if ( ito > stats->nrseq_buf ) ito = stats->nrseq_buf;
// Count GC content
gc = count = 0;
for (; i<ito; i++)
{
c = stats->rseq_buf[i];
if ( c==2 || c==4 )
{
gc++;
count++;
}
else if ( c==1 || c==8 )
count++;
}
return count ? (float)gc/count : 0;
}
void realloc_rseq_buffer(stats_t *stats)
{
int n = stats->nbases*10;
if ( stats->info->gcd_bin_size > n ) n = stats->info->gcd_bin_size;
if ( stats->mrseq_buf<n )
{
stats->rseq_buf = realloc(stats->rseq_buf,sizeof(uint8_t)*n);
if (!stats->rseq_buf) {
error("Could not reallocate reference sequence buffer");
}
stats->mrseq_buf = n;
}
}
void realloc_gcd_buffer(stats_t *stats, int seq_len)
{
hts_expand0(gc_depth_t,stats->igcd+1,stats->ngcd,stats->gcd);
realloc_rseq_buffer(stats);
}
void realloc_buffers(stats_t *stats, int seq_len)
{
int n = 2*(1 + seq_len - stats->nbases) + stats->nbases;
stats->quals_1st = realloc(stats->quals_1st, n*stats->nquals*sizeof(uint64_t));
if ( !stats->quals_1st )
error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len,n*stats->nquals*sizeof(uint64_t));
memset(stats->quals_1st + stats->nbases*stats->nquals, 0, (n-stats->nbases)*stats->nquals*sizeof(uint64_t));
stats->quals_2nd = realloc(stats->quals_2nd, n*stats->nquals*sizeof(uint64_t));
if ( !stats->quals_2nd )
error("Could not realloc buffers, the sequence too long: %d (2x%ld)\n", seq_len,n*stats->nquals*sizeof(uint64_t));
memset(stats->quals_2nd + stats->nbases*stats->nquals, 0, (n-stats->nbases)*stats->nquals*sizeof(uint64_t));
if ( stats->mpc_buf )
{
stats->mpc_buf = realloc(stats->mpc_buf, n*stats->nquals*sizeof(uint64_t));
if ( !stats->mpc_buf )
error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len,n*stats->nquals*sizeof(uint64_t));
memset(stats->mpc_buf + stats->nbases*stats->nquals, 0, (n-stats->nbases)*stats->nquals*sizeof(uint64_t));
}
stats->acgtno_cycles_1st = realloc(stats->acgtno_cycles_1st, n*sizeof(acgtno_count_t));
if ( !stats->acgtno_cycles_1st )
error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len, n*sizeof(acgtno_count_t));
memset(stats->acgtno_cycles_1st + stats->nbases, 0, (n-stats->nbases)*sizeof(acgtno_count_t));
stats->acgtno_cycles_2nd = realloc(stats->acgtno_cycles_2nd, n*sizeof(acgtno_count_t));
if ( !stats->acgtno_cycles_2nd )
error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len, n*sizeof(acgtno_count_t));
memset(stats->acgtno_cycles_2nd + stats->nbases, 0, (n-stats->nbases)*sizeof(acgtno_count_t));
stats->acgtno_revcomp = realloc(stats->acgtno_revcomp, n*sizeof(acgtno_count_t));
if ( !stats->acgtno_revcomp )
error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len, n*sizeof(acgtno_count_t));
memset(stats->acgtno_revcomp + stats->nbases, 0, (n-stats->nbases)*sizeof(acgtno_count_t));
stats->read_lengths = realloc(stats->read_lengths, n*sizeof(uint64_t));
if ( !stats->read_lengths )
error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len,n*sizeof(uint64_t));
memset(stats->read_lengths + stats->nbases, 0, (n-stats->nbases)*sizeof(uint64_t));
stats->read_lengths_1st = realloc(stats->read_lengths_1st, n*sizeof(uint64_t));
if ( !stats->read_lengths_1st )
error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len,n*sizeof(uint64_t));
memset(stats->read_lengths_1st + stats->nbases, 0, (n-stats->nbases)*sizeof(uint64_t));
stats->read_lengths_2nd = realloc(stats->read_lengths_2nd, n*sizeof(uint64_t));
if ( !stats->read_lengths_2nd )
error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len,n*sizeof(uint64_t));
memset(stats->read_lengths_2nd + stats->nbases, 0, (n-stats->nbases)*sizeof(uint64_t));
stats->insertions = realloc(stats->insertions, n*sizeof(uint64_t));
if ( !stats->insertions )
error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len,n*sizeof(uint64_t));
memset(stats->insertions + stats->nbases, 0, (n-stats->nbases)*sizeof(uint64_t));
stats->deletions = realloc(stats->deletions, n*sizeof(uint64_t));
if ( !stats->deletions )
error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len,n*sizeof(uint64_t));
memset(stats->deletions + stats->nbases, 0, (n-stats->nbases)*sizeof(uint64_t));
stats->ins_cycles_1st = realloc(stats->ins_cycles_1st, (n+1)*sizeof(uint64_t));
if ( !stats->ins_cycles_1st )
error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len,(n+1)*sizeof(uint64_t));
memset(stats->ins_cycles_1st + stats->nbases + 1, 0, (n-stats->nbases)*sizeof(uint64_t));
stats->ins_cycles_2nd = realloc(stats->ins_cycles_2nd, (n+1)*sizeof(uint64_t));
if ( !stats->ins_cycles_2nd )
error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len,(n+1)*sizeof(uint64_t));
memset(stats->ins_cycles_2nd + stats->nbases + 1, 0, (n-stats->nbases)*sizeof(uint64_t));
stats->del_cycles_1st = realloc(stats->del_cycles_1st, (n+1)*sizeof(uint64_t));
if ( !stats->del_cycles_1st )
error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len,(n+1)*sizeof(uint64_t));
memset(stats->del_cycles_1st + stats->nbases + 1, 0, (n-stats->nbases)*sizeof(uint64_t));
stats->del_cycles_2nd = realloc(stats->del_cycles_2nd, (n+1)*sizeof(uint64_t));
if ( !stats->del_cycles_2nd )
error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len,(n+1)*sizeof(uint64_t));
memset(stats->del_cycles_2nd + stats->nbases + 1, 0, (n-stats->nbases)*sizeof(uint64_t));
stats->nbases = n;
// Realloc the coverage distribution buffer
int *rbuffer = calloc(sizeof(int),seq_len*5);
if (!rbuffer) {
error("Could not allocate coverage distribution buffer");
}
n = stats->cov_rbuf.size-stats->cov_rbuf.start;
memcpy(rbuffer,stats->cov_rbuf.buffer+stats->cov_rbuf.start,n);
if ( stats->cov_rbuf.start>1 )
memcpy(rbuffer+n,stats->cov_rbuf.buffer,stats->cov_rbuf.start);
stats->cov_rbuf.start = 0;
free(stats->cov_rbuf.buffer);
stats->cov_rbuf.buffer = rbuffer;
stats->cov_rbuf.size = seq_len*5;
realloc_rseq_buffer(stats);
}
void update_checksum(bam1_t *bam_line, stats_t *stats)
{
uint8_t *name = (uint8_t*) bam_get_qname(bam_line);
int len = 0;
while ( name[len] ) len++;
stats->checksum.names += crc32(0L, name, len);
int seq_len = bam_line->core.l_qseq;
if ( !seq_len ) return;
uint8_t *seq = bam_get_seq(bam_line);
stats->checksum.reads += crc32(0L, seq, (seq_len+1)/2);
uint8_t *qual = bam_get_qual(bam_line);
stats->checksum.quals += crc32(0L, qual, (seq_len+1)/2);
}
// Collect statistics about the barcode tags specified by init_barcode_tags method
static void collect_barcode_stats(bam1_t* bam_line, stats_t* stats) {
uint32_t nbases, tag, i;
acgtno_count_t *acgtno;
uint64_t *quals;
int32_t *separator, *maxqual;
for (tag = 0; tag < stats->ntags; tag++) {
const char *barcode_tag = stats->tags_barcode[tag].tag_name, *qual_tag = stats->tags_barcode[tag].qual_name;
uint8_t* bc = bam_aux_get(bam_line, barcode_tag);
if (!bc)
continue;
char* barcode = bam_aux2Z(bc);
if (!barcode)
continue;
uint32_t barcode_len = strlen(barcode);
if (!barcode_len) {
continue; //consider 0 size barcode same as no barcode - avoids issues with realloc below
}
if (!stats->tags_barcode[tag].nbases) { // tag seen for the first time
uint32_t offset = 0;
for (i = 0; i < stats->ntags; i++)
offset += stats->tags_barcode[i].nbases;
stats->tags_barcode[tag].offset = offset;
stats->tags_barcode[tag].nbases = barcode_len;
stats->acgtno_barcode = realloc(stats->acgtno_barcode, (offset + barcode_len) * sizeof(acgtno_count_t));
stats->quals_barcode = realloc(stats->quals_barcode, (offset + barcode_len) * stats->nquals * sizeof(uint64_t));
if (!stats->acgtno_barcode || !stats->quals_barcode)
error("Error allocating memory. Aborting!\n");
memset(stats->acgtno_barcode + offset, 0, barcode_len*sizeof(acgtno_count_t));
memset(stats->quals_barcode + offset*stats->nquals, 0, barcode_len*stats->nquals*sizeof(uint64_t));
}
nbases = stats->tags_barcode[tag].nbases;
if (barcode_len > nbases) {
fprintf(stderr, "Barcodes with tag %s differ in length at sequence '%s'\n", barcode_tag, bam_get_qname(bam_line));
continue;
}
acgtno = stats->acgtno_barcode + stats->tags_barcode[tag].offset;
quals = stats->quals_barcode + stats->tags_barcode[tag].offset*stats->nquals;
maxqual = &stats->tags_barcode[tag].max_qual;
separator = &stats->tags_barcode[tag].tag_sep;
int error_flag = 0;
for (i = 0; i < barcode_len; i++) {
switch (barcode[i]) {
case 'A':
acgtno[i].a++;
break;
case 'C':
acgtno[i].c++;
break;
case 'G':
acgtno[i].g++;
break;
case 'T':
acgtno[i].t++;
break;
case 'N':
acgtno[i].n++;
break;
default:
if (*separator >= 0) {
if (*separator != i) {
if (stats->error_number < ERROR_LIMIT) {
fprintf(stderr, "Barcode separator for tag %s is in a different position or wrong barcode content('%s') at sequence '%s'\n", barcode_tag, barcode, bam_get_qname(bam_line));
stats->error_number++;
}
error_flag = 1;
}
} else {
*separator = i;
}
}
/* don't process the rest of the tag bases */
if (error_flag)
break;
}
/* skip to the next tag */
if (error_flag)
continue;
uint8_t* qt = bam_aux_get(bam_line, qual_tag);
if (!qt)
continue;
char* barqual = bam_aux2Z(qt);
if (!barqual)
continue;
uint32_t barqual_len = strlen(barqual);
if (barqual_len == barcode_len) {
for (i = 0; i < barcode_len; i++) {
int32_t qual = (int32_t)barqual[i] - '!'; // Phred + 33
if (qual >= 0 && qual < stats->nquals) {
quals[i * stats->nquals + qual]++;
if (qual > *maxqual)
*maxqual = qual;
}
}
} else {
if (stats->error_number++ < ERROR_LIMIT) {
fprintf(stderr, "%s length and %s length don't match for sequence '%s'\n", barcode_tag, qual_tag, bam_get_qname(bam_line));
}
}
}
}
// These stats should only be calculated for the original reads ignoring
// supplementary artificial reads otherwise we'll accidentally double count
void collect_orig_read_stats(bam1_t *bam_line, stats_t *stats, int* gc_count_out)
{
int seq_len = bam_line->core.l_qseq;
stats->total_len += seq_len; // This ignores clipping so only count primary
if ( bam_line->core.flag & BAM_FQCFAIL ) stats->nreads_QCfailed++;
if ( bam_line->core.flag & BAM_FPAIRED ) stats->nreads_paired_tech++;
uint32_t order = IS_PAIRED(bam_line) ? (IS_READ1(bam_line) ? READ_ORDER_FIRST : 0) + (IS_READ2(bam_line) ? READ_ORDER_LAST : 0) : READ_ORDER_FIRST;
// Count GC and ACGT per cycle. Note that cycle is approximate, clipping is ignored
uint8_t *seq = bam_get_seq(bam_line);
int i, read_cycle, gc_count = 0, reverse = IS_REVERSE(bam_line);
acgtno_count_t *acgtno_cycles = (order == READ_ORDER_FIRST) ? stats->acgtno_cycles_1st : (order == READ_ORDER_LAST) ? stats->acgtno_cycles_2nd : NULL ;
if (acgtno_cycles) {
for (i=0; i<seq_len; i++)
{
// Read cycle for current index
read_cycle = (reverse ? seq_len-i-1 : i);
// Conversion from uint8_t coding:
// -12-4---8------5
// =ACMGRSVTWYHKDBN
switch (bam_seqi(seq, i)) {
case 1:
acgtno_cycles[ read_cycle ].a++;
reverse ? stats->acgtno_revcomp[ read_cycle ].t++ : stats->acgtno_revcomp[ read_cycle ].a++;
break;
case 2:
acgtno_cycles[ read_cycle ].c++;
reverse ? stats->acgtno_revcomp[ read_cycle ].g++ : stats->acgtno_revcomp[ read_cycle ].c++;
gc_count++;
break;
case 4:
acgtno_cycles[ read_cycle ].g++;
reverse ? stats->acgtno_revcomp[ read_cycle ].c++ : stats->acgtno_revcomp[ read_cycle ].g++;
gc_count++;
break;
case 8:
reverse ? stats->acgtno_revcomp[ read_cycle ].a++ : stats->acgtno_revcomp[ read_cycle ].t++;
acgtno_cycles[ read_cycle ].t++;
break;
case 15:
acgtno_cycles[ read_cycle ].n++;
break;
default:
/*
* count "=" sequences in "other" along
* with MRSVWYHKDB ambiguity codes
*/
acgtno_cycles[ read_cycle ].other++;
break;
}
}
}
int gc_idx_min = gc_count*(stats->ngc-1)/seq_len;
int gc_idx_max = (gc_count+1)*(stats->ngc-1)/seq_len;
if ( gc_idx_max >= stats->ngc ) gc_idx_max = stats->ngc - 1;
// Determine which array (1st or 2nd read) will these stats go to,
// trim low quality bases from end the same way BWA does,
// fill GC histogram
uint64_t *quals = NULL;
uint8_t *bam_quals = bam_get_qual(bam_line);
switch (order) {
case READ_ORDER_FIRST:
quals = stats->quals_1st;
stats->nreads_1st++;
stats->total_len_1st += seq_len;
for (i=gc_idx_min; i<gc_idx_max; i++)
stats->gc_1st[i]++;
break;
case READ_ORDER_LAST:
quals = stats->quals_2nd;
stats->nreads_2nd++;
stats->total_len_2nd += seq_len;
for (i=gc_idx_min; i<gc_idx_max; i++)
stats->gc_2nd[i]++;
break;
default:
stats->nreads_other++;
}
if ( stats->info->trim_qual>0 )
stats->nbases_trimmed += bwa_trim_read(stats->info->trim_qual, bam_quals, seq_len, reverse);
// Quality histogram and average quality. Clipping is neglected.
if (quals) {
for (i=0; i<seq_len; i++)
{
uint8_t qual = bam_quals[ reverse ? seq_len-i-1 : i];
if ( qual>=stats->nquals )
error("TODO: quality too high %d>=%d (%s %"PRIhts_pos" %s)\n", qual, stats->nquals, sam_hdr_tid2name(stats->info->sam_header, bam_line->core.tid), bam_line->core.pos+1, bam_get_qname(bam_line));
if ( qual>stats->max_qual )
stats->max_qual = qual;
quals[ i*stats->nquals+qual ]++;
stats->sum_qual += qual;
}
}
// Barcode statistics
if (order == READ_ORDER_FIRST) {
collect_barcode_stats(bam_line, stats);
}
// Look at the flags and increment appropriate counters (mapped, paired, etc)
if ( IS_UNMAPPED(bam_line) )
{
stats->nreads_unmapped++;
}
else
{
stats->nbases_mapped += seq_len; // This ignores clipping so only count primary
if ( !bam_line->core.qual )
stats->nreads_mq0++;
if ( !IS_PAIRED_AND_MAPPED(bam_line) )
stats->nreads_single_mapped++;
else
{
stats->nreads_paired_and_mapped++;
if (IS_PROPERLYPAIRED(bam_line)) stats->nreads_properly_paired++;
if ( bam_line->core.tid!=bam_line->core.mtid )
stats->nreads_anomalous++;
}
}
*gc_count_out = gc_count;
}