Skip to content

Give HaplotypeMatrix a ploidy, and write and read haploid stores - #445

Merged
andrewkern merged 2 commits into
mainfrom
fix/442-to-zarr-ploidy
Nov 19, 2026
Merged

andrewkern merged 2 commits into
mainfrom
fix/442-to-zarr-ploidy

Conversation

@andrewkern

@andrewkern andrewkern commented Nov 18, 2026 •

Copy link
Copy Markdown
Member

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_zarr took rows 2i and 2i + 1 as the two copies of sample i, 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 takes ploidy=, the attribute can be assigned, and every subset and copy keeps it. This is the int form of the ploidy= from #121; the dict form by sample name is not in this PR.

  • to_zarr writes (n_variants, n_samples, ploidy), in both store layouts. It raises a ValueError when the rows do not make whole samples.
  • from_zarr reads a store with a ploidy axis of 1 (what bio2zarr writes for haploid calls) into a ploidy=1 matrix: the eager path, the host streaming path and the kvikio decoder. StreamingHaplotypeMatrix.ploidy comes from the store metadata.
  • 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, through one helper (require_diploid_rows): GenotypeMatrix.from_haplotype_matrix (and so genotype-mode LD), heterozygosity_observed, inbreeding_coefficient, fst_weir_cockerham scalar and windowed.
  • A ploidy=1 matrix always counts as phased: each row is one chromosome.
  • get_population_matrix with a row list that does not make whole individuals gives a ploidy=1 subset, so to_zarr on it writes one sample per row.
  • load_pop_file and filter(genotypes=) use the matrix's ploidy. load_pop_file raises when the sample names do not fit the rows.

GenotypeMatrix.to_zarr did 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_zarr refuses a haploid store with a message that points to HaplotypeMatrix.from_zarr.

Behavior changes

  • A tree sequence with no individuals (the legacy msprime.simulate gives one) now loads as ploidy=1, so the pairing consumers raise on it where they paired adjacent rows before. from_ts(ts, ploidy=2) or matrix.ploidy = 2 gives the old reading.
  • On a ploidy=1 matrix, set_unphased() has no effect on phased.
  • repr of both matrix classes shows the ploidy.

Not in this PR

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.

@andrewkern
andrewkern requested a review from nspope November 18, 2026 05:32
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
andrewkern force-pushed the fix/442-to-zarr-ploidy branch from ba2723a to 504455e Compare November 18, 2026 05:34
@andrewkern
andrewkern changed the base branch from fix/403-phased-zarr-round-trip to main November 18, 2026 05:35
@andrewkern andrewkern closed this Nov 18, 2026
@andrewkern andrewkern reopened this Nov 18, 2026

@nspope nspope left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good, one routing issue to fix

Comment thread pg_gpu/_utils.py
is_genotype = isinstance(matrix, GenotypeMatrix)
extra = {}
ploidy = None if is_genotype else matrix.ploidy
if metadata:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if i'm understanding right:

  1. we initialize ploidy on the line above
  2. if metadata is not None, we do a check and downgrade ploidy
  3. 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)?

Comment thread pg_gpu/genotype_matrix.py Outdated
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:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread pg_gpu/diversity.py Outdated
ndarray, float64, shape (n_variants,)
Observed heterozygosity per variant.
"""
if ploidy != 1:

@nspope nspope Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@andrewkern
andrewkern merged commit 8d77e5c into main Nov 19, 2026
2 checks passed
@andrewkern
andrewkern deleted the fix/442-to-zarr-ploidy branch November 19, 2026 20:30
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.

HaplotypeMatrix.to_zarr assumes two haplotype rows per sample: an odd row count fails, haploid data are paired up

2 participants