Skip to content

Read bigWigs as signal and control channels in the loader — Closes #30 - #31

Draft
conradbzura wants to merge 14 commits into
mainfrom
30-read-bigwig-channels
Draft

conradbzura wants to merge 14 commits into
mainfrom
30-read-bigwig-channels

Conversation

@conradbzura

@conradbzura conradbzura commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

A caller who already holds bigWigs, from ENCODE or from cherimoya pipeline's figwig bam2bw, could not use quadrat's loader: require_complete refused a bigWig by its first bytes. This PR makes a bigWig a channel anywhere a track is one. build_training_loader, extract_loci, extract_signal, group_track, window_group_sums and TrackStore take a bigWig as a signal or a control: alone, in a group, beside tracks, or beside piled-up Alignments.

Before After
signals=["s.bw"] refused: "is not a track … does not begin as a Parquet file does" signals=["s.bw"] read through figwig, only over the windows, into the same window cache a track is grouped into
Signal made elsewhere had to be piled up again from the BAMs A bigWig trains as it is, and reaches every batch byte for byte as cherimoya's PeakGenerator reads it

A bigWig is a third kind of track beside counts and coverage deltas. Every reader of values already branches on a track's kind, so the change adds one branch to each reader and none to the loader's control flow. The sampler, the dataset, the window cache's layout and the batches are unchanged.

Stacked on #29, which is stacked on #26. This branch is cut from 28-managed-pileup, and it targets main so CI runs, since the workflow runs only on pull requests into main. Until #26 and #29 merge, the diff also shows their eleven commits. This PR's own commits are the last three. Merge #26, then #29, then this.

Closes #30

Proposed changes

figwig as a declared dependency (pyproject.toml)

The issue asked for a choice between pybigtools and pyBigWig as an optional extra. This uses neither: it uses figwig. tangermeme 1.6, already a base dependency, depends on figwig, so no install gains a package, and an extra would gate nothing. figwig is also the reader tangermeme.io.extract_loci uses, which is what PeakGenerator reads through, so quadrat and cherimoya produce a window's values with the same code. It is declared directly (figwig>=0.1) because quadrat now imports it, and imported only on first use, so import quadrat, and a build from tracks alone, load none of it. tests/test_quadrat.py pins that guarantee. The pyproject.toml comment records the choice.

A bigWig as a kind of track (quadrat.tables, quadrat.stores)

  • Detection is by content, the little-endian bigWig magic 26 FC 8F 88, where the Parquet magic is tested today. track_signal answers (BIGWIG, None), a format tag every reader dispatches on before it reads a value. A big-endian bigWig, which figwig does not read, is refused with a sentence naming UCSC's bigWigToBedGraph and bedGraphToBigWig as the remedy.
  • Contigs, from the data index: track_contigs answers the contigs that hold data, as criterion Port the stores and the sparse window cache #4 asks, not every contig the chromosome tree names. On the ENCODE bigWigs of the benchmark, the tree names all 455 contigs of the assembly while data sits on 70 to 193 of them. The parser in quadrat.tables reads the header, the chromosome B+ tree and the leaves of the data index's R-tree with struct and numpy, from the published format, and maps each leaf's contig id to its name: about 5 ms for a 45 MB file. figwig exposes no public answer to "which contigs hold data", which is why it is parsed here. A bigWig holding no interval has no data index and answers no contig, so require_track_contigs refuses it as it refuses an empty track.
  • What opening refuses: every index figwig's reader refuses, checked before any value is read: a header cut short, a file cut short before its index, a tree that reaches a node twice, a chromosome tree whose values are not eight bytes, a data block spanning two contigs or lying past the end of the file, blocks out of order or ending before they start, a tree's missing magic number, and, beyond what figwig checks, a contig id the chromosome tree does not name and a chromosome tree whose keys are of no bytes. Every read is checked against the file's size before it is made, and the nodes together may hold no more than the file, so a corrupt size is refused rather than allocated and a hostile file cannot make the walk long. require_complete runs the same walk, so a file it passes is one figwig reads.
  • Opening: stores.open_track (renamed from track_frame) answers (reader, signal, scale), where the reader is a LazyFrame for a table, a figwig.BigWigReader for a bigWig, or None for a bigWig holding no data, which every reader reads as zeros.
  • TrackStore: it verifies a bigWig once at construction and reads a window with a per-process reader. It pads a window that starts before base 0, and reads zeros on a contig the file does not name. Each window costs a figwig read, whose time grows with the file's whole index, as bigwig_windows' docstring states. The loader does not read through TrackStore.

Grouping and totals (quadrat.cache)

  • One reader of values: stores.bigwig_windows reads a contig's windows in chunks of one width each, since figwig reads one width per call and a peak and a negative differ by twice the jitter margin. A chunk holds at most 64 MiB of dense float32, or one window where a window is wider. TrackStore.window, group_track and window_group_sums all read through it.
  • Cleaning values: NaN reads as zero and an infinity is clamped by numpy.nan_to_num, as tangermeme cleans the same read. Every base whose value has any bit set becomes a site, so a -0.0 survives the sparse round trip and scatters back to the bytes a dense read holds.
  • Windows before base 0: a window starting before base 0, which figwig refuses, is read from base 0 and its own row shifted in place.
  • Channels in parallel: a build reads up to 8 bigWig channels at once on a thread pool, each with up to 8 figwig threads, never more threads in all than the process's CPUs. The pool lives for the whole contig loop. Results are folded in a fixed order, so the cache's bytes do not depend on which thread finishes first.
  • Cost: a bigWig costs a row per non-zero base of every window. A bigWig of 5′ counts is as sparse as the counts track of the same reads. One of coverage or fold-change is dense in its windows, bounded like a coverage-deltas channel at windows × width × 10 bytes a channel. Reading also holds a transient: up to 8 channels at once, each with a chunk, typically 64 MiB, a quarter-size mask and figwig's buffers, about 64 MiB at ENCODE's 32 KiB blocks, so typically about 1.1 GiB in all, plus 26 bytes a site while sites are found, about 3.3 GiB across 8 dense channels. Each figwig read scans the file's whole index, and a set of windows costs one read per contig, distinct width and chunk. group_track's docstring states the cost, and bigwig_windows' the reads.
  • No pileup extra needed for bigWigs alone: the SQL that joins counts is transpiled only when a channel of counts is present, so grouping bigWigs, alone or with coverage deltas, imports neither giql nor polars_bio, given a reference that is indexed or can be.
  • Totals: window_group_sums totals a bigWig over the same chunks in float64, so the count filters and the outlier mask read it as group_track does.

The cache key (quadrat.cache)

A single file, a Parquet table or a bigWig, is now keyed by its path and its stat. This is a fix of its own (b6476b2): a single-file Parquet track was keyed by its path alone before, so one rewritten in place was read through the entry grouped from its old rows.

n_cpus moves to quadrat._engine

The thread pool sizes itself as the pileup does, so n_cpus moved from quadrat.pileup.plan into quadrat._engine, where both import it. quadrat.cache therefore does not import the pileup subpackage.

Verified on js031

  • Suite: the full suite passes on Linux at aaa7cf3, and CI passes on Python 3.11 to 3.14.
  • Byte-identity: given cherimoya's own bigWig of ENCSR483RKN (K562 ATAC), quadrat's loader produced batches byte-identical to upstream cherimoya PeakGenerator at 5729b57. The parity harness checks the per-locus arrays (L2), both epochs' sampling plans (L3), and all 212,662 samples of X, y and label (L4). It passed at every review round, last at aaa7cf3. In the suite, test_extract_loci_should_match_tangermeme_over_the_same_bigwig checks the same against tangermeme's extract_loci.
  • Benchmark at aaa7cf3: one bigWig per BAM of a mixed-assay corpus, from figwig bam2bw; the same BAMs piled up as quadrat's own tracks. Medians of 3. A build is cold: the loader made from its inputs with no window-cache entry, the tracks already piled up and the pileup not counted (a warm build, which finds its entry, takes 0.05–0.15 s). Memory is peak PSS over the process tree; iteration is 2 epochs; the iteration peak is with 4 workers.
Channels Input Build Build CPU Build peak Iterate, 1 worker Iterate, 4 workers Iterate peak
1 cherimoya, bigWigs 0.71 s 7.3 s 3.8 GB 3.8 s 1.9 s 3.2 GB
1 quadrat, its own tracks 3.09 s 48 s 1.7 GB 5.7 s 1.9 s 2.3 GB
1 quadrat, bigWigs 2.13 s 9.4 s 1.1 GB 5.5 s 1.5 s 1.4 GB
10 cherimoya, bigWigs 4.59 s 32 s 11.1 GB 7.9 s 4.8 s 10.2 GB
10 quadrat, its own tracks 26.0 s 233 s 6.7 GB 7.4 s 2.5 s 7.2 GB
10 quadrat, bigWigs 5.04 s 27 s 2.9 GB 7.0 s 2.2 s 3.3 GB
36 cherimoya, bigWigs 15.2 s 101 s 32.0 GB 26.5 s 12.1 s 29.2 GB
36 quadrat, its own tracks 74.5 s 729 s 15.1 GB 15.1 s 4.5 s 13.3 GB
36 quadrat, bigWigs 11.6 s 66 s 5.4 GB 12.8 s 3.5 s 4.8 GB

Read from bigWigs, quadrat builds at 36 channels in three quarters of cherimoya's wall time, on two thirds of its CPU and a sixth of its memory, and iterates with 4 workers in under a third of its time (with 1 worker, in under half) on a sixth of its memory. Against its own tracks, it builds in less than a sixth of the wall time and about a third of the memory. At 1 channel cherimoya builds faster, 0.7 s against 2.1 s, but quadrat's build grows more slowly with channels, by 9.5 s from 1 to 36 against cherimoya's 14.5 s, and overtakes it between 10 and 36 channels. Before the thread pool, the same 36 channels built in 60.3 s on about 1.5 cores.

Decisions for the owner

  • figwig, not pybigtools or pyBigWig, and as a base dependency, not an extra. The reasons are above. Revisit if figwig's packaging, or numba's, which it needs, ever leaves a supported Python without wheels.
  • The thread budget is the library's. 8 channels at once and 8 figwig threads each, capped by the process's CPU affinity. Pre-1.0, a parameter can come later if a caller needs one.
  • Recorded, not fixed here: window_group_sums totals a track window as the difference of two float64 prefix sums. A value far smaller than one before it cancels: 2.0 then 2.2e-16 totals 0.0 over the second base alone. Its docstring calls the arithmetic exact. The bigWig path sums each window directly and does not cancel. It predates this PR, so it is ledgered rather than fixed.

Test cases

# Test Suite Given When Then Coverage Target
1 test_tables A bigWig under .bw or under no suffix; a directory holding one require_complete Returns the path; refuses the directory as no track Detection by content
2 test_tables A bigWig; a big-endian bigWig; an empty file track_signal (BIGWIG, None); refuses, naming the UCSC remedy only for the big-endian file Kind and refusal
3 test_tables A bigWig whose chromosome tree names a contig it holds no data on; one holding no data; any set of up to 400 contig names with data on any subset track_contigs Only the contigs holding data; no contig; exactly the subset Contigs from the data index, and a property
4 test_tables An index of 300 contigs; a hand-nested two-level chromosome tree track_contigs Each root is an inner node, and every contig is named Branch walks of both trees
5 test_tables A tree, either one, that reaches a node twice; a block spanning two contigs or past the end; blocks out of order; blocks whose starts or ends go backwards, or a block ending before it starts or larger than the file; a chromosome tree's value size, key size or item count corrupt; overlapping index nodes; a missing tree magic number; a header cut short; a file cut before its index or shrinking while read; a leaf naming a contig the tree does not; any bytes written over the header or trees require_complete, track_contigs ValueError naming the file and the defect Refusals on opening
6 test_stores A bigWig; one cut before its index, with blocks out of order, or with a block past the end; one holding no data open_track, TrackStore() A figwig reader; ValueError on opening; None Opening
7 test_stores Windows of two widths, interleaved; empty, before-0 and absent-contig windows; no reader bigwig_windows Chunks of one width holding each window's values; nothing The one reader of values
8 TestTrackStore A bigWig of runs and single bases; NaN; past a contig's end; a contig it does not name, warnings as errors window Each base's value; zeros, and no warning Base-resolution read
9 TestTrackStore A window from base -3; an empty span; a bigWig beside a track window Zeros before 0, equal to the track; shape (1, 0); each read as its own kind Window bounds, mixed channels
10 TestTrackStore A store pickled after a read window again Opens its own reader, once; same values Per-process reader
11 TestTrackStore Any non-zero float32 values at any bases window over any span Equals the values written Property
12 test_cache A bigWig and the track of its values; windows of two widths past both ends group_track, window_group_sums Identical arrays and totals Grouping oracle
13 test_cache Any values in runs of any length; windows from -50 to 1,100 in two widths group_track, window_group_sums Identical to the track's arrays; equal to the dense values summed in float64; densifies to the values written Properties
14 test_cache Windows of 2^24+1 bases on a 2^25 contig, one from -3 group_track, window_group_sums Equal to the track's Several chunks, shift in a chunk
15 test_cache Empty, before-0, repeated and absent-contig windows; an empty bigWig group_track, window_group_sums Equal to the track's; nothing at all Skipped windows
16 test_cache A bigWig written with -0.0, 0.0 and 1.0 group_track -0.0 and 1.0 are sites, 0.0 is not Bit test
17 test_cache A bigWig grouped with tracks either way round; a bigWig beside a track window_group_sums, group_track Each group totals its members; channels kept apart Mixed groups
18 test_cache A single Parquet file or a bigWig, touched in place window_cache_key The key moves Stat keying
19 test_loci A bigWig on 1, 2 and windows on chr1; one holding nothing on them; one on chr2 require_track_contigs Refuses with the new wording, twice; passes Contig check
20 test_loci One bigWig given to both packages, with and without jitter extract_loci against tangermeme Identical sequences, signal and mask Byte-identity with tangermeme
21 test_loci A bigWig, in an interpreter where giql and polars_bio will not import extract_signal Raises nothing bigWigs need no pileup extra
22 test_loci Bigwigs and tracks of the same values, with controls and a floor; a track then a bigWig, target_idx 1 or -1 extract_loci, extract_signal Identical output; keeps what the bigWig alone keeps Signal, control, count
23 test_loader Five bigWigs grouped 1+2 and a control pair, with and without a cache build_training_loader, two epochs Batches equal those from the tracks Loader end to end
24 test_loader A group mixing a bigWig and a track; an unstranded Alignments and a bigWig build_training_loader Batches equal the all-track build; batches equal those of the same bigWig beside the pooled track the Alignments pile up into Mixed groups
25 test_loader bigWig signals built twice; then one touched build_training_loader, verbose Reuses the entry; misses it Cache hit and miss
26 test_loader A bigWig control on other contig names build_training_loader Refuses, naming controls, with no entry written Control contig check
27 test_loader The golden corpus's channels written as bigWigs, under each golden configuration build_training_loader, two epochs Batch digests equal those recorded from upstream PeakGenerator Byte-identity in the suite (criterion #6)
28 test_cache Three bigWigs of 1e16, -1e16 and 1 in one group, on 1 CPU and on 16; three with the second's block zeroed window_group_sums Totals 1 either way; ValueError naming the second file The channel pool's order and failure
29 test_stores A reader answering ±inf and NaN bigwig_windows The largest finite float32 of each sign, and zero Cleaning as tangermeme cleans
30 test_builders The bigWig builders, and the ones that rewrite a bigWig's trees Each one Writes what a reader reads back, missing deciding a zero interval's fate; changes exactly the node or field it names The suite's oracles
31 test_quadrat figwig made unimportable; a fresh interpreter stores.open_track on a bigWig; import quadrat ImportError naming figwig and no extra; figwig never imported Import guarantee

The integer rule, any numbers.Integral but a bool, was written inline
in require_index and again in the Jitter, Exclusion and Aggregate field
checks. It now lives once in quadrat._engine, the lowest layer, so
require_index, those fields, and the sampler and loader arguments that
follow all refuse the same values in the same words.

A plain int is answered before the ABC test, which costs several times
the call on the per-draw epoch path; bool is a subclass and fails it.

as_jitter and validate_signal_groups keep their own checks, whose
messages name what require_integer cannot: the Jitter alternative, and
the whole group specification.
PeakNegativeMixSampler(True, True) built a sampler over one peak and
one negative, set_epoch(True) set epoch 1, RechunkedLoader read True as
a batch of one, and in_window=True built one-base windows, because each
normalised through int() or not at all, which admits a bool and
truncates a float.

Every integer argument of both samplers and their validate_arguments,
RechunkedLoader, auto_fetch_size and build_training_loader, and the
window widths load_windows and LocusDataset take, now goes through
require_integer and raises TypeError naming the argument.
build_training_loader makes these refusals before anything is read; a
float fetch_size is now a TypeError where it was a ValueError. Both
validate_arguments answer the values they normalised, and
auto_fetch_size still takes the prefetch_factor of None a loader
without workers holds.

require_index now always takes the row count; the one caller that used
it as a bare integer check, the dataset's epoch, calls require_integer.
LocusDataset bounded a draw by its two window frames and never by the
cache it reads, so a cache over more windows answered another window's
signal for every draw, and one over fewer failed only at the first read
past its end. WindowSignalCache now answers n_windows from the counts
array_meta recorded, or counts its arrays where it has none, and the
dataset refuses a missing signal cache, and a signal or control cache
whose count is not the frames' rows combined, as it already refuses a
sampler of the wrong size. The caches and widths are read-only
attributes, so nothing checked at construction can be bypassed by
assigning another.

A cache over other windows of the same count still passes; no count
can tell it apart.
load_windows raised FileNotFoundError for a missing reference, while
SequenceStore, and so extract_sequences and extract_loci, raised
pyfaidx's FastaNotFoundError, and chrom_lengths fell through to a scan
that failed in the engine's words. Both types are OSError, but a
caller handling one missed the other.

The refusal now lives in reference.require_reference, which
chrom_lengths and SequenceStore call before opening the file, so every
entry point, the pileups included, raises FileNotFoundError in the same
words. A path running through a file counts as missing; one that
cannot be examined raises OSError, and a reference that exists but
cannot be opened still raises pyfaidx's error. chrom_lengths is where
the published docs state this, and every other reader points there.
A bigWig or any other file given as a track passed require_complete,
track_frame, track_contigs and TrackStore, and failed later in polars'
words, naming no file. The port had dropped upstream's suffix test on
purpose, since a single-file table need carry no suffix. track_signal,
the one verifier of a track, now reads the four bytes every Parquet
file begins with and refuses a file without them with a ValueError
naming the path and saying what a track is; track_frame and
track_contigs consult it for a single file as for a directory. A
directory neither named as a track nor holding any Parquet is refused
in the same words, rather than told to pile up again.

Each entry point's refusal of a missing track is unchanged.
extract_loci(signals=[]) answered zero-channel signal tensors, and its
default target_idx of 0 then named no track without raising. An empty
signals or controls list is now refused with a ValueError saying to
pass None to read none; zero channels mean nothing to either.
Exclusion(Exclusion(...)) was refused with a message saying to list
both, but Exclusion([Exclusion(...), "b.bed"]) passed construction and
failed later when the regions were read. An Exclusion anywhere in a
list or tuple of regions now gets the top-level refusal.
_has_bam_index answered a bool, and a key over an alignment needs the
index's path to stat it. bam_index_path answers that path, or None,
with the same two htslib spellings counted and a CSI still not, the
.bam.bai spelling first where both exist. warn_unindexed_split reads
it as the bool it read before.
…ctories in one place

default_cache_dir takes a kind, "windows" or "tracks", each a directory
of its own under the one root QUADRAT_CACHE_DIR or the XDG convention
decides, and states that nothing reclaims either. make_scratch_dir is
the scratch-directory creation WindowSignalCache.from_arrays did
inline, QUADRAT_SCRATCH_DIR included, so a second caller makes its
scratch directory where the first does.
window_cache_key indexed and hashed the reference inline, and
_hash_track stamped each Parquet file inline. hash_reference and
file_stamp hold the two, with the reference's contract and the reasons
for it moving to hash_reference, so a second key folds the same inputs
the same way. The bytes folded in are unchanged, so every existing
window entry keeps its key.
build_training_loader accepts a quadrat.managed.Alignments, one or more
BAM or SAM paths and an Aggregate, wherever it accepts a track, in
signals and in controls. Each is piled up with pileup_alignments into an
entry under track_dir, keyed by alignments_key, or found there from an
earlier call, and is then read as the tracks it piled up into. A
stranded aggregate makes two channels and is a group of its own; one
inside a larger group is refused before anything is piled up, for
signals and controls alike, since a mirror would reverse the whole
group. Alignments cannot be subclassed.

The key holds the package version, MANIFEST_VERSION, each alignment's
absolute path and file_stamp, each index's file_stamp or its absence,
every field of the aggregate, and the reference through hash_reference.
An entry is staged and committed as a window entry is, so it is never
complete before every track is written. A complete entry is answered
without a lock; on a miss an flock on a sibling lock file serialises
callers, so ranks of one job sharing a directory pile it up once. The
entry is keyed by the alignments and not the windows, so changing the
geometry, the exclusions, the filters or the loci regroups the tracks
and piles nothing up again.

track_dir is a directory, or None for default_cache_dir("tracks"), or
for a scratch directory removed before the loader returns where
cache_dir is False. False is refused: scratch tracks under a persisted
window cache would key a window entry nothing could hit again.

The Aggregate test strategy moves to tests/__init__.py, shared by the
aggregate and managed tests.

Closes #28
@conradbzura conradbzura self-assigned this Nov 30, 2026
conradbzura added a commit that referenced this pull request Nov 30, 2026
Round 1 of the PR #31 review: B1-B6, A1-A12, A15, and the notes A13
and A14 asked for.
conradbzura added a commit that referenced this pull request Nov 30, 2026
Round 2 of the PR #31 review: B8-B12, A14, A16-A35.
conradbzura added a commit that referenced this pull request Nov 30, 2026
conradbzura added a commit that referenced this pull request Nov 30, 2026
Round 3 of the PR #31 review: A28, B13-B16, A14, A17, A25, A36-A52.
conradbzura added a commit that referenced this pull request Nov 30, 2026
Docs/qa review round 1 of PR #31: B1-B14, A1-A24.
conradbzura added a commit that referenced this pull request Nov 30, 2026
Docs/qa review round 2 of PR #31: B1, B8, B15-B22, A1-A48.
tangermeme already depends on it, so nothing new is installed. It is
named because quadrat is about to import it directly, and a dependency
of a dependency can be dropped without notice.
A single Parquet file has no record and no per-contig files, so the
window cache key folded in only its path: a file rewritten in place
kept its key, and a build would read the entry grouped from the old
rows. It is now keyed by its path, size and modification time, as each
file of a track directory already is.
A track now takes one of two forms: a table, or a bigWig, told by its
first four bytes and read through figwig. The loader, extract_loci,
extract_signal, group_track, window_group_sums and TrackStore take a
bigWig as a signal or a control, alone, in a group, or beside tables
and piled-up alignments.

A bigWig's contigs are the ones its data index holds a block on, read
by a parser of the header, the chromosome tree and the index that
checks every rule figwig's reader checks, and refuses a corrupt size
before allocating it, so a file require_complete passes, and opening
accepts, is one figwig reads rather than one that fails mid-build.

Grouping reads only the windows, a contig and a width at a time, in
chunks of at most 64 MiB of dense float32 or one window where a window
is wider, and keeps every base whose value has any bit set, so a
window scatters back to the bytes a dense read holds. NaN reads as
zero and an infinity is clamped, as tangermeme's extract_loci makes
them, so quadrat and cherimoya read the same bigWig to identical
batches. Up to eight bigWig channels are read at once on a thread
pool and folded in channel order. A window before a contig's first
base is padded with zeros, and a contig the file does not name reads
as zeros, as does a bigWig holding no interval. Grouping bigWigs and
coverage deltas needs nothing the pileup extra installs.

A big-endian bigWig, which figwig does not read, is refused with the
UCSC tools that convert one. n_cpus moves from quadrat.pileup.plan to
quadrat._engine, where the window cache's pool and the planner both
read it.
@conradbzura
conradbzura force-pushed the 30-read-bigwig-channels branch from e53d80f to aaa7cf3 Compare November 30, 2026 19:09
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.

Read bigWigs as signal and control channels in the loader

1 participant