Skip to content

fix(samtools): match samtools stats and flagstat 1.22.1 exactly - #198

Merged
ewels merged 2 commits into
seqeralabs:mainfrom
rhassaine:fix/samtools-stats-parity
Nov 26, 2026
Merged

ewels merged 2 commits into
seqeralabs:mainfrom
rhassaine:fix/samtools-stats-parity

Conversation

@rhassaine

Copy link
Copy Markdown
Contributor

RustQC's samtools stats differed from samtools on some inputs: the GC-depth (GCD) percentiles, the depth-1 coverage bin (off by one) and the last digit of the error rate. The GCD section also changed with --threads. This reproduces samtools 1.22.1's arithmetic while keeping the single pass:

  • GCD: per-bin GC rounded like rint() (ties to even), single-precision percentiles as in stats.c, and the last bin handled as samtools does; bins are restored to contig order after merging, so the result no longer depends on the thread count.
  • Coverage: samtools' round buffer is reproduced per contig, including the position it carries over and never counts at the end.
  • Error rate and averages use single precision where samtools does.
  • flagstat now fills the QC-failed column (it was always 0), and several SN counters use samtools' exact conditions.

Library API: BamStatResult gains fields, the per-cycle quality tables are now [u64; 256], and BamStatAccum::flush_cov_buf_all is removed.

Checked byte for byte (all non-# lines) against samtools 1.22.1, the build the nf-core module uses, on the eight RustQC-benchmarks datasets, RustQC's test BAMs and synthetic edge-case BAMs, at 1, 2 and 6 threads. stats, flagstat and idxstats all match.

🤖 Generated with Claude Code

rhassaine and others added 2 commits November 26, 2026 13:55
Port the remaining details of samtools stats.c and bam_stat.c (1.22.1) so
every data line of the stats output and the whole flagstat output match
samtools, independent of --threads.

samtools stats:
- GCD: normalise bin GC with rint() in double precision (ties to even),
  compute percentiles and depth scaling in single precision as samtools
  does, compare GC groups like fabs(float - float) < 0.1, and give
  supplementary reads a GC of 0. Bins are put back in BAM order before
  output, because samtools leaves the last bin un-normalised; before, the
  "last" bin depended on how contigs were split across threads.
- COV: simulate the samtools round buffer per contig. Its flush to the end
  visits only size - 1 slots, so one slot is carried into the next contig
  and dropped after the last one. The carry is resolved after all contigs
  are merged, so the result does not depend on --threads.
- SN: error rate and the averages are float divisions in samtools; the
  insert-size summary halves each orientation separately and keeps
  insert size 0 for same-contig pairs; filtered sequences is 0; QC-failed,
  unmapped, properly paired, duplicated and different-chromosome counts
  use samtools' own conditions; mismatches and duplicates include
  supplementary reads; non-primary alignments counts secondary records.
- First/last fragments follow samtools' read order (read1 only / read2
  only); read lengths include hard clips; ID only lists indels up to 300
  bases and skips leading deletions like count_indels; GCT skips empty
  cycles; FFQ/LFQ share one maximum quality and keep all 256 quality
  values (missing qualities are 255).

samtools flagstat: count QC-passed and QC-failed records separately
(port of flagstat_loop) and compute percentages in single precision.

Library API: BamStatResult gains the samtools-only counters and a
FlagstatCounts; ffq/lfq rows are [u64; 256]; the public
BamStatAccum::flush_cov_buf_all is gone (coverage is finished per contig).

Verified byte for byte (all non-comment lines of stats, full flagstat and
idxstats) against samtools 1.22.1 (bioconda h96c455f_0) on the eight
RustQC-benchmarks datasets and on synthetic BAMs with QC-fail,
supplementary, secondary, hard-clipped, spliced and unmapped reads, at
--threads 1, 2 and 6.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…nd stats on every flag

samtools gives SECONDARY priority over SUPPLEMENTARY in `flagstat_loop`
(bam_stat.c) and in `stats.c`: a record carrying both flags is secondary
only. The flagstat writer already did this through `FlagstatCounts`, but the
per-field counters behind `samtools stats` still counted such a record as
secondary and as supplementary, so `SN supplementary alignments` was too
high (3072 against samtools' 6144 on the all-flags input below). Use
`else if`, so primary + secondary + supplementary == total.

Add the regression tests that expose it, all checked against samtools
1.22.1 (bioconda build h96c455f_0):

- all 4096 flag values in three mate placements: flagstat and the `SN`
  section of stats against samtools-generated golden files, on the serial
  and the per-contig parallel path (integration test);
- one flagged record between two plain reads for QC-failed, QC-failed
  duplicate, secondary+supplementary, QC-failed 0xf00 and the
  "properly paired needs a mapped read" case (0x4f);
- unit tests against a transcription of samtools' flagstat_loop for every
  flag and placement, merged and partitioned counters, dual flags with
  QC-fail and duplicate, and large-count percentage rounding (expected
  strings produced by compiling samtools' percent() unchanged).

The test cases and the semantics they pin come from seqeralabs#175
(Nico DeVeaux) and seqeralabs#131 (Benjamin Demaille).

Co-authored-by: Nico DeVeaux <105398+NicoDeVeaux@users.noreply.github.com>
Co-authored-by: Benjamin Demaille <41732816+BenjaminDEMAILLE@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants