Repository navigation
Add a polarized flag to HaplotypeMatrix and warn on unpolarized derived-state statistics - #449
Merged
Merged
Conversation
…ate statistics HaplotypeMatrix.polarized records whether allele code 0 is the ancestral allele at every site. It is False by default and from from_vcf, and True from from_ts, from a load with ancestral= and from polarize. set_polarized() and a polarized= argument on the loaders declare it. Every subset and copy keeps it, the stream has it, and to_zarr and from_zarr keep it through a store. The statistics whose value changes when the ancestral and a derived allele change places emit UnpolarizedDataWarning on a matrix that is not marked. One user call warns once: the scalar functions use a depth guard, and the dispatchers and every windowed entry point decide by the names asked for. A caller's own statistic under windowed_analysis warns as a direct call does. One guard factory now serves this warning and the unphased one. A recode of data marked polarized raises when it would move code 0, so a second polarize call no longer changes the codes back. The set of statistics is fixed by an experiment in the tests: each one must warn exactly when its value changes under the swap. Statistics that depend on code 0 at multiallelic sites only do not warn; a test pins that set and the docs name it. Fixes #439
nspope
approved these changes
Nov 20, 2026
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 #439. This is the second of its two PRs; #448 was the first.
The problem
pg_gpu reads allele code 0 as the ancestral allele. #448 added a way to recode by an ancestral-allele tag, but nothing recorded whether a matrix had been recoded, so a statistic of a derived state on a plain VCF load was still wrong with no sign of it.
What this PR adds
HaplotypeMatrix.polarized: whether allele code 0 is the ancestral allele at every site.Falseby default and fromfrom_vcf;Truefromfrom_ts, from a load withancestral=, and frompolarize.set_polarized()/set_unpolarized(), and apolarized=argument on the constructor,from_vcfandfrom_zarr, declare it for data whose REF already is ancestral. They change no allele code.StreamingHaplotypeMatrixhas it, and its chunks take it from the stream.to_zarrrecords it as a store attribute;from_zarr(polarized=None)reads it back, eager and streaming;allel_zarr_to_vczcarries it.UnpolarizedDataWarningfrom each statistic of a derived state on a matrix that is not marked. One user call warns once. The values do not change.A second recode is refused.
polarize, or a load withancestral=, raises on marked data when it would move code 0. In #448 a second call with the same codes changed the codes back with no error.Which statistics warn: decided by experiment
I did not take the list from the issue.
tests/test_unpolarized_warning.pyexchanges codes 0 and 1 at half of the sites of a matrix, runs each statistic on both, and asserts that it warns exactly when its value changes. It covers the scalar functions, eachdiversity_statsname, eachFrequencySpectrumweight, and each windowed statistic in the pipeline map, so a new statistic cannot join either side unseen.The experiment gave three results that the issue's list did not have:
singleton_count, and the windowedsingletonsandn_singletons, count derived singletons.eta1andminus_eta1weights depend on the ancestral state; their starred forms do not.genetic_relatedness(polarised=True)with centring is the same either way at a biallelic site, but not at a multiallelic one.The full list is in the new docs page,
polarization.rst.Multiallelic sites: a choice to check
A second run of the experiment, on data with sites of three and more alleles, found statistics that are symmetric at a biallelic site but depend on code 0 at a multiallelic one, because they count each derived allele apart:
mu_sfs(scalar and windowed),eta1_star,minus_eta1_star, andFrequencySpectrumwith thepiweight (and so its Tajima's D).These do not warn. On data that are mostly biallelic, a warning there would be a false alarm for nearly every user. The docs page names them, and a test pins the exact set.
genetic_relatedness(polarised=True)is in the same class and does warn, since that argument asks for the derived state. If you think the others should warn too, it is a small change.One result I could not explain: the windowed
local_pca_jackknifevalues differ between the two multiallelic matrices by more than the test's tolerance, and the plainlocal_pcavalues do not. It is left out of the multiallelic test, with a comment.How one call warns once
_warnings._depth_guardis now one factory for both; the phase names are kept.diversity_stats,windowed_analysis, the threeWindowedAnalyzermethods and the two fused engines decide by the names asked for, through one helper (windowed_analysis._warn_scan). The engines sumtheta_hfor every request, so what is computed cannot decide.windowed_analysisruns outside the guards and warns as a direct call does.FrequencySpectrumwarns once for each object.Behavior changes
theta_h, Fay and Wu's H,singletonsand the like on a plain VCF or Zarr load now gets the warning.polarizeraises where it used to swap back (see above).reprof both matrix classes showspolarized.Not in this PR
Two items from the plan on #439 are left out:
GenotypeMatrix.daf_histogramon one stays silent.Also not done: the quickstart, the examples page, the README and the tour notebook call derived statistics on plain loads, so their output will now show the warning.
utils/genome_scan.pydid the same; it now takes--ancestral TAG.Other files
pyproject.tomlhas one new line in the test suite's warning filters (the fixtures are not polarized), sopixi.lockchanges with it.Tests
tests/test_unpolarized_warning.py(new): the experiment above on biallelic and multiallelic data; once-per-call through nested calls, the per-window fallback,WindowedAnalyzer, direct engine calls and a stream; the flag, its propagation, the store round trip on both layouts, the loads withancestral=andpolarized=, and the refused second recode.Full GPU suite: 3729 passed. Moments parity tests: 91 passed. Lint and the pipeline-map check pass.