Skip to content

Use numerically stable centering and scaling in trait_covariance and trait_correlation - #3518

Open
chenyangsu wants to merge 1 commit into
tskit-dev:mainfrom
chenyangsu:fix/trait-stats-overflow
Open

chenyangsu wants to merge 1 commit into
tskit-dev:mainfrom
chenyangsu:fix/trait-stats-overflow

Conversation

@chenyangsu

Copy link
Copy Markdown

Description

On ts_10_mut_recomb_fixture, ts.trait_correlation(W + 1e9) returns [0.00902, 0.000882] instead of [0.111953, 0.361111] from cancellation in sum(x^2) - n * mean^2. Scaling by 1e200 returns NaN, scaling by 1e-200 raises ValueError as np.std underflows to zero, and ts.trait_covariance on constant 1e308 weights returns NaN instead of 0.

Both C functions now scale each column by a power of two (frexp/ldexp), shift by the first sample, and sum two-pass squared deviations (Chan, Golub, and LeVeque 1983). TreeSequence.trait_correlation checks constancy directly. Happy to use Welford's update instead if you prefer.

Testing: pytest tests/test_tree_stats.py -k "TraitCovariance or TraitCorrelation" (109 passed, 6 new regression tests failed before the fix), pytest tests/test_python_c.py tests/test_tree_stats.py -m "not slow" (1480 passed), clang-format --dry-run -Werror and ruff check/ruff format --check clean.

Fixes #3495

PR Checklist:

  • Tests that fully cover new/changed functionality.
  • Documentation including tutorial content if appropriate.
  • Changelogs, if there are API changes.

@jeromekelleher-bot

Copy link
Copy Markdown

🤖 AI generated message

Thanks for your interest in tskit, @chenyangsu, and for the work you have put into this.

We have just adopted a contribution policy (#3521), because maintainer time for review is limited. We now expect contributions to come from your own use of tskit, or from wanting to get involved in the project and learn how it works.

Could you read the policy and let us know how this pull request fits with it? It would help most to know what you were doing with tskit when you needed this change.

This branch has not been deployed

No deployments
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.

overflow in trait_correlation

2 participants