Repository navigation
Conversation
A CG now counts as a CpG only when both bases are uppercase, i.e. real reference or variant bases. Lowercase bases are those load_contig synthesized from N and other ambiguity codes; random sequence has a CG every 16 bases, so assembly gaps produced 26% of all CpG records on hs38DH. The scan is a memchr substring search shared by the methylation walk, the VCF classifier and the bedGraph writer. VCF alleles are uppercased when parsed so that lowercase keeps the single meaning of an ambiguity-resolved reference base. Whole-genome methylate on hs38DH: 87 s to 52 s.
A haplotype with no variants on a contig borrows the reference instead of copying it, and the reference's CpGs and their island contexts are found once and shared by every such haplotype; only the methylation draw is per haplotype. The bedGraph writer streams records directly in that case, and otherwise merges per-haplotype counts with a sort instead of a BTreeMap. methylate on chr1 without a VCF: 3.7 s to 1.7 s, 1.75 GB to 0.6 GB.
Golden-BAM XM/YM context classification now ignores lowercase (synthesized) reference bases, matching the methylation VCF and the CpG truth bedGraph. VCF alleles are uppercased when haplotypes are built rather than when the VCF is parsed, so methylate echoes REF/ALT unchanged (symbolic and breakend alleles included) and simulate can still match records in methylation VCFs whose alleles are lowercase.
|
Navigate logical layers of code changes, visualize relationships, and explore their blast radius. 🧰 Additional context used📚 Code guidelines (1)No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Advanced Run ID: ⛔ Files ignored due to path filters (1)
📒 Files selected for processing (9)
Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review. 📝 WalkthroughWalkthroughHaplotype extraction now supports borrowed reference sequences and owned variant sequences. CpG scans recognize uppercase ChangesCpG Recognition and Methylation Output
Priority: ➖ Normal Estimated code review effort: 3 (Moderate) | ~20 minutes Change: Bug fix Suggested reviewers: Merge Risk: ⚪ Minimal · up to No identified issue remains that needs correction before merging. Security Architecture ReviewSecurity architecture risk: 🔵 Low · up to The change has limited design risk and does not show increased privileges or a new service boundary. Older methylation VCFs should be regenerated: newly detected incompatibilities can stop simulation after output files have already been created, leaving incomplete results. Retained concerns
Security review detailsSecurity Blast Radius
Security Findings and Attack Paths
Trust Boundaries and Controls
Resilience and Maintainability Implications
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. A rabbit checks each letter’s face, Comment |
nh13
left a comment
There was a problem hiding this comment.
Nice speedup, and skipping CpGs in N runs makes sense. I'd fix two things before merge: old VCFs loading silently (and the default-threads abort), and the XM/YM context next to Ns. Docs and test gaps are inline. I checked the extract_fragment run-copy rewrite against main with a randomized differential test (960k cases, including overlapping variants and contig ends) and the output is identical.
Outside the diff:
apply_standalone_record(src/vcf/methylation.rs:1077) doesn't check the reference base, so an old methylation VCF with records inside N runs loads silently and sets bits at positions that are no longer CpGs. Warn or fail when a record isn't on an uppercaseCG.- NM/MD uppercase the reference base (
src/methylation_tags.rs:271,:304) but XM/YM now skip lowercase, so a resolvedcread as T is a bisulfite match in NM/MD and.in XM/YM. Document it or make them agree. - The "(uppercase)" docs at
src/vcf/methylation.rs:63,:932and:1422are stale, as is themethylatehelp ("every CpG dinucleotide",src/commands/methylate.rs:18, and the module doc at line 3).
| } | ||
| let next1 = *ref_bytes.get(ref_idx + 1)?; | ||
| if next1.eq_ignore_ascii_case(&b'G') { | ||
| if next1 == b'G' { |
There was a problem hiding this comment.
A real C next to a resolved base is now called CHH/CHG (ACgT gives CHH, and the new test pins it). Bismark calls that context unknown (U/u) when the neighbour is an N, since it might have been a G, and treats other IUPAC codes as non-G. Returning None (.) when the deciding neighbour is lowercase is the closer match, and probably what the README's "no CpG calls there" intends.
| golden BAM. For a given `--seed`, methylation values differ from earlier | ||
| versions on any reference that contains ambiguity codes. Methylation VCFs | ||
| written by earlier versions should be regenerated: most still load, but one | ||
| with a variant next to an ambiguity code is rejected with an MT/MB length |
There was a problem hiding this comment.
Users won't see this message with the default --threads: it aborts with exit 134 from a pooled-writer panic before the mismatch prints. --threads 1 gives the clean error. The abort predates this PR, but please fix the error path or reword this.
| contain a `CG` about every 16 bases, and each of these was written as a CpG | ||
| record; on hs38DH they were 26% of all records. A `CG` now counts as a CpG | ||
| only when both bases are real reference or variant bases. `simulate` applies | ||
| the same rule to its CpG truth bedGraph and to the `XM`/`YM` tags in the |
There was a problem hiding this comment.
CHG/CHH calls at a resolved C also become . in XM/YM, not only CpG calls. The lowercase-ALT entry (lines 28-30) could also say this changes simulate output for a given --seed, since --max-n-frac no longer rejects those reads.
| } | ||
|
|
||
| #[test] | ||
| fn methylate_emits_no_cpgs_inside_a_run_of_n() { |
There was a problem hiding this comment.
This passes because seed 42 happens to resolve one CG in the Ns (the comment says "several"). After a rand upgrade it could resolve none and still pass. A second seed or a longer N run would fix that. No test covers the N-run rule on the methylate --vcf path either, which is where the MT/MB mismatch comes from.
| let runs = island_runs(mask); | ||
| /// open-sea relative to the island `runs` produced by [`island_runs`]: inside | ||
| /// a run is an island, within [`SHORE_WIDTH_BP`] of one is a shore. | ||
| fn classify_cpg_contexts(cpg_top_c: &[u32], runs: &[(u32, u32)]) -> Vec<CpgContext> { |
There was a problem hiding this comment.
nit: no test fails if the upstream-shore branch or either SHORE_WIDTH_BP boundary breaks. Only the downstream branch is covered.
| .map(|hap| MethylationTable::from_haplotype(hap, reference, model, rng)) | ||
| .map(|hap| { | ||
| if hap.is_reference() { | ||
| let sites = reference_sites.get_or_insert_with(|| CpgSites::find(reference)); |
There was a problem hiding this comment.
nit: no test covers this reference fast path with lowercase bases. Uppercasing the reference here still passes every test.
| // Variants present → materialize each haplotype, walk its bases looking | ||
| // for CpGs, and map each one back to a reference position via the per-base | ||
| // `ref_positions` returned by `extract_fragment`. | ||
| let mut per_haplotype: Vec<CpgCounts> = Vec::new(); |
There was a problem hiding this comment.
nit: per_haplotype holds one entry per (haplotype, CpG), while meth.rs uses the same name for a per-haplotype Vec. Maybe per_hap_cpg?
| # Vec<bool> would cost 8x the memory at whole-chromosome scale. See | ||
| # MethylationTable in src/meth.rs. | ||
| bitvec = "1" | ||
| memchr = "2" |
There was a problem hiding this comment.
nit: bstr already pulls in memchr and has find_iter, so this costs nothing. Fine either way.
Summary
Makes
methylate2.5–3.7× faster on a single thread, and stops it assigning methylation to CpGs that only exist becauseNs were resolved to random bases. This is offered as an alternative to the per-contig threading in #21: on hs38DH without a VCF it takes 24 s single-threaded, with lower memory and no new concurrency.Behaviour change
A
CGnow counts as a CpG only when both bases are uppercase.Fasta::load_contigalready uppercases realACGTand stores bases synthesized fromNand other ambiguity codes in lowercase, so this excludes CpGs made of invented bases. Random sequence has aCGevery 16 bases, so assembly gaps produced 26% of all CpG records on hs38DH (41.8 M records before, 30.9 M after).methylate's VCF and bedGraph,simulate's CpG truth bedGraph, and the golden BAM'sXM/YMtags all follow the rule.--seed, methylation values differ from earlier versions on any reference containing ambiguity codes, because removing CpGs shifts the random draws. On a reference without ambiguity codes the output is byte-identical tomain.methylatestill echoes REF/ALT exactly as given.Output-preserving speed-ups
memchrsubstring search forCGreplaces five hand-written scan loops.BTreeMap.Haplotype::extract_fragmentcopies the reference run between variants in bulk instead of one base at a time.simulateuses this too.Benchmarks
hs38DH, single thread, BGZF VCF plus bedGraph,
--seed 1. The VCF case uses 3.5 Mmutate-generated variants.main(ac66f99)Testing
cargo ci-fmt,cargo ci-lint,cargo ci-test(448 passed).simulateFASTQs and golden BAM are byte-identical tomainon a reference with variants and no ambiguity codes.mainagainst the branch over 60 random seeds × 3 scenarios (ploidy 1–3; SNPs, MNPs, indels, multi-allelic and contig-edge variants):methylateandsimulateoutputs were byte-identical wherever the behaviour change does not apply.N(VCF and bedGraph); lowercase dinucleotides skipped by the scan, the methylation table and the golden-BAM context classifier; island runs merge and separate correctly;Haplotype::sequenceborrows without variants, includes inserted bases, and uppercases lowercase alternate alleles.Not addressed
With a VCF, each haplotype is still copied in full four times per contig along with a per-base position array, which is why memory is unchanged in that case.
Summary by CodeRabbit
methylateandsimulatenow count CpGs only when both bases are real, preventing calls at ambiguous reference positions.simulate --max-n-frac.methylateruns faster and uses less memory when no VCF is provided.simulatealso benefits from faster haplotype fragment extraction.