Skip to content

Polarize allele codes by an ancestral-allele tag - #448

Merged
andrewkern merged 2 commits into
mainfrom
feature/439-ancestral-allele
Nov 20, 2026
Merged

andrewkern merged 2 commits into
mainfrom
feature/439-ancestral-allele

Conversation

@andrewkern

Copy link
Copy Markdown
Member

Part of #439 (the first of the two PRs planned there). Asked for in #438.

The problem

pg_gpu reads allele code 0 as the ancestral allele. A VCF gives code 0 to REF, which is not the ancestral allele in general. Nothing read an ancestral-allele field, so the statistics of a derived state (the unfolded SFS, theta_h, theta_l, Fay and Wu's H, Zeng's E, max_daf, the sign of ihs and nsl) took REF as ancestral, with no error.

What this PR adds

  • HaplotypeMatrix.from_zarr(..., ancestral='AA') and HaplotypeMatrix.from_vcf(..., ancestral='AA'), for any INFO tag. from_zarr works on the eager and the streaming path (host and kvikio).
  • HaplotypeMatrix.polarize(ancestral, alleles=None), for an array that the caller has: integer allele codes, or allele strings matched against the site's alleles.
hm = HaplotypeMatrix.from_vcf("data.vcf.gz", ancestral="AA")

How it works

  • Codes on the host, once. zarr_io.ancestral_codes matches the tag against the site's allele strings and gives one int8 per variant: the code of the ancestral allele, or -1 for unknown. The match ignores case. Of a value in the Ensembl form (A|||) the part before the first | counts.
  • One swap rule on the GPU. swap_ancestral is a RawKernel: at a site whose ancestral allele has code a > 0, codes 0 and a change places, and negative values (missing calls) stay. The same rule serves biallelic and multiallelic sites, and a multiallelic site keeps its other codes.
  • Unknown sites are dropped, with an UnknownAncestralWarning that gives the count. A site is unknown when the value is empty or is none of the site's alleles (which covers ., N, -). All sites unknown raises, because that means a wrong tag or wrong alleles.
  • Bounds, mask and span do not change. A per-base statistic still divides by bases that include the dropped sites; the warning says so.
  • Streaming. ZarrGenotypeSource.set_ancestral reads the strings once (after the eager-or-streaming decision, not in the size probe), drops the unknown variants from the source, and keeps the source's bounds. The chunk builder recodes each block. The source's row range can then have gaps, so _zarr_row_range also returns the rows of the block that are the source's own.
  • Lower case (a low-confidence call in many files) counts as known; ancestral_lowercase_known=False makes it unknown.
  • fields['allele'], if the matrix has it, changes its columns with the codes, so the strings keep naming the codes and a second polarization by the same tag changes nothing.

Limits, by design

  • No polarized flag yet. No matrix records that it is polarized, and no statistic warns on data that are not. That is the second PR. Until then, a second polarize call with the same integer codes swaps the codes back; the docstring says so.
  • The genotype loaders do not take ancestral=. I found no genotype statistic that reads the ancestral state.
  • from_zarr needs a VCZ store with variant_<tag> and variant_allele, as vcf_to_zarr writes. A store from to_zarr or a scikit-allel store has neither and raises a clear error.
  • from_vcf reads at most three ALT alleles per site (the reader's default), so a later ALT allele as the ancestral state counts as unknown.
  • Per-allele fields other than allele (AC, AF) keep their column order.
  • The option to keep unknown sites comes with the flag in the second PR.

Tests

tests/test_ancestral.py (new). A tree sequence is the truth: the fixtures write it to a VCF whose REF is a random allele of each site, with the true ancestral allele in AA (lower case at some sites, a placeholder at others).

  • All four load paths (VCF, eager store, host streaming, kvikio streaming) give the tree sequence's own matrix on a biallelic simulation, and the same ancestral class on a multiallelic one.
  • The unfolded SFS, theta_h, theta_l, Fay and Wu's H, Zeng's E, max_daf and ihs equal their values on the tree sequence. A control shows that the load with no ancestral= gives a different matrix and SFS.
  • Regions, sample subsets of a stream, fields and mask alignment, the bounds with unknown sites at both ends of a store (eager against streaming), the string matcher, the kernel, polarize, and the errors.

Full GPU suite: 3545 passed. Lint and the pipeline-map check pass.

Docs

Changelog, quickstart, the features page (it now says that code 0 is read as ancestral), the API page (the new warning), and the pipeline map.

pg_gpu reads allele code 0 as the ancestral allele, and a VCF gives code
0 to REF. HaplotypeMatrix.from_zarr and from_vcf take ancestral='AA' (an
INFO tag) and recode each site so that code 0 is the allele the tag
names; HaplotypeMatrix.polarize does the same for an array of ancestral
alleles or allele codes.

At a site whose ancestral allele has code a > 0, codes 0 and a change
places, in one GPU kernel that serves biallelic and multiallelic sites.
A site with no known ancestral allele is dropped with an
UnknownAncestralWarning; the bounds, the mask and the span do not
change. The streaming source drops those sites up front and the chunk
builder recodes each block, so the streaming path gives the matrix of
the eager one.

No matrix records that it is polarized, and the genotype loaders do not
take ancestral=.

Part of #439
@andrewkern
andrewkern requested a review from nspope November 19, 2026 21:27

@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, two minor issues to fix

Comment thread docs/source/changelog.rst Outdated

pg_gpu reads allele code 0 as the ancestral allele, and a VCF gives code
0 to REF. ``HaplotypeMatrix.from_zarr`` and ``HaplotypeMatrix.from_vcf``
now take ``ancestral='AA'`` (any INFO tag) and recode each site so that

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.

Suggested change
now take ``ancestral='AA'`` (any INFO tag) and recode each site so that
now take an ``ancestral`` argument (typically `'AA'`, but any INFO tag in the VCF may be used) and recode each site so that

Comment thread docs/source/changelog.rst Outdated
``variant_allele``, as ``vcf_to_zarr`` writes, and works on the eager
and the streaming path. A store from ``to_zarr`` has neither array and
raises.
* No matrix records that it is polarized, and no statistic warns on data

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.

Suggested change
* No matrix records that it is polarized, and no statistic warns on data
* The ancestral state must be set explicitly for polarized statistics to be correct. No matrix records that it is polarized, and no statistic warns on data

Comment thread docs/source/features.rst Outdated
state (``theta_h``, ``theta_l``, Fay and Wu's H, Zeng's E, ``max_daf``,
``daf_histogram``, the unfolded ``sfs`` and ``joint_sfs``, and the sign of
``ihs`` and ``nsl``) depend on it. A VCF gives code 0 to REF; load with
``ancestral='AA'`` (``HaplotypeMatrix.from_vcf`` and ``from_zarr``) to

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.

Suggested change
``ancestral='AA'`` (``HaplotypeMatrix.from_vcf`` and ``from_zarr``) to
the ``ancestral='INFO tag'`` (for example `'AA'`) argument to ``HaplotypeMatrix.from_vcf`` and ``from_zarr`` to

Comment thread pg_gpu/haplotype_matrix.py Outdated
The ancestral allele of each site: either integer allele codes
(-1 for unknown), or allele strings as a VCF ``AA`` tag gives
them, which need ``alleles``. It is aligned with the
underlying variant axis, as ``fields`` are, not with the view

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.

"It is aligned with the underlying variant axis" could be stated more plainly, like "The length is expected to match the number of variants in the HaplotypeMatrix, not the view (subset) of variants from applying an accessible mask"

Comment thread pg_gpu/_gpu_genotype_prep.py Outdated
if haps.dtype != cp.int8 or not haps.flags.c_contiguous:
raise ValueError("haps must be a C-contiguous int8 array")
n_var = haps.shape[1]
codes = cp.ascontiguousarray(cp.asarray(codes, dtype=cp.int8))

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 is casting to int8 without a range check. The callers (that I can see) do a check before invoking it, but it'd be safer to check here. Otherwise this function could silently give garbage via overflow.

read_ancestral_codes(store, ancestral,
data.get('variant_indices'),
ancestral_lowercase_known),
context=f"from_zarr(ancestral={ancestral!r})")

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.

Say the store read above (lines 1000-1004) failed (filesystem issues, or whatever). Then store is None. But, read_ancestral_codes doesn't handle that gracefully, so you'll get an obscure error. For example,

from pg_gpu.zarr_io import read_ancestral_codes

store = None
read_ancestral_codes(store, "AA")
# TypeError: argument of type 'NoneType' is not a container or iterable

swap_ancestral checks that the codes are integers that fit int8 before
the cast. The eager loader raises a clear error when ancestral= is given
and the store does not open as a group. The changelog, the features page
and the polarize docstring take the reviewer's wording.
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.

2 participants