Repository navigation
Read bigWigs as signal and control channels in the loader — Closes #30 - #31
Draft
conradbzura wants to merge 14 commits into
Draft
conradbzura wants to merge 14 commits into
conradbzura wants to merge 14 commits into
Conversation
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
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
Round 3 of the PR #31 review: A40.
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
force-pushed
the
30-read-bigwig-channels
branch
from
November 30, 2026 19:09
e53d80f to
aaa7cf3
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
A caller who already holds bigWigs, from ENCODE or from
cherimoya pipeline'sfigwig bam2bw, could not use quadrat's loader:require_completerefused 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_sumsandTrackStoretake a bigWig as a signal or a control: alone, in a group, beside tracks, or beside piled-upAlignments.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 intoPeakGeneratorreads itA 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 targetsmainso CI runs, since the workflow runs only on pull requests intomain. 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
pybigtoolsandpyBigWigas 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 readertangermeme.io.extract_lociuses, which is whatPeakGeneratorreads 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, soimport quadrat, and a build from tracks alone, load none of it.tests/test_quadrat.pypins that guarantee. Thepyproject.tomlcomment records the choice.A bigWig as a kind of track (
quadrat.tables,quadrat.stores)26 FC 8F 88, where the Parquet magic is tested today.track_signalanswers(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'sbigWigToBedGraphandbedGraphToBigWigas the remedy.track_contigsanswers 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 inquadrat.tablesreads the header, the chromosome B+ tree and the leaves of the data index's R-tree withstructand 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, sorequire_track_contigsrefuses it as it refuses an empty track.require_completeruns the same walk, so a file it passes is one figwig reads.stores.open_track(renamed fromtrack_frame) answers(reader, signal, scale), where the reader is aLazyFramefor a table, afigwig.BigWigReaderfor a bigWig, orNonefor 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, asbigwig_windows' docstring states. The loader does not read throughTrackStore.Grouping and totals (
quadrat.cache)stores.bigwig_windowsreads 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 densefloat32, or one window where a window is wider.TrackStore.window,group_trackandwindow_group_sumsall read through it.numpy.nan_to_num, as tangermeme cleans the same read. Every base whose value has any bit set becomes a site, so a-0.0survives the sparse round trip and scatters back to the bytes a dense read holds.group_track's docstring states the cost, andbigwig_windows' the reads.pileupextra 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.window_group_sumstotals a bigWig over the same chunks infloat64, so the count filters and the outlier mask read it asgroup_trackdoes.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_cpusmoves toquadrat._engineThe thread pool sizes itself as the pileup does, so
n_cpusmoved fromquadrat.pileup.planintoquadrat._engine, where both import it.quadrat.cachetherefore does not import the pileup subpackage.Verified on js031
aaa7cf3, and CI passes on Python 3.11 to 3.14.PeakGeneratorat5729b57. 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 ataaa7cf3. In the suite,test_extract_loci_should_match_tangermeme_over_the_same_bigwigchecks the same against tangermeme'sextract_loci.aaa7cf3: one bigWig per BAM of a mixed-assay corpus, from figwigbam2bw; 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.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
pybigtoolsorpyBigWig, 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.window_group_sumstotals a track window as the difference of twofloat64prefix 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_tables.bwor under no suffix; a directory holding onerequire_completetest_tablestrack_signal(BIGWIG, None); refuses, naming the UCSC remedy only for the big-endian filetest_tablestrack_contigstest_tablestrack_contigstest_tablesrequire_complete,track_contigsValueErrornaming the file and the defecttest_storesopen_track,TrackStore()ValueErroron opening;Nonetest_storesbigwig_windowsTestTrackStorewindowTestTrackStorewindow(1, 0); each read as its own kindTestTrackStorewindowagainTestTrackStorefloat32values at any baseswindowover any spantest_cachegroup_track,window_group_sumstest_cachegroup_track,window_group_sumsfloat64; densifies to the values writtentest_cachegroup_track,window_group_sumstest_cachegroup_track,window_group_sumstest_cache-0.0,0.0and1.0group_track-0.0and1.0are sites,0.0is nottest_cachewindow_group_sums,group_tracktest_cachewindow_cache_keytest_loci1,2and windows onchr1; one holding nothing on them; one onchr2require_track_contigstest_lociextract_lociagainst tangermemetest_lociextract_signalpileupextratest_locitarget_idx1 or -1extract_loci,extract_signaltest_loaderbuild_training_loader, two epochstest_loaderAlignmentsand a bigWigbuild_training_loaderAlignmentspile up intotest_loaderbuild_training_loader, verbosetest_loaderbuild_training_loadercontrols, with no entry writtentest_loaderbuild_training_loader, two epochsPeakGeneratortest_cachewindow_group_sumsValueErrornaming the second filetest_storesbigwig_windowsfloat32of each sign, and zerotest_buildersmissingdeciding a zero interval's fate; changes exactly the node or field it namestest_quadratstores.open_trackon a bigWig;import quadratImportErrornaming figwig and no extra; figwig never imported