Reference¶
bam2tensor package¶
bam2tensor.embedding module¶
Genome methylation embedding for CpG site indexing and coordinate conversion.
This module provides the GenomeMethylationEmbedding class, which manages the mapping between genomic coordinates and matrix column indices for methylation data. It parses reference genome FASTA files to identify all CpG sites and provides efficient bidirectional lookup between:
Genomic coordinates (chromosome, position)
Matrix embedding indices (column numbers in the sparse output matrix)
The CpG site index is cached to disk as a gzipped JSON file, allowing fast subsequent runs on the same reference genome.
Example
Create an embedding for the human genome:
from bam2tensor.embedding import GenomeMethylationEmbedding
embedding = GenomeMethylationEmbedding(
genome_name="hg38",
expected_chromosomes=["chr" + str(i) for i in range(1, 23)] + ["chrX", "chrY"],
fasta_source="/path/to/GRCh38.fa",
verbose=True,
)
# Get total CpG count
print(f"Total CpG sites: {embedding.total_cpg_sites:,}")
# Convert between coordinate systems
chrom, pos = embedding.embedding_to_genomic_position(12345)
idx = embedding.genomic_position_to_embedding("chr1", 10525)
- CACHE_FILE_SUFFIX¶
The suffix appended to genome_name for cache files.
- class GenomeMethylationEmbedding(genome_name, expected_chromosomes, fasta_source, window_size=None, skip_cache=False, verbose=False)¶
Bases:
objectManages CpG site positions and coordinate conversions for a reference genome.
This class parses a reference genome FASTA file to identify all CpG sites (positions where cytosine is followed by guanine), creating a mapping between genomic coordinates and linear embedding indices. This mapping is essential for interpreting the sparse matrices produced by bam2tensor.
The embedding assigns each CpG site a unique integer index, ordered by: 1. Chromosome order (as specified in expected_chromosomes) 2. Genomic position within each chromosome
CpG site data is cached to disk after the first parse, significantly speeding up subsequent runs on the same genome.
- Parameters:
genome_name (str)
expected_chromosomes (list[str])
fasta_source (str)
window_size (int | None)
skip_cache (bool)
verbose (bool)
- genome_name¶
Identifier for this genome (used for cache file naming).
- fasta_source¶
Path to the reference FASTA file.
- expected_chromosomes¶
List of chromosome names to include.
- verbose¶
Whether to print progress information.
- cpg_sites_dict¶
Dictionary mapping chromosome names to sorted lists of CpG positions (1-based coordinates). Its keys are in
expected_chromosomesorder.
- chromosome_lengths¶
Dictionary mapping each chromosome name to the length of its sequence in the reference FASTA. Used to check that a BAM was aligned to this reference.
- total_cpg_sites¶
Total number of CpG sites across all chromosomes.
- chromosome_offsets¶
Dictionary mapping each chromosome name to the matrix column of its first CpG site. The column of the i-th CpG (0-based) on a chromosome is
chromosome_offsets[chrom] + i.
- cpgs_per_chr_cumsum¶
Cumulative CpG count over
expected_chromosomes(the column just past each chromosome).
- cache_file¶
Path to the cache file for this genome.
Example
>>> # xdoctest: +SKIP >>> embedding = GenomeMethylationEmbedding( ... genome_name="hg38", ... expected_chromosomes=["chr1", "chr2"], ... fasta_source="reference.fa", ... ) >>> embedding.total_cpg_sites 2847432 >>> embedding.embedding_to_genomic_position(0) ('chr1', 10525) >>> embedding.genomic_position_to_embedding("chr1", 10525) 0
- embedding_to_genomic_position(embedding)¶
Convert a matrix column index to genomic coordinates.
Given an embedding index (column number in the sparse matrix), returns the corresponding chromosome name and 1-based genomic position.
This is the inverse of genomic_position_to_embedding().
- Parameters:
embedding (
int|int64) – The matrix column index (0-based). Must be in the range [0, total_cpg_sites).- Returns:
chromosome is the chromosome name (e.g., “chr1”)
position is the 1-based genomic coordinate of the CpG site
- Return type:
A tuple of (chromosome, position) where
- Raises:
AssertionError – If embedding is out of range.
Example
>>> # xdoctest: +SKIP >>> embedding = GenomeMethylationEmbedding(...) >>> chrom, pos = embedding.embedding_to_genomic_position(12345) >>> print(f"Column 12345 is {chrom}:{pos}") Column 12345 is chr1:987654
- genomic_position_to_embedding(chrom, pos)¶
Convert genomic coordinates to a matrix column index.
Given a chromosome name and 1-based genomic position, returns the corresponding matrix column index (embedding position).
This is the inverse of embedding_to_genomic_position().
- Parameters:
chrom (
str) – The chromosome name (e.g., “chr1”). Must be one of the chromosomes in expected_chromosomes.pos (
int) – The 1-based genomic position of the CpG site. Must be a valid CpG position in the specified chromosome.
- Return type:
int- Returns:
The matrix column index (0-based) corresponding to this CpG site.
- Raises:
KeyError – If
posis not a CpG site onchrom. (An unknown chromosome name also results in aKeyError.)
Example
>>> # xdoctest: +SKIP >>> embedding = GenomeMethylationEmbedding(...) >>> col_idx = embedding.genomic_position_to_embedding("chr1", 10525) >>> print(f"chr1:10525 is at column {col_idx}") chr1:10525 is at column 0
- load_embedding_cache()¶
Load CpG site index from a previously saved cache file.
Attempts to load the cache file “{genome_name}.cache.json.gz” and restore all CpG site data. If successful, this avoids the slow FASTA parsing step.
Provenance is validated before the cached data is trusted: the cache must be readable, must have been written by the same version of bam2tensor, must have been built from the current
fasta_source, and must contain every expected chromosome. A cache that fails any of these checks is rejected with aFileNotFoundErrorso the caller falls through to a fresh FASTA parse and overwrites the stale cache on save.The FASTA is identified by its SHA-256. Hashing a multi-gigabyte reference on every run is slow, so the cache also records which file it was built from: the resolved path, device, inode, size, modification time and change time, all taken when the cache was written. When the current
fasta_sourcestill leads to that same file and none of these differ — and the FASTA had not been modified within a couple of seconds of the cache being written, when a rewrite could go unnoticed — the file is taken to be unchanged and is not re-read. Otherwise (a different path, a symlink that now points elsewhere, a file that was replaced even with its size and timestamps preserved, a copy, or a cache that predates these fields) the SHA-256 is recomputed and compared. Size and modification time alone are never enough: two different references can share both.A cache that is valid but was built for a different chromosome list is not silently replaced: the same genome name is being used for two different column layouts, so a
ValueErrorasks the user to disambiguate.- Return type:
bool- Returns:
True if the cache was successfully loaded.
- Raises:
FileNotFoundError – If the cache file does not exist, or if the cache is stale or unusable (unreadable/truncated file, version mismatch, FASTA SHA-256 mismatch, or missing chromosomes or chromosome lengths).
ValueError – If the cache was built for a different list of expected chromosomes.
Note
Only
cpg_sites_dictis populated from the cache. The instance’s own configuration (genome_name,fasta_source,expected_chromosomes) is left untouched.
- parse_fasta_for_cpg_sites()¶
Parse the reference FASTA to find all CpG sites.
Scans each chromosome in the reference genome FASTA file to identify all CpG dinucleotide positions (where C is immediately followed by G). Results are stored in self.cpg_sites_dict, and the length of each chromosome’s sequence in self.chromosome_lengths.
This operation is slow for large genomes (~10 minutes for GRCh38/hg38) but only needs to be done once per genome. Results should be cached using save_embedding_cache() for faster subsequent runs.
The method populates self.cpg_sites_dict with the structure:
{ "chr1": [10525, 10542, 10563, ...], # 1-based positions "chr2": [10182, 10193, 10218, ...], ... }
Positions are 1-based to match standard genomic coordinate conventions (e.g., samtools faidx uses 1-based coordinates).
Only chromosomes listed in self.expected_chromosomes are processed; other sequences in the FASTA are skipped with a message (if verbose).
- Raises:
FileNotFoundError – If the FASTA file cannot be read.
ValueError – If any expected chromosome is absent from the FASTA. The message lists the missing names and the sequences that are available, and flags
chrprefix mismatches (UCSC vs. Ensembl naming).
- Return type:
None
- Return type:
NoneFor the human genome (GRCh38), expect approximately 28 million CpG sites across all chromosomes.
- save_embedding_cache()¶
Save the CpG site index to a compressed cache file.
Serializes the CpG site positions and metadata to a gzipped JSON file. The cache file is named “{genome_name}.cache.json.gz” and contains: - genome_name: The genome identifier - fasta_source: Path to the original FASTA file - fasta_sha256: SHA-256 of the FASTA file bytes (for cache validation) - fasta_realpath, fasta_device, fasta_inode, fasta_ctime_ns,
fasta_size, fasta_mtime_ns: Identity, size and times of the file that fasta_source resolved to when the cache was written, and fasta_stat_time_ns, the time they were recorded (a fast path for cache validation)
bam2tensor_version: Version that produced this cache
total_cpg_sites: Total CpG count across all included chromosomes
expected_chromosomes: List of included chromosomes
cpg_sites_dict: Dictionary of chromosome -> list of CpG positions
chromosome_lengths: Dictionary of chromosome -> sequence length
The cache can be loaded by future GenomeMethylationEmbedding instances to avoid re-parsing the FASTA file.
- Raises:
AssertionError – If cpg_sites_dict is empty (nothing to cache).
- Return type:
None
Note
Cache files use compression level 3 for a balance between file size and write speed. The cache is written to a temporary file and renamed into place, so an interrupted run (or several jobs starting at once in the same directory) can never leave a truncated cache behind.
- Return type:
None
bam2tensor.functions module¶
Core methylation extraction functions for bam2tensor.
This module contains the main function for extracting methylation data from BAM files: extract_methylation_data_from_bam(). This function reads aligned bisulfite-sequencing (BS-seq) and enzymatic methylation sequencing (EM-seq) reads and generates a sparse matrix representation of methylation states at each CpG site, with one row per sequenced DNA fragment.
- The extraction process:
Iterates through each chromosome in the genome embedding
For each aligned read that passes the read filters: a. Determines which bisulfite strand the fragment derives from b. Identifies the CpG sites whose informative base the read covers c. Extracts the methylation state at each of those CpGs, keeping
a call only where the read shows an intact CpG on a base of sufficient quality
Combines the two mates of a read pair into a single fragment
Builds a sparse COO matrix with one row per fragment
- Methylation State Encoding:
1: Methylated (cytosine remained as C after bisulfite treatment)
0: Unmethylated (cytosine converted to T by bisulfite treatment)
-1: No usable call. The fragment covers the CpG, but the read does not show an intact CpG there (an indel, SNV or other unexpected base at either base of the CpG), the base carrying the call is below the minimum base quality, the CpG lies in the masked 3’ end of the fragment (opt-in), or the two mates of a pair disagree.
- Strands and the informative base:
A fragment derives from either the top or the bottom strand of the original DNA, and both mates of a proper pair report on that same strand. BAM stores every read in top-strand orientation, so for a CpG whose C is at reference position p:
a top-strand fragment carries the call on the C, at p (C = methylated, T = unmethylated);
a bottom-strand fragment carries it on the G, at p + 1 (G = methylated, A = unmethylated).
Each read is therefore decoded at whichever of the two bases is informative for its fragment’s strand, whatever the read’s own alignment orientation.
- Supported Aligners:
The module supports BAM files from aligners that provide strand information: - Bismark: Uses the XM call string (Z=methylated CpG, z=unmethylated
CpG) and the XG tag (CT=top strand, GA=bottom strand)
Biscuit: Uses the YD tag (f=top strand, r=bottom strand)
bwameth: Uses the YD tag (f=top strand, r=bottom strand), as Biscuit
gem3/Blueprint: Uses the XB tag (C=top strand, G=bottom strand)
Example
>>> # xdoctest: +SKIP
>>> from bam2tensor.embedding import GenomeMethylationEmbedding
>>> from bam2tensor.functions import extract_methylation_data_from_bam
>>>
>>> # Create genome embedding
>>> embedding = GenomeMethylationEmbedding(
... genome_name="hg38",
... expected_chromosomes=["chr1", "chr2"],
... fasta_source="reference.fa",
... )
>>>
>>> # Extract methylation data
>>> result = extract_methylation_data_from_bam(
... input_bam="sample.bam",
... genome_methylation_embedding=embedding,
... quality_limit=20,
... )
>>>
>>> print(f"Extracted {result.matrix.shape[0]} reads, {result.matrix.nnz} data points")
- class ExtractionResult(matrix, tlen, stats)¶
Bases:
NamedTupleResult of methylation extraction from a BAM file.
- Parameters:
matrix (coo_matrix)
tlen (ndarray)
stats (dict[str, int])
- matrix¶
Sparse COO matrix of shape (n_fragments, n_cpg_sites) with methylation states: 1 (methylated), 0 (unmethylated), -1 (no data). Each row is one sequenced DNA fragment: the two mates of a read pair combined, or a single read.
- tlen¶
1-D numpy array of shape (n_fragments,) containing the length of each fragment (the absolute BAM TLEN). 0 for single-end reads or reads with unmapped mates.
- stats¶
Counts describing what the extraction saw and discarded, for quality control (the CLI stores them in the output file’s metadata). Keys:
reads_used: reads that passed every read filter (mapping quality, flags, proper pair), whether or not they cover a CpG.reads_dropped_improper_pair: reads skipped because they are paired but not flagged as a proper pair.reads_without_md: reads the non-converted filter could not evaluate for lack of anMDtag.fragments_from_two_mates: fragments in which the calls of two mates were combined (counted before the fragment-level filters).cpg_observations: CpGs decoded, counted per read (before the two mates of a pair are combined).cpg_not_intact: observations stored as-1because the read does not show an intact CpG there.cpg_reference_mismatch: how many of those disagree with the reference in a way a wrong strand tag cannot explain (the count behind the reference check).cpg_low_base_quality: observations stored as-1because the base carrying the call is below the minimum base quality.cpg_masked_3prime: calls stored as-1because they lie in the masked 3’ end of their fragment (counted per fragment, after the mates are combined).strand_checksandstrand_contradictions: the strand-tag check (CpGs examined, and how many contradict their read’s strand tag).
- matrix: coo_matrix¶
Alias for field number 0
- stats: dict[str, int]¶
Alias for field number 2
- tlen: ndarray¶
Alias for field number 1
- check_chromosome_lengths(bam_lengths, reference_lengths)¶
Check that the BAM was aligned to chromosomes of the reference’s lengths.
A BAM records the length of every sequence it was aligned to. If a chromosome has one length there and another in the reference FASTA the CpG index was built from, the two are different assemblies (hg19 and hg38, say) that merely share chromosome names. Positions do not correspond between them, so the reads would be decoded at positions that are not CpGs in the genome they were aligned to.
Only chromosomes present under the same name on both sides are compared.
- Parameters:
bam_lengths (
dict[str,int]) – Sequence name to length, from the BAM header.reference_lengths (
dict[str,int]) – Chromosome name to length, from the reference FASTA (GenomeMethylationEmbedding.chromosome_lengths).
- Raises:
ValueError – If any shared chromosome differs in length.
- Return type:
None
Example
>>> check_chromosome_lengths({"chr1": 1000}, {"chr1": 1000, "chr2": 500})
- check_chromosome_overlap(bam_references, embedding_chromosomes)¶
Check that BAM and embedding chromosome names overlap.
Detects the common mistake where a BAM file uses one chromosome naming convention (e.g.,
1,2,3from Ensembl) while the reference embedding uses another (e.g.,chr1,chr2,chr3from UCSC). If no overlap is found but adding or stripping achrprefix would create overlap, raises a clear error with guidance.- Parameters:
bam_references (
tuple[str,...] |list[str]) – Tuple or list of chromosome/contig names from the BAM file header (e.g., frompysam.AlignmentFile.references).embedding_chromosomes (
list[str]) – List of chromosome names from the genome embedding (i.e., the expected chromosomes).
- Raises:
ValueError – If there is no overlap between BAM and embedding chromosome names, with a diagnostic message indicating whether a
chrprefix mismatch is the likely cause.- Return type:
None
- count_non_cpg_retained_reference(aligned_segment, is_reverse_parent_strand, cpg_positions=None)¶
Count retained non-CpG bases validated against the reference.
For a correctly bisulfite- or EM-seq-converted read, every non-CpG cytosine on the parent strand should have been converted. On the forward-parent strand that means every non-CpG
Cin the reference should appear asTin the read; on the reverse-parent strand every non-CpGGshould appear asA. Positions where the read still carries the unconverted base and the reference genuinely has aC/G(i.e., the mismatch is not a SNP) count as retained.This is a port of the logic in
nebiolabs/mark-nonconverted-reads, re-using the read’s existingMDtag (viapysam.AlignedSegment.get_aligned_pairs()withwith_seq=True) instead of requiring a separate reference FASTA.Which cytosines are in CpG context — and so exempt — is best taken from the CpG index via
cpg_positions. Without it, the context is inferred from the neighbouring reference base as reconstructed from the read, which cannot see a neighbour lying just outside the alignment: a methylated CpG cut by the end of the read is then counted as a retained non-CpG cytosine.Note
The count is only as good as the
MDtag. bwa-meth writesMDrelative to its bisulfite-converted reference. For the directional libraries bwa-meth is designed for, that gives the exact count, with one blind spot: a readCover a referenceT(orGoverA) is a SNP that conversion makes invisible, so it is counted as retained. For a non-directional library aligned with bwa-meth the tag does not describe the read as stored, and retained cytosines are undercounted.- Parameters:
aligned_segment (
AlignedSegment) – A pysam aligned read. Must carry anMDtag. bwa-meth writes one; gem3 does not for bisulfite alignments, so its reads cannot be evaluated unless the tag is added afterwards (for example withsamtools calmd).is_reverse_parent_strand (
bool) –Trueif the read derives from the reverse (OB/CTOB) bisulfite parent strand,Falsefor the forward (OT/CTOT) strand.cpg_positions (
Container[int] |None) – 0-based reference positions of theCof every CpG the read touches, including a CpG whoseCorGlies just outside the alignment. IfNone, CpG context is inferred from the read’s own reconstruction of the reference.
- Return type:
int- Returns:
The number of reference-validated retained non-CpG cytosines (or guanines, for the reverse parent strand). Returns
0when the read has no sequence or noMDtag is present.
- count_non_cpg_retained_xm(xm_tag)¶
Count retained non-CpG cytosines in a Bismark XM methylation string.
Bismark’s
XMtag encodes per-base methylation context. Uppercase letters indicate a cytosine that remained asCin the read (i.e., was not converted by bisulfite/EM-seq treatment).H,XandUcorrespond to retained cytosines in CHH, CHG and unknown-context positions respectively. A high count of these on a single read is a strong signal of incomplete conversion.- Parameters:
xm_tag (
str) – The value of a read’s BismarkXMtag.- Return type:
int- Returns:
The count of
H,XandUcharacters inxm_tag.
Example
>>> count_non_cpg_retained_xm("..Z..hhh..HHH..z..") 3
- detect_aligner(input_bam, sample_size=1000)¶
Detect the aligner used to produce a BAM file by checking read tags.
Samples up to
sample_sizereads from the BAM file and checks for aligner-specific tags:XM(Bismark),YD(Biscuit/bwameth), orXB(gem3/Blueprint).- Parameters:
input_bam (
str) – Path to an indexed BAM file.sample_size (
int) – Maximum number of reads to examine. Only primary, non-duplicate, non-QC-failed reads are considered.
- Return type:
str- Returns:
A human-readable string identifying the detected aligner, such as
"Bismark (XM tag)"or"Unknown".
Note
A BAM that cannot be opened at all (missing file or index) is reported as
"Unknown (could not open BAM)". An I/O error while opening or reading it (for exampleOSErrorfrom a truncated file) propagates to the caller, with the file handle closed.
- extract_methylation_data_from_bam(input_bam, genome_methylation_embedding, quality_limit=20, filter_non_converted=False, non_converted_threshold=3, filter_em_overconversion=False, em_overconversion_min_cpgs=3, threads=1, verbose=False, debug=False, min_base_quality=20, mask_3prime=0, keep_improper_pairs=False, allow_length_mismatch=False)¶
Extract per-fragment CpG methylation data from a BAM file.
Parses a bisulfite-sequencing or EM-seq BAM file and extracts methylation states at each CpG site covered by aligned reads. Returns a sparse matrix where each row represents one sequenced DNA fragment and each column represents a CpG site.
Rows are fragments. The two mates of a read pair come from the same molecule, so their calls are combined into a single row; a single-end read, or a read whose mate is unusable, is a row on its own. Where the mates overlap, a CpG they both cover is recorded once: the shared call if they agree, the available call if only one mate has one, and
-1if they disagree. Mates are combined when both pass the read filters and map to the same chromosome within 100 kb of each other; otherwise each is reported as its own fragment.- The function applies several filters to reads:
Mapping quality must be >= quality_limit (default 20)
Duplicate reads are excluded
QC-failed reads are excluded
Secondary and supplementary alignments are excluded
Unmapped reads are excluded (including unmapped mates placed at their mapped mate’s position)
Paired reads that are not flagged as a proper pair are excluded (unless
keep_improper_pairs); single-end reads are keptReads without a recognised strand tag are excluded
A call is kept only where it can be trusted; otherwise the CpG is recorded as
-1(the fragment covers it, but there is no usable call):Intact CpG. The read must show a CpG where the reference has one: the methylated or unmethylated base at the base that carries the call, and the reference base at the CpG’s other base (where the read covers it), with nothing inserted between them. A molecule carrying a CpG-destroying variant (CpG to TpG/CpA is the commonest human SNP) has no CpG to be methylated, and on one strand such a variant is indistinguishable from an unmethylated CpG unless the other base is checked.
Base quality. The base carrying the call must have a Phred quality of at least
min_base_quality(default 20; reads without base qualities are not filtered).3’ end masking (opt-in,
mask_3prime). End repair fills recessed 3’ ends with unmethylated cytosines before conversion, so CpGs near the 3’ end of a fragment’s original strand read as unmethylated whatever the molecule carried.mask_3prime=Ndiscards calls within N bases of that end.
- Two additional, opt-in filters are available:
Non-converted reads (
filter_non_converted): drops fragments in which a read has too many retained non-CpG cytosines, the hallmark of incomplete bisulfite/EM-seq conversion. Ports the per-read logic ofnebiolabs/mark-nonconverted-reads; because incomplete conversion affects the whole molecule, a read that fails takes its mate with it. For Biscuit/bwameth/gem3 reads this needs theMDtag; reads without one cannot be evaluated, are kept, and trigger aRuntimeWarningreporting how many were affected.EM-seq fragment-level over-conversion (
filter_em_overconversion): drops fragments whose CpG calls (across both mates) are all unmethylated, a heuristic for the EM-seq artifact described by Loyfer et al. (bioRxiv 2026.03.24.713040). CpGs without a usable call are left out of that decision.
Every read is decoded at the base that is informative for the strand its fragment derives from: the
Cof a CpG for a top-strand fragment, theGfor a bottom-strand fragment (BAM stores reads in top-strand orientation). This is independent of the read’s own alignment orientation, so both mates of a pair are used. Two tag dialects are supported, detected automatically per read:- Bismark (XM tag present):
Takes the fragment’s strand from the XG tag (CT = top, GA = bottom)
Uses binary search to find the CpGs whose informative base the read covers
Reads the XM call string there: Z=methylated(1), z=unmethylated(0), anything else=-1
- Biscuit/bwameth/gem3 (YD or XB tag):
Takes the fragment’s strand from the tag (YD f / XB C = top, YD r / XB G = bottom)
Uses binary search to find the CpGs whose informative base the read covers
Reads the base there: top strand C=methylated(1), T=unmethylated(0); bottom strand G=methylated(1), A=unmethylated(0); anything else=-1
In both dialects the intact-CpG, base-quality and 3’ end rules above are then applied from the read’s own bases and qualities, so the two give identical output for the same reads.
Strand-tag check. Decoding from bases relies on the strand tag being right. It is checked against the reads themselves: the base of a CpG that the tag says cannot be converted (the G for a top-strand read, the C for a bottom-strand read) is examined wherever a read covers it with sufficient base quality. If more than 2% of at least 1,000 such CpGs show the other strand’s conversion product, a
RuntimeWarningreports it. That pattern means many reads are mis-tagged — typically a non-directional library aligned by an aligner that assumes a directional one. In a mis-tagged read every unmethylated CpG fails the intact-CpG rule and is recorded as-1, so only methylated calls survive and methylation is overstated. Withverbose=Truethe counts are printed for every BAM.Reference check. The BAM must have been aligned to the reference the CpG index was built from. Chromosomes whose length in the BAM header differs from the reference raise a
ValueError(unlessallow_length_mismatch). Independently, if more than 10% of at least 1,000 decoded CpGs mismatch the reference in their read, aRuntimeWarningreports it: real data stays within a few percent, while a BAM decoded against the wrong reference fails at most CpGs. (CpGs whose only fault is the other strand’s conversion product at the CpG’s other base are left to the strand-tag check.)Filters that depend on the BAM’s own annotations. The proper-pair and base-quality filters trust the flag and the qualities in the BAM. If more than half of the otherwise usable reads are dropped as improper pairs, or more than half of the otherwise usable calls for low base quality (at least 1,000 in either case), a
RuntimeWarningsays so and names the option that turns the filter off.- Parameters:
input_bam (
str) – Path to the input BAM file. The file must be indexed (have a corresponding .bam.bai file).genome_methylation_embedding (
GenomeMethylationEmbedding) – A GenomeMethylationEmbedding object that defines the CpG site positions and provides coordinate conversion methods.quality_limit (
int) – Minimum mapping quality (MAPQ) threshold for reads. Reads with MAPQ below this value are skipped. Default is 20, which excludes reads mapping to multiple locations equally well.filter_non_converted (
bool) – If True, drop fragments in which a read carries at leastnon_converted_thresholdretained non-CpG cytosines, a signature of incomplete bisulfite/EM-seq conversion. Default False.non_converted_threshold (
int) – Minimum count of retained non-CpG cytosines required for the non-converted filter to drop a read. Matches the NEBmark-nonconverted-readsdefault of 3.filter_em_overconversion (
bool) – If True, drop fragments whose CpG calls are all unmethylated and number at leastem_overconversion_min_cpgs— the Loyfer et al. EM-seq fragment-level over-conversion heuristic. Default False.em_overconversion_min_cpgs (
int) – Minimum number of CpG calls required before the over-conversion filter will drop a fragment. Matches the regime in Loyfer et al. Fig. 1C where the EM-seq artifact is clearly separable from WGBS.threads (
int) – Number of worker processes to use, one chromosome per worker. Default 1 (in-process, no IPC overhead). Values above 1 fan out per-chromosome extraction across worker processes; output is bitwise-identical tothreads=1because per-chromosome results are concatenated incpg_sites_dictorder, whatever order the workers finish in. Each worker is sent only the CpG positions of the chromosome it is processing, not the whole embedding. Recommended: leave at 1 for small BAMs (worker startup dominates); set to the number of physical cores for whole-genome WGBS BAMs. Workers are started with thespawnmethod, so a script that passesthreads > 1must do so from underif __name__ == "__main__":(standardmultiprocessingpractice).verbose (
bool) – If True, display a progress bar and print the total read count. Useful for monitoring progress on large files.debug (
bool) – If True, print the calls decoded from every read and each filter decision. Significantly slower.min_base_quality (
int) – Minimum Phred base quality of the base that carries a CpG call. Calls on lower-quality bases are recorded as-1. Default 20; 0 disables the filter. Reads stored without base qualities are never filtered.mask_3prime (
int) – Number of bases at the 3’ end of each fragment’s original strand in which calls are recorded as-1, to remove the end-repair fill-in artifact. The end is the fragment’s right-hand end for a top-strand fragment and its left-hand end for a bottom-strand one, taken from the alignment of the mate that starts there; a read whose mate is not available estimates it from the template length, and a single-end read uses its own end. The distance is measured on the aligned fragment, so bases already trimmed from the reads before alignment are not counted. Default 0 (off).keep_improper_pairs (
bool) – If True, keep paired reads that are not flagged as a proper pair. Default False.allow_length_mismatch (
bool) – If True, do not require the chromosome lengths in the BAM header to match the reference. Only for a reference that is a deliberately truncated copy of the one the BAM was aligned to. Default False.
- Returns:
matrix: A scipy.sparse.coo_matrix with shape (n_fragments, n_cpg_sites) where n_fragments is the number of fragments that passed filters and covered at least one CpG site, n_cpg_sites is genome_methylation_embedding.total_cpg_sites, and values are: 1 (methylated), 0 (unmethylated), -1 (no data). Within a row, CpGs are in ascending column order. Values are stored as int64. The matrix uses COO format for efficient construction; convert to CSR (tocsr()) for row slicing or CSC (tocsc()) for column slicing.
tlen: A 1-D numpy int32 array of shape (n_fragments,) containing the length of each fragment (the absolute value of the BAM TLEN field). Values are 0 for single-end reads or reads with unmapped mates.
stats: A dict of counts describing what was decoded and what was discarded; see
ExtractionResult.
- Return type:
An ExtractionResult named tuple with three fields
- Raises:
FileNotFoundError – If the BAM file index (.bam.bai) is missing. The BAM file must be indexed with samtools index.
ValueError – If
threadsis less than 1, ormin_base_qualityormask_3primeis negative.
Example
>>> # xdoctest: +SKIP >>> from bam2tensor.embedding import GenomeMethylationEmbedding >>> from bam2tensor.functions import extract_methylation_data_from_bam >>> import scipy.sparse >>> >>> # Create embedding (or load from cache) >>> embedding = GenomeMethylationEmbedding( ... genome_name="hg38", ... expected_chromosomes=["chr1", "chr22"], ... fasta_source="GRCh38.fa", ... ) >>> >>> # Extract methylation data >>> result = extract_methylation_data_from_bam( ... input_bam="sample.bam", ... genome_methylation_embedding=embedding, ... quality_limit=30, # Stricter quality filter ... verbose=True, ... ) >>> >>> # Analyze results >>> print(f"Fragments with CpG data: {result.matrix.shape[0]:,}") >>> print(f"Total CpG sites: {result.matrix.shape[1]:,}") >>> print(f"Data points: {result.matrix.nnz:,}") >>> >>> # Save to file >>> scipy.sparse.save_npz("sample.methylation.npz", result.matrix)
Note
Rows are ordered by chromosome, in the order of the embedding’s
expected_chromosomes(the same order as the columns), and within a chromosome by where each fragment’s first CpG-covering read appears in the (coordinate-sorted) BAM.A
ValueErroralso propagates from the checks on the BAM header: no chromosome name in common with the reference, or a chromosome whose length differs from the reference.See also
GenomeMethylationEmbedding: For creating the genome embedding. scipy.sparse.coo_matrix: Documentation on the output format.
- is_em_overconversion_read(read_cpg_states, min_cpgs)¶
Identify reads flagged as EM-seq fragment-level over-conversion.
Loyfer et al. (bioRxiv 2026.03.24.713040) report that EM-seq produces a reproducible ~1–2.5% of multi-CpG fragments that appear fully unmethylated across every covered CpG, driven by failed TET protection and subsequent APOBEC hyper-conversion of an entire molecule. At constitutively methylated loci these reads are purely technical. Without a per-region methylation prior, the simplest correction consistent with their observation is: drop reads whose CpG calls are all unmethylated and number at least
min_cpgs(the paper’s Fig. 1C regime where the artifact diverges clearly from WGBS).CpGs without a usable call (
-1) are left out of the decision altogether: they are neither evidence of methylation nor counted towardsmin_cpgs. Otherwise a single low-quality base would shield an otherwise fully unmethylated fragment from the filter.This heuristic also drops genuinely fully-unmethylated biological fragments, so callers should opt in only when the downstream application can tolerate that trade-off.
- Parameters:
read_cpg_states (
list[int]) – Per-CpG methylation state values for a single read, in column-order, using the bam2tensor encoding (``1``=methylated, ``0``=unmethylated, ``-1``=no data).min_cpgs (
int) – Minimum number of CpG calls required to apply the filter. Reads with fewer calls are never flagged.
- Return type:
bool- Returns:
Truewhen the read has at leastmin_cpgsCpG calls and every one of them is unmethylated (value0).-1(no usable call) values are ignored.
Example
>>> is_em_overconversion_read([0, 0, 0], min_cpgs=3) True >>> is_em_overconversion_read([0, 0, 1], min_cpgs=3) False >>> is_em_overconversion_read([0, 0], min_cpgs=3) False >>> is_em_overconversion_read([0, 0, -1], min_cpgs=3) False >>> is_em_overconversion_read([0, 0, -1, 0], min_cpgs=3) True
bam2tensor.metadata module¶
Metadata utilities for bam2tensor .npz output files.
This module provides functions to embed and retrieve provenance metadata
inside the .methylation.npz files produced by bam2tensor. The metadata
is stored as a metadata.json entry appended to the ZIP archive that
underlies every .npz file. scipy.sparse.load_npz silently ignores
this extra entry, so existing downstream code is unaffected.
- Output format versions:
The
format_versionmetadata entry identifies how the matrix in a file is laid out, independently of the bam2tensor release that wrote it (seeOUTPUT_FORMAT_VERSION):2 — One row per sequenced DNA fragment (
"row_unit": "fragment"). The two mates of a read pair are combined into a single row, and every read is decoded on the base that carries its call, so both strands of every aligner dialect are represented.tlenholds the fragment length (absolute BAM TLEN). A value of-1means the fragment covers the CpG but there is no usable call: the read does not show an intact CpG there, the base carrying the call is below the minimum base quality, the CpG lies in the masked 3’ end of the fragment, or the two mates disagree. Rows follow the order ofexpected_chromosomes, as the columns do. Thefiltersandextraction_statsmetadata entries record the settings used and what they discarded.1 — Files with no
format_versionentry (releases up to and including 2.8). One row per read. For Bismark BAMs both mates were separate rows and calls from bottom-strand alignments were recorded as-1; for Biscuit, bwameth and gem3 BAMs only read 1 of each pair was used.tlenholds the signed BAM TLEN of each read.
Example
Writing metadata (done automatically by the CLI):
>>> # xdoctest: +SKIP
>>> from bam2tensor.metadata import write_npz_metadata, read_npz_metadata
>>> write_npz_metadata("sample.methylation.npz", {
... "bam2tensor_version": "2.2",
... "genome_name": "hg38",
... })
>>> read_npz_metadata("sample.methylation.npz")
{'bam2tensor_version': '2.2', 'genome_name': 'hg38'}
Reading metadata from an existing file:
>>> # xdoctest: +SKIP
>>> meta = read_npz_metadata("sample.methylation.npz")
>>> if meta is not None:
... print(meta["genome_name"])
hg38
- compute_cpg_index_crc32(embedding)¶
Compute a CRC32 checksum over the CpG site positions in an embedding.
The checksum captures the exact column mapping of the sparse matrix: which chromosomes are included, in what order, and which genomic positions are CpG sites within each chromosome. Two embeddings with the same checksum will produce identical column semantics.
The checksum is defined over the text
chrom pos1,pos2,..., one line per chromosome inexpected_chromosomesorder, joined by newlines. It is computed incrementally, one chromosome at a time, so the whole-genome text (hundreds of megabytes for a human reference) is never held in memory at once.- Parameters:
embedding (
GenomeMethylationEmbedding) – A fully initialised GenomeMethylationEmbedding whosecpg_sites_dictis populated.- Return type:
str- Returns:
The CRC32 checksum as an 8-character lowercase hexadecimal string.
Example
>>> # xdoctest: +SKIP >>> from bam2tensor.embedding import GenomeMethylationEmbedding >>> emb = GenomeMethylationEmbedding( ... genome_name="hg38", ... expected_chromosomes=["chr1"], ... fasta_source="ref.fa", ... ) >>> compute_cpg_index_crc32(emb) 'a1b2c3d4'
- compute_fasta_sha256(fasta_source)¶
Compute the SHA-256 of a FASTA file’s bytes on disk.
Used to stamp the CpG-site cache (see
bam2tensor.embedding.GenomeMethylationEmbedding) so a cache can be rejected when the underlying FASTA changes (e.g. a user swaps a soft-masked build for a hard-masked one).- Parameters:
fasta_source (
str) – Path to the reference FASTA file.- Return type:
str- Returns:
The hex-encoded SHA-256 digest of the file’s bytes.
- read_npz_metadata(npz_path)¶
Read the
metadata.jsonentry from a.npzfile.- Parameters:
npz_path (
str) – Path to the.npzfile.- Return type:
dict|None- Returns:
The metadata dictionary, or
Noneif the file does not contain ametadata.jsonentry (e.g. files produced by older versions).
Example
>>> # xdoctest: +SKIP >>> meta = read_npz_metadata("sample.methylation.npz") >>> meta["genome_name"] 'hg38'
- read_npz_tlen(npz_path)¶
Read the
tlen.npyentry from a.npzfile.- Parameters:
npz_path (
str) – Path to the.npzfile.- Return type:
ndarray|None- Returns:
The template-length array (one entry per matrix row), or
Noneif the file does not contain atlen.npyentry (e.g. files produced by older versions). In format version 2 files the values are fragment lengths (non-negative); in earlier files they are the signed BAM TLEN of each read.
Example
>>> # xdoctest: +SKIP >>> tlen = read_npz_tlen("sample.methylation.npz") >>> if tlen is not None: ... print(f"Median fragment length: {np.median(np.abs(tlen)):.0f}")
- write_npz_metadata(npz_path, metadata)¶
Append a
metadata.jsonentry to an existing.npzfile.The metadata is serialised as compact JSON and appended to the ZIP archive.
scipy.sparse.load_npzignores unrecognised entries, so the file remains fully compatible with existing code.- Parameters:
npz_path (
str) – Path to the.npzfile (must already exist).metadata (
dict) – A JSON-serialisable dictionary of metadata to embed.
- Return type:
None
Example
>>> # xdoctest: +SKIP >>> write_npz_metadata("out.npz", {"genome_name": "hg38"})
- write_npz_tlen(npz_path, tlen)¶
Append a
tlen.npyentry to an existing.npzfile.The array is serialised with
numpy.save()and appended to the ZIP archive.scipy.sparse.load_npzignores this extra entry, so the file remains compatible with existing sparse-matrix code.- Parameters:
npz_path (
str) – Path to the.npzfile (must already exist).tlen (
ndarray) – A 1-D numpy array of template lengths, one per matrix row.
- Return type:
None
Example
>>> # xdoctest: +SKIP >>> write_npz_tlen("out.npz", np.array([300, -300, 0], dtype=np.int32))
bam2tensor.reference module¶
Reference genome download and caching utilities.
Provides functionality to download and cache reference genome FASTA files from well-known sources (UCSC, NCBI) for common genomes like hg38, hg19, mm10, and T2T-CHM13. This avoids the need for users to manually locate and download reference FASTAs.
Example
>>> # xdoctest: +SKIP
>>> from bam2tensor.reference import download_reference, list_available_genomes
>>>
>>> # See what genomes are available
>>> genomes = list_available_genomes()
>>> for name, info in genomes.items():
... print(f"{name}: {info['description']}")
>>>
>>> # Download hg38
>>> fasta_path = download_reference("hg38", verbose=True)
>>> print(f"Reference saved to: {fasta_path}")
- download_reference(genome_name, verbose=False)¶
Download and cache a reference genome FASTA file.
Downloads a gzipped FASTA file from a well-known source (UCSC or NCBI), decompresses it, and stores it in the bam2tensor cache directory. If the genome has already been downloaded, returns the path to the cached file without re-downloading.
The download and decompression happen in temporary files next to the final location; the FASTA only appears under its final name once it has been fully decompressed and validated. An interrupted or failed download therefore never leaves a partial file that a later run would mistake for a complete cached genome.
- Parameters:
genome_name (
str) – The genome identifier to download. Must be one of the keys in KNOWN_GENOMES (e.g., “hg38”, “hg19”, “mm10”, “T2T-CHM13”).verbose (
bool) – If True, display download progress and status messages.
- Return type:
Path- Returns:
Path to the decompressed reference FASTA file in the cache directory.
- Raises:
ValueError – If genome_name is not a recognized genome in KNOWN_GENOMES.
OSError – If the downloaded file is truncated, corrupt, or does not look like a FASTA.
Example
>>> # xdoctest: +SKIP >>> fasta_path = download_reference("hg38", verbose=True) Downloading Human GRCh38/hg38 (UCSC)... >>> print(fasta_path) /home/user/.cache/bam2tensor/hg38/hg38.fa
- get_cache_dir()¶
Get the bam2tensor cache directory for downloaded references.
Returns the platform-appropriate cache directory, creating it if it does not already exist. Uses
~/.cache/bam2tensorby default, or respects theXDG_CACHE_HOMEenvironment variable on Linux/macOS.- Return type:
Path- Returns:
Path to the bam2tensor cache directory. The directory is created if it does not exist.
Example
>>> # xdoctest: +SKIP >>> cache_dir = get_cache_dir() >>> print(cache_dir) /home/user/.cache/bam2tensor
- get_cached_reference(genome_name)¶
Check if a reference genome FASTA is already cached locally.
Looks for a previously downloaded and decompressed FASTA file in the bam2tensor cache directory.
- Parameters:
genome_name (
str) – The genome identifier (e.g., “hg38”, “mm10”). Must be a key in KNOWN_GENOMES.- Return type:
Path|None- Returns:
Path to the cached FASTA file if it exists, or None if the genome has not been downloaded yet.
Example
>>> # xdoctest: +SKIP >>> path = get_cached_reference("hg38") >>> if path: ... print(f"Found cached reference: {path}") ... else: ... print("Not cached yet")
- list_available_genomes()¶
List all known genome references available for download.
Returns the dictionary of genomes that can be downloaded using download_reference(), along with their descriptions and URLs.
- Return type:
dict[str,dict[str,str]]- Returns:
A dictionary mapping genome names to their metadata. Each value is a dict with keys ‘url’, ‘description’, and ‘expected_chromosomes’.
Example
>>> genomes = list_available_genomes() >>> "hg38" in genomes True >>> "description" in genomes["hg38"] True