Debian Codegraph @

samtools/stats.c.pysam.c

raw symbols SCIP
1 #include "samtools.pysam.h"
2
3 /* stats.c -- This is the former bamcheck integrated into samtools/htslib.
4
5 Copyright (C) 2012-2024 Genome Research Ltd.
6
7 Author: Petr Danecek <[email protected]>
8 Author: Sam Nicholls <[email protected]>
9
10 Permission is hereby granted, free of charge, to any person obtaining a copy
11 of this software and associated documentation files (the "Software"), to deal
12 in the Software without restriction, including without limitation the rights
13 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14 copies of the Software, and to permit persons to whom the Software is
15 furnished to do so, subject to the following conditions:
16
17 The above copyright notice and this permission notice shall be included in
18 all copies or substantial portions of the Software.
19
20 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
23 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
25 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
26 DEALINGS IN THE SOFTWARE. */
27
28 /* Assumptions, approximations and other issues:
29 - GC-depth graph does not split reads, the starting position determines which bin is incremented.
30 There are small overlaps between bins (max readlen-1). However, the bins are big (20k).
31 - coverage distribution ignores softclips and deletions
32 - some stats require sorted BAMs
33 - GC content graph can have an untidy, step-like pattern when BAM contains multiple read lengths.
34 - 'bases mapped' (stats->nbases_mapped) is calculated from read lengths given by BAM (core.l_qseq)
35 - With the -t option, the whole reads are used. Except for the number of mapped bases (cigar)
36 counts, no splicing is done, no indels or soft clips are considered, even small overlap is
37 good enough to include the read in the stats.
38 - GC content of reads not calculated for "=" sequences
39
40 */
41
42 #include <config.h>
43
44 #include <unistd.h> // for isatty()
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <stdarg.h>
48 #include <string.h>
49 #include <math.h>
50 #include <ctype.h>
51 #include <inttypes.h>
52 #include <getopt.h>
53 #include <errno.h>
54 #include <assert.h>
55 #include <zlib.h> // for crc32
56 #include <htslib/faidx.h>
57 #include <htslib/sam.h>
58 #include <htslib/hts.h>
59 #include <htslib/hts_defs.h>
60 #include "samtools.h"
61 #include <htslib/khash.h>
62 #include <htslib/kstring.h>
63 #include "stats_isize.h"
64 #include "sam_opts.h"
65 #include "bedidx.h"
66
67 #define BWA_MIN_RDLEN 35
68 #define DEFAULT_CHUNK_NO 8
69 #define DEFAULT_PAIR_MAX 10000
70 #define ERROR_LIMIT 200
71 // From the spec
72 // 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.
73 #define IS_PAIRED(bam) ((bam)->core.flag&BAM_FPAIRED)
74 #define IS_PAIRED_AND_MAPPED(bam) (((bam)->core.flag&BAM_FPAIRED) && !((bam)->core.flag&BAM_FUNMAP) && !((bam)->core.flag&BAM_FMUNMAP))
75 #define IS_PROPERLYPAIRED(bam) (((bam)->core.flag&(BAM_FPAIRED|BAM_FPROPER_PAIR)) == (BAM_FPAIRED|BAM_FPROPER_PAIR) && !((bam)->core.flag&BAM_FUNMAP))
76 #define IS_UNMAPPED(bam) ((bam)->core.flag&BAM_FUNMAP)
77 #define IS_REVERSE(bam) ((bam)->core.flag&BAM_FREVERSE)
78 #define IS_MATE_REVERSE(bam) ((bam)->core.flag&BAM_FMREVERSE)
79 #define IS_READ1(bam) ((bam)->core.flag&BAM_FREAD1)
80 #define IS_READ2(bam) ((bam)->core.flag&BAM_FREAD2)
81 #define IS_DUP(bam) ((bam)->core.flag&BAM_FDUP)
82 #define IS_ORIGINAL(bam) (((bam)->core.flag&(BAM_FSECONDARY|BAM_FSUPPLEMENTARY)) == 0)
83
84 #define READ_ORDER_NONE 0
85 #define READ_ORDER_FIRST 1
86 #define READ_ORDER_LAST 2
87 #define READ_ORDER_MIDDLE 3
88
89 #define REG_INC 100
90 #define POS_INC 1000
91
92 // The GC-depth graph works as follows: split the reference sequence into
93 // segments and calculate GC content and depth in each bin. Then sort
94 // these segments by their GC and plot the depth distribution by means
95 // of 10th, 25th, etc. depth percentiles.
96 typedef struct
97 {
98 float gc;
99 uint32_t depth;
100 }
101 gc_depth_t;
102
103 // For coverage distribution, a simple pileup
104 typedef struct
105 {
106 hts_pos_t pos;
107 int size, start;
108 int *buffer;
109 }
110 round_buffer_t;
111
112 typedef struct
113 {
114 int npos, mpos, cpos;
115 hts_pair_pos_t *pos;
116 }
117 regions_t;
118
119 typedef struct
120 {
121 uint64_t a;
122 uint64_t c;
123 uint64_t g;
124 uint64_t t;
125 uint64_t n;
126 uint64_t other;
127 }
128 acgtno_count_t;
129
130 typedef struct
131 {
132 char tag_name[3];
133 char qual_name[3];
134 uint32_t nbases;
135 int32_t tag_sep; // Index of the separator (if present)
136 int32_t max_qual;
137 uint32_t offset; // Where the tag stats info is located in the allocated memory
138 }
139 barcode_info_t;
140
141 typedef struct
142 {
143 // Auxiliary data
144 int flag_require, flag_filter;
145 faidx_t *fai; // Reference sequence for GC-depth graph
146 int argc; // Command line arguments to be printed on the output
147 char **argv;
148 int gcd_bin_size; // The size of GC-depth bin
149 int nisize; // The maximum insert size that the allocated array can hold - 0 indicates no limit
150 int trim_qual; // bwa trim quality
151 float isize_main_bulk; // There are always some unrealistically big insert sizes, report only the main part
152 int cov_min,cov_max,cov_step; // Minimum, maximum coverage and size of the coverage bins
153 samFile* sam;
154 sam_hdr_t* sam_header;
155
156 // Filters
157 int filter_readlen;
158
159 // Misc
160 char *split_tag; // Tag on which to perform stats splitting
161 char *split_prefix; // Path or string prefix for filenames created when splitting
162 int remove_overlaps;
163 int cov_threshold;
164 }
165 stats_info_t;
166
167 typedef struct
168 {
169 // Dimensions of the quality histogram holder (quals_1st,quals_2nd), GC content holder (gc_1st,gc_2nd),
170 // insert size histogram holder
171 int nquals; // The number of quality bins
172 int nbases; // The maximum sequence length the allocated array can hold
173 int ngc; // The size of gc_1st and gc_2nd
174 int nindels; // The maximum indel length for indel distribution
175
176 // Arrays for the histogram data
177 uint64_t *quals_1st, *quals_2nd;
178 uint64_t *gc_1st, *gc_2nd;
179 acgtno_count_t *acgtno_cycles_1st, *acgtno_cycles_2nd;
180 acgtno_count_t *acgtno_revcomp;
181 uint64_t *read_lengths, *read_lengths_1st, *read_lengths_2nd;
182 uint64_t *insertions, *deletions;
183 uint64_t *ins_cycles_1st, *ins_cycles_2nd, *del_cycles_1st, *del_cycles_2nd;
184 isize_t *isize;
185 uint64_t* mapping_qualities;
186
187 // The extremes encountered
188 int max_len; // Maximum read length
189 int max_len_1st; // Maximum read length for forward reads
190 int max_len_2nd; // Maximum read length for reverse reads
191 int max_qual; // Maximum quality
192 int is_sorted;
193
194 // Summary numbers
195 uint64_t total_len;
196 uint64_t total_len_1st;
197 uint64_t total_len_2nd;
198 uint64_t total_len_dup;
199 uint64_t nreads_1st;
200 uint64_t nreads_2nd;
201 uint64_t nreads_other;
202 uint64_t nreads_filtered;
203 uint64_t nreads_dup;
204 uint64_t nreads_unmapped;
205 uint64_t nreads_single_mapped;
206 uint64_t nreads_paired_and_mapped;
207 uint64_t nreads_properly_paired;
208 uint64_t nreads_paired_tech;
209 uint64_t nreads_anomalous;
210 uint64_t nreads_mq0;
211 uint64_t nbases_mapped;
212 uint64_t nbases_mapped_cigar;
213 uint64_t nbases_trimmed; // bwa trimmed bases
214 uint64_t nmismatches;
215 uint64_t nreads_QCfailed, nreads_secondary, nreads_supplementary;
216 struct {
217 uint32_t names, reads, quals;
218 } checksum;
219
220 // GC-depth related data
221 uint32_t ngcd, igcd; // The maximum number of GC depth bins and index of the current bin
222 gc_depth_t *gcd; // The GC-depth bins holder
223 int32_t tid; // Position of the current bin
224 hts_pos_t gcd_pos, pos; // Position of the last read
225
226 // Coverage distribution related data
227 int ncov; // The number of coverage bins
228 uint64_t *cov; // The coverage frequencies
229 round_buffer_t cov_rbuf; // Pileup round buffer
230
231 // Mismatches by read cycle
232 uint8_t *rseq_buf; // A buffer for reference sequence to check the mismatches against
233 int mrseq_buf; // The size of the buffer
234 hts_pos_t rseq_pos; // The coordinate of the first base in the buffer
235 int64_t nrseq_buf; // The used part of the buffer
236 uint64_t *mpc_buf; // Mismatches per cycle
237
238 // Target regions
239 int nregions;
240 hts_pos_t reg_from, reg_to;
241 regions_t *regions;
242
243 // Auxiliary data
244 double sum_qual; // For calculating average quality value
245 void *rg_hash; // Read groups to include, the array is null-terminated
246
247 // Split
248 char* split_name;
249
250 stats_info_t* info; // Pointer to options and settings struct
251 hts_pair_pos_t *chunks;
252 uint32_t nchunks;
253
254 uint32_t pair_count; // Number of active pairs in the pairing hash table
255 uint64_t target_count; // Number of bases covered by the target file
256 uint32_t last_pair_tid;
257 uint32_t last_read_flush;
258
259 // Barcode statistics
260 acgtno_count_t *acgtno_barcode;
261 uint64_t *quals_barcode;
262 barcode_info_t *tags_barcode;
263 uint32_t ntags;
264 uint32_t error_number;
265 }
266 stats_t;
267 KHASH_MAP_INIT_STR(c2stats, stats_t*)
268
269 typedef struct {
270 uint32_t first; // 1 - first read, 2 - second read
271 uint32_t n, m; // number of chunks, allocated chunks
272 hts_pair_pos_t *chunks; // chunk array of size m
273 } pair_t;
274 KHASH_MAP_INIT_STR(qn2pair, pair_t*)
275
276 KHASH_SET_INIT_STR(rg)
277
278
279 static void HTS_NORETURN error(const char *format, ...);
280 int is_in_regions(bam1_t *bam_line, stats_t *stats);
281 void realloc_buffers(stats_t *stats, int seq_len);
282
283 static int regions_lt(const void *r1, const void *r2) {
284 int64_t from_diff = ((hts_pair_pos_t *)r1)->beg - ((hts_pair_pos_t *)r2)->beg;
285 int64_t to_diff = ((hts_pair_pos_t *)r1)->end - ((hts_pair_pos_t *)r2)->end;
286
287 return from_diff > 0 ? 1 : from_diff < 0 ? -1 : to_diff > 0 ? 1 : to_diff < 0 ? -1 : 0;
288 }
289
290 // Coverage distribution methods
291 static inline int coverage_idx(int min, int max, int n, int step, int depth)
292 {
293 if ( depth < min )
294 return 0;
295
296 if ( depth > max )
297 return n-1;
298
299 return 1 + (depth - min) / step;
300 }
301
302 static inline int round_buffer_lidx2ridx(int offset, int size, hts_pos_t refpos, hts_pos_t pos)
303 {
304 return (offset + (pos-refpos) % size) % size;
305 }
306
307 void round_buffer_flush(stats_t *stats, hts_pos_t pos)
308 {
309 int ibuf,idp;
310
311 if ( pos==stats->cov_rbuf.pos )
312 return;
313
314 hts_pos_t new_pos = pos;
315 if ( pos==-1 || pos - stats->cov_rbuf.pos >= stats->cov_rbuf.size )
316 {
317 // Flush the whole buffer, but in sequential order,
318 pos = stats->cov_rbuf.pos + stats->cov_rbuf.size - 1;
319 }
320
321 if ( pos < stats->cov_rbuf.pos )
322 error("Expected coordinates in ascending order, got %"PRIhts_pos" after %"PRIhts_pos"\n", pos, stats->cov_rbuf.pos);
323
324 int ifrom = stats->cov_rbuf.start;
325 int ito = round_buffer_lidx2ridx(stats->cov_rbuf.start, stats->cov_rbuf.size, stats->cov_rbuf.pos, pos-1);
326 if ( ifrom>ito )
327 {
328 for (ibuf=ifrom; ibuf<stats->cov_rbuf.size; ibuf++)
329 {
330 if ( !stats->cov_rbuf.buffer[ibuf] )
331 continue;
332 idp = coverage_idx(stats->info->cov_min,stats->info->cov_max,stats->ncov,stats->info->cov_step,stats->cov_rbuf.buffer[ibuf]);
333 stats->cov[idp]++;
334 stats->cov_rbuf.buffer[ibuf] = 0;
335 }
336 ifrom = 0;
337 }
338 for (ibuf=ifrom; ibuf<=ito; ibuf++)
339 {
340 if ( !stats->cov_rbuf.buffer[ibuf] )
341 continue;
342 idp = coverage_idx(stats->info->cov_min,stats->info->cov_max,stats->ncov,stats->info->cov_step,stats->cov_rbuf.buffer[ibuf]);
343 stats->cov[idp]++;
344 stats->cov_rbuf.buffer[ibuf] = 0;
345 }
346 stats->cov_rbuf.start = (new_pos==-1) ? 0 : round_buffer_lidx2ridx(stats->cov_rbuf.start, stats->cov_rbuf.size, stats->cov_rbuf.pos, pos);
347 stats->cov_rbuf.pos = new_pos;
348 }
349
350 /**
351 * [from, to) - 0 based half-open
352 */
353 static void round_buffer_insert_read(round_buffer_t *rbuf, hts_pos_t from, hts_pos_t to)
354 {
355 if ( to-from > rbuf->size )
356 error("The read length too big (%"PRIhts_pos"), please increase the buffer length (currently %d)\n", to-from, rbuf->size);
357 if ( from < rbuf->pos )
358 error("The reads are not sorted (%"PRIhts_pos" comes after %"PRIhts_pos").\n", from, rbuf->pos);
359
360 int ifrom, ito, ibuf;
361 ifrom = round_buffer_lidx2ridx(rbuf->start, rbuf->size, rbuf->pos, from);
362 ito = round_buffer_lidx2ridx(rbuf->start, rbuf->size, rbuf->pos, to);
363 if ( ifrom>ito )
364 {
365 for (ibuf=ifrom; ibuf<rbuf->size; ibuf++)
366 rbuf->buffer[ibuf]++;
367 ifrom = 0;
368 }
369 for (ibuf=ifrom; ibuf<ito; ibuf++)
370 rbuf->buffer[ibuf]++;
371 }
372
373 // Calculate the number of bases in the read trimmed by BWA
374 int bwa_trim_read(int trim_qual, uint8_t *quals, int len, int reverse)
375 {
376 if ( len<BWA_MIN_RDLEN ) return 0;
377
378 // Although the name implies that the read cannot be trimmed to more than BWA_MIN_RDLEN,
379 // the calculation can in fact trim it to (BWA_MIN_RDLEN-1). (bwa_trim_read in bwa/bwaseqio.c).
380 int max_trimmed = len - BWA_MIN_RDLEN + 1;
381 int l, sum=0, max_sum=0, max_l=0;
382
383 for (l=0; l<max_trimmed; l++)
384 {
385 sum += trim_qual - quals[ reverse ? l : len-1-l ];
386 if ( sum<0 ) break;
387 if ( sum>max_sum )
388 {
389 max_sum = sum;
390 // This is the correct way, but bwa clips from some reason one base less
391 // max_l = l+1;
392 max_l = l;
393 }
394 }
395 return max_l;
396 }
397
398
399 void count_indels(stats_t *stats,bam1_t *bam_line)
400 {
401 int is_fwd = IS_REVERSE(bam_line) ? 0 : 1;
402 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;
403 int icig;
404 int icycle = 0;
405 int read_len = bam_line->core.l_qseq;
406 for (icig=0; icig<bam_line->core.n_cigar; icig++)
407 {
408 int cig = bam_cigar_op(bam_get_cigar(bam_line)[icig]);
409 int ncig = bam_cigar_oplen(bam_get_cigar(bam_line)[icig]);
410 if ( !ncig ) continue; // curiously, this can happen: 0D
411
412 if ( cig==BAM_CINS )
413 {
414 int idx = is_fwd ? icycle : read_len-icycle-ncig;
415 if ( idx<0 )
416 error("FIXME: read_len=%d vs icycle=%d\n", read_len,icycle);
417 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));
418 if ( order == READ_ORDER_FIRST )
419 stats->ins_cycles_1st[idx]++;
420 if ( order == READ_ORDER_LAST )
421 stats->ins_cycles_2nd[idx]++;
422 icycle += ncig;
423 if ( ncig<=stats->nindels )
424 stats->insertions[ncig-1]++;
425 continue;
426 }
427 if ( cig==BAM_CDEL )
428 {
429 int idx = is_fwd ? icycle-1 : read_len-icycle-1;
430 if ( idx<0 ) continue; // discard meaningless deletions
431 if ( idx >= stats->nbases ) error("FIXME: %d vs %d\n", idx,stats->nbases);
432 if ( order == READ_ORDER_FIRST )
433 stats->del_cycles_1st[idx]++;
434 if ( order == READ_ORDER_LAST )
435 stats->del_cycles_2nd[idx]++;
436 if ( ncig<=stats->nindels )
437 stats->deletions[ncig-1]++;
438 continue;
439 }
440 if ( cig!=BAM_CREF_SKIP && cig!=BAM_CHARD_CLIP && cig!=BAM_CPAD )
441 icycle += ncig;
442 }
443 }
444
445 int unclipped_length(bam1_t *bam_line)
446 {
447 int icig, read_len = bam_line->core.l_qseq;
448 for (icig=0; icig<bam_line->core.n_cigar; icig++)
449 {
450 int cig = bam_cigar_op(bam_get_cigar(bam_line)[icig]);
451 if ( cig==BAM_CHARD_CLIP )
452 read_len += bam_cigar_oplen(bam_get_cigar(bam_line)[icig]);
453 }
454 return read_len;
455 }
456
457 void count_mismatches_per_cycle(stats_t *stats, bam1_t *bam_line, int read_len)
458 {
459 int is_fwd = IS_REVERSE(bam_line) ? 0 : 1;
460 int icig, iread=0, icycle=0;
461 hts_pos_t iref = bam_line->core.pos - stats->rseq_pos;
462 uint8_t *read = bam_get_seq(bam_line);
463 uint8_t *quals = bam_get_qual(bam_line);
464 uint64_t *mpc_buf = stats->mpc_buf;
465 for (icig=0; icig<bam_line->core.n_cigar; icig++)
466 {
467 int cig = bam_cigar_op(bam_get_cigar(bam_line)[icig]);
468 int ncig = bam_cigar_oplen(bam_get_cigar(bam_line)[icig]);
469 if ( cig==BAM_CINS )
470 {
471 iread += ncig;
472 icycle += ncig;
473 continue;
474 }
475 if ( cig==BAM_CDEL )
476 {
477 iref += ncig;
478 continue;
479 }
480 if ( cig==BAM_CSOFT_CLIP )
481 {
482 icycle += ncig;
483 // Soft-clips are present in the sequence, but the position of the read marks a start of the sequence after clipping
484 // iref += ncig;
485 iread += ncig;
486 continue;
487 }
488 if ( cig==BAM_CHARD_CLIP )
489 {
490 icycle += ncig;
491 continue;
492 }
493 // Ignore H and N CIGARs. The letter are inserted e.g. by TopHat and often require very large
494 // chunk of refseq in memory. Not very frequent and not noticeable in the stats.
495 if ( cig==BAM_CREF_SKIP || cig==BAM_CHARD_CLIP || cig==BAM_CPAD ) continue;
496 if ( cig!=BAM_CMATCH && cig!=BAM_CEQUAL && cig!=BAM_CDIFF ) // not relying on precalculated diffs
497 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));
498
499 if ( ncig+iref > stats->nrseq_buf )
500 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);
501
502 int im;
503 for (im=0; im<ncig; im++)
504 {
505 uint8_t cread = bam_seqi(read,iread);
506 uint8_t cref = stats->rseq_buf[iref];
507
508 // ---------------15
509 // =ACMGRSVTWYHKDBN
510 if ( cread==15 )
511 {
512 int idx = is_fwd ? icycle : read_len-icycle-1;
513 if ( idx>stats->max_len )
514 error("mpc: %d>%d\n",idx,stats->max_len);
515 idx = idx*stats->nquals;
516 if ( idx>=stats->nquals*stats->nbases )
517 error("FIXME: mpc_buf overflow\n");
518 mpc_buf[idx]++;
519 }
520 else if ( cref && cread && cref!=cread )
521 {
522 uint8_t qual = quals[iread] + 1;
523 if ( qual>=stats->nquals )
524 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));
525
526 int idx = is_fwd ? icycle : read_len-icycle-1;
527 if ( idx>stats->max_len )
528 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));
529
530 idx = idx*stats->nquals + qual;
531 if ( idx>=stats->nquals*stats->nbases )
532 error("FIXME: mpc_buf overflow\n");
533 mpc_buf[idx]++;
534 }
535
536 iref++;
537 iread++;
538 icycle++;
539 }
540 }
541 }
542
543 void read_ref_seq(stats_t *stats, int32_t tid, hts_pos_t pos, hts_pos_t end)
544 {
545 int i;
546 hts_pos_t fai_ref_len;
547 char *fai_ref;
548
549 if (end < pos+stats->mrseq_buf-1)
550 end = pos+stats->mrseq_buf-1;
551 else if (stats->mrseq_buf < end - pos) {
552 size_t sz = end - pos;
553 uint8_t *new_rseq = realloc(stats->rseq_buf, sz);
554 if (!new_rseq)
555 error("Couldn't expand the reference sequence buffer\n");
556 stats->rseq_buf = new_rseq;
557 stats->mrseq_buf = sz;
558 }
559
560 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);
561 if ( fai_ref_len < 0 ) error("Failed to fetch the sequence \"%s\"\n", sam_hdr_tid2name(stats->info->sam_header, tid));
562
563 uint8_t *ptr = stats->rseq_buf;
564 for (i=0; i<fai_ref_len; i++)
565 {
566 // Conversion between uint8_t coding and ACGT
567 // -12-4---8-------
568 // =ACMGRSVTWYHKDBN
569 switch (fai_ref[i])
570 {
571 case 'A':
572 case 'a': *ptr = 1; break;
573 case 'C':
574 case 'c': *ptr = 2; break;
575 case 'G':
576 case 'g': *ptr = 4; break;
577 case 'T':
578 case 't': *ptr = 8; break;
579 default: *ptr = 0; break;
580 }
581 ptr++;
582 }
583 free(fai_ref);
584
585 if ( fai_ref_len < stats->mrseq_buf ) memset(ptr,0, stats->mrseq_buf - fai_ref_len);
586 stats->nrseq_buf = fai_ref_len;
587 stats->rseq_pos = pos;
588 stats->tid = tid;
589 }
590
591 float fai_gc_content(stats_t *stats, hts_pos_t pos, int len)
592 {
593 uint32_t gc,count,c;
594 hts_pos_t i = pos - stats->rseq_pos, ito = i + len;
595 assert( i>=0 );
596
597 if ( ito > stats->nrseq_buf ) ito = stats->nrseq_buf;
598
599 // Count GC content
600 gc = count = 0;
601 for (; i<ito; i++)
602 {
603 c = stats->rseq_buf[i];
604 if ( c==2 || c==4 )
605 {
606 gc++;
607 count++;
608 }
609 else if ( c==1 || c==8 )
610 count++;
611 }
612 return count ? (float)gc/count : 0;
613 }
614
615 void realloc_rseq_buffer(stats_t *stats)
616 {
617 int n = stats->nbases*10;
618 if ( stats->info->gcd_bin_size > n ) n = stats->info->gcd_bin_size;
619 if ( stats->mrseq_buf<n )
620 {
621 stats->rseq_buf = realloc(stats->rseq_buf,sizeof(uint8_t)*n);
622 if (!stats->rseq_buf) {
623 error("Could not reallocate reference sequence buffer");
624 }
625 stats->mrseq_buf = n;
626 }
627 }
628
629 void realloc_gcd_buffer(stats_t *stats, int seq_len)
630 {
631 hts_expand0(gc_depth_t,stats->igcd+1,stats->ngcd,stats->gcd);
632 realloc_rseq_buffer(stats);
633 }
634
635 void realloc_buffers(stats_t *stats, int seq_len)
636 {
637 int n = 2*(1 + seq_len - stats->nbases) + stats->nbases;
638
639 stats->quals_1st = realloc(stats->quals_1st, n*stats->nquals*sizeof(uint64_t));
640 if ( !stats->quals_1st )
641 error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len,n*stats->nquals*sizeof(uint64_t));
642 memset(stats->quals_1st + stats->nbases*stats->nquals, 0, (n-stats->nbases)*stats->nquals*sizeof(uint64_t));
643
644 stats->quals_2nd = realloc(stats->quals_2nd, n*stats->nquals*sizeof(uint64_t));
645 if ( !stats->quals_2nd )
646 error("Could not realloc buffers, the sequence too long: %d (2x%ld)\n", seq_len,n*stats->nquals*sizeof(uint64_t));
647 memset(stats->quals_2nd + stats->nbases*stats->nquals, 0, (n-stats->nbases)*stats->nquals*sizeof(uint64_t));
648
649 if ( stats->mpc_buf )
650 {
651 stats->mpc_buf = realloc(stats->mpc_buf, n*stats->nquals*sizeof(uint64_t));
652 if ( !stats->mpc_buf )
653 error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len,n*stats->nquals*sizeof(uint64_t));
654 memset(stats->mpc_buf + stats->nbases*stats->nquals, 0, (n-stats->nbases)*stats->nquals*sizeof(uint64_t));
655 }
656
657 stats->acgtno_cycles_1st = realloc(stats->acgtno_cycles_1st, n*sizeof(acgtno_count_t));
658 if ( !stats->acgtno_cycles_1st )
659 error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len, n*sizeof(acgtno_count_t));
660 memset(stats->acgtno_cycles_1st + stats->nbases, 0, (n-stats->nbases)*sizeof(acgtno_count_t));
661
662 stats->acgtno_cycles_2nd = realloc(stats->acgtno_cycles_2nd, n*sizeof(acgtno_count_t));
663 if ( !stats->acgtno_cycles_2nd )
664 error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len, n*sizeof(acgtno_count_t));
665 memset(stats->acgtno_cycles_2nd + stats->nbases, 0, (n-stats->nbases)*sizeof(acgtno_count_t));
666
667 stats->acgtno_revcomp = realloc(stats->acgtno_revcomp, n*sizeof(acgtno_count_t));
668 if ( !stats->acgtno_revcomp )
669 error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len, n*sizeof(acgtno_count_t));
670 memset(stats->acgtno_revcomp + stats->nbases, 0, (n-stats->nbases)*sizeof(acgtno_count_t));
671
672 stats->read_lengths = realloc(stats->read_lengths, n*sizeof(uint64_t));
673 if ( !stats->read_lengths )
674 error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len,n*sizeof(uint64_t));
675 memset(stats->read_lengths + stats->nbases, 0, (n-stats->nbases)*sizeof(uint64_t));
676
677 stats->read_lengths_1st = realloc(stats->read_lengths_1st, n*sizeof(uint64_t));
678 if ( !stats->read_lengths_1st )
679 error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len,n*sizeof(uint64_t));
680 memset(stats->read_lengths_1st + stats->nbases, 0, (n-stats->nbases)*sizeof(uint64_t));
681
682 stats->read_lengths_2nd = realloc(stats->read_lengths_2nd, n*sizeof(uint64_t));
683 if ( !stats->read_lengths_2nd )
684 error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len,n*sizeof(uint64_t));
685 memset(stats->read_lengths_2nd + stats->nbases, 0, (n-stats->nbases)*sizeof(uint64_t));
686
687 stats->insertions = realloc(stats->insertions, n*sizeof(uint64_t));
688 if ( !stats->insertions )
689 error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len,n*sizeof(uint64_t));
690 memset(stats->insertions + stats->nbases, 0, (n-stats->nbases)*sizeof(uint64_t));
691
692 stats->deletions = realloc(stats->deletions, n*sizeof(uint64_t));
693 if ( !stats->deletions )
694 error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len,n*sizeof(uint64_t));
695 memset(stats->deletions + stats->nbases, 0, (n-stats->nbases)*sizeof(uint64_t));
696
697 stats->ins_cycles_1st = realloc(stats->ins_cycles_1st, (n+1)*sizeof(uint64_t));
698 if ( !stats->ins_cycles_1st )
699 error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len,(n+1)*sizeof(uint64_t));
700 memset(stats->ins_cycles_1st + stats->nbases + 1, 0, (n-stats->nbases)*sizeof(uint64_t));
701
702 stats->ins_cycles_2nd = realloc(stats->ins_cycles_2nd, (n+1)*sizeof(uint64_t));
703 if ( !stats->ins_cycles_2nd )
704 error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len,(n+1)*sizeof(uint64_t));
705 memset(stats->ins_cycles_2nd + stats->nbases + 1, 0, (n-stats->nbases)*sizeof(uint64_t));
706
707 stats->del_cycles_1st = realloc(stats->del_cycles_1st, (n+1)*sizeof(uint64_t));
708 if ( !stats->del_cycles_1st )
709 error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len,(n+1)*sizeof(uint64_t));
710 memset(stats->del_cycles_1st + stats->nbases + 1, 0, (n-stats->nbases)*sizeof(uint64_t));
711
712 stats->del_cycles_2nd = realloc(stats->del_cycles_2nd, (n+1)*sizeof(uint64_t));
713 if ( !stats->del_cycles_2nd )
714 error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len,(n+1)*sizeof(uint64_t));
715 memset(stats->del_cycles_2nd + stats->nbases + 1, 0, (n-stats->nbases)*sizeof(uint64_t));
716
717 stats->nbases = n;
718
719 // Realloc the coverage distribution buffer
720 int *rbuffer = calloc(sizeof(int),seq_len*5);
721 if (!rbuffer) {
722 error("Could not allocate coverage distribution buffer");
723 }
724 n = stats->cov_rbuf.size-stats->cov_rbuf.start;
725 memcpy(rbuffer,stats->cov_rbuf.buffer+stats->cov_rbuf.start,n);
726 if ( stats->cov_rbuf.start>1 )
727 memcpy(rbuffer+n,stats->cov_rbuf.buffer,stats->cov_rbuf.start);
728 stats->cov_rbuf.start = 0;
729 free(stats->cov_rbuf.buffer);
730 stats->cov_rbuf.buffer = rbuffer;
731 stats->cov_rbuf.size = seq_len*5;
732
733 realloc_rseq_buffer(stats);
734 }
735
736 void update_checksum(bam1_t *bam_line, stats_t *stats)
737 {
738 uint8_t *name = (uint8_t*) bam_get_qname(bam_line);
739 int len = 0;
740 while ( name[len] ) len++;
741 stats->checksum.names += crc32(0L, name, len);
742
743 int seq_len = bam_line->core.l_qseq;
744 if ( !seq_len ) return;
745
746 uint8_t *seq = bam_get_seq(bam_line);
747 stats->checksum.reads += crc32(0L, seq, (seq_len+1)/2);
748
749 uint8_t *qual = bam_get_qual(bam_line);
750 stats->checksum.quals += crc32(0L, qual, (seq_len+1)/2);
751 }
752
753 // Collect statistics about the barcode tags specified by init_barcode_tags method
754 static void collect_barcode_stats(bam1_t* bam_line, stats_t* stats) {
755 uint32_t nbases, tag, i;
756 acgtno_count_t *acgtno;
757 uint64_t *quals;
758 int32_t *separator, *maxqual;
759
760 for (tag = 0; tag < stats->ntags; tag++) {
761 const char *barcode_tag = stats->tags_barcode[tag].tag_name, *qual_tag = stats->tags_barcode[tag].qual_name;
762 uint8_t* bc = bam_aux_get(bam_line, barcode_tag);
763 if (!bc)
764 continue;
765
766 char* barcode = bam_aux2Z(bc);
767 if (!barcode)
768 continue;
769
770 uint32_t barcode_len = strlen(barcode);
771 if (!barcode_len) {
772 continue; //consider 0 size barcode same as no barcode - avoids issues with realloc below
773 }
774 if (!stats->tags_barcode[tag].nbases) { // tag seen for the first time
775 uint32_t offset = 0;
776 for (i = 0; i < stats->ntags; i++)
777 offset += stats->tags_barcode[i].nbases;
778
779 stats->tags_barcode[tag].offset = offset;
780 stats->tags_barcode[tag].nbases = barcode_len;
781 stats->acgtno_barcode = realloc(stats->acgtno_barcode, (offset + barcode_len) * sizeof(acgtno_count_t));
782 stats->quals_barcode = realloc(stats->quals_barcode, (offset + barcode_len) * stats->nquals * sizeof(uint64_t));
783
784 if (!stats->acgtno_barcode || !stats->quals_barcode)
785 error("Error allocating memory. Aborting!\n");
786
787 memset(stats->acgtno_barcode + offset, 0, barcode_len*sizeof(acgtno_count_t));
788 memset(stats->quals_barcode + offset*stats->nquals, 0, barcode_len*stats->nquals*sizeof(uint64_t));
789 }
790
791 nbases = stats->tags_barcode[tag].nbases;
792 if (barcode_len > nbases) {
793 fprintf(samtools_stderr, "Barcodes with tag %s differ in length at sequence '%s'\n", barcode_tag, bam_get_qname(bam_line));
794 continue;
795 }
796
797 acgtno = stats->acgtno_barcode + stats->tags_barcode[tag].offset;
798 quals = stats->quals_barcode + stats->tags_barcode[tag].offset*stats->nquals;
799 maxqual = &stats->tags_barcode[tag].max_qual;
800 separator = &stats->tags_barcode[tag].tag_sep;
801 int error_flag = 0;
802
803 for (i = 0; i < barcode_len; i++) {
804 switch (barcode[i]) {
805 case 'A':
806 acgtno[i].a++;
807 break;
808 case 'C':
809 acgtno[i].c++;
810 break;
811 case 'G':
812 acgtno[i].g++;
813 break;
814 case 'T':
815 acgtno[i].t++;
816 break;
817 case 'N':
818 acgtno[i].n++;
819 break;
820 default:
821 if (*separator >= 0) {
822 if (*separator != i) {
823 if (stats->error_number < ERROR_LIMIT) {
824 fprintf(samtools_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));
825 stats->error_number++;
826 }
827 error_flag = 1;
828 }
829 } else {
830 *separator = i;
831 }
832 }
833
834 /* don't process the rest of the tag bases */
835 if (error_flag)
836 break;
837 }
838
839 /* skip to the next tag */
840 if (error_flag)
841 continue;
842
843 uint8_t* qt = bam_aux_get(bam_line, qual_tag);
844 if (!qt)
845 continue;
846
847 char* barqual = bam_aux2Z(qt);
848 if (!barqual)
849 continue;
850
851 uint32_t barqual_len = strlen(barqual);
852 if (barqual_len == barcode_len) {
853 for (i = 0; i < barcode_len; i++) {
854 int32_t qual = (int32_t)barqual[i] - '!'; // Phred + 33
855 if (qual >= 0 && qual < stats->nquals) {
856 quals[i * stats->nquals + qual]++;
857 if (qual > *maxqual)
858 *maxqual = qual;
859 }
860 }
861 } else {
862 if (stats->error_number++ < ERROR_LIMIT) {
863 fprintf(samtools_stderr, "%s length and %s length don't match for sequence '%s'\n", barcode_tag, qual_tag, bam_get_qname(bam_line));
864 }
865 }
866 }
867 }
868
869 // These stats should only be calculated for the original reads ignoring
870 // supplementary artificial reads otherwise we'll accidentally double count
871 void collect_orig_read_stats(bam1_t *bam_line, stats_t *stats, int* gc_count_out)
872 {
873 int seq_len = bam_line->core.l_qseq;
874 stats->total_len += seq_len; // This ignores clipping so only count primary
875
876 if ( bam_line->core.flag & BAM_FQCFAIL ) stats->nreads_QCfailed++;
877 if ( bam_line->core.flag & BAM_FPAIRED ) stats->nreads_paired_tech++;
878
879 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;
880
881 // Count GC and ACGT per cycle. Note that cycle is approximate, clipping is ignored
882 uint8_t *seq = bam_get_seq(bam_line);
883 int i, read_cycle, gc_count = 0, reverse = IS_REVERSE(bam_line);
884
885 acgtno_count_t *acgtno_cycles = (order == READ_ORDER_FIRST) ? stats->acgtno_cycles_1st : (order == READ_ORDER_LAST) ? stats->acgtno_cycles_2nd : NULL ;
886 if (acgtno_cycles) {
887 for (i=0; i<seq_len; i++)
888 {
889 // Read cycle for current index
890 read_cycle = (reverse ? seq_len-i-1 : i);
891
892 // Conversion from uint8_t coding:
893 // -12-4---8------5
894 // =ACMGRSVTWYHKDBN
895 switch (bam_seqi(seq, i)) {
896 case 1:
897 acgtno_cycles[ read_cycle ].a++;
898 reverse ? stats->acgtno_revcomp[ read_cycle ].t++ : stats->acgtno_revcomp[ read_cycle ].a++;
899 break;
900 case 2:
901 acgtno_cycles[ read_cycle ].c++;
902 reverse ? stats->acgtno_revcomp[ read_cycle ].g++ : stats->acgtno_revcomp[ read_cycle ].c++;
903 gc_count++;
904 break;
905 case 4:
906 acgtno_cycles[ read_cycle ].g++;
907 reverse ? stats->acgtno_revcomp[ read_cycle ].c++ : stats->acgtno_revcomp[ read_cycle ].g++;
908 gc_count++;
909 break;
910 case 8:
911 reverse ? stats->acgtno_revcomp[ read_cycle ].a++ : stats->acgtno_revcomp[ read_cycle ].t++;
912 acgtno_cycles[ read_cycle ].t++;
913 break;
914 case 15:
915 acgtno_cycles[ read_cycle ].n++;
916 break;
917 default:
918 /*
919 * count "=" sequences in "other" along
920 * with MRSVWYHKDB ambiguity codes
921 */
922 acgtno_cycles[ read_cycle ].other++;
923 break;
924 }
925 }
926 }
927 int gc_idx_min = gc_count*(stats->ngc-1)/seq_len;
928 int gc_idx_max = (gc_count+1)*(stats->ngc-1)/seq_len;
929 if ( gc_idx_max >= stats->ngc ) gc_idx_max = stats->ngc - 1;
930
931 // Determine which array (1st or 2nd read) will these stats go to,
932 // trim low quality bases from end the same way BWA does,
933 // fill GC histogram
934 uint64_t *quals = NULL;
935 uint8_t *bam_quals = bam_get_qual(bam_line);
936
937 switch (order) {
938 case READ_ORDER_FIRST:
939 quals = stats->quals_1st;
940 stats->nreads_1st++;
941 stats->total_len_1st += seq_len;
942 for (i=gc_idx_min; i<gc_idx_max; i++)
943 stats->gc_1st[i]++;
944 break;
945 case READ_ORDER_LAST:
946 quals = stats->quals_2nd;
947 stats->nreads_2nd++;
948 stats->total_len_2nd += seq_len;
949 for (i=gc_idx_min; i<gc_idx_max; i++)
950 stats->gc_2nd[i]++;
951 break;
952 default:
953 stats->nreads_other++;
954 }
955 if ( stats->info->trim_qual>0 )
956 stats->nbases_trimmed += bwa_trim_read(stats->info->trim_qual, bam_quals, seq_len, reverse);
957
958 // Quality histogram and average quality. Clipping is neglected.
959 if (quals) {
960 for (i=0; i<seq_len; i++)
961 {
962 uint8_t qual = bam_quals[ reverse ? seq_len-i-1 : i];
963 if ( qual>=stats->nquals )
964 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));
965 if ( qual>stats->max_qual )
966 stats->max_qual = qual;
967
968 quals[ i*stats->nquals+qual ]++;
969 stats->sum_qual += qual;
970 }
971 }
972
973 // Barcode statistics
974 if (order == READ_ORDER_FIRST) {
975 collect_barcode_stats(bam_line, stats);
976 }
977
978 // Look at the flags and increment appropriate counters (mapped, paired, etc)
979 if ( IS_UNMAPPED(bam_line) )
980 {
981 stats->nreads_unmapped++;
982 }
983 else
984 {
985 stats->nbases_mapped += seq_len; // This ignores clipping so only count primary
986
987 if ( !bam_line->core.qual )
988 stats->nreads_mq0++;
989 if ( !IS_PAIRED_AND_MAPPED(bam_line) )
990 stats->nreads_single_mapped++;
991 else
992 {
993 stats->nreads_paired_and_mapped++;
994
995 if (IS_PROPERLYPAIRED(bam_line)) stats->nreads_properly_paired++;
996
997 if ( bam_line->core.tid!=bam_line->core.mtid )
998 stats->nreads_anomalous++;
999 }
1000 }
1001 *gc_count_out = gc_count;
1002 }
1003
1004 static int cleanup_overlaps(khash_t(qn2pair) *read_pairs, hts_pos_t max) {
1005 if ( !read_pairs )
1006 return 0;
1007
1008 int count = 0;
1009 khint_t k;
1010 for (k = kh_begin(read_pairs); k < kh_end(read_pairs); k++) {
1011 if ( kh_exist(read_pairs, k) ) {
1012 char *key = (char *)kh_key(read_pairs, k);
1013 pair_t *val = kh_val(read_pairs, k);
1014 if ( val && val->chunks ) {
1015 if ( val->chunks[val->n-1].end < max ) {
1016 free(val->chunks);
1017 free(val);
1018 free(key);
1019 kh_del(qn2pair, read_pairs, k);
1020 count++;
1021 }
1022 } else {
1023 free(key);
1024 kh_del(qn2pair, read_pairs, k);
1025 count++;
1026 }
1027 }
1028 }
1029 if ( max == INT64_MAX )
1030 kh_destroy(qn2pair, read_pairs);
1031
1032 return count;
1033 }
1034
1035 /**
1036 * [pmin, pmax) - 0 based half-open
1037 */
1038 static void remove_overlaps(bam1_t *bam_line, khash_t(qn2pair) *read_pairs, stats_t *stats, hts_pos_t pmin, hts_pos_t pmax) {
1039 if ( !bam_line || !read_pairs || !stats )
1040 return;
1041
1042 uint32_t order = (IS_READ1(bam_line) ? READ_ORDER_FIRST : 0) + (IS_READ2(bam_line) ? READ_ORDER_LAST : 0);
1043 if ( !(bam_line->core.flag & BAM_FPAIRED) ||
1044 (bam_line->core.flag & BAM_FMUNMAP) ||
1045 (llabs(bam_line->core.isize) >= 2*bam_line->core.l_qseq) ||
1046 (order != READ_ORDER_FIRST && order != READ_ORDER_LAST) ) {
1047 if ( pmin >= 0 )
1048 round_buffer_insert_read(&(stats->cov_rbuf), pmin, pmax);
1049 return;
1050 }
1051
1052 char *qname = bam_get_qname(bam_line);
1053 if ( !qname ) {
1054 fprintf(samtools_stderr, "Error retrieving qname for line starting at pos %"PRIhts_pos"\n", bam_line->core.pos);
1055 return;
1056 }
1057
1058 khint_t k = kh_get(qn2pair, read_pairs, qname);
1059 if ( k == kh_end(read_pairs) ) { //first chunk from this template
1060 if ( pmin == -1 )
1061 return;
1062
1063 int ret;
1064 char *s = strdup(qname);
1065 if ( !s ) {
1066 fprintf(samtools_stderr, "Error allocating memory\n");
1067 return;
1068 }
1069
1070 k = kh_put(qn2pair, read_pairs, s, &ret);
1071 if ( -1 == ret ) {
1072 error("Error inserting read '%s' in pair hash table\n", qname);
1073 }
1074
1075 pair_t *pc = calloc(1, sizeof(pair_t));
1076 if ( !pc ) {
1077 fprintf(samtools_stderr, "Error allocating memory\n");
1078 return;
1079 }
1080
1081 pc->m = DEFAULT_CHUNK_NO;
1082 pc->chunks = calloc(pc->m, sizeof(hts_pair_pos_t));
1083 if ( !pc->chunks ) {
1084 fprintf(samtools_stderr, "Error allocating memory\n");
1085 free(pc);
1086 return;
1087 }
1088
1089 pc->chunks[0].beg = pmin;
1090 pc->chunks[0].end = pmax;
1091 pc->n = 1;
1092 pc->first = order;
1093
1094 kh_val(read_pairs, k) = pc;
1095 stats->pair_count++;
1096 } else { //template already present
1097 pair_t *pc = kh_val(read_pairs, k);
1098 if ( !pc ) {
1099 fprintf(samtools_stderr, "Invalid hash table entry\n");
1100 return;
1101 }
1102
1103 if ( order == pc->first ) { //chunk from an existing line
1104 if ( pmin == -1 )
1105 return;
1106
1107 if ( pc->n == pc->m ) {
1108 hts_pair_pos_t *tmp = realloc(pc->chunks, (pc->m<<1)*sizeof(hts_pair_pos_t));
1109 if ( !tmp ) {
1110 fprintf(samtools_stderr, "Error allocating memory\n");
1111 return;
1112 }
1113 pc->chunks = tmp;
1114 pc->m<<=1;
1115 }
1116
1117 pc->chunks[pc->n].beg = pmin;
1118 pc->chunks[pc->n].end = pmax;
1119 pc->n++;
1120 } else { //the other line, check for overlapping
1121 if ( pmin == -1 && kh_exist(read_pairs, k) ) { //job done, delete entry
1122 char *key = (char *)kh_key(read_pairs, k);
1123 pair_t *val = kh_val(read_pairs, k);
1124 if ( val) {
1125 free(val->chunks);
1126 free(val);
1127 }
1128 free(key);
1129 kh_del(qn2pair, read_pairs, k);
1130 stats->pair_count--;
1131 return;
1132 }
1133
1134 int i;
1135 for (i=0; i<pc->n; i++) {
1136 if ( pmin >= pc->chunks[i].end )
1137 continue;
1138
1139 if ( pmax <= pc->chunks[i].beg ) //no overlap
1140 break;
1141
1142 if ( pmin < pc->chunks[i].beg ) { //overlap at the beginning
1143 round_buffer_insert_read(&(stats->cov_rbuf), pmin, pc->chunks[i].beg);
1144 pmin = pc->chunks[i].beg;
1145 }
1146
1147 if ( pmax <= pc->chunks[i].end ) { //completely contained
1148 stats->nbases_mapped_cigar -= (pmax - pmin);
1149 return;
1150 } else { //overlap at the end
1151 stats->nbases_mapped_cigar -= (pc->chunks[i].end - pmin);
1152 pmin = pc->chunks[i].end;
1153 }
1154 }
1155 }
1156 }
1157 round_buffer_insert_read(&(stats->cov_rbuf), pmin, pmax);
1158 }
1159
1160 void collect_stats(bam1_t *bam_line, stats_t *stats, khash_t(qn2pair) *read_pairs)
1161 {
1162 if ( !is_in_regions(bam_line,stats) )
1163 return;
1164 if ( stats->rg_hash )
1165 {
1166 const uint8_t *rg = bam_aux_get(bam_line, "RG");
1167 if ( !rg ) return; // certain read groups were requested but this record has none
1168 khint_t k = kh_get(rg, stats->rg_hash, (const char*)(rg + 1));
1169 if ( k == kh_end((kh_rg_t *)stats->rg_hash) ) return;
1170 }
1171 if ( stats->info->flag_require && (bam_line->core.flag & stats->info->flag_require)!=stats->info->flag_require )
1172 {
1173 stats->nreads_filtered++;
1174 return;
1175 }
1176 if ( stats->info->flag_filter && (bam_line->core.flag & stats->info->flag_filter) )
1177 {
1178 stats->nreads_filtered++;
1179 return;
1180 }
1181 if ( stats->info->filter_readlen!=-1 && bam_line->core.l_qseq!=stats->info->filter_readlen )
1182 return;
1183
1184 update_checksum(bam_line, stats);
1185
1186 // Secondary reads don't count for most stats purposes
1187 if ( bam_line->core.flag & BAM_FSECONDARY )
1188 {
1189 stats->nreads_secondary++;
1190 return;
1191 }
1192
1193 if ( bam_line->core.flag & BAM_FSUPPLEMENTARY )
1194 {
1195 stats->nreads_supplementary++;
1196 }
1197
1198 // If line has no sequence cannot continue
1199 int seq_len = bam_line->core.l_qseq;
1200 if ( !seq_len ) return;
1201
1202 if ( IS_DUP(bam_line) )
1203 {
1204 stats->total_len_dup += seq_len;
1205 stats->nreads_dup++;
1206 }
1207
1208 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;
1209
1210 int read_len = unclipped_length(bam_line);
1211 if ( read_len >= stats->nbases )
1212 realloc_buffers(stats,read_len);
1213 // Update max_len observed
1214 if ( stats->max_len<read_len )
1215 stats->max_len = read_len;
1216 if ( order == READ_ORDER_FIRST && stats->max_len_1st < read_len )
1217 stats->max_len_1st = read_len;
1218 if ( order == READ_ORDER_LAST && stats->max_len_2nd < read_len )
1219 stats->max_len_2nd = read_len;
1220 if ( ( bam_line->core.flag & (BAM_FUNMAP|BAM_FSECONDARY|BAM_FSUPPLEMENTARY|BAM_FQCFAIL|BAM_FDUP) ) == 0 )
1221 stats->mapping_qualities[bam_line->core.qual]++;
1222
1223 int i;
1224 int gc_count = 0;
1225
1226 // These stats should only be calculated for the original reads ignoring supplementary artificial reads
1227 // otherwise we'll accidentally double count
1228 if ( IS_ORIGINAL(bam_line) ) {
1229 stats->read_lengths[read_len]++;
1230 if ( order == READ_ORDER_FIRST ) stats->read_lengths_1st[read_len]++;
1231 if ( order == READ_ORDER_LAST ) stats->read_lengths_2nd[read_len]++;
1232 collect_orig_read_stats(bam_line, stats, &gc_count);
1233 }
1234
1235 // Look at the flags and increment appropriate counters (mapped, paired, etc)
1236 if ( IS_UNMAPPED(bam_line) ) return;
1237
1238 count_indels(stats, bam_line);
1239
1240 if ( IS_PAIRED_AND_MAPPED(bam_line) && IS_ORIGINAL(bam_line) )
1241 {
1242 // The insert size is tricky, because for long inserts the libraries are
1243 // prepared differently and the pairs point in other direction. BWA does
1244 // not set the paired flag for them. Similar thing is true also for 454
1245 // reads. Mates mapped to different chromosomes have isize==0.
1246 int32_t isize = bam_line->core.isize;
1247 if ( isize<0 ) isize = -isize;
1248 if ( stats->info->nisize > 0 && isize > stats->info->nisize )
1249 isize = stats->info->nisize;
1250 if ( isize>0 || bam_line->core.tid==bam_line->core.mtid )
1251 {
1252 hts_pos_t pos_fst = bam_line->core.mpos - bam_line->core.pos;
1253 int is_fst = IS_READ1(bam_line) ? 1 : -1;
1254 int is_fwd = IS_REVERSE(bam_line) ? -1 : 1;
1255 int is_mfwd = IS_MATE_REVERSE(bam_line) ? -1 : 1;
1256
1257 if ( is_fwd*is_mfwd>0 )
1258 stats->isize->inc_other(stats->isize->data, isize);
1259 else if ( is_fst*pos_fst>=0 )
1260 {
1261 if ( is_fst*is_fwd>0 )
1262 stats->isize->inc_inward(stats->isize->data, isize);
1263 else
1264 stats->isize->inc_outward(stats->isize->data, isize);
1265 }
1266 else if ( is_fst*pos_fst<0 )
1267 {
1268 if ( is_fst*is_fwd>0 )
1269 stats->isize->inc_outward(stats->isize->data, isize);
1270 else
1271 stats->isize->inc_inward(stats->isize->data, isize);
1272 }
1273 }
1274 }
1275
1276 // Number of mismatches
1277 uint8_t *nm = bam_aux_get(bam_line,"NM");
1278 if (nm)
1279 stats->nmismatches += bam_aux2i(nm);
1280
1281 // Number of mapped bases from cigar
1282 if ( bam_line->core.n_cigar == 0)
1283 error("FIXME: mapped read with no cigar?\n");
1284 int readlen=seq_len;
1285 if ( stats->regions )
1286 {
1287 // Count only on-target bases
1288 hts_pos_t iref = bam_line->core.pos + 1;
1289 for (i=0; i<bam_line->core.n_cigar; i++)
1290 {
1291 int cig = bam_cigar_op(bam_get_cigar(bam_line)[i]);
1292 int ncig = bam_cigar_oplen(bam_get_cigar(bam_line)[i]);
1293 if ( !ncig ) continue; // curiously, this can happen: 0D
1294 if ( cig==BAM_CDEL ) readlen += ncig;
1295 else if ( cig==BAM_CMATCH || cig==BAM_CEQUAL || cig==BAM_CDIFF )
1296 {
1297 if ( iref < stats->reg_from ) ncig -= stats->reg_from-iref;
1298 else if ( iref+ncig-1 > stats->reg_to ) ncig -= iref+ncig-1 - stats->reg_to;
1299 if ( ncig<0 ) ncig = 0;
1300 stats->nbases_mapped_cigar += ncig;
1301 iref += bam_cigar_oplen(bam_get_cigar(bam_line)[i]);
1302 }
1303 else if ( cig==BAM_CINS )
1304 {
1305 iref += ncig;
1306 if ( iref>=stats->reg_from && iref<=stats->reg_to )
1307 stats->nbases_mapped_cigar += ncig;
1308 }
1309 }
1310 }
1311 else
1312 {
1313 // Count the whole read
1314 for (i=0; i<bam_line->core.n_cigar; i++)
1315 {
1316 int cig = bam_cigar_op(bam_get_cigar(bam_line)[i]);
1317 if ( cig==BAM_CMATCH || cig==BAM_CINS || cig==BAM_CEQUAL || cig==BAM_CDIFF )
1318 stats->nbases_mapped_cigar += bam_cigar_oplen(bam_get_cigar(bam_line)[i]);
1319 if ( cig==BAM_CDEL )
1320 readlen += bam_cigar_oplen(bam_get_cigar(bam_line)[i]);
1321 }
1322 }
1323
1324 if ( stats->tid==bam_line->core.tid && bam_line->core.pos<stats->pos )
1325 stats->is_sorted = 0;
1326 stats->pos = bam_line->core.pos;
1327
1328 if ( stats->is_sorted )
1329 {
1330 if ( stats->tid==-1 || stats->tid!=bam_line->core.tid ) {
1331 round_buffer_flush(stats, -1);
1332 }
1333
1334 //cleanup the pair hash table to free memory
1335 stats->last_read_flush++;
1336 if ( stats->pair_count > DEFAULT_PAIR_MAX && stats->last_read_flush > DEFAULT_PAIR_MAX) {
1337 stats->pair_count -= cleanup_overlaps(read_pairs, bam_line->core.pos);
1338 stats->last_read_flush = 0;
1339 }
1340
1341 if ( stats->last_pair_tid != bam_line->core.tid) {
1342 stats->pair_count -= cleanup_overlaps(read_pairs, INT64_MAX-1);
1343 stats->last_pair_tid = bam_line->core.tid;
1344 stats->last_read_flush = 0;
1345 }
1346
1347 // Mismatches per cycle and GC-depth graph. For simplicity, reads overlapping GCD bins
1348 // are not splitted which results in up to seq_len-1 overlaps. The default bin size is
1349 // 20kbp, so the effect is negligible.
1350 if ( stats->info->fai )
1351 {
1352 hts_pos_t inc_ref = 0;
1353 int inc_gcd = 0;
1354 // First pass or new chromosome, or read goes beyond the rseq buffer
1355 if ( stats->rseq_pos==-1 || stats->tid != bam_line->core.tid
1356 || stats->rseq_pos+stats->nrseq_buf < bam_line->core.pos+readlen) {
1357 inc_ref=bam_line->core.pos+readlen;
1358 inc_gcd=1;
1359 }
1360 // Read overlaps the next gcd bin
1361 else if ( stats->gcd_pos+stats->info->gcd_bin_size < bam_line->core.pos+readlen )
1362 {
1363 inc_gcd = 1;
1364 if ( stats->rseq_pos+stats->nrseq_buf < bam_line->core.pos+stats->info->gcd_bin_size ) inc_ref = bam_line->core.pos+stats->info->gcd_bin_size;
1365 }
1366 if ( inc_gcd )
1367 {
1368 stats->igcd++;
1369 if ( stats->igcd >= stats->ngcd )
1370 realloc_gcd_buffer(stats, readlen);
1371 if ( inc_ref )
1372 read_ref_seq(stats, bam_line->core.tid,
1373 bam_line->core.pos, inc_ref);
1374 stats->gcd_pos = bam_line->core.pos;
1375 stats->gcd[ stats->igcd ].gc = fai_gc_content(stats, stats->gcd_pos, stats->info->gcd_bin_size);
1376 }
1377
1378 count_mismatches_per_cycle(stats,bam_line,read_len);
1379 }
1380 // No reference and first pass, new chromosome or sequence going beyond the end of the gcd bin
1381 else if ( stats->gcd_pos==-1 || stats->tid != bam_line->core.tid || bam_line->core.pos - stats->gcd_pos > stats->info->gcd_bin_size )
1382 {
1383 // First pass or a new chromosome
1384 stats->tid = bam_line->core.tid;
1385 stats->gcd_pos = bam_line->core.pos;
1386 stats->igcd++;
1387 if ( stats->igcd >= stats->ngcd )
1388 realloc_gcd_buffer(stats, readlen);
1389 }
1390 stats->gcd[ stats->igcd ].depth++;
1391 // When no reference sequence is given, approximate the GC from the read (much shorter window, but otherwise OK)
1392 if ( !stats->info->fai )
1393 stats->gcd[ stats->igcd ].gc += (float) gc_count / seq_len;
1394
1395 // Coverage distribution graph
1396 round_buffer_flush(stats,bam_line->core.pos);
1397 if ( stats->regions ) {
1398 hts_pos_t p = bam_line->core.pos, pnew, pmin = 0, pmax = 0;
1399 uint32_t j = 0;
1400 i = 0;
1401 while ( j < bam_line->core.n_cigar && i < stats->nchunks ) {
1402 int op = bam_cigar_op(bam_get_cigar(bam_line)[j]);
1403 int oplen = bam_cigar_oplen(bam_get_cigar(bam_line)[j]);
1404 switch(op) {
1405 case BAM_CMATCH:
1406 case BAM_CEQUAL:
1407 case BAM_CDIFF:
1408 pmin = MAX(p, stats->chunks[i].beg-1); // 0 based
1409 pmax = MIN(p+oplen, stats->chunks[i].end); // 1 based
1410 if ( pmax > pmin ) {
1411 if ( stats->info->remove_overlaps )
1412 remove_overlaps(bam_line, read_pairs, stats, pmin, pmax);
1413 else
1414 round_buffer_insert_read(&(stats->cov_rbuf), pmin, pmax);
1415 }
1416 break;
1417 case BAM_CDEL:
1418 break;
1419 }
1420 pnew = p + (bam_cigar_type(op)&2 ? oplen : 0); // consumes reference
1421
1422 if ( pnew >= stats->chunks[i].end ) {
1423 // go to the next chunk
1424 i++;
1425 } else {
1426 // go to the next CIGAR op
1427 j++;
1428 p = pnew;
1429 }
1430 }
1431 } else {
1432 hts_pos_t p = bam_line->core.pos;
1433 uint32_t j;
1434 for (j = 0; j < bam_line->core.n_cigar; j++) {
1435 int op = bam_cigar_op(bam_get_cigar(bam_line)[j]);
1436 int oplen = bam_cigar_oplen(bam_get_cigar(bam_line)[j]);
1437 switch(op) {
1438 case BAM_CMATCH:
1439 case BAM_CEQUAL:
1440 case BAM_CDIFF:
1441 if ( stats->info->remove_overlaps )
1442 remove_overlaps(bam_line, read_pairs, stats, p, p+oplen);
1443 else
1444 round_buffer_insert_read(&(stats->cov_rbuf), p, p+oplen);
1445 break;
1446 case BAM_CDEL:
1447 break;
1448 }
1449 p += bam_cigar_type(op)&2 ? oplen : 0; // consumes reference
1450 }
1451 }
1452 if ( stats->info->remove_overlaps )
1453 remove_overlaps(bam_line, read_pairs, stats, -1LL, -1LL); //remove the line from the hash table
1454 }
1455 }
1456
1457 // Sort by GC and depth
1458 #define GCD_t(x) ((gc_depth_t *)x)
1459 static int gcd_cmp(const void *a, const void *b)
1460 {
1461 if ( GCD_t(a)->gc < GCD_t(b)->gc ) return -1;
1462 if ( GCD_t(a)->gc > GCD_t(b)->gc ) return 1;
1463 if ( GCD_t(a)->depth < GCD_t(b)->depth ) return -1;
1464 if ( GCD_t(a)->depth > GCD_t(b)->depth ) return 1;
1465 return 0;
1466 }
1467 #undef GCD_t
1468
1469 float gcd_percentile(gc_depth_t *gcd, int N, int p)
1470 {
1471 float n,d;
1472 int k;
1473
1474 n = (float)p*(N+1)/100;
1475 k = n;
1476 if ( k<=0 )
1477 return gcd[0].depth;
1478 if ( k>=N )
1479 return gcd[N-1].depth;
1480
1481 d = n - k;
1482 return gcd[k-1].depth + d*(gcd[k].depth - gcd[k-1].depth);
1483 }
1484
1485 void output_stats(FILE *to, stats_t *stats, int sparse)
1486 {
1487 // Calculate average insert size and standard deviation (from the main bulk data only)
1488 int isize, ibulk=0, icov, imapq=0;
1489 uint64_t nisize=0, nisize_inward=0, nisize_outward=0, nisize_other=0, cov_sum=0;
1490 double bulk=0, avg_isize=0, sd_isize=0;
1491 for (isize=0; isize<stats->isize->nitems(stats->isize->data); isize++)
1492 {
1493 // Each pair was counted twice
1494 stats->isize->set_inward(stats->isize->data, isize, stats->isize->inward(stats->isize->data, isize) * 0.5);
1495 stats->isize->set_outward(stats->isize->data, isize, stats->isize->outward(stats->isize->data, isize) * 0.5);
1496 stats->isize->set_other(stats->isize->data, isize, stats->isize->other(stats->isize->data, isize) * 0.5);
1497
1498 nisize_inward += stats->isize->inward(stats->isize->data, isize);
1499 nisize_outward += stats->isize->outward(stats->isize->data, isize);
1500 nisize_other += stats->isize->other(stats->isize->data, isize);
1501 nisize += stats->isize->inward(stats->isize->data, isize) + stats->isize->outward(stats->isize->data, isize) + stats->isize->other(stats->isize->data, isize);
1502 }
1503
1504 for (isize=0; isize<stats->isize->nitems(stats->isize->data); isize++)
1505 {
1506 uint64_t num = stats->isize->inward(stats->isize->data, isize) + stats->isize->outward(stats->isize->data, isize) + stats->isize->other(stats->isize->data, isize);
1507 if (num > 0) ibulk = isize + 1;
1508 bulk += num;
1509 avg_isize += isize * (stats->isize->inward(stats->isize->data, isize) + stats->isize->outward(stats->isize->data, isize) + stats->isize->other(stats->isize->data, isize));
1510
1511 if ( bulk/nisize > stats->info->isize_main_bulk )
1512 {
1513 ibulk = isize+1;
1514 nisize = bulk;
1515 break;
1516 }
1517 }
1518 avg_isize /= nisize ? nisize : 1;
1519 for (isize=1; isize<ibulk; isize++)
1520 sd_isize += (stats->isize->inward(stats->isize->data, isize) + stats->isize->outward(stats->isize->data, isize) +stats->isize->other(stats->isize->data, isize)) * (isize-avg_isize)*(isize-avg_isize) / (nisize ? nisize : 1);
1521 sd_isize = sqrt(sd_isize);
1522
1523 fprintf(to, "# This file was produced by samtools stats (%s+htslib-%s) and can be plotted using plot-bamstats\n", samtools_version(), hts_version());
1524 if( stats->split_name != NULL ){
1525 fprintf(to, "# This file contains statistics only for reads with tag: %s=%s\n", stats->info->split_tag, stats->split_name);
1526 }
1527 else{
1528 fprintf(to, "# This file contains statistics for all reads.\n");
1529 }
1530 fprintf(to, "# The command line was: %s",stats->info->argv[0]);
1531 int i;
1532 for (i=1; i<stats->info->argc; i++)
1533 fprintf(to, " %s", stats->info->argv[i]);
1534 fprintf(to, "\n");
1535 fprintf(to, "# CHK, Checksum\t[2]Read Names\t[3]Sequences\t[4]Qualities\n");
1536 fprintf(to, "# CHK, CRC32 of reads which passed filtering followed by addition (32bit overflow)\n");
1537 fprintf(to, "CHK\t%08x\t%08x\t%08x\n", stats->checksum.names,stats->checksum.reads,stats->checksum.quals);
1538 fprintf(to, "# Summary Numbers. Use `grep ^SN | cut -f 2-` to extract this part.\n");
1539 fprintf(to, "SN\traw total sequences:\t%ld\t# excluding supplementary and secondary reads\n", (long)(stats->nreads_filtered+stats->nreads_1st+stats->nreads_2nd+stats->nreads_other)); // not counting excluded seqs (and none of the below)
1540 fprintf(to, "SN\tfiltered sequences:\t%ld\n", (long)stats->nreads_filtered);
1541 fprintf(to, "SN\tsequences:\t%ld\n", (long)(stats->nreads_1st+stats->nreads_2nd+stats->nreads_other));
1542 fprintf(to, "SN\tis sorted:\t%d\n", stats->is_sorted ? 1 : 0);
1543 fprintf(to, "SN\t1st fragments:\t%ld\n", (long)stats->nreads_1st);
1544 fprintf(to, "SN\tlast fragments:\t%ld\n", (long)stats->nreads_2nd);
1545 fprintf(to, "SN\treads mapped:\t%ld\n", (long)(stats->nreads_paired_and_mapped+stats->nreads_single_mapped));
1546 fprintf(to, "SN\treads mapped and paired:\t%ld\t# paired-end technology bit set + both mates mapped\n", (long)stats->nreads_paired_and_mapped);
1547 fprintf(to, "SN\treads unmapped:\t%ld\n", (long)stats->nreads_unmapped);
1548 fprintf(to, "SN\treads properly paired:\t%ld\t# proper-pair bit set\n", (long)stats->nreads_properly_paired);
1549 fprintf(to, "SN\treads paired:\t%ld\t# paired-end technology bit set\n", (long)stats->nreads_paired_tech);
1550 fprintf(to, "SN\treads duplicated:\t%ld\t# PCR or optical duplicate bit set\n", (long)stats->nreads_dup);
1551 fprintf(to, "SN\treads MQ0:\t%ld\t# mapped and MQ=0\n", (long)stats->nreads_mq0);
1552 fprintf(to, "SN\treads QC failed:\t%ld\n", (long)stats->nreads_QCfailed);
1553 fprintf(to, "SN\tnon-primary alignments:\t%ld\n", (long)stats->nreads_secondary);
1554 fprintf(to, "SN\tsupplementary alignments:\t%ld\n", (long)stats->nreads_supplementary);
1555 fprintf(to, "SN\ttotal length:\t%ld\t# ignores clipping\n", (long)stats->total_len);
1556 fprintf(to, "SN\ttotal first fragment length:\t%ld\t# ignores clipping\n", (long)stats->total_len_1st);
1557 fprintf(to, "SN\ttotal last fragment length:\t%ld\t# ignores clipping\n", (long)stats->total_len_2nd);
1558 fprintf(to, "SN\tbases mapped:\t%ld\t# ignores clipping\n", (long)stats->nbases_mapped); // the length of the whole read goes here, including soft-clips etc.
1559 fprintf(to, "SN\tbases mapped (cigar):\t%ld\t# more accurate\n", (long)stats->nbases_mapped_cigar); // only matched and inserted bases are counted here
1560 fprintf(to, "SN\tbases trimmed:\t%ld\n", (long)stats->nbases_trimmed);
1561 fprintf(to, "SN\tbases duplicated:\t%ld\n", (long)stats->total_len_dup);
1562 fprintf(to, "SN\tmismatches:\t%ld\t# from NM fields\n", (long)stats->nmismatches);
1563 fprintf(to, "SN\terror rate:\t%e\t# mismatches / bases mapped (cigar)\n", stats->nbases_mapped_cigar ? (float)stats->nmismatches/stats->nbases_mapped_cigar : 0);
1564 float avg_read_length = (stats->nreads_1st +
1565 stats->nreads_2nd +
1566 stats->nreads_other)
1567 ? (float)stats->total_len / (stats->nreads_1st +
1568 stats->nreads_2nd +
1569 stats->nreads_other)
1570 : 0;
1571 fprintf(to, "SN\taverage length:\t%.0f\n", avg_read_length);
1572 fprintf(to, "SN\taverage first fragment length:\t%.0f\n", stats->nreads_1st? (float)stats->total_len_1st/stats->nreads_1st:0);
1573 fprintf(to, "SN\taverage last fragment length:\t%.0f\n", stats->nreads_2nd? (float)stats->total_len_2nd/stats->nreads_2nd:0);
1574 fprintf(to, "SN\tmaximum length:\t%d\n", stats->max_len);
1575 fprintf(to, "SN\tmaximum first fragment length:\t%d\n", stats->max_len_1st);
1576 fprintf(to, "SN\tmaximum last fragment length:\t%d\n", stats->max_len_2nd);
1577 fprintf(to, "SN\taverage quality:\t%.1f\n", stats->total_len?stats->sum_qual/stats->total_len:0);
1578 fprintf(to, "SN\tinsert size average:\t%.1f\n", avg_isize);
1579 fprintf(to, "SN\tinsert size standard deviation:\t%.1f\n", sd_isize);
1580 fprintf(to, "SN\tinward oriented pairs:\t%ld\n", (long)nisize_inward);
1581 fprintf(to, "SN\toutward oriented pairs:\t%ld\n", (long)nisize_outward);
1582 fprintf(to, "SN\tpairs with other orientation:\t%ld\n", (long)nisize_other);
1583 fprintf(to, "SN\tpairs on different chromosomes:\t%ld\n", (long)stats->nreads_anomalous/2);
1584 fprintf(to, "SN\tpercentage of properly paired reads (%%):\t%.1f\n", (stats->nreads_1st+stats->nreads_2nd+stats->nreads_other)? (float)(100*stats->nreads_properly_paired)/(stats->nreads_1st+stats->nreads_2nd+stats->nreads_other):0);
1585 if ( stats->target_count ) {
1586 fprintf(to, "SN\tbases inside the target:\t%" PRIu64 "\n", stats->target_count);
1587 for (icov=stats->info->cov_threshold+1; icov<stats->ncov; icov++)
1588 cov_sum += stats->cov[icov];
1589 fprintf(to, "SN\tpercentage of target genome with coverage > %d (%%):\t%.2f\n", stats->info->cov_threshold, (float)(100*cov_sum)/stats->target_count);
1590 }
1591
1592 int ibase,iqual;
1593 if ( stats->max_len<stats->nbases ) stats->max_len++;
1594 if ( stats->max_qual+1<stats->nquals ) stats->max_qual++;
1595 fprintf(to, "# First Fragment Qualities. Use `grep ^FFQ | cut -f 2-` to extract this part.\n");
1596 fprintf(to, "# Columns correspond to qualities and rows to cycles. First column is the cycle number.\n");
1597 for (ibase=0; ibase<stats->max_len_1st; ibase++)
1598 {
1599 fprintf(to, "FFQ\t%d",ibase+1);
1600 for (iqual=0; iqual<=stats->max_qual; iqual++)
1601 {
1602 fprintf(to, "\t%ld", (long)stats->quals_1st[ibase*stats->nquals+iqual]);
1603 }
1604 fprintf(to, "\n");
1605 }
1606 fprintf(to, "# Last Fragment Qualities. Use `grep ^LFQ | cut -f 2-` to extract this part.\n");
1607 fprintf(to, "# Columns correspond to qualities and rows to cycles. First column is the cycle number.\n");
1608 for (ibase=0; ibase<stats->max_len_2nd; ibase++)
1609 {
1610 fprintf(to, "LFQ\t%d",ibase+1);
1611 for (iqual=0; iqual<=stats->max_qual; iqual++)
1612 {
1613 fprintf(to, "\t%ld", (long)stats->quals_2nd[ibase*stats->nquals+iqual]);
1614 }
1615 fprintf(to, "\n");
1616 }
1617 if ( stats->mpc_buf )
1618 {
1619 fprintf(to, "# Mismatches per cycle and quality. Use `grep ^MPC | cut -f 2-` to extract this part.\n");
1620 fprintf(to, "# Columns correspond to qualities, rows to cycles. First column is the cycle number, second\n");
1621 fprintf(to, "# is the number of N's and the rest is the number of mismatches\n");
1622 for (ibase=0; ibase<stats->max_len; ibase++)
1623 {
1624 fprintf(to, "MPC\t%d",ibase+1);
1625 for (iqual=0; iqual<=stats->max_qual; iqual++)
1626 {
1627 fprintf(to, "\t%ld", (long)stats->mpc_buf[ibase*stats->nquals+iqual]);
1628 }
1629 fprintf(to, "\n");
1630 }
1631 }
1632 fprintf(to, "# GC Content of first fragments. Use `grep ^GCF | cut -f 2-` to extract this part.\n");
1633 int ibase_prev = 0;
1634 for (ibase=0; ibase<stats->ngc; ibase++)
1635 {
1636 if ( stats->gc_1st[ibase]==stats->gc_1st[ibase_prev] ) continue;
1637 fprintf(to, "GCF\t%.2f\t%ld\n", (ibase+ibase_prev)*0.5*100./(stats->ngc-1), (long)stats->gc_1st[ibase_prev]);
1638 ibase_prev = ibase;
1639 }
1640 fprintf(to, "# GC Content of last fragments. Use `grep ^GCL | cut -f 2-` to extract this part.\n");
1641 ibase_prev = 0;
1642 for (ibase=0; ibase<stats->ngc; ibase++)
1643 {
1644 if ( stats->gc_2nd[ibase]==stats->gc_2nd[ibase_prev] ) continue;
1645 fprintf(to, "GCL\t%.2f\t%ld\n", (ibase+ibase_prev)*0.5*100./(stats->ngc-1), (long)stats->gc_2nd[ibase_prev]);
1646 ibase_prev = ibase;
1647 }
1648 fprintf(to, "# ACGT content per cycle. Use `grep ^GCC | cut -f 2-` to extract this part. The columns are: cycle; A,C,G,T base counts as a percentage of all A/C/G/T bases [%%]; and N and O counts as a percentage of all A/C/G/T bases [%%]\n");
1649 for (ibase=0; ibase<stats->max_len; ibase++)
1650 {
1651 acgtno_count_t *acgtno_count_1st = &(stats->acgtno_cycles_1st[ibase]);
1652 acgtno_count_t *acgtno_count_2nd = &(stats->acgtno_cycles_2nd[ibase]);
1653 uint64_t acgt_sum = acgtno_count_1st->a + acgtno_count_1st->c + acgtno_count_1st->g + acgtno_count_1st->t +
1654 acgtno_count_2nd->a + acgtno_count_2nd->c + acgtno_count_2nd->g + acgtno_count_2nd->t;
1655 if ( ! acgt_sum ) continue;
1656 fprintf(to, "GCC\t%d\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\n", ibase+1,
1657 100.*(acgtno_count_1st->a + acgtno_count_2nd->a)/acgt_sum,
1658 100.*(acgtno_count_1st->c + acgtno_count_2nd->c)/acgt_sum,
1659 100.*(acgtno_count_1st->g + acgtno_count_2nd->g)/acgt_sum,
1660 100.*(acgtno_count_1st->t + acgtno_count_2nd->t)/acgt_sum,
1661 100.*(acgtno_count_1st->n + acgtno_count_2nd->n)/acgt_sum,
1662 100.*(acgtno_count_1st->other + acgtno_count_2nd->other)/acgt_sum);
1663 }
1664 fprintf(to, "# ACGT content per cycle, read oriented. Use `grep ^GCT | cut -f 2-` to extract this part. The columns are: cycle; A,C,G,T base counts as a percentage of all A/C/G/T bases [%%]\n");
1665 for (ibase=0; ibase<stats->max_len; ibase++)
1666 {
1667 acgtno_count_t *acgtno_count = &(stats->acgtno_revcomp[ibase]);
1668 uint64_t acgt_sum = acgtno_count->a + acgtno_count->c + acgtno_count->g + acgtno_count->t;
1669 if ( ! acgt_sum ) continue;
1670 fprintf(to, "GCT\t%d\t%.2f\t%.2f\t%.2f\t%.2f\n", ibase+1,
1671 100.*(acgtno_count->a)/acgt_sum,
1672 100.*(acgtno_count->c)/acgt_sum,
1673 100.*(acgtno_count->g)/acgt_sum,
1674 100.*(acgtno_count->t)/acgt_sum);
1675 }
1676
1677 uint64_t tA=0, tC=0, tG=0, tT=0, tN=0;
1678 fprintf(to, "# ACGT content per cycle for first fragments. Use `grep ^FBC | cut -f 2-` to extract this part. The columns are: cycle; A,C,G,T base counts as a percentage of all A/C/G/T bases [%%]; and N and O counts as a percentage of all A/C/G/T bases [%%]\n");
1679 for (ibase=0; ibase<stats->max_len; ibase++)
1680 {
1681 acgtno_count_t *acgtno_count_1st = &(stats->acgtno_cycles_1st[ibase]);
1682 uint64_t acgt_sum_1st = acgtno_count_1st->a + acgtno_count_1st->c + acgtno_count_1st->g + acgtno_count_1st->t;
1683 tA += acgtno_count_1st->a;
1684 tC += acgtno_count_1st->c;
1685 tG += acgtno_count_1st->g;
1686 tT += acgtno_count_1st->t;
1687 tN += acgtno_count_1st->n;
1688
1689 if ( acgt_sum_1st )
1690 fprintf(to, "FBC\t%d\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\n", ibase+1,
1691 100.*acgtno_count_1st->a/acgt_sum_1st,
1692 100.*acgtno_count_1st->c/acgt_sum_1st,
1693 100.*acgtno_count_1st->g/acgt_sum_1st,
1694 100.*acgtno_count_1st->t/acgt_sum_1st,
1695 100.*acgtno_count_1st->n/acgt_sum_1st,
1696 100.*acgtno_count_1st->other/acgt_sum_1st);
1697
1698 }
1699 fprintf(to, "# ACGT raw counters for first fragments. Use `grep ^FTC | cut -f 2-` to extract this part. The columns are: A,C,G,T,N base counters\n");
1700 fprintf(to, "FTC\t%" PRId64 "\t%" PRId64 "\t%" PRId64 "\t%" PRId64 "\t%" PRId64 "\n", tA, tC, tG, tT, tN);
1701 tA=0, tC=0, tG=0, tT=0, tN=0;
1702 fprintf(to, "# ACGT content per cycle for last fragments. Use `grep ^LBC | cut -f 2-` to extract this part. The columns are: cycle; A,C,G,T base counts as a percentage of all A/C/G/T bases [%%]; and N and O counts as a percentage of all A/C/G/T bases [%%]\n");
1703 for (ibase=0; ibase<stats->max_len; ibase++)
1704 {
1705 acgtno_count_t *acgtno_count_2nd = &(stats->acgtno_cycles_2nd[ibase]);
1706 uint64_t acgt_sum_2nd = acgtno_count_2nd->a + acgtno_count_2nd->c + acgtno_count_2nd->g + acgtno_count_2nd->t;
1707 tA += acgtno_count_2nd->a;
1708 tC += acgtno_count_2nd->c;
1709 tG += acgtno_count_2nd->g;
1710 tT += acgtno_count_2nd->t;
1711 tN += acgtno_count_2nd->n;
1712
1713 if ( acgt_sum_2nd )
1714 fprintf(to, "LBC\t%d\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\n", ibase+1,
1715 100.*acgtno_count_2nd->a/acgt_sum_2nd,
1716 100.*acgtno_count_2nd->c/acgt_sum_2nd,
1717 100.*acgtno_count_2nd->g/acgt_sum_2nd,
1718 100.*acgtno_count_2nd->t/acgt_sum_2nd,
1719 100.*acgtno_count_2nd->n/acgt_sum_2nd,
1720 100.*acgtno_count_2nd->other/acgt_sum_2nd);
1721
1722 }
1723 fprintf(to, "# ACGT raw counters for last fragments. Use `grep ^LTC | cut -f 2-` to extract this part. The columns are: A,C,G,T,N base counters\n");
1724 fprintf(to, "LTC\t%" PRId64 "\t%" PRId64 "\t%" PRId64 "\t%" PRId64 "\t%" PRId64 "\n", tA, tC, tG, tT, tN);
1725
1726 int tag;
1727 for (tag=0; tag<stats->ntags; tag++) {
1728 if (stats->tags_barcode[tag].nbases) {
1729 fprintf(to, "# ACGT content per cycle for barcodes. Use `grep ^%sC | cut -f 2-` to extract this part. The columns are: cycle; A,C,G,T base counts as a percentage of all A/C/G/T bases [%%]; and N counts as a percentage of all A/C/G/T bases [%%]\n",
1730 stats->tags_barcode[tag].tag_name);
1731 for (ibase=0; ibase<stats->tags_barcode[tag].nbases; ibase++)
1732 {
1733 if (ibase == stats->tags_barcode[tag].tag_sep)
1734 continue;
1735
1736 acgtno_count_t *acgtno_count = stats->acgtno_barcode + stats->tags_barcode[tag].offset + ibase;
1737 uint64_t acgt_sum = acgtno_count->a + acgtno_count->c + acgtno_count->g + acgtno_count->t;
1738
1739 if ( acgt_sum )
1740 fprintf(to, "%sC%d\t%d\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\n", stats->tags_barcode[tag].tag_name,
1741 stats->tags_barcode[tag].tag_sep < 0 || ibase < stats->tags_barcode[tag].tag_sep ? 1 : 2,
1742 stats->tags_barcode[tag].tag_sep < 0 || ibase < stats->tags_barcode[tag].tag_sep ? ibase+1 : ibase-stats->tags_barcode[tag].tag_sep,
1743 100.*acgtno_count->a/acgt_sum,
1744 100.*acgtno_count->c/acgt_sum,
1745 100.*acgtno_count->g/acgt_sum,
1746 100.*acgtno_count->t/acgt_sum,
1747 100.*acgtno_count->n/acgt_sum);
1748 }
1749
1750 fprintf(to, "# Barcode Qualities. Use `grep ^%sQ | cut -f 2-` to extract this part.\n", stats->tags_barcode[tag].qual_name);
1751 fprintf(to, "# Columns correspond to qualities and rows to barcode cycles. First column is the cycle number.\n");
1752 for (ibase=0; ibase<stats->tags_barcode[tag].nbases; ibase++)
1753 {
1754 if (ibase == stats->tags_barcode[tag].tag_sep)
1755 continue;
1756
1757 fprintf(to, "%sQ%d\t%d", stats->tags_barcode[tag].qual_name,
1758 stats->tags_barcode[tag].tag_sep < 0 || ibase < stats->tags_barcode[tag].tag_sep ? 1 : 2,
1759 stats->tags_barcode[tag].tag_sep < 0 || ibase < stats->tags_barcode[tag].tag_sep ? ibase+1 : ibase-stats->tags_barcode[tag].tag_sep);
1760 for (iqual=0; iqual<=stats->tags_barcode[tag].max_qual; iqual++)
1761 {
1762 fprintf(to, "\t%ld", (long)stats->quals_barcode[(stats->tags_barcode[tag].offset + ibase)*stats->nquals+iqual]);
1763 }
1764 fprintf(to, "\n");
1765 }
1766 }
1767 }
1768
1769 fprintf(to, "# Insert sizes. Use `grep ^IS | cut -f 2-` to extract this part. The columns are: insert size, pairs total, inward oriented pairs, outward oriented pairs, other pairs\n");
1770 for (isize=0; isize<ibulk; isize++) {
1771 long in = (long)(stats->isize->inward(stats->isize->data, isize));
1772 long out = (long)(stats->isize->outward(stats->isize->data, isize));
1773 long other = (long)(stats->isize->other(stats->isize->data, isize));
1774 if (!sparse || in + out + other > 0) {
1775 fprintf(to, "IS\t%d\t%ld\t%ld\t%ld\t%ld\n", isize, in+out+other,
1776 in , out, other);
1777 }
1778 }
1779
1780 fprintf(to, "# Read lengths. Use `grep ^RL | cut -f 2-` to extract this part. The columns are: read length, count\n");
1781 int ilen;
1782 for (ilen=0; ilen<stats->max_len; ilen++)
1783 {
1784 if ( stats->read_lengths[ilen+1]>0 )
1785 fprintf(to, "RL\t%d\t%ld\n", ilen+1, (long)stats->read_lengths[ilen+1]);
1786 }
1787
1788 fprintf(to, "# Read lengths - first fragments. Use `grep ^FRL | cut -f 2-` to extract this part. The columns are: read length, count\n");
1789 for (ilen=0; ilen<stats->max_len_1st; ilen++)
1790 {
1791 if ( stats->read_lengths_1st[ilen+1]>0 )
1792 fprintf(to, "FRL\t%d\t%ld\n", ilen+1, (long)stats->read_lengths_1st[ilen+1]);
1793 }
1794
1795 fprintf(to, "# Read lengths - last fragments. Use `grep ^LRL | cut -f 2-` to extract this part. The columns are: read length, count\n");
1796 for (ilen=0; ilen<stats->max_len_2nd; ilen++)
1797 {
1798 if ( stats->read_lengths_2nd[ilen+1]>0 )
1799 fprintf(to, "LRL\t%d\t%ld\n", ilen+1, (long)stats->read_lengths_2nd[ilen+1]);
1800 }
1801
1802 fprintf(to, "# Mapping qualities for reads !(UNMAP|SECOND|SUPPL|QCFAIL|DUP). Use `grep ^MAPQ | cut -f 2-` to extract this part. The columns are: mapq, count\n");
1803 for (imapq=0; imapq < 256; imapq++)
1804 {
1805 if ( stats->mapping_qualities[imapq]>0 )
1806 fprintf(to, "MAPQ\t%d\t%ld\n", imapq, (long)stats->mapping_qualities[imapq]);
1807 }
1808
1809 fprintf(to, "# Indel distribution. Use `grep ^ID | cut -f 2-` to extract this part. The columns are: length, number of insertions, number of deletions\n");
1810
1811 for (ilen=0; ilen<stats->nindels; ilen++)
1812 {
1813 if ( stats->insertions[ilen]>0 || stats->deletions[ilen]>0 )
1814 fprintf(to, "ID\t%d\t%ld\t%ld\n", ilen+1, (long)stats->insertions[ilen], (long)stats->deletions[ilen]);
1815 }
1816
1817 fprintf(to, "# Indels per cycle. Use `grep ^IC | cut -f 2-` to extract this part. The columns are: cycle, number of insertions (fwd), .. (rev) , number of deletions (fwd), .. (rev)\n");
1818 for (ilen=0; ilen<=stats->nbases; ilen++)
1819 {
1820 // For deletions we print the index of the cycle before the deleted base (1-based) and for insertions
1821 // the index of the cycle of the first inserted base (also 1-based)
1822 if ( stats->ins_cycles_1st[ilen]>0 || stats->ins_cycles_2nd[ilen]>0 || stats->del_cycles_1st[ilen]>0 || stats->del_cycles_2nd[ilen]>0 )
1823 fprintf(to, "IC\t%d\t%ld\t%ld\t%ld\t%ld\n", ilen+1, (long)stats->ins_cycles_1st[ilen], (long)stats->ins_cycles_2nd[ilen], (long)stats->del_cycles_1st[ilen], (long)stats->del_cycles_2nd[ilen]);
1824 }
1825
1826 fprintf(to, "# Coverage distribution. Use `grep ^COV | cut -f 2-` to extract this part.\n");
1827 if ( stats->cov[0] )
1828 fprintf(to, "COV\t[<%d]\t%d\t%ld\n",stats->info->cov_min,stats->info->cov_min-1, (long)stats->cov[0]);
1829 for (icov=1; icov<stats->ncov-1; icov++)
1830 if ( stats->cov[icov] )
1831 fprintf(to, "COV\t[%d-%d]\t%d\t%ld\n",stats->info->cov_min + (icov-1)*stats->info->cov_step, stats->info->cov_min + icov*stats->info->cov_step-1,stats->info->cov_min + icov*stats->info->cov_step-1, (long)stats->cov[icov]);
1832 if ( stats->cov[stats->ncov-1] )
1833 fprintf(to, "COV\t[%d<]\t%d\t%ld\n",stats->info->cov_min + (stats->ncov-2)*stats->info->cov_step-1,stats->info->cov_min + (stats->ncov-2)*stats->info->cov_step-1, (long)stats->cov[stats->ncov-1]);
1834
1835 // Calculate average GC content, then sort by GC and depth
1836 fprintf(to, "# GC-depth. Use `grep ^GCD | cut -f 2-` to extract this part. The columns are: GC%%, unique sequence percentiles, 10th, 25th, 50th, 75th and 90th depth percentile\n");
1837 uint32_t igcd;
1838 for (igcd=0; igcd<stats->igcd; igcd++)
1839 {
1840 if ( stats->info->fai )
1841 stats->gcd[igcd].gc = rint(100. * stats->gcd[igcd].gc);
1842 else
1843 if ( stats->gcd[igcd].depth )
1844 stats->gcd[igcd].gc = rint(100. * stats->gcd[igcd].gc / stats->gcd[igcd].depth);
1845 }
1846 if ( stats->ngcd )
1847 qsort(stats->gcd, stats->igcd+1, sizeof(gc_depth_t), gcd_cmp);
1848 igcd = 0;
1849 while ( igcd < stats->igcd )
1850 {
1851 // Calculate percentiles (10,25,50,75,90th) for the current GC content and print
1852 uint32_t nbins=0, itmp=igcd;
1853 float gc = stats->gcd[igcd].gc;
1854 while ( itmp<stats->igcd && fabs(stats->gcd[itmp].gc-gc)<0.1 )
1855 {
1856 nbins++;
1857 itmp++;
1858 }
1859 fprintf(to, "GCD\t%.1f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\n", gc, (igcd+nbins+1)*100./(stats->igcd+1),
1860 gcd_percentile(&(stats->gcd[igcd]),nbins,10) *avg_read_length/stats->info->gcd_bin_size,
1861 gcd_percentile(&(stats->gcd[igcd]),nbins,25) *avg_read_length/stats->info->gcd_bin_size,
1862 gcd_percentile(&(stats->gcd[igcd]),nbins,50) *avg_read_length/stats->info->gcd_bin_size,
1863 gcd_percentile(&(stats->gcd[igcd]),nbins,75) *avg_read_length/stats->info->gcd_bin_size,
1864 gcd_percentile(&(stats->gcd[igcd]),nbins,90) *avg_read_length/stats->info->gcd_bin_size
1865 );
1866 igcd += nbins;
1867 }
1868 }
1869
1870 static void init_regions(stats_t *stats, const char *file, stats_info_t* info)
1871 {
1872 FILE *fp = fopen(file,"r");
1873 if ( !fp ) error("%s: %s\n",file,strerror(errno));
1874
1875 kstring_t line = { 0, 0, NULL };
1876 int warned = 0, r, p, new_p;
1877 int prev_tid=-1;
1878 hts_pos_t prev_pos=-1LL;
1879 while (line.l = 0, kgetline(&line, (kgets_func *)fgets, fp) >= 0)
1880 {
1881 if ( line.s[0] == '#' ) continue;
1882
1883 int i = 0;
1884 while ( i<line.l && !isspace(line.s[i]) ) i++;
1885 if ( i>=line.l ) error("Could not parse the file: %s [%s]\n", file, line.s);
1886 line.s[i] = '\0';
1887
1888 int tid = bam_name2id(stats->info->sam_header, line.s);
1889 if ( tid < 0 )
1890 {
1891 if ( !warned )
1892 fprintf(samtools_stderr,"Warning: Some sequences not present in the BAM, e.g. \"%s\". This message is printed only once.\n", line.s);
1893 warned = 1;
1894 continue;
1895 }
1896
1897 if ( tid >= stats->nregions )
1898 {
1899 if(!(stats->regions = realloc(stats->regions,sizeof(regions_t)*(tid+REG_INC))))
1900 error("Could not allocate memory for region.\n");
1901
1902 int j;
1903 for (j=stats->nregions; j<tid+REG_INC; j++)
1904 {
1905 stats->regions[j].npos = stats->regions[j].mpos = stats->regions[j].cpos = 0;
1906 stats->regions[j].pos = NULL;
1907 }
1908 stats->nregions = tid+REG_INC;
1909 }
1910 int npos = stats->regions[tid].npos;
1911 if ( npos >= stats->regions[tid].mpos )
1912 {
1913 stats->regions[tid].mpos = npos+POS_INC;
1914 if (!(stats->regions[tid].pos = realloc(stats->regions[tid].pos, sizeof(hts_pair_pos_t)*stats->regions[tid].mpos)))
1915 error("Could not allocate memory for interval.\n");
1916 }
1917
1918 if ( (sscanf(&line.s[i+1],"%"SCNd64" %"SCNd64, &stats->regions[tid].pos[npos].beg, &stats->regions[tid].pos[npos].end))!=2 ) error("Could not parse the region [%s]\n", &line.s[i+1]);
1919 if ( prev_tid==-1 || prev_tid!=tid )
1920 {
1921 prev_tid = tid;
1922 prev_pos = stats->regions[tid].pos[npos].beg;
1923 }
1924 if ( prev_pos>stats->regions[tid].pos[npos].beg )
1925 error("The positions are not in chromosomal order (%s:%"PRIhts_pos" comes after %"PRIhts_pos")\n", line.s, stats->regions[tid].pos[npos].beg, prev_pos);
1926 stats->regions[tid].npos++;
1927 if ( stats->regions[tid].npos > stats->nchunks )
1928 stats->nchunks = stats->regions[tid].npos;
1929 }
1930 free(line.s);
1931 if ( !stats->regions ) error("Unable to map the -t sequences to the BAM sequences.\n");
1932 fclose(fp);
1933
1934 // sort region intervals and remove duplicates
1935 for (r = 0; r < stats->nregions; r++) {
1936 regions_t *reg = &stats->regions[r];
1937 if ( reg->npos > 1 ) {
1938 qsort(reg->pos, reg->npos, sizeof(hts_pair_pos_t), regions_lt);
1939 for (new_p = 0, p = 1; p < reg->npos; p++) {
1940 if ( reg->pos[new_p].end < reg->pos[p].beg )
1941 reg->pos[++new_p] = reg->pos[p];
1942 else if ( reg->pos[new_p].end < reg->pos[p].end )
1943 reg->pos[new_p].end = reg->pos[p].end;
1944 }
1945 reg->npos = ++new_p;
1946 }
1947 for (p = 0; p < reg->npos; p++) {
1948 if (reg->pos[p].end < HTS_POS_MAX) {
1949 stats->target_count += (reg->pos[p].end - reg->pos[p].beg + 1);
1950 } else {
1951 uint64_t hdr_end = sam_hdr_tid2len(info->sam_header, r);
1952 if (hdr_end)
1953 stats->target_count += (hdr_end - reg->pos[p].beg + 1);
1954 }
1955 }
1956 }
1957
1958 if (!(stats->chunks = calloc(stats->nchunks, sizeof(hts_pair_pos_t))))
1959 error("Could not allocate memory for chunk.\n");
1960 }
1961
1962 void destroy_regions(stats_t *stats)
1963 {
1964 int i;
1965 for (i=0; i<stats->nregions; i++)
1966 {
1967 if ( !stats->regions[i].mpos ) continue;
1968 free(stats->regions[i].pos);
1969 }
1970 if ( stats->regions ) free(stats->regions);
1971 if ( stats->chunks ) free(stats->chunks);
1972 }
1973
1974 void reset_regions(stats_t *stats)
1975 {
1976 int i;
1977 for (i=0; i<stats->nregions; i++)
1978 stats->regions[i].cpos = 0;
1979 }
1980
1981 int is_in_regions(bam1_t *bam_line, stats_t *stats)
1982 {
1983 if ( !stats->regions ) return 1;
1984
1985 if ( bam_line->core.tid >= stats->nregions || bam_line->core.tid<0 ) return 0;
1986 if ( !stats->is_sorted ) error("The BAM must be sorted in order for -t to work.\n");
1987
1988 regions_t *reg = &stats->regions[bam_line->core.tid];
1989 if ( reg->cpos==reg->npos ) return 0; // done for this chr
1990
1991 // Find a matching interval or skip this read. No splicing of reads is done, no indels or soft clips considered,
1992 // even small overlap is enough to include the read in the stats.
1993 int i = reg->cpos;
1994 while ( i<reg->npos && reg->pos[i].end<=bam_line->core.pos ) i++;
1995 if ( i>=reg->npos ) { reg->cpos = reg->npos; return 0; }
1996 int64_t endpos = bam_endpos(bam_line);
1997 if ( endpos < reg->pos[i].beg ) return 0;
1998
1999 //found a read overlapping a region
2000 reg->cpos = i;
2001 stats->reg_from = reg->pos[i].beg;
2002 stats->reg_to = reg->pos[i].end;
2003
2004 //now find all the overlapping chunks
2005 stats->nchunks = 0;
2006 while (i < reg->npos) {
2007 if (bam_line->core.pos < reg->pos[i].end && endpos >= reg->pos[i].beg) {
2008 stats->chunks[stats->nchunks].beg = MAX(bam_line->core.pos+1, reg->pos[i].beg);
2009 stats->chunks[stats->nchunks].end = MIN(endpos, reg->pos[i].end);
2010 stats->nchunks++;
2011 }
2012 i++;
2013 }
2014
2015 return 1;
2016 }
2017
2018 int replicate_regions(stats_t *stats, hts_itr_multi_t *iter, stats_info_t *info) {
2019 if ( !stats || !iter)
2020 return 1;
2021
2022 int i, j, tid;
2023 stats->nregions = iter->n_reg;
2024 stats->regions = calloc(stats->nregions, sizeof(regions_t));
2025 stats->chunks = calloc(stats->nchunks, sizeof(hts_pair_pos_t));
2026 if ( !stats->regions || !stats->chunks )
2027 return 1;
2028
2029 for (i = 0; i < iter->n_reg; i++) {
2030 tid = iter->reg_list[i].tid;
2031 if ( tid < 0 )
2032 continue;
2033
2034 if ( tid >= stats->nregions ) {
2035 regions_t *tmp = realloc(stats->regions, (tid+10) * sizeof(regions_t));
2036 if ( !tmp )
2037 return 1;
2038 stats->regions = tmp;
2039 memset(stats->regions + stats->nregions, 0,
2040 (tid+10-stats->nregions) * sizeof(regions_t));
2041 stats->nregions = tid+10;
2042 }
2043
2044 stats->regions[tid].mpos = stats->regions[tid].npos = iter->reg_list[i].count;
2045 stats->regions[tid].pos = calloc(stats->regions[tid].mpos, sizeof(hts_pair_pos_t));
2046 if ( !stats->regions[tid].pos )
2047 return 1;
2048
2049 for (j = 0; j < stats->regions[tid].npos; j++) {
2050 stats->regions[tid].pos[j].beg = iter->reg_list[i].intervals[j].beg+1;
2051 stats->regions[tid].pos[j].end = iter->reg_list[i].intervals[j].end;
2052 if (stats->regions[tid].pos[j].end < HTS_POS_MAX) {
2053 stats->target_count += (stats->regions[tid].pos[j].end - stats->regions[tid].pos[j].beg + 1);
2054 } else {
2055 uint64_t hdr_end = sam_hdr_tid2len(info->sam_header, tid);
2056 if (hdr_end)
2057 stats->target_count += (hdr_end - stats->regions[tid].pos[j].beg + 1);
2058 }
2059 }
2060 }
2061
2062 return 0;
2063 }
2064
2065 static void init_group_id(stats_t *stats, stats_info_t *info, const char *id)
2066 {
2067 stats->rg_hash = kh_init(rg);
2068 if (!stats->rg_hash) error("Could not initialise RG set\n");
2069 sam_hdr_t *hdr = info->sam_header;
2070 const char *key;
2071 kstring_t sm = KS_INITIALIZE;
2072 int i, ret, nrg = sam_hdr_count_lines(hdr, "RG");
2073 if (nrg < 0) error("Could not parse header\n");
2074
2075 for (i=0; i<nrg; i++) {
2076 key = sam_hdr_line_name(hdr, "RG", i);
2077 if (!strcmp(key, id)) {
2078 kh_put(rg, stats->rg_hash, key, &ret);
2079 if (ret == -1) { ks_free(&sm); error("Could not add key \"%s\" to RG set\n", key); }
2080 } else { /* Check for SM name, as per manual */
2081 if (!sam_hdr_find_tag_pos(hdr, "RG", i, "SM", &sm)) {
2082 if (!strcmp(ks_c_str(&sm), id)) {
2083 kh_put(rg, stats->rg_hash, key, &ret);
2084 if (ret == -1) { ks_free(&sm); error("Could not add key \"%s\" to RG set\n", key); }
2085 }
2086 }
2087 }
2088 }
2089
2090 ks_free(&sm);
2091 }
2092
2093
2094 static void HTS_FORMAT(HTS_PRINTF_FMT, 1, 2) HTS_NORETURN
2095 error(const char *format, ...)
2096 {
2097 if ( !format )
2098 {
2099 fprintf(samtools_stdout, "About: The program collects statistics from BAM files. The output can be visualized using plot-bamstats.\n");
2100 fprintf(samtools_stdout, "Usage: samtools stats [OPTIONS] file.bam\n");
2101 fprintf(samtools_stdout, " samtools stats [OPTIONS] file.bam chr:from-to\n");
2102 fprintf(samtools_stdout, "Options:\n");
2103 fprintf(samtools_stdout, " -c, --coverage <int>,<int>,<int> Coverage distribution min,max,step [1,1000,1]\n");
2104 fprintf(samtools_stdout, " -d, --remove-dups Exclude from statistics reads marked as duplicates\n");
2105 fprintf(samtools_stdout, " -X, --customized-index-file Use a customized index file\n");
2106 fprintf(samtools_stdout, " -f, --required-flag <str|int> Required flag, 0 for unset. See also `samtools flags` [0]\n");
2107 fprintf(samtools_stdout, " -F, --filtering-flag <str|int> Filtering flag, 0 for unset. See also `samtools flags` [0]\n");
2108 fprintf(samtools_stdout, " --GC-depth <float> the size of GC-depth bins (decreasing bin size increases memory requirement) [2e4]\n");
2109 fprintf(samtools_stdout, " -h, --help This help message\n");
2110 fprintf(samtools_stdout, " -i, --insert-size <int> Maximum insert size [8000]\n");
2111 fprintf(samtools_stdout, " -I, --id <string> Include only listed read group or sample name\n");
2112 fprintf(samtools_stdout, " -l, --read-length <int> Include in the statistics only reads with the given read length [-1]\n");
2113 fprintf(samtools_stdout, " -m, --most-inserts <float> Report only the main part of inserts [0.99]\n");
2114 fprintf(samtools_stdout, " -P, --split-prefix <str> Path or string prefix for filepaths output by -S (default is input filename)\n");
2115 fprintf(samtools_stdout, " -q, --trim-quality <int> The BWA trimming parameter [0]\n");
2116 fprintf(samtools_stdout, " -r, --ref-seq <file> Reference sequence (required for GC-depth and mismatches-per-cycle calculation).\n");
2117 fprintf(samtools_stdout, " -s, --sam Ignored (input format is auto-detected).\n");
2118 fprintf(samtools_stdout, " -S, --split <tag> Also write statistics to separate files split by tagged field.\n");
2119 fprintf(samtools_stdout, " -t, --target-regions <file> Do stats in these regions only. Tab-delimited file chr,from,to, 1-based, inclusive.\n");
2120 fprintf(samtools_stdout, " -x, --sparse Suppress outputting IS rows where there are no insertions.\n");
2121 fprintf(samtools_stdout, " -p, --remove-overlaps Remove overlaps of paired-end reads from coverage and base count computations.\n");
2122 fprintf(samtools_stdout, " -g, --cov-threshold <int> Only bases with coverage above this value will be included in the target percentage computation [0]\n");
2123 sam_global_opt_help(samtools_stdout, "-.--.@-.");
2124 fprintf(samtools_stdout, "\n");
2125 }
2126 else
2127 {
2128 va_list ap;
2129 va_start(ap, format);
2130 vfprintf(samtools_stderr, format, ap);
2131 va_end(ap);
2132 }
2133 samtools_exit(1);
2134 }
2135
2136 void cleanup_stats_info(stats_info_t* info){
2137 if (info->fai) fai_destroy(info->fai);
2138 if (info->sam) sam_close(info->sam);
2139 free(info);
2140 }
2141
2142 void cleanup_stats(stats_t* stats)
2143 {
2144 free(stats->cov_rbuf.buffer); free(stats->cov);
2145 free(stats->quals_1st); free(stats->quals_2nd);
2146 free(stats->gc_1st); free(stats->gc_2nd);
2147 stats->isize->isize_free(stats->isize->data);
2148 free(stats->isize);
2149 free(stats->gcd);
2150 free(stats->rseq_buf);
2151 free(stats->mpc_buf);
2152 free(stats->acgtno_cycles_1st);
2153 free(stats->acgtno_cycles_2nd);
2154 free(stats->acgtno_revcomp);
2155 free(stats->read_lengths);
2156 free(stats->read_lengths_1st);
2157 free(stats->read_lengths_2nd);
2158 free(stats->insertions);
2159 free(stats->deletions);
2160 free(stats->ins_cycles_1st);
2161 free(stats->ins_cycles_2nd);
2162 free(stats->del_cycles_1st);
2163 free(stats->del_cycles_2nd);
2164 if (stats->acgtno_barcode) free(stats->acgtno_barcode);
2165 if (stats->quals_barcode) free(stats->quals_barcode);
2166 free(stats->tags_barcode);
2167 destroy_regions(stats);
2168 if ( stats->rg_hash ) kh_destroy(rg, stats->rg_hash);
2169 free(stats->split_name);
2170 free(stats->mapping_qualities);
2171 free(stats);
2172 }
2173
2174 void output_split_stats(khash_t(c2stats) *split_hash, char* bam_fname, int sparse)
2175 {
2176 int i = 0;
2177 kstring_t output_filename = { 0, 0, NULL };
2178 stats_t *curr_stats = NULL;
2179 for(i = kh_begin(split_hash); i != kh_end(split_hash); ++i){
2180 if(!kh_exist(split_hash, i)) continue;
2181 curr_stats = kh_value(split_hash, i);
2182 round_buffer_flush(curr_stats, -1);
2183
2184 output_filename.l = 0;
2185 if (curr_stats->info->split_prefix)
2186 kputs(curr_stats->info->split_prefix, &output_filename);
2187 else
2188 kputs(bam_fname, &output_filename);
2189 kputc('_', &output_filename);
2190 kputs(curr_stats->split_name, &output_filename);
2191 kputs(".bamstat", &output_filename);
2192
2193 FILE *to = fopen(output_filename.s, "w");
2194 if(to == NULL){
2195 error("Could not open '%s' for writing.\n", output_filename.s);
2196 }
2197 output_stats(to, curr_stats, sparse);
2198 fclose(to);
2199 }
2200
2201 free(output_filename.s);
2202 }
2203
2204 void destroy_split_stats(khash_t(c2stats) *split_hash)
2205 {
2206 if (!split_hash)
2207 return;
2208
2209 int i = 0;
2210 stats_t *curr_stats = NULL;
2211 for(i = kh_begin(split_hash); i != kh_end(split_hash); ++i){
2212 if(!kh_exist(split_hash, i)) continue;
2213 curr_stats = kh_value(split_hash, i);
2214 cleanup_stats(curr_stats);
2215 }
2216 kh_destroy(c2stats, split_hash);
2217 }
2218
2219 stats_info_t* stats_info_init(int argc, char *argv[])
2220 {
2221 stats_info_t* info = calloc(1, sizeof(stats_info_t));
2222 if (!info) {
2223 return NULL;
2224 }
2225
2226 info->nisize = 8000;
2227 info->isize_main_bulk = 0.99; // There are always outliers at the far end
2228 info->gcd_bin_size = 20e3;
2229 info->cov_min = 1;
2230 info->cov_max = 1000;
2231 info->cov_step = 1;
2232 info->filter_readlen = -1;
2233 info->argc = argc;
2234 info->argv = argv;
2235 info->remove_overlaps = 0;
2236 info->cov_threshold = 0;
2237
2238 return info;
2239 }
2240
2241 int init_stat_info_fname(stats_info_t* info, const char* bam_fname, const htsFormat* in_fmt)
2242 {
2243 // .. bam
2244 samFile* sam;
2245 if ((sam = sam_open_format(bam_fname, "r", in_fmt)) == 0) {
2246 print_error_errno("stats", "failed to open \"%s\"", bam_fname);
2247 return 1;
2248 }
2249 info->sam = sam;
2250 info->sam_header = sam_hdr_read(sam);
2251 if (info->sam_header == NULL) {
2252 print_error("stats", "failed to read header for \"%s\"", bam_fname);
2253 return 1;
2254 }
2255 return 0;
2256 }
2257
2258 stats_t* stats_init(void)
2259 {
2260 stats_t *stats = calloc(1,sizeof(stats_t));
2261 if (!stats)
2262 return NULL;
2263
2264 stats->ngc = 200;
2265 stats->nquals = 256;
2266 stats->nbases = 300;
2267 stats->rseq_pos = -1;
2268 stats->tid = -1;
2269 stats->gcd_pos = -1LL;
2270 stats->igcd = 0;
2271 stats->is_sorted = 1;
2272 stats->nindels = stats->nbases;
2273 stats->split_name = NULL;
2274 stats->nchunks = 0;
2275 stats->pair_count = 0;
2276 stats->last_pair_tid = -2;
2277 stats->last_read_flush = 0;
2278 stats->target_count = 0;
2279
2280 return stats;
2281 }
2282
2283 static int init_barcode_tags(stats_t* stats) {
2284 stats->ntags = 4;
2285 stats->tags_barcode = calloc(stats->ntags, sizeof(barcode_info_t));
2286 if (!stats->tags_barcode)
2287 return -1;
2288 stats->tags_barcode[0] = (barcode_info_t){"BC", "QT", 0, -1, -1, 0};
2289 stats->tags_barcode[1] = (barcode_info_t){"CR", "CY", 0, -1, -1, 0};
2290 stats->tags_barcode[2] = (barcode_info_t){"OX", "BZ", 0, -1, -1, 0};
2291 stats->tags_barcode[3] = (barcode_info_t){"RX", "QX", 0, -1, -1, 0};
2292 return 0;
2293 }
2294
2295 static void init_stat_structs(stats_t* stats, stats_info_t* info, const char* group_id, const char* targets)
2296 {
2297 // Give stats_t a pointer to the info struct
2298 // This saves us having to pass the stats_info_t to every function
2299 stats->info = info;
2300
2301 // Init structures
2302 // .. coverage bins and round buffer
2303 if ( info->cov_step > info->cov_max - info->cov_min + 1 )
2304 {
2305 info->cov_step = info->cov_max - info->cov_min;
2306 if ( info->cov_step <= 0 )
2307 info->cov_step = 1;
2308 }
2309 stats->ncov = 3 + (info->cov_max-info->cov_min) / info->cov_step;
2310 info->cov_max = info->cov_min + ((info->cov_max-info->cov_min)/info->cov_step +1)*info->cov_step - 1;
2311 stats->cov = calloc(sizeof(uint64_t),stats->ncov);
2312 if (!stats->cov) goto nomem;
2313 stats->cov_rbuf.size = stats->nbases*5;
2314 stats->cov_rbuf.buffer = calloc(sizeof(int32_t),stats->cov_rbuf.size);
2315 if (!stats->cov_rbuf.buffer) goto nomem;
2316 if ( group_id ) init_group_id(stats, info, group_id);
2317 // .. arrays
2318 stats->quals_1st = calloc(stats->nquals*stats->nbases,sizeof(uint64_t));
2319 if (!stats->quals_1st) goto nomem;
2320 stats->quals_2nd = calloc(stats->nquals*stats->nbases,sizeof(uint64_t));
2321 if (!stats->quals_2nd) goto nomem;
2322 stats->gc_1st = calloc(stats->ngc,sizeof(uint64_t));
2323 if (!stats->gc_1st) goto nomem;
2324 stats->gc_2nd = calloc(stats->ngc,sizeof(uint64_t));
2325 if (!stats->gc_2nd) goto nomem;
2326 stats->isize = init_isize_t(info->nisize ?info->nisize+1 :0);
2327 if (!stats->isize) goto nomem;
2328 stats->gcd = calloc(stats->ngcd,sizeof(gc_depth_t));
2329 if (!stats->gcd) goto nomem;
2330 if (info->fai) {
2331 stats->mpc_buf = calloc(stats->nquals*stats->nbases,sizeof(uint64_t));
2332 if (!stats->mpc_buf) goto nomem;
2333 } else {
2334 stats->mpc_buf = NULL;
2335 }
2336 stats->acgtno_cycles_1st = calloc(stats->nbases,sizeof(acgtno_count_t));
2337 if (!stats->acgtno_cycles_1st) goto nomem;
2338 stats->acgtno_cycles_2nd = calloc(stats->nbases,sizeof(acgtno_count_t));
2339 if (!stats->acgtno_cycles_2nd) goto nomem;
2340 stats->acgtno_revcomp = calloc(stats->nbases,sizeof(acgtno_count_t));
2341 if (!stats->acgtno_revcomp) goto nomem;
2342 stats->read_lengths = calloc(stats->nbases,sizeof(uint64_t));
2343 if (!stats->read_lengths) goto nomem;
2344 stats->read_lengths_1st = calloc(stats->nbases,sizeof(uint64_t));
2345 if (!stats->read_lengths_1st) goto nomem;
2346 stats->read_lengths_2nd = calloc(stats->nbases,sizeof(uint64_t));
2347 if (!stats->read_lengths_2nd) goto nomem;
2348 stats->insertions = calloc(stats->nbases,sizeof(uint64_t));
2349 if (!stats->insertions) goto nomem;
2350 stats->deletions = calloc(stats->nbases,sizeof(uint64_t));
2351 if (!stats->deletions) goto nomem;
2352 stats->ins_cycles_1st = calloc(stats->nbases+1,sizeof(uint64_t));
2353 if (!stats->ins_cycles_1st) goto nomem;
2354 stats->ins_cycles_2nd = calloc(stats->nbases+1,sizeof(uint64_t));
2355 if (!stats->ins_cycles_2nd) goto nomem;
2356 stats->del_cycles_1st = calloc(stats->nbases+1,sizeof(uint64_t));
2357 if (!stats->del_cycles_1st) goto nomem;
2358 stats->del_cycles_2nd = calloc(stats->nbases+1,sizeof(uint64_t));
2359 if (!stats->del_cycles_2nd) goto nomem;
2360 stats->mapping_qualities = calloc(256,sizeof(uint64_t));
2361 if(!stats->mapping_qualities) goto nomem;
2362 if (init_barcode_tags(stats) < 0)
2363 goto nomem;
2364 realloc_rseq_buffer(stats);
2365 if ( targets )
2366 init_regions(stats, targets, info);
2367 return;
2368 nomem:
2369 error("Out of memory");
2370 }
2371
2372 static stats_t* get_curr_split_stats(bam1_t* bam_line, khash_t(c2stats)* split_hash, stats_info_t* info, char* targets)
2373 {
2374 stats_t *curr_stats = NULL;
2375 const uint8_t *tag_val = bam_aux_get(bam_line, info->split_tag);
2376 if(tag_val == 0){
2377 error("Tag '%s' not found in bam_line.\n", info->split_tag);
2378 }
2379 char* split_name = strdup(bam_aux2Z(tag_val));
2380
2381 // New stats object, under split
2382 khiter_t k = kh_get(c2stats, split_hash, split_name);
2383 if(k == kh_end(split_hash)){
2384 curr_stats = stats_init(); // mallocs new instance
2385 if (!curr_stats) {
2386 error("Couldn't allocate split stats");
2387 }
2388 init_stat_structs(curr_stats, info, NULL, targets);
2389 curr_stats->split_name = split_name;
2390
2391 // Record index in hash
2392 int ret = 0;
2393 khiter_t iter = kh_put(c2stats, split_hash, split_name, &ret);
2394 if( ret < 0 ){
2395 error("Failed to insert key '%s' into split_hash", split_name);
2396 }
2397 kh_val(split_hash, iter) = curr_stats; // store pointer to stats
2398 }
2399 else{
2400 curr_stats = kh_value(split_hash, k);
2401 free(split_name); // don't need to hold on to this if it wasn't new
2402 }
2403 return curr_stats;
2404 }
2405
2406 int main_stats(int argc, char *argv[])
2407 {
2408 char *targets = NULL;
2409 char *bam_fname = NULL;
2410 char *bam_idx_fname = NULL;
2411 char *group_id = NULL;
2412 int sparse = 0, has_index_file = 0, ret = 1;
2413 sam_global_args ga = SAM_GLOBAL_ARGS_INIT;
2414
2415 stats_info_t *info = stats_info_init(argc, argv);
2416 if (!info) {
2417 fprintf(samtools_stderr, "Could not allocate memory for info.\n");
2418 return 1;
2419 }
2420
2421 static const struct option loptions[] =
2422 {
2423 SAM_OPT_GLOBAL_OPTIONS('-', 0, '-', '-', 0, '@'),
2424 {"help", no_argument, NULL, 'h'},
2425 {"remove-dups", no_argument, NULL, 'd'},
2426 {"sam", no_argument, NULL, 's'},
2427 {"customized-index-file", required_argument, NULL, 'X'},
2428 {"ref-seq", required_argument, NULL, 'r'},
2429 {"coverage", required_argument, NULL, 'c'},
2430 {"read-length", required_argument, NULL, 'l'},
2431 {"insert-size", required_argument, NULL, 'i'},
2432 {"most-inserts", required_argument, NULL, 'm'},
2433 {"trim-quality", required_argument, NULL, 'q'},
2434 {"target-regions", required_argument, NULL, 't'},
2435 {"required-flag", required_argument, NULL, 'f'},
2436 {"filtering-flag", required_argument, NULL, 'F'},
2437 {"id", required_argument, NULL, 'I'},
2438 {"GC-depth", required_argument, NULL, 1},
2439 {"sparse", no_argument, NULL, 'x'},
2440 {"split", required_argument, NULL, 'S'},
2441 {"split-prefix", required_argument, NULL, 'P'},
2442 {"remove-overlaps", no_argument, NULL, 'p'},
2443 {"cov-threshold", required_argument, NULL, 'g'},
2444 {NULL, 0, NULL, 0}
2445 };
2446 int opt, tmp_flag;
2447
2448 while ( (opt=getopt_long(argc,argv,"?hdsXxpr:c:l:i:t:m:q:f:F:g:I:S:P:@:",loptions,NULL))>0 )
2449 {
2450 switch (opt)
2451 {
2452 case 'f':
2453 tmp_flag = bam_str2flag(optarg);
2454
2455 if (tmp_flag < 0) {
2456 print_error("stats", "Unknown flag '%s'", optarg);
2457 return 1;
2458 }
2459
2460 info->flag_require = tmp_flag;
2461 break;
2462
2463 case 'F':
2464 tmp_flag = bam_str2flag(optarg);
2465
2466 if (tmp_flag < 0) {
2467 print_error("stats", "Unknown flag '%s'", optarg);
2468 return 1;
2469 }
2470
2471 info->flag_filter |= tmp_flag;
2472 break;
2473
2474 case 'd': info->flag_filter |= BAM_FDUP; break;
2475 case 'X': has_index_file = 1; break;
2476 case 's': break;
2477 case 'r': info->fai = fai_load(optarg);
2478 if (info->fai==NULL)
2479 error("Could not load faidx: %s\n", optarg);
2480 break;
2481 case 1 : info->gcd_bin_size = atof(optarg); break;
2482 case 'c': if ( sscanf(optarg,"%d,%d,%d",&info->cov_min,&info->cov_max,&info->cov_step)!= 3 )
2483 error("Unable to parse -c %s\n", optarg);
2484 break;
2485 case 'l': info->filter_readlen = atoi(optarg); break;
2486 case 'i': info->nisize = atoi(optarg); break;
2487 case 'm': info->isize_main_bulk = atof(optarg); break;
2488 case 'q': info->trim_qual = atoi(optarg); break;
2489 case 't': targets = optarg; break;
2490 case 'I': group_id = optarg; break;
2491 case 'x': sparse = 1; break;
2492 case 'S': info->split_tag = optarg; break;
2493 case 'P': info->split_prefix = optarg; break;
2494 case 'p': info->remove_overlaps = 1; break;
2495 case 'g': info->cov_threshold = atoi(optarg);
2496 if ( info->cov_threshold < 0 || info->cov_threshold == INT_MAX )
2497 error("Unsupported value for coverage threshold %d\n", info->cov_threshold);
2498 break;
2499 case '?':
2500 case 'h': error(NULL);
2501 /* no break */
2502 default:
2503 if (parse_sam_global_opt(opt, optarg, loptions, &ga) != 0)
2504 error("Unknown argument: %s\n", optarg);
2505 break;
2506 }
2507 }
2508
2509 bam_fname = argv[optind++];
2510 if ( !bam_fname )
2511 {
2512 if ( isatty(STDIN_FILENO) )
2513 error(NULL);
2514 bam_fname = "-";
2515 }
2516
2517 if (init_stat_info_fname(info, bam_fname, &ga.in)) {
2518 cleanup_stats_info(info);
2519 return 1;
2520 }
2521
2522 if (has_index_file && !(bam_idx_fname = argv[optind++])) {
2523 fprintf(samtools_stderr, "No index file provided\n");
2524 cleanup_stats_info(info);
2525 return 1;
2526 }
2527
2528 if (ga.nthreads > 0)
2529 hts_set_threads(info->sam, ga.nthreads);
2530
2531 stats_t *all_stats = stats_init();
2532 if (!all_stats) {
2533 fprintf(samtools_stderr, "Could not allocate memory for stats.\n");
2534 cleanup_stats_info(info);
2535 return 1;
2536 }
2537 stats_t *curr_stats = NULL;
2538 init_stat_structs(all_stats, info, group_id, targets);
2539 // Init
2540 // .. hash
2541 khash_t(c2stats)* split_hash = kh_init(c2stats);
2542 if (!split_hash) goto cleanup_all_stats;
2543
2544 khash_t(qn2pair)* read_pairs = kh_init(qn2pair);
2545 if (!read_pairs) goto cleanup_split_hash;
2546
2547 // Collect statistics
2548 bam1_t *bam_line = bam_init1();
2549 if (!bam_line) goto cleanup_read_pairs;
2550
2551 if (optind < argc) {
2552 // Region:interval arguments in the command line
2553 hts_idx_t *bam_idx = NULL;
2554 if (has_index_file) {
2555 bam_idx = sam_index_load2(info->sam, bam_fname, bam_idx_fname);
2556 } else {
2557 // If an index filename has not been specified, look alongside the alignment file
2558 bam_idx = sam_index_load(info->sam, bam_fname);
2559 }
2560
2561 if (bam_idx) {
2562 hts_itr_multi_t *iter = sam_itr_regarray(bam_idx, info->sam_header, &argv[optind], argc - optind);
2563 if (iter) {
2564 if (!targets) {
2565 all_stats->nchunks = argc-optind;
2566 if (replicate_regions(all_stats, iter, info))
2567 fprintf(samtools_stderr, "Replications of the regions failed\n");
2568 }
2569
2570 if ( all_stats->nregions && all_stats->regions ) {
2571 while ((ret = sam_itr_next(info->sam, iter, bam_line)) >= 0) {
2572 if (info->split_tag) {
2573 curr_stats = get_curr_split_stats(bam_line, split_hash, info, targets);
2574 collect_stats(bam_line, curr_stats, read_pairs);
2575 }
2576 collect_stats(bam_line, all_stats, read_pairs);
2577 }
2578
2579 if (ret < -1) {
2580 fprintf(samtools_stderr, "Failure while running the iterator\n");
2581 hts_itr_multi_destroy(iter);
2582 hts_idx_destroy(bam_idx);
2583 goto cleanup;
2584 }
2585 }
2586 hts_itr_multi_destroy(iter);
2587 } else {
2588 fprintf(samtools_stderr, "Multi-region iterator could not be created\n");
2589 hts_idx_destroy(bam_idx);
2590 goto cleanup;
2591 }
2592 hts_idx_destroy(bam_idx);
2593 } else {
2594 if (has_index_file)
2595 fprintf(samtools_stderr, "Invalid index file '%s'\n", bam_idx_fname);
2596 fprintf(samtools_stderr, "Random alignment retrieval only works for indexed files\n");
2597 goto cleanup;
2598 }
2599 } else {
2600 if ( info->cov_threshold > 0 && !targets ) {
2601 fprintf(samtools_stderr, "Coverage percentage calculation requires a list of target regions\n");
2602 goto cleanup;
2603 }
2604
2605 // Stream through the entire BAM ignoring off-target regions if -t is given
2606 while ((ret = sam_read1(info->sam, info->sam_header, bam_line)) >= 0) {
2607 if (info->split_tag) {
2608 curr_stats = get_curr_split_stats(bam_line, split_hash, info, targets);
2609 collect_stats(bam_line, curr_stats, read_pairs);
2610 }
2611 collect_stats(bam_line, all_stats, read_pairs);
2612 }
2613
2614 if (ret < -1) {
2615 fprintf(samtools_stderr, "Failure while decoding file\n");
2616 goto cleanup;
2617 }
2618 }
2619
2620 round_buffer_flush(all_stats, -1);
2621 output_stats(samtools_stdout, all_stats, sparse);
2622 if (info->split_tag)
2623 output_split_stats(split_hash, bam_fname, sparse);
2624
2625 ret = 0;
2626 cleanup:
2627 bam_destroy1(bam_line);
2628 sam_hdr_destroy(info->sam_header);
2629 sam_global_args_free(&ga);
2630
2631 cleanup_read_pairs:
2632 cleanup_overlaps(read_pairs, INT64_MAX);
2633 cleanup_split_hash:
2634 destroy_split_stats(split_hash);
2635 cleanup_all_stats:
2636 cleanup_stats(all_stats);
2637 cleanup_stats_info(info);
2638
2639 return ret;
2640 }