Skip to content

NaN values in two-locus (LD) statistics - #3515

Open
apragsdale wants to merge 7 commits into
tskit-dev:mainfrom
apragsdale:ld_nans
Open

apragsdale wants to merge 7 commits into
tskit-dev:mainfrom
apragsdale:ld_nans

Conversation

@apragsdale

@apragsdale apragsdale commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Description

The ratio LD statistics (r2, r and D_prime) have terms like p(1-p) in the denominator, so when an allele has frequency 0 or 1, it results in a NaN value. In either site or branch mode, summing over that NaN leads to a whole result being NaN, which can be unexpected (see issues #3441, #3474).

There are a number of ways this can happen:

  • a multiallelic site has an allele carried by no samples (e.g., successive mutations on the same branch, creating a "ghost" allele - issue NaN's in ld_matrix output with "ghost" alleles #3474)
  • A sample set doesn't carry one or more alleles at a site, or doesn't inclue samples under some of the branches (issue nans in ld_matrix #3441)
  • Multi-population statistics will often have one or both of these issues

The proposed desired behavior is that alleles and branches that do not or cannot contribute to polymorphism in a sample should not be considered and not affect results.

I tried to write out a number of "rules" (proposed) that the tests in this PR try to address. Note that these are just the tests. Working on fixes, but thought it'd be helpful to get feedback first:

Site mode

  1. Only alleles carried by at least one sample in the sample set contribute to the stat
  2. A site that is monomorphic in the sample (whether due to subsetting or a back mutation) should result in NaN for ratio statistics and their computed value for non-ratio statistics (which is typically zero)
  3. When subsetting reduces a multiallelic site to fewer alleles, the statistic is computed and summed or normalized over the remaining alleles only. The result should equal the result from a simplified ts.

Branch mode

  1. The result considers only branches that subtend at least one, but not all, of the sample set.
  2. If no branches contribute (for example, a sample set with just one sample), every statistic returns NaN, since nothing is computed. This changes the behavior of non-ratio statistics, which currently return 0, but I think this change makes behavior more consistent across statistics. If no branches contribute in branch mode, we return zero. Since this is a sum, it indicates that we had nothing to compute, rather than a nan. It's also much cleaner, code-wise.

Multi-population statistic

  1. For ratio statistics only, a site or branch must be polymorphic in both sample sets to contribute. For non-ratio statistics, they keep their current behavior (we can easily imagine valid and useful statistics that return nonzero meaningful values when a site is fixed in one of the sample sets).

Some tricky situations/inconsistencies

  • What do we do about polarized statistics when the sample set lacks the ancestral allele? The single-site statistics don't do anything special here and treat all derived alleles as they are. I.e., we don't relabel the mutation at the root the "ancestral" allele. We should do the same, but document this behavior.
  • Currently, r and D_prime return zero when a site doesn't carry a mutation, while r2 returns NaN. If we follow point 3 above, all should be NaN.

Eventually.... this PR
Fixes #3441.
Fixes #3474

PR Checklist:

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

@codecov

codecov Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.38710% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 91.73%. Comparing base (6efeadb) to head (6c69e8d).

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3515      +/-   ##
==========================================
+ Coverage   91.72%   91.73%   +0.01%     
==========================================
  Files          37       37              
  Lines       30839    30893      +54     
  Branches     4921     4938      +17     
==========================================
+ Hits        28286    28339      +53     
  Misses       2223     2223              
- Partials      330      331       +1     
Flag Coverage Δ
C 82.36% <91.93%> (+0.04%) ⬆️
c-python 77.04% <65.57%> (-0.02%) ⬇️
python-tests 96.44% <ø> (ø)
python-tests-no-jit 33.26% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

Components Coverage Δ
Python API 98.73% <ø> (ø)
Python C interface 91.21% <ø> (ø)
C library 91.30% <98.38%> (+0.02%) ⬆️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@apragsdale

Copy link
Copy Markdown
Contributor Author

There are some corner cases in site mode with multi-allelic sites, in which the normalization weights in the two-way r2 statistic do not sum to

Consider the example below with four samples in two sample sets, with one site:

sample 0 1 2 3
sample set 0 0 1 1
allele C A T A
import tskit

tables = tskit.Tree.generate_star(4).tree_sequence.dump_tables()
tables.sites.add_row(position=0, ancestral_state="A")
tables.mutations.add_row(site=0, node=0, derived_state="C")
tables.mutations.add_row(site=0, node=2, derived_state="T")
ts = tables.tree_sequence()

ts.ld_matrix(sample_sets=[[0, 1], [2, 3]], indexes=(0, 1))  # two-way r2 of the site with itself

A is the only allele carried by both sample sets, so C and T are dropped (following rules laid out above). In each set, half the samples carry A, so r2 should be 1.

r2 is a weighted average over alleles, and the weights add up to 1:

allele weight used?
A 1/2 yes
C 1/4 no, only in sample set 0
T 1/4 no, only in sample set 1

After dropping C and T, only 1/2 of the weight is left:

r2
previous result: nan (C and T give nan)
drop C and T, result: 1 × 1/2 = 0.5
drop C and T, then divide by 1/2, result: 1

For one-way statistics (or two-way with the same sample set twice), a dropped allele always has weight 0, so dividing by the remaining weight doesn't change behavior as we'd divide by 1..

At multiallelic sites, alleles not carried by any sample in a sample set
no longer contribute to that set's statistics or their normalisation.
If either site is monomorphic in the sample set, the summary function is
evaluated on the fixed allele, giving nan for ratio statistics and zero
otherwise. Two-way statistics are unchanged.
For two-way statistics, an allele contributes to the result for a pair of
sample sets only if it is carried by both sets, matching the one-way rule
when the same set is passed twice. Each site-mode result is now divided
by the total weight of the allele pairs used, so it is a weighted average
over those pairs; this replaces counting the alleles used per result.
With no branches that can produce polymorphism, branch-mode statistics
are an empty sum, so every statistic is zero.
Only alleles carried by both sample sets are now used for two-way
statistics, which changes the expected values for disjoint sets.
@petrelharp

Copy link
Copy Markdown
Contributor

Ping me (elsewhere) when I should have a look at this?

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.

NaN's in ld_matrix output with "ghost" alleles nans in ld_matrix

2 participants