Repository navigation
Give HaplotypeMatrix a ploidy, and write and read haploid stores - #445
Merged
Merged
Conversation
HaplotypeMatrix.ploidy is the number of rows per sample, 1 or 2 (the default). to_zarr writes the store with it; it used to pair rows 2i and 2i + 1 whatever the matrix held, so an odd row count failed with a broadcast error and haploid rows were joined into false diploids. from_zarr reads a store with a ploidy axis of 1 into a ploidy-1 matrix, on the eager path, the host streaming path and the kvikio decoder. from_ts gives ploidy 1 for a tree sequence with no individuals or with one sample node per individual, and takes ploidy= to declare the layout. The consumers that group adjacent rows into individuals raise on a ploidy-1 matrix: GenotypeMatrix.from_haplotype_matrix, heterozygosity_observed and fst_weir_cockerham, scalar and windowed. A ploidy-1 matrix always counts as phased. A population subset whose rows do not make whole individuals has ploidy 1. The store writers refuse sample names that do not fit the sample axis, load_pop_file refuses names that do not fit the rows, and GenotypeMatrix.to_zarr refuses a genotype above 2. Fixes #442
andrewkern
force-pushed
the
fix/442-to-zarr-ploidy
branch
from
November 18, 2026 05:34
ba2723a to
504455e
Compare
andrewkern
changed the base branch from
fix/403-phased-zarr-round-trip
to
main
November 18, 2026 05:35
nspope
approved these changes
Nov 18, 2026
nspope
left a comment
Collaborator
There was a problem hiding this comment.
Looks good, one routing issue to fix
| is_genotype = isinstance(matrix, GenotypeMatrix) | ||
| extra = {} | ||
| ploidy = None if is_genotype else matrix.ploidy | ||
| if metadata: |
Collaborator
There was a problem hiding this comment.
if i'm understanding right:
- we initialize ploidy on the line above
- if metadata is not None, we do a check and downgrade ploidy
- so if metadata=None or metadata=False, like is done by default for
population_rows, then we trust the attribute and sail through the check
For example:
import numpy as np
from pg_gpu import HaplotypeMatrix, GenotypeMatrix
from pg_gpu._utils import population_rows
# 4 individuals, 8 haplotype rows, canonical pairing
# individual 0 = rows 0,1 -> alleles (0,0) -> true dosage 0
# individual 1 = rows 2,3 -> alleles (1,1) -> true dosage 2
hap = np.array([
[0, 0, 0], # row 0 (individual 0, copy 1)
[0, 0, 0], # row 1 (individual 0, copy 2)
[1, 1, 1], # row 2 (individual 1, copy 1)
[1, 1, 1], # row 3 (individual 1, copy 2)
[0, 1, 0], # row 4 (individual 2)
[0, 1, 0], # row 5 (individual 2)
[1, 0, 1], # row 6 (individual 3)
[1, 0, 1], # row 7 (individual 3)
], dtype=np.int8)
hm = HaplotypeMatrix(hap, np.array([1, 2, 3]), 1, 3)
print("hm.ploidy:", hm.ploidy)
rows = [0, 2] # not a real individual. row 0 is ind 0 and row 2 is ind 1
sub = population_rows(hm, rows)
print("sub.ploidy:", sub.ploidy) # still 2, even though rows aren't a pair
gm = GenotypeMatrix.from_haplotype_matrix(sub) # the new safety check this PR adds
print("fabricated genotype dosage:", gm.genotypes.get())
# fabricated genotype dosage: [[1 1 1]]... so, shouldn't the check run unconditionally (rather that gated by if metadata)?
| from ._warnings import require_diploid_rows | ||
| require_diploid_rows(hap_matrix, "GenotypeMatrix.from_haplotype_matrix") | ||
| n_hap = hap_matrix.haplotypes.shape[0] | ||
| if n_hap % 2 != 0: |
Collaborator
There was a problem hiding this comment.
this check is done in a number of places---for example, _haplotypes_to_gt used in HaplotypeMatrix.to_zarr---so may be worth abstracting it out as a small helper, to keep error messages consistent
| ndarray, float64, shape (n_variants,) | ||
| Observed heterozygosity per variant. | ||
| """ | ||
| if ploidy != 1: |
Collaborator
There was a problem hiding this comment.
I notice that ploidy is passed as an argument to this function---is there a reason to not read it off the haplotype matrix directly now, to keep things internally consistent?
A population subset whose rows do not make whole individuals gets ploidy 1 from every caller. The check ran only when the subset carried sample names and fields, so the statistics' own subsets (population_rows) kept ploidy 2 and the genotype conversion paired unrelated gametes. require_whole_samples is the one check that haplotype rows divide into samples, for the genotype conversion, to_zarr, materialize and heterozygosity_observed. heterozygosity_observed and inbreeding_coefficient take their ploidy from the matrix by default.
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.
Fixes #442.
Based on
main. #441, which this PR was stacked on, is merged; the branch is rebased on it and has one commit.The fault
HaplotypeMatrix.to_zarrtook rows2iand2i + 1as the two copies of samplei, whatever the matrix held. An odd number of rows failed with a broadcast error. An even number of haploid rows gave a store with false diploids, whose sample axis and sample names disagreed. The matrix had no way to say which layout it had, and no loader could read a haploid store back.The fix
HaplotypeMatrix.ploidy: the number of rows per sample, 1 or 2 (the default). The constructor takesploidy=, the attribute can be assigned, and every subset and copy keeps it. This is the int form of theploidy=from #121; the dict form by sample name is not in this PR.to_zarrwrites(n_variants, n_samples, ploidy), in both store layouts. It raises aValueErrorwhen the rows do not make whole samples.from_zarrreads a store with a ploidy axis of 1 (what bio2zarr writes for haploid calls) into aploidy=1matrix: the eager path, the host streaming path and the kvikio decoder.StreamingHaplotypeMatrix.ploidycomes from the store metadata.from_tsgivesploidy=1for a tree sequence with no individuals or with one sample node per individual, and takesploidy=to declare the layout.ploidy=1matrix, through one helper (require_diploid_rows):GenotypeMatrix.from_haplotype_matrix(and so genotype-mode LD),heterozygosity_observed,inbreeding_coefficient,fst_weir_cockerhamscalar and windowed.ploidy=1matrix always counts as phased: each row is one chromosome.get_population_matrixwith a row list that does not make whole individuals gives aploidy=1subset, soto_zarron it writes one sample per row.load_pop_fileandfilter(genotypes=)use the matrix's ploidy.load_pop_fileraises when the sample names do not fit the rows.GenotypeMatrix.to_zarrdid not have the pairing fault: its rows are individuals, and the round trip is exact. Two smaller faults are fixed. The store writers now refuse sample names that do not fit the sample axis (for both matrix classes), and a genotype above 2 raises where it was written as a homozygote.GenotypeMatrix.from_zarrrefuses a haploid store with a message that points toHaplotypeMatrix.from_zarr.Behavior changes
msprime.simulategives one) now loads asploidy=1, so the pairing consumers raise on it where they paired adjacent rows before.from_ts(ts, ploidy=2)ormatrix.ploidy = 2gives the old reading.ploidy=1matrix,set_unphased()has no effect onphased.reprof both matrix classes shows the ploidy.Not in this PR
from_vcfstill refuses a VCF with haploid calls: Letfrom_vcfread a haploid VCF #444.-2padding as a row: Streamingfrom_zarrloads a mixed-ploidy store that the eager loader refuses, with the-2padding as haplotype rows #443.num_diploidsfor its sample count (17 uses); its docstring says what it holds at ploidy 1.Tests
tests/test_ploidy.py(new): the attribute and its propagation through every subset;from_ts; the haploid round trip (both layouts, eager, host streaming, kvikio, sample subsets, pop files, layout conversion); the writer checks; the pairing consumers, with the windowed engines and the chunked engine; phase at ploidy 1.Full GPU suite: 3460 passed. Moments parity tests: 80 passed. Both ran before the rebase on the last commit of #441 (the loaders read the phase record from a store handle they already have); after it, the eight ploidy, phase, zarr and streaming test files pass (480). Lint and the pipeline-map check pass.