From aff5b6babcefa39e673b67b2db2360b726d640b6 Mon Sep 17 00:00:00 2001 From: Aaron Ragsdale Date: Wed, 18 Nov 2026 20:34:25 -0600 Subject: [PATCH 1/9] Add tests for LD calculations involving nan values --- python/tests/test_ld_matrix.py | 176 +++++++++++++++++++++++++++++++++ 1 file changed, 176 insertions(+) diff --git a/python/tests/test_ld_matrix.py b/python/tests/test_ld_matrix.py index 4d6e47ddcc..4c61f0fe65 100644 --- a/python/tests/test_ld_matrix.py +++ b/python/tests/test_ld_matrix.py @@ -2398,3 +2398,179 @@ def test_multipopulation_r2_varying_unequal_set_sizes(genotypes, sample_sets, ex norm_hap_weighted_ij(1, state, max(a) + 1, max(b) + 1, norm[i, j], params) np.testing.assert_allclose((result * norm).sum(), expected) + + +# Tests for how the LD matrix handles alleles and branches that are not polymorphic +# in a sample set or sets. See issues raised in #3441 and #3474. Here we +# define ratio and non-ratio stats, which are reused in pytest below. + +# Note that the unbiased statistics are undefined for small sample sets, so +# tests that subset to two samples use only the biased statistics that are +# defined for small sample sizes. +RATIO_STATS = ["r", "r2", "D_prime"] +NONRATIO_STATS = ["D", "D2", "Dz", "pi2"] + + +def set_up_ts_with_ghost_allele(): + """ + Four samples, with samples 0 and 1 sharing parent node 4. + + Site 0 has two successive mutations on the same branch above node 4: + A -> G -> T, + so allele G is carried by no samples (a "ghost" allele). Site 1 is a + biallelic A -> C above node 4. The mutations at sites 0 and 1 therefore + both split the samples into {0, 1} and {2, 3} carrying the derived and + ancestral allele, resp. + + Site 2 has a mutation A -> C followed by a back mutation C -> A above + node 4, so it is monomorphic in the samples. + """ + tables = tskit.TableCollection(sequence_length=10) + for _ in range(4): + tables.nodes.add_row(flags=tskit.NODE_IS_SAMPLE, time=0) + tables.nodes.add_row(time=1) + tables.nodes.add_row(time=2) + tables.nodes.add_row(time=3) + for parent, child in [(4, 0), (4, 1), (5, 2), (5, 4), (6, 3), (6, 5)]: + tables.edges.add_row(left=0, right=10, parent=parent, child=child) + tables.sites.add_row(position=2, ancestral_state="A") + tables.mutations.add_row(site=0, node=4, derived_state="G", time=1.5) + tables.mutations.add_row(site=0, node=4, derived_state="T", time=1.2, parent=0) + tables.sites.add_row(position=6, ancestral_state="A") + tables.mutations.add_row(site=1, node=4, derived_state="C", time=1.5) + tables.sites.add_row(position=8, ancestral_state="A") + tables.mutations.add_row(site=2, node=4, derived_state="C", time=1.5) + tables.mutations.add_row(site=2, node=4, derived_state="A", time=1.2, parent=3) + tables.sort() + return tables.tree_sequence() + + +@pytest.mark.parametrize("stat", sorted(SUMMARY_FUNCS.keys())) +def test_ghost_allele_site_mode(stat): + # Uses the ghost allele tree sequence set up above. + # Sites 0 and 1 have the same allele sharing patterns, so the ghost allele + # at site 0 should be ignored and every pairing of the two sites should + # give the same value as site 1 with itself. + ts = set_up_ts_with_ghost_allele() + ld = ts.ld_matrix(sites=[[0, 1]], stat=stat) + ld_site1 = ld[1, 1] + np.testing.assert_(np.all(np.isclose(ld, ld_site1))) + + +@pytest.mark.parametrize("stat", RATIO_STATS + NONRATIO_STATS) +def test_monomorphic_site_site_mode(stat): + # Uses the ghost allele tree sequence set up above. + # Site 2 is monomorphic due to a back mutation, so any LD statistic + # computed for a pair with site 2 should be nan for ratio statistics and + # zero otherwise. + ts = set_up_ts_with_ghost_allele() + ld = ts.ld_matrix(sites=[[0, 1, 2], [2]], stat=stat) + if stat in RATIO_STATS: + np.testing.assert_(np.all(np.isnan(ld))) + else: + np.testing.assert_(np.all(ld == 0)) + + +@pytest.mark.parametrize("stat", RATIO_STATS + NONRATIO_STATS) +def test_monomorphic_sample_set_site_mode(stat): + # Uses the ghost allele tree sequence set up above. + # Samples 0 and 1 carry the same alleles at every site, so all sites are + # monomorphic within this sample set. + ts = set_up_ts_with_ghost_allele() + ld = ts.ld_matrix(sample_sets=[0, 1], stat=stat) + if stat in RATIO_STATS: + np.testing.assert_(np.all(np.isnan(ld))) + else: + np.testing.assert_(np.all(ld == 0)) + + +def set_up_star_ts_with_multiallelic_site(): + """ + A star tree with four samples (using one of the examples from issue #3441). + + Site 0 is triallelic: sample 0 carries C, sample 2 carries T, and samples + 1 and 3 carry the ancestral A. Site 1 is biallelic, with sample 0 + carrying G. + """ + 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") + tables.sites.add_row(position=0.5, ancestral_state="A") + tables.mutations.add_row(site=1, node=0, derived_state="G") + return tables.tree_sequence() + + +@pytest.mark.parametrize("stat", RATIO_STATS + NONRATIO_STATS) +def test_multiallelic_site_becomes_biallelic_in_subset(stat): + # Within sample set [0, 1], site 0 is biallelic (C vs A) and allele T is + # absent. Allele T should not contribute, so the result should match the + # tree sequence simplified to these samples. + ts = set_up_star_ts_with_multiallelic_site() + sample_set = [0, 1] + ld = ts.ld_matrix(sample_sets=sample_set, stat=stat) + ld_simplified = ts.simplify(sample_set).ld_matrix(stat=stat) + np.testing.assert_(np.all(np.isclose(ld, ld_simplified))) + if stat == "r2" or stat == "r": + # Both sites have alleles at freq=0.5 in positive LD. + np.testing.assert_(np.all(np.isclose(ld, 1))) + + +@pytest.mark.parametrize("stat", RATIO_STATS + NONRATIO_STATS) +def test_multiallelic_site_becomes_monomorphic_in_subset(stat): + # Samples 1 and 3 both carry the ancestral allele at both sites + # and are monomorphic. + ts = set_up_star_ts_with_multiallelic_site() + ld = ts.ld_matrix(sample_sets=[1, 3], stat=stat) + if stat in RATIO_STATS: + np.testing.assert_(np.all(np.isnan(ld))) + else: + np.testing.assert_(np.all(ld == 0)) + + +def set_up_branch_mode_ts(): + ts = msprime.sim_ancestry( + 6, sequence_length=10, recombination_rate=0.05, random_seed=2 + ) + # Get the positions of tree sequence break points. + positions = [list(ts.breakpoints(as_array=True)[:-1])] + return ts, positions + + +@pytest.mark.parametrize("stat", sorted(SUMMARY_FUNCS.keys())) +def test_branch_mode_subset_matches_simplified(stat): + # Branches subtending none, or all, of the sample set cannot produce + # polymorphism in it and should not contribute. These branches would be + # removed by simplifying to the sample set, and we expect results to match. + ts, positions = set_up_branch_mode_ts() + sample_set = [0, 1, 2, 3, 4] + ld = ts.ld_matrix( + sample_sets=sample_set, positions=positions, mode="branch", stat=stat + ) + ld_simplified = ts.simplify(sample_set).ld_matrix( + positions=positions, mode="branch", stat=stat + ) + np.testing.assert_(np.all(np.isfinite(ld))) + np.testing.assert_(np.all(np.isclose(ld, ld_simplified))) + + +@pytest.mark.parametrize("stat", sorted(SUMMARY_FUNCS.keys())) +def test_branch_mode_single_sample_is_nan(stat): + # With a single sample, there is no polymorphism (no branches we compute + # over!), so nothing is computed and every statistic is nan. <- This would + # be a breaking change but I think makes sense?? + ts, positions = set_up_branch_mode_ts() + ld = ts.ld_matrix(sample_sets=[0], positions=positions, mode="branch", stat=stat) + np.testing.assert_(np.all(np.isnan(ld))) + + +def test_branch_mode_two_way_r2_not_nan(): + # Example from issue #3441: two-way r2 between disjoint sample sets. + ts, positions = set_up_branch_mode_ts() + ld = ts.ld_matrix( + sample_sets=[[0, 1, 2, 3], [4, 5]], + indexes=(0, 1), + positions=positions, + mode="branch", + ) + np.testing.assert_(np.all(np.isfinite(ld))) From 5792ce061bcf387474d86edcb6679206f25ecb45 Mon Sep 17 00:00:00 2001 From: Aaron Ragsdale Date: Fri, 20 Nov 2026 11:37:41 -0800 Subject: [PATCH 2/9] Only use alleles carried by the sample set in site-mode LD 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. --- c/tskit/trees.c | 115 +++++++++++++++++++++++++++++---- python/tests/test_ld_matrix.py | 51 +++++++++++---- 2 files changed, 140 insertions(+), 26 deletions(-) diff --git a/c/tskit/trees.c b/c/tskit/trees.c index 2fcf399e20..da75e125f4 100644 --- a/c/tskit/trees.c +++ b/c/tskit/trees.c @@ -2374,6 +2374,11 @@ typedef struct { double *weights; double *norm; double *result_tmp; + // For each result: whether to skip the ancestral allele, and the number of + // alleles at each site that the statistic is averaged over. + bool *skip_ancestral; + tsk_size_t *num_a_used; + tsk_size_t *num_b_used; tsk_bitset_t AB_samples; } two_locus_work_t; @@ -2387,8 +2392,13 @@ two_locus_work_init(tsk_size_t max_alleles, tsk_size_t num_samples, out->norm = tsk_malloc(result_dim * sizeof(*out->norm)); out->result_tmp = tsk_malloc(result_dim * max_alleles * max_alleles * sizeof(*out->result_tmp)); + out->skip_ancestral = tsk_malloc(result_dim * sizeof(*out->skip_ancestral)); + out->num_a_used = tsk_malloc(result_dim * sizeof(*out->num_a_used)); + out->num_b_used = tsk_malloc(result_dim * sizeof(*out->num_b_used)); tsk_memset(&out->AB_samples, 0, sizeof(out->AB_samples)); - if (out->weights == NULL || out->norm == NULL || out->result_tmp == NULL) { + if (out->weights == NULL || out->norm == NULL || out->result_tmp == NULL + || out->skip_ancestral == NULL || out->num_a_used == NULL + || out->num_b_used == NULL) { ret = tsk_trace_error(TSK_ERR_NO_MEMORY); goto out; } @@ -2406,15 +2416,19 @@ two_locus_work_free(two_locus_work_t *work) tsk_safe_free(work->weights); tsk_safe_free(work->norm); tsk_safe_free(work->result_tmp); + tsk_safe_free(work->skip_ancestral); + tsk_safe_free(work->num_a_used); + tsk_safe_free(work->num_b_used); tsk_bitset_free(&work->AB_samples); } static int compute_general_normed_two_site_stat_result(const tsk_bitset_t *state, const tsk_size_t *allele_counts, tsk_size_t a_off, tsk_size_t b_off, - tsk_size_t num_a_alleles, tsk_size_t num_b_alleles, tsk_size_t state_dim, - tsk_size_t result_dim, general_stat_func_t *f, sample_count_stat_params_t *f_params, - norm_func_t *norm_f, bool polarised, two_locus_work_t *restrict work, double *result) + tsk_size_t num_a_alleles, tsk_size_t num_b_alleles, const tsk_size_t *num_a_carried, + const tsk_size_t *num_b_carried, tsk_size_t state_dim, tsk_size_t result_dim, + general_stat_func_t *f, sample_count_stat_params_t *f_params, norm_func_t *norm_f, + bool polarised, two_locus_work_t *restrict work, double *result) { int ret = 0; // Sample sets and b sites are rows, a sites are columns @@ -2423,16 +2437,49 @@ compute_general_normed_two_site_stat_result(const tsk_bitset_t *state, // a2 [s1, s2, s3] [s1, s2, s3] [s1, s2, s3] // a3 [s1, s2, s3] [s1, s2, s3] [s1, s2, s3] tsk_size_t k, mut_a, mut_b, result_row_len = num_b_alleles * result_dim; + tsk_size_t count_a, count_b; uint8_t is_polarised = polarised ? 1 : 0; + bool one_way = f_params->set_indexes == NULL; + bool both_sites_vary; double *restrict hap_row, *restrict result_tmp_row; double *restrict norm = work->norm; double *restrict weights = work->weights; double *restrict result_tmp = work->result_tmp; + bool *restrict skip_ancestral = work->skip_ancestral; + tsk_size_t *restrict num_a_used = work->num_a_used; + tsk_size_t *restrict num_b_used = work->num_b_used; tsk_bitset_t AB_samples = work->AB_samples; - for (mut_a = is_polarised; mut_a < num_a_alleles; mut_a++) { + // For each result, decide whether to skip the ancestral allele and how many + // alleles at each site to average over. + for (k = 0; k < result_dim; k++) { + if (one_way) { + // Only alleles carried by sample set k are used. If either site is + // monomorphic in sample set k, we keep the ancestral allele even for + // polarised statistics, so that the summary function is evaluated on + // the fixed allele: this gives nan for ratio statistics (0 / 0) and + // zero for all others. + both_sites_vary = num_a_carried[k] >= 2 && num_b_carried[k] >= 2; + skip_ancestral[k] = polarised && both_sites_vary; + num_a_used[k] = num_a_carried[k]; + num_b_used[k] = num_b_carried[k]; + if (skip_ancestral[k] && allele_counts[a_off + k] > 0) { + num_a_used[k]--; + } + if (skip_ancestral[k] && allele_counts[b_off + k] > 0) { + num_b_used[k]--; + } + } else { + // Two-way statistics use every allele at both sites. + skip_ancestral[k] = polarised; + num_a_used[k] = num_a_alleles - is_polarised; + num_b_used[k] = num_b_alleles - is_polarised; + } + } + + for (mut_a = 0; mut_a < num_a_alleles; mut_a++) { result_tmp_row = GET_2D_ROW(result_tmp, result_row_len, mut_a); - for (mut_b = is_polarised; mut_b < num_b_alleles; mut_b++) { + for (mut_b = 0; mut_b < num_b_alleles; mut_b++) { for (k = 0; k < state_dim; k++) { tsk_bitset_intersect(state, a_off + (mut_a * state_dim) + k, state, b_off + (mut_b * state_dim) + k, &AB_samples); @@ -2447,12 +2494,25 @@ compute_general_normed_two_site_stat_result(const tsk_bitset_t *state, if (ret != 0) { goto out; } - ret = norm_f(result_dim, weights, num_a_alleles - is_polarised, - num_b_alleles - is_polarised, norm, f_params); - if (ret != 0) { - goto out; - } for (k = 0; k < result_dim; k++) { + // For one-way statistics, result k is computed from sample set k, + // and alleles not carried by the sample set are skipped. Two-way + // statistics use every allele, so we treat each allele as carried. + count_a = one_way ? allele_counts[a_off + (mut_a * state_dim) + k] : 1; + count_b = one_way ? allele_counts[b_off + (mut_b * state_dim) + k] : 1; + if (count_a == 0 || count_b == 0 + || (skip_ancestral[k] && (mut_a == 0 || mut_b == 0))) { + continue; + } + // norm_f fills in a coefficient for every result from a single pair + // of allele numbers, but the number of alleles used can differ + // between results, so we call it for each result and keep only the + // k-th coefficient. + ret = norm_f( + result_dim, weights, num_a_used[k], num_b_used[k], norm, f_params); + if (ret != 0) { + goto out; + } result[k] += result_tmp_row[k] * norm[k]; } result_tmp_row += result_dim; // Advance to the next column @@ -2651,6 +2711,27 @@ get_mutation_sample_sets(const tsk_bitset_t *allele_samples, tsk_size_t num_samp } } +// For each site and sample set, count the alleles carried by at least one sample +// in the sample set. A site varies within a sample set if this is two or more. +// The result is an array of length (n_sites * num_sample_sets). +static void +get_num_carried_alleles(tsk_size_t n_sites, const tsk_size_t *num_alleles, + const tsk_size_t *site_offsets, const tsk_size_t *allele_counts, + tsk_size_t num_sample_sets, tsk_size_t *num_carried_alleles) +{ + tsk_size_t s, m, k; + + for (s = 0; s < n_sites; s++) { + for (m = 0; m < num_alleles[s]; m++) { + for (k = 0; k < num_sample_sets; k++) { + if (allele_counts[site_offsets[s] + (m * num_sample_sets) + k] > 0) { + num_carried_alleles[(s * num_sample_sets) + k]++; + } + } + } + } +} + static int tsk_treeseq_two_site_count_stat(const tsk_treeseq_t *self, tsk_size_t state_dim, tsk_size_t num_sample_sets, const tsk_size_t *sample_set_sizes, @@ -2667,6 +2748,7 @@ tsk_treeseq_two_site_count_stat(const tsk_treeseq_t *self, tsk_size_t state_dim, double *result_row; const tsk_size_t num_samples = self->num_samples; tsk_size_t *num_alleles = NULL, *site_offsets = NULL, *allele_counts = NULL; + tsk_size_t *num_carried_alleles = NULL; tsk_size_t result_row_len = n_cols * result_dim; tsk_size_t max_ss_size = 0, max_alleles = 0, n_alleles = 0; two_locus_work_t work; @@ -2686,7 +2768,9 @@ tsk_treeseq_two_site_count_stat(const tsk_treeseq_t *self, tsk_size_t state_dim, // depends on n_sites num_alleles = tsk_malloc(n_sites * sizeof(*num_alleles)); site_offsets = tsk_malloc(n_sites * sizeof(*site_offsets)); - if (num_alleles == NULL || site_offsets == NULL) { + num_carried_alleles + = tsk_calloc(n_sites * num_sample_sets, sizeof(*num_carried_alleles)); + if (num_alleles == NULL || site_offsets == NULL || num_carried_alleles == NULL) { ret = tsk_trace_error(TSK_ERR_NO_MEMORY); goto out; } @@ -2726,6 +2810,8 @@ tsk_treeseq_two_site_count_stat(const tsk_treeseq_t *self, tsk_size_t state_dim, } get_mutation_sample_sets(&allele_samples, num_sample_sets, sample_set_sizes, sample_sets, self->sample_index_map, &allele_sample_sets, allele_counts); + get_num_carried_alleles(n_sites, num_alleles, site_offsets, allele_counts, + num_sample_sets, num_carried_alleles); // For each row/column pair, fill in the sample set in the result matrix. for (i = 0; i < n_rows; i++) { result_row = GET_2D_ROW(result, result_row_len, i); @@ -2740,7 +2826,9 @@ tsk_treeseq_two_site_count_stat(const tsk_treeseq_t *self, tsk_size_t state_dim, // at least one site is multiallelic ret = compute_general_normed_two_site_stat_result(&allele_sample_sets, allele_counts, site_offsets[row_idx[i]], site_offsets[col_idx[j]], - num_alleles[row_idx[i]], num_alleles[col_idx[j]], state_dim, + num_alleles[row_idx[i]], num_alleles[col_idx[j]], + &(num_carried_alleles[row_idx[i] * num_sample_sets]), + &(num_carried_alleles[col_idx[j] * num_sample_sets]), state_dim, result_dim, f, f_params, norm_f, polarised, &work, &(result_row[j * result_dim])); } @@ -2757,6 +2845,7 @@ tsk_treeseq_two_site_count_stat(const tsk_treeseq_t *self, tsk_size_t state_dim, tsk_safe_free(num_alleles); tsk_safe_free(site_offsets); tsk_safe_free(allele_counts); + tsk_safe_free(num_carried_alleles); two_locus_work_free(&work); tsk_bitset_free(&allele_samples); tsk_bitset_free(&allele_sample_sets); diff --git a/python/tests/test_ld_matrix.py b/python/tests/test_ld_matrix.py index 4c61f0fe65..ec77b9b5c2 100644 --- a/python/tests/test_ld_matrix.py +++ b/python/tests/test_ld_matrix.py @@ -552,10 +552,39 @@ def compute_general_two_site_stat_result( norm = np.zeros(result_dim, np.float64) result_tmp = np.zeros(result_dim, np.float64) - polarised_val = 1 if polarised else 0 - for mut_a in range(polarised_val, num_row_alleles): + # Below, use_row[m, k] (and likewise use_col) is True if allele m + # contributes to result k. This mirrors the per-result setup in the C + # function compute_general_normed_two_site_stat_result, which checks if + # alleles at a site are carried by the samples in the sample set, and + # whether the site is monomorphic. For one-way statistics, only alleles + # carried by sample set k are used (the C code precomputes these counts + # once per site in get_num_carried_alleles). Polarised statistics skip the + # ancestral allele only when both sites vary within the sample set, so that + # monomorphic sites give nan for ratio statistics and zero otherwise. + # Two-way statistics use every allele. + + use_row = np.ones((num_row_alleles, result_dim), dtype=bool) + use_col = np.ones((num_col_alleles, result_dim), dtype=bool) + if params["set_indexes"] is None: + # One-way statistics: mark which alleles at each site are carried by + # at least one sample in sample set k, then skip the ancestral allele + # (if polarised) only where both sites vary within the sample set. + for use, site_offset in [(use_row, row_site_offset), (use_col, col_site_offset)]: + for m, k in np.ndindex(use.shape): + allele_samples.intersect( + int(site_offset + m), sample_sets, k, ss_A_samples + ) + use[m, k] = ss_A_samples.count(0) > 0 + both_sites_vary = (use_row.sum(axis=0) >= 2) & (use_col.sum(axis=0) >= 2) + skip_ancestral = bool(polarised) & both_sites_vary + else: + skip_ancestral = np.full(result_dim, bool(polarised)) + use_row[0] &= ~skip_ancestral + use_col[0] &= ~skip_ancestral + + for mut_a in range(num_row_alleles): a = int(mut_a + row_site_offset) - for mut_b in range(polarised_val, num_col_alleles): + for mut_b in range(num_col_alleles): b = int(mut_b + col_site_offset) allele_samples.intersect(a, allele_samples, b, AB_samples) for k in range(state_dim): @@ -573,17 +602,13 @@ def compute_general_two_site_stat_result( func(state_dim, weights, result_dim, result_tmp, params) - norm_func( - result_dim, - weights, - num_row_alleles - polarised_val, - num_col_alleles - polarised_val, - norm, - params, - ) - for k in range(result_dim): - result[k] += result_tmp[k] * norm[k] + if use_row[mut_a, k] and use_col[mut_b, k]: + # As in C, norm_func is called once per result, since the + # number of alleles used can differ between results. + n_a, n_b = use_row[:, k].sum(), use_col[:, k].sum() + norm_func(result_dim, weights, n_a, n_b, norm, params) + result[k] += result_tmp[k] * norm[k] def two_site_count_stat( From 34382dcd9cec2aafff0a3000eee351f255866266 Mon Sep 17 00:00:00 2001 From: Aaron Ragsdale Date: Fri, 20 Nov 2026 12:00:29 -0800 Subject: [PATCH 3/9] Only use alleles carried by both sample sets in two-way site LD 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. --- c/tskit/trees.c | 130 ++++++++++++++++----------------- python/tests/test_ld_matrix.py | 83 ++++++++++++++------- 2 files changed, 118 insertions(+), 95 deletions(-) diff --git a/c/tskit/trees.c b/c/tskit/trees.c index da75e125f4..158085b0fb 100644 --- a/c/tskit/trees.c +++ b/c/tskit/trees.c @@ -2374,11 +2374,10 @@ typedef struct { double *weights; double *norm; double *result_tmp; - // For each result: whether to skip the ancestral allele, and the number of - // alleles at each site that the statistic is averaged over. + // For each result: whether to skip the ancestral allele, and the total + // weight of the allele pairs used. bool *skip_ancestral; - tsk_size_t *num_a_used; - tsk_size_t *num_b_used; + double *weight_sum; tsk_bitset_t AB_samples; } two_locus_work_t; @@ -2393,12 +2392,10 @@ two_locus_work_init(tsk_size_t max_alleles, tsk_size_t num_samples, out->result_tmp = tsk_malloc(result_dim * max_alleles * max_alleles * sizeof(*out->result_tmp)); out->skip_ancestral = tsk_malloc(result_dim * sizeof(*out->skip_ancestral)); - out->num_a_used = tsk_malloc(result_dim * sizeof(*out->num_a_used)); - out->num_b_used = tsk_malloc(result_dim * sizeof(*out->num_b_used)); + out->weight_sum = tsk_malloc(result_dim * sizeof(*out->weight_sum)); tsk_memset(&out->AB_samples, 0, sizeof(out->AB_samples)); if (out->weights == NULL || out->norm == NULL || out->result_tmp == NULL - || out->skip_ancestral == NULL || out->num_a_used == NULL - || out->num_b_used == NULL) { + || out->skip_ancestral == NULL || out->weight_sum == NULL) { ret = tsk_trace_error(TSK_ERR_NO_MEMORY); goto out; } @@ -2417,11 +2414,28 @@ two_locus_work_free(two_locus_work_t *work) tsk_safe_free(work->norm); tsk_safe_free(work->result_tmp); tsk_safe_free(work->skip_ancestral); - tsk_safe_free(work->num_a_used); - tsk_safe_free(work->num_b_used); + tsk_safe_free(work->weight_sum); tsk_bitset_free(&work->AB_samples); } +// Returns true if an allele is carried by the sample set(s) used for result k: +// sample set k for one-way statistics, or both sample sets of the k-th index +// pair for two-way statistics. Alleles that are not carried are not used, so +// that samples outside the sample set(s) do not affect the result. +static bool +allele_carried(const tsk_size_t *allele_counts, tsk_size_t allele_offset, tsk_size_t k, + const tsk_id_t *set_indexes) +{ + tsk_size_t i, j; + + if (set_indexes == NULL) { + return allele_counts[allele_offset + k] > 0; + } + i = (tsk_size_t) set_indexes[2 * k]; + j = (tsk_size_t) set_indexes[2 * k + 1]; + return allele_counts[allele_offset + i] > 0 && allele_counts[allele_offset + j] > 0; +} + static int compute_general_normed_two_site_stat_result(const tsk_bitset_t *state, const tsk_size_t *allele_counts, tsk_size_t a_off, tsk_size_t b_off, @@ -2437,44 +2451,24 @@ compute_general_normed_two_site_stat_result(const tsk_bitset_t *state, // a2 [s1, s2, s3] [s1, s2, s3] [s1, s2, s3] // a3 [s1, s2, s3] [s1, s2, s3] [s1, s2, s3] tsk_size_t k, mut_a, mut_b, result_row_len = num_b_alleles * result_dim; - tsk_size_t count_a, count_b; - uint8_t is_polarised = polarised ? 1 : 0; - bool one_way = f_params->set_indexes == NULL; - bool both_sites_vary; + const tsk_id_t *set_indexes = f_params->set_indexes; double *restrict hap_row, *restrict result_tmp_row; double *restrict norm = work->norm; double *restrict weights = work->weights; double *restrict result_tmp = work->result_tmp; bool *restrict skip_ancestral = work->skip_ancestral; - tsk_size_t *restrict num_a_used = work->num_a_used; - tsk_size_t *restrict num_b_used = work->num_b_used; + double *restrict weight_sum = work->weight_sum; tsk_bitset_t AB_samples = work->AB_samples; - // For each result, decide whether to skip the ancestral allele and how many - // alleles at each site to average over. + // Only alleles carried by the sample set(s) for each result are used (see + // allele_carried). If either site has fewer than two such alleles (e.g., it + // is monomorphic in the sample set), we keep the ancestral allele even for + // polarised statistics, so that the summary function is evaluated on the + // fixed allele: this gives nan for ratio statistics (0 / 0) and zero for all + // others. for (k = 0; k < result_dim; k++) { - if (one_way) { - // Only alleles carried by sample set k are used. If either site is - // monomorphic in sample set k, we keep the ancestral allele even for - // polarised statistics, so that the summary function is evaluated on - // the fixed allele: this gives nan for ratio statistics (0 / 0) and - // zero for all others. - both_sites_vary = num_a_carried[k] >= 2 && num_b_carried[k] >= 2; - skip_ancestral[k] = polarised && both_sites_vary; - num_a_used[k] = num_a_carried[k]; - num_b_used[k] = num_b_carried[k]; - if (skip_ancestral[k] && allele_counts[a_off + k] > 0) { - num_a_used[k]--; - } - if (skip_ancestral[k] && allele_counts[b_off + k] > 0) { - num_b_used[k]--; - } - } else { - // Two-way statistics use every allele at both sites. - skip_ancestral[k] = polarised; - num_a_used[k] = num_a_alleles - is_polarised; - num_b_used[k] = num_b_alleles - is_polarised; - } + skip_ancestral[k] = polarised && num_a_carried[k] >= 2 && num_b_carried[k] >= 2; + weight_sum[k] = 0; } for (mut_a = 0; mut_a < num_a_alleles; mut_a++) { @@ -2494,30 +2488,31 @@ compute_general_normed_two_site_stat_result(const tsk_bitset_t *state, if (ret != 0) { goto out; } + ret = norm_f( + result_dim, weights, num_a_alleles, num_b_alleles, norm, f_params); + if (ret != 0) { + goto out; + } for (k = 0; k < result_dim; k++) { - // For one-way statistics, result k is computed from sample set k, - // and alleles not carried by the sample set are skipped. Two-way - // statistics use every allele, so we treat each allele as carried. - count_a = one_way ? allele_counts[a_off + (mut_a * state_dim) + k] : 1; - count_b = one_way ? allele_counts[b_off + (mut_b * state_dim) + k] : 1; - if (count_a == 0 || count_b == 0 + if (!allele_carried( + allele_counts, a_off + (mut_a * state_dim), k, set_indexes) + || !allele_carried( + allele_counts, b_off + (mut_b * state_dim), k, set_indexes) || (skip_ancestral[k] && (mut_a == 0 || mut_b == 0))) { continue; } - // norm_f fills in a coefficient for every result from a single pair - // of allele numbers, but the number of alleles used can differ - // between results, so we call it for each result and keep only the - // k-th coefficient. - ret = norm_f( - result_dim, weights, num_a_used[k], num_b_used[k], norm, f_params); - if (ret != 0) { - goto out; - } result[k] += result_tmp_row[k] * norm[k]; + weight_sum[k] += norm[k]; } result_tmp_row += result_dim; // Advance to the next column } } + // Divide by the total weight of the allele pairs used, so that each result + // is a weighted average over those pairs. For uniform ("total") weighting, + // this is the mean over the allele pairs used. + for (k = 0; k < result_dim; k++) { + result[k] /= weight_sum[k]; + } out: return ret; } @@ -2711,21 +2706,23 @@ get_mutation_sample_sets(const tsk_bitset_t *allele_samples, tsk_size_t num_samp } } -// For each site and sample set, count the alleles carried by at least one sample -// in the sample set. A site varies within a sample set if this is two or more. -// The result is an array of length (n_sites * num_sample_sets). +// For each site and result, count the alleles carried by the sample set(s) used +// for that result (see allele_carried). The result is an array of length +// (n_sites * result_dim). static void get_num_carried_alleles(tsk_size_t n_sites, const tsk_size_t *num_alleles, const tsk_size_t *site_offsets, const tsk_size_t *allele_counts, - tsk_size_t num_sample_sets, tsk_size_t *num_carried_alleles) + tsk_size_t num_sample_sets, tsk_size_t result_dim, const tsk_id_t *set_indexes, + tsk_size_t *num_carried_alleles) { tsk_size_t s, m, k; for (s = 0; s < n_sites; s++) { for (m = 0; m < num_alleles[s]; m++) { - for (k = 0; k < num_sample_sets; k++) { - if (allele_counts[site_offsets[s] + (m * num_sample_sets) + k] > 0) { - num_carried_alleles[(s * num_sample_sets) + k]++; + for (k = 0; k < result_dim; k++) { + if (allele_carried(allele_counts, + site_offsets[s] + (m * num_sample_sets), k, set_indexes)) { + num_carried_alleles[(s * result_dim) + k]++; } } } @@ -2768,8 +2765,7 @@ tsk_treeseq_two_site_count_stat(const tsk_treeseq_t *self, tsk_size_t state_dim, // depends on n_sites num_alleles = tsk_malloc(n_sites * sizeof(*num_alleles)); site_offsets = tsk_malloc(n_sites * sizeof(*site_offsets)); - num_carried_alleles - = tsk_calloc(n_sites * num_sample_sets, sizeof(*num_carried_alleles)); + num_carried_alleles = tsk_calloc(n_sites * result_dim, sizeof(*num_carried_alleles)); if (num_alleles == NULL || site_offsets == NULL || num_carried_alleles == NULL) { ret = tsk_trace_error(TSK_ERR_NO_MEMORY); goto out; @@ -2811,7 +2807,7 @@ tsk_treeseq_two_site_count_stat(const tsk_treeseq_t *self, tsk_size_t state_dim, get_mutation_sample_sets(&allele_samples, num_sample_sets, sample_set_sizes, sample_sets, self->sample_index_map, &allele_sample_sets, allele_counts); get_num_carried_alleles(n_sites, num_alleles, site_offsets, allele_counts, - num_sample_sets, num_carried_alleles); + num_sample_sets, result_dim, f_params->set_indexes, num_carried_alleles); // For each row/column pair, fill in the sample set in the result matrix. for (i = 0; i < n_rows; i++) { result_row = GET_2D_ROW(result, result_row_len, i); @@ -2827,8 +2823,8 @@ tsk_treeseq_two_site_count_stat(const tsk_treeseq_t *self, tsk_size_t state_dim, ret = compute_general_normed_two_site_stat_result(&allele_sample_sets, allele_counts, site_offsets[row_idx[i]], site_offsets[col_idx[j]], num_alleles[row_idx[i]], num_alleles[col_idx[j]], - &(num_carried_alleles[row_idx[i] * num_sample_sets]), - &(num_carried_alleles[col_idx[j] * num_sample_sets]), state_dim, + &(num_carried_alleles[row_idx[i] * result_dim]), + &(num_carried_alleles[col_idx[j] * result_dim]), state_dim, result_dim, f, f_params, norm_f, polarised, &work, &(result_row[j * result_dim])); } diff --git a/python/tests/test_ld_matrix.py b/python/tests/test_ld_matrix.py index ec77b9b5c2..dfea34fd76 100644 --- a/python/tests/test_ld_matrix.py +++ b/python/tests/test_ld_matrix.py @@ -552,33 +552,34 @@ def compute_general_two_site_stat_result( norm = np.zeros(result_dim, np.float64) result_tmp = np.zeros(result_dim, np.float64) + weight_sum = np.zeros(result_dim, np.float64) + set_indexes = params["set_indexes"] + # Below, use_row[m, k] (and likewise use_col) is True if allele m # contributes to result k. This mirrors the per-result setup in the C - # function compute_general_normed_two_site_stat_result, which checks if - # alleles at a site are carried by the samples in the sample set, and - # whether the site is monomorphic. For one-way statistics, only alleles - # carried by sample set k are used (the C code precomputes these counts + # function compute_general_normed_two_site_stat_result. Only alleles + # carried by the sample set(s) for result k are used: sample set k for + # one-way statistics, or both sample sets of the k-th index pair for two-way + # statistics (see allele_carried in C, which also precomputes these counts # once per site in get_num_carried_alleles). Polarised statistics skip the - # ancestral allele only when both sites vary within the sample set, so that - # monomorphic sites give nan for ratio statistics and zero otherwise. - # Two-way statistics use every allele. - - use_row = np.ones((num_row_alleles, result_dim), dtype=bool) - use_col = np.ones((num_col_alleles, result_dim), dtype=bool) - if params["set_indexes"] is None: - # One-way statistics: mark which alleles at each site are carried by - # at least one sample in sample set k, then skip the ancestral allele - # (if polarised) only where both sites vary within the sample set. - for use, site_offset in [(use_row, row_site_offset), (use_col, col_site_offset)]: - for m, k in np.ndindex(use.shape): - allele_samples.intersect( - int(site_offset + m), sample_sets, k, ss_A_samples - ) - use[m, k] = ss_A_samples.count(0) > 0 - both_sites_vary = (use_row.sum(axis=0) >= 2) & (use_col.sum(axis=0) >= 2) - skip_ancestral = bool(polarised) & both_sites_vary - else: - skip_ancestral = np.full(result_dim, bool(polarised)) + # ancestral allele only when both sites have two or more such alleles, so + # that monomorphic sites give nan for ratio statistics and zero otherwise. + use = [] + for site_offset, num_alleles in [ + (row_site_offset, num_row_alleles), + (col_site_offset, num_col_alleles), + ]: + # carried[m, s] is True if allele m is carried by sample set s. + carried = np.zeros((num_alleles, state_dim), dtype=bool) + for m, s in np.ndindex(carried.shape): + allele_samples.intersect(int(site_offset + m), sample_sets, s, ss_A_samples) + carried[m, s] = ss_A_samples.count(0) > 0 + if set_indexes is not None: + carried = np.array([carried[:, i] & carried[:, j] for i, j in set_indexes]).T + use.append(carried) + use_row, use_col = use + both_sites_vary = (use_row.sum(axis=0) >= 2) & (use_col.sum(axis=0) >= 2) + skip_ancestral = bool(polarised) & both_sites_vary use_row[0] &= ~skip_ancestral use_col[0] &= ~skip_ancestral @@ -602,13 +603,19 @@ def compute_general_two_site_stat_result( func(state_dim, weights, result_dim, result_tmp, params) + norm_func( + result_dim, weights, num_row_alleles, num_col_alleles, norm, params + ) for k in range(result_dim): if use_row[mut_a, k] and use_col[mut_b, k]: - # As in C, norm_func is called once per result, since the - # number of alleles used can differ between results. - n_a, n_b = use_row[:, k].sum(), use_col[:, k].sum() - norm_func(result_dim, weights, n_a, n_b, norm, params) result[k] += result_tmp[k] * norm[k] + weight_sum[k] += norm[k] + + # As in C, divide by the total weight of the allele pairs used, so that each + # result is a weighted average over those pairs (for uniform weighting, the + # mean over the allele pairs used). + with np.errstate(divide="ignore", invalid="ignore"): + result /= weight_sum def two_site_count_stat( @@ -2553,6 +2560,26 @@ def test_multiallelic_site_becomes_monomorphic_in_subset(stat): np.testing.assert_(np.all(ld == 0)) +@pytest.mark.parametrize("stat", ["r2", "D2"]) +@pytest.mark.parametrize( + "set_up_ts, sample_set", + [ + (set_up_ts_with_ghost_allele, [0, 1, 2, 3]), + (set_up_star_ts_with_multiallelic_site, [0, 1]), + ], +) +def test_two_way_same_sample_set_matches_one_way(set_up_ts, sample_set, stat): + # With the same sample set passed twice, a two-way statistic should equal + # the one-way statistic for that sample set, including at sites with + # alleles that are not carried by the sample set. + ts = set_up_ts() + two_way = ts.ld_matrix( + sample_sets=[sample_set, sample_set], indexes=(0, 1), stat=stat + ) + one_way = ts.ld_matrix(sample_sets=sample_set, stat=stat) + np.testing.assert_(np.all(np.isclose(two_way, one_way, equal_nan=True))) + + def set_up_branch_mode_ts(): ts = msprime.sim_ancestry( 6, sequence_length=10, recombination_rate=0.05, random_seed=2 From 20c9a1955c3555c4cced5083838fa97ac5afcadc Mon Sep 17 00:00:00 2001 From: Aaron Ragsdale Date: Fri, 20 Nov 2026 13:47:05 -0800 Subject: [PATCH 4/9] Branch stat mode adds to stat only if polymorphic in sample sets --- c/tskit/trees.c | 33 ++++++++++++++++++++++++++++++++- python/tests/test_ld_matrix.py | 13 ++++++++++++- 2 files changed, 44 insertions(+), 2 deletions(-) diff --git a/c/tskit/trees.c b/c/tskit/trees.c index 158085b0fb..d2b1530487 100644 --- a/c/tskit/trees.c +++ b/c/tskit/trees.c @@ -3173,6 +3173,21 @@ advance_collect_edges(iter_state *s, tsk_id_t index) return ret; } +// Returns true if both branches can produce polymorphism in sample set s, that is, +// each branch subtends at least one, but not all, of the samples in the set. The +// weights for sample set s are the counts of AB, Ab and aB samples. +static bool +branches_vary_in_set( + const double *weights, tsk_size_t s, const tsk_size_t *sample_set_sizes) +{ + const double *row = GET_2D_ROW(weights, 3, s); + double n = (double) sample_set_sizes[s]; + double count_a = row[0] + row[1]; + double count_b = row[0] + row[2]; + + return count_a > 0 && count_a < n && count_b > 0 && count_b < n; +} + static int compute_two_tree_branch_state_update(const tsk_treeseq_t *ts, tsk_id_t c, const iter_state *A_state, const iter_state *B_state, tsk_size_t state_dim, @@ -3185,6 +3200,9 @@ compute_two_tree_branch_state_update(const tsk_treeseq_t *ts, tsk_id_t c, double *restrict B_branch_len = B_state->branch_len; double *weights_row; tsk_size_t n, k, a_row, b_row; + bool varies; + const tsk_id_t *set_indexes = f_params->set_indexes; + const tsk_size_t *sample_set_sizes = f_params->sample_set_sizes; const double *restrict A_branch_len = A_state->branch_len; const tsk_bitset_t *restrict A_state_samples = A_state->node_samples; const tsk_bitset_t *restrict B_state_samples = B_state->node_samples; @@ -3219,7 +3237,20 @@ compute_two_tree_branch_state_update(const tsk_treeseq_t *ts, tsk_id_t c, goto out; } for (k = 0; k < result_dim; k++) { - result[k] += result_tmp[k] * a_len * b_len; + // Only pairs of branches that can produce polymorphism in the sample + // set(s) for result k contribute: sample set k for one-way statistics, + // or both sample sets of the k-th index pair for two-way statistics. + if (set_indexes == NULL) { + varies = branches_vary_in_set(weights, k, sample_set_sizes); + } else { + varies = branches_vary_in_set( + weights, (tsk_size_t) set_indexes[2 * k], sample_set_sizes) + && branches_vary_in_set(weights, + (tsk_size_t) set_indexes[2 * k + 1], sample_set_sizes); + } + if (varies) { + result[k] += result_tmp[k] * a_len * b_len; + } } } out: diff --git a/python/tests/test_ld_matrix.py b/python/tests/test_ld_matrix.py index dfea34fd76..a88a5139e1 100644 --- a/python/tests/test_ld_matrix.py +++ b/python/tests/test_ld_matrix.py @@ -1970,8 +1970,19 @@ def compute_branch_stat_update( weights[2, k] = w_B - w_AB # w_aB stat_func(state_dim, weights, result_dim, result_tmp, params) + # As in the C function compute_two_tree_branch_state_update, only pairs of + # branches that can produce polymorphism contribute: each branch must + # subtend at least one, but not all, of the samples in sample set k + # (one-way), or in both sample sets of the k-th index pair (two-way). + n = np.asarray(params["sample_set_sizes"]) + count_A = weights[0] + weights[1] + count_B = weights[0] + weights[2] + varies = (count_A > 0) & (count_A < n) & (count_B > 0) & (count_B < n) + if params["set_indexes"] is not None: + varies = [varies[i] and varies[j] for i, j in params["set_indexes"]] for k in range(result_dim): - result[k] += result_tmp[k] * a_len * b_len + if varies[k]: + result[k] += result_tmp[k] * a_len * b_len def compute_branch_stat( From e5ce15ad4ca294f8a369c85e7ad5d8b884970c25 Mon Sep 17 00:00:00 2001 From: Aaron Ragsdale Date: Fri, 20 Nov 2026 13:53:10 -0800 Subject: [PATCH 5/9] Expect zero for branch LD with a single-sample set With no branches that can produce polymorphism, branch-mode statistics are an empty sum, so every statistic is zero. --- python/tests/test_ld_matrix.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/python/tests/test_ld_matrix.py b/python/tests/test_ld_matrix.py index a88a5139e1..827b1afe15 100644 --- a/python/tests/test_ld_matrix.py +++ b/python/tests/test_ld_matrix.py @@ -2618,13 +2618,13 @@ def test_branch_mode_subset_matches_simplified(stat): @pytest.mark.parametrize("stat", sorted(SUMMARY_FUNCS.keys())) -def test_branch_mode_single_sample_is_nan(stat): - # With a single sample, there is no polymorphism (no branches we compute - # over!), so nothing is computed and every statistic is nan. <- This would - # be a breaking change but I think makes sense?? +def test_branch_mode_single_sample_is_zero(stat): + # With a single sample, no branch can produce polymorphism, so no branches + # contribute. Branch statistics are sums over contributing branches, so + # every statistic is zero (an empty sum). ts, positions = set_up_branch_mode_ts() ld = ts.ld_matrix(sample_sets=[0], positions=positions, mode="branch", stat=stat) - np.testing.assert_(np.all(np.isnan(ld))) + np.testing.assert_(np.all(ld == 0)) def test_branch_mode_two_way_r2_not_nan(): From 3fdbe3589a9961f81dc5fcc577e5a621ea39791c Mon Sep 17 00:00:00 2001 From: Aaron Ragsdale Date: Fri, 20 Nov 2026 14:06:27 -0800 Subject: [PATCH 6/9] Update two-way D2_unbiased C test values for disjoint sample sets Only alleles carried by both sample sets are now used for two-way statistics, which changes the expected values for disjoint sets. --- c/tests/test_stats.c | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/c/tests/test_stats.c b/c/tests/test_stats.c index 50a1c84417..5568b4bd07 100644 --- a/c/tests/test_stats.c +++ b/c/tests/test_stats.c @@ -3066,8 +3066,8 @@ test_two_site_correlated_multiallelic(void) -0.008818342151675485, -0.008818342151675485 }; double truth_pi2_unbiased[4] = { 0.0582010582010582, 0.0582010582010582, 0.0582010582010582, 0.0582010582010582 }; - double truth_D2_unbiased_disjoint[4] = { 0.007407407407407407, 0.007407407407407407, - 0.007407407407407407, 0.007407407407407407 }; + double truth_D2_unbiased_disjoint[4] = { 0.06666666666666667, 0.06666666666666667, + 0.06666666666666667, 0.06666666666666667 }; tsk_treeseq_from_text( &ts, 20, nodes, edges, NULL, tree_sites, mutations, NULL, NULL, 0); @@ -3176,6 +3176,7 @@ test_two_site_correlated_multiallelic(void) assert_arrays_almost_equal(result_size, result, truth_D2_unbiased); // two disjoint sample sets with 5 and 4 samples {0,1,2,3,4}{5,6,7,8} + // only alleles carried by both sample sets are used sample_set_sizes[0] = 5; sample_set_sizes[1] = 4; tsk_memset(result, 0, sizeof(*result) * result_size); @@ -3258,8 +3259,8 @@ test_two_site_uncorrelated_multiallelic(void) 0.005291005291005289, -0.015873015873015872 }; double truth_pi2_unbiased[4] = { 0.06349206349206349, 0.06216931216931215, 0.06216931216931215, 0.06349206349206349 }; - double truth_D2_unbiased_disjoint[4] = { 0.008333333333333333, - -0.0027777777777777775, -0.0027777777777777775, 0.03518518518518518 }; + double truth_D2_unbiased_disjoint[4] + = { 0.075, -0.008333333333333333, -0.008333333333333333, 0.035185185185185174 }; tsk_treeseq_from_text( &ts, 20, nodes, edges, NULL, tree_sites, mutations, NULL, NULL, 0); @@ -3369,6 +3370,7 @@ test_two_site_uncorrelated_multiallelic(void) assert_arrays_almost_equal(result_size, result, truth_D2_unbiased); // two disjoint sample sets with 5 and 4 samples {0,1,2,3,4}{5,6,7,8} + // only alleles carried by both sample sets are used sample_set_sizes[0] = 5; sample_set_sizes[1] = 4; tsk_memset(result, 0, sizeof(*result) * result_size); From c6abd004a7bd0f21a2ac2d8960f48d12208f6232 Mon Sep 17 00:00:00 2001 From: Aaron Ragsdale Date: Fri, 20 Nov 2026 15:26:45 -0800 Subject: [PATCH 7/9] Document LD calculation with unobserved sites and branches --- docs/stats.md | 101 ++++++++++++++++++++++++++++--------------- python/CHANGELOG.rst | 5 +++ 2 files changed, 70 insertions(+), 36 deletions(-) diff --git a/docs/stats.md b/docs/stats.md index 61c9cf29b4..c0bfa7101b 100644 --- a/docs/stats.md +++ b/docs/stats.md @@ -742,6 +742,8 @@ ld = ts.ld_matrix(sites=[[1, 2], [1, 2, 3]]) print(ld) ``` +(sec_stats_two_locus_computational_details)= + #### Computational details Because we allow for two-locus statistics to be computed for multi-allelic @@ -754,16 +756,21 @@ These are statistic-specific and not chosen by the user, with choices motivated by [Zhao (2007)](https://doi.org/10.1017/S0016672307008634). Briefly, consider a pair of sites with {math}`n` alleles at the first locus and -{math}`m` alleles at the second. (Whether this includes the ancestral allele -depends on whether the statistic is polarised.) Write {math}`f_{ij}` as the -statistic computed for focal alleles {math}`A_i` and {math}`B_j`. Then the +{math}`m` alleles at the second that are carried by the sample set (or by both +sample sets, for two-way statistics; see +{ref}`sec_stats_two_locus_unobserved`). (Whether this includes the ancestral +allele depends on whether the statistic is polarised.) Write {math}`f_{ij}` as +the statistic computed for focal alleles {math}`A_i` and {math}`B_j`. Then the weighting schemes are defined as: -- `hap_weighted`: {math}`\sum_{i=1}^{n}\sum_{j=1}^{m}p(A_{i}B_{j})f_{ij}`, +- `hap_weighted`: {math}`\sum_{i=1}^{n}\sum_{j=1}^{m}p(A_{i}B_{j})f_{ij} \big/ \sum_{i=1}^{n}\sum_{j=1}^{m}p(A_{i}B_{j})`, where {math}`p(A_{i}B_{j})` is the frequency of haplotype {math}`A_{i}B_{j}`. This method was first introduced in [Karlin (1981)](https://doi.org/10.1111/j.1469-1809.1981.tb00308.x) and reviewed in - [Zhao (2007)](https://doi.org/10.1017/S0016672307008634). + [Zhao (2007)](https://doi.org/10.1017/S0016672307008634). For one-way + statistics the denominator is one, but for two-way statistics it can be less + than one if the two sample sets carry different alleles, so we divide by + the total weight {math}`p(A_{i}B_{j})` of the allele pairs that contribute. - `total_weighted`: {math}`\frac{1}{n m}\sum_{i=1}^{n}\sum_{j=1}^{m}f_{ij}`. This method assigns equal weight to each of the possible pairs of focal @@ -780,10 +787,18 @@ alleles. (For this purpose, the "derived" alleles at a site are all alleles except that stored as the ``ancestral_state`` for the site.) Unpolarised statistics compute statistics over all pairs of alleles, derived and ancestral. In either case, the result is averaged over these values, using one of the -weighting scheme (described below for each statistics). The option for +weighting schemes (described below for each statistic). The option for polarisation is not exposed to the user, and we list which statistics are polarised below. +For polarised statistics, to ensure sensible results when either site is +monomorphic in the sample set, we do not skip the ancestral allele, so that the +statistic is computed for the single allele that the sample set carries. If the +sample set does not carry the ancestral allele at a site, all of the alleles it +carries are treated as derived. For example, if the ancestral allele is `A` and the sample set carries +only alleles `C` and `T`, polarised {math}`D` is zero at that site, since +{math}`D_C = -D_T`. + (sec_stats_two_locus_branch)= #### Branch mode @@ -796,8 +811,10 @@ generated by a single mutation occurring on each of the two trees. For two trees, one with {math}`n` branches and the other with {math}`m` branches, there are {math}`nm` possible pairs of branches that may carry the -pair of mutations. For each pair, we compute the two-locus statistic, and then -sum these values weighted by the product of the two branch lengths. Given that +pair of mutations. For each pair of branches that could produce a polymorphism +within the sample set (see {ref}`sec_stats_two_locus_unobserved`), we compute +the two-locus statistic, and then sum these values weighted by the product of +the two branch lengths. Given that the two mutations occur, this accounts for the relative probability that the two mutations fall on any pair of branches. @@ -919,13 +936,33 @@ ts.ld_matrix(sample_sets=[[0, 1, 2, 3], [4, 5, 6, 7]], indexes=(0, 1)) # -> 2 di ts.ld_matrix(sample_sets=[[0, 1, 2, 3], [4, 5, 6, 7]], indexes=[(0, 1)]) # -> 3 dimensions ``` -#### Why are there `nan` values in the LD matrix? +(sec_stats_two_locus_unobserved)= + +#### Alleles and branches not seen in a sample set + +Alleles and branches that are not observed in a sample set do not affect the LD +computed for that sample set. For example, LD computed for a subset of samples +gives the same values as LD computed after simplifying the tree sequence to +those samples. In the next example, allele `T` is carried only by sample 2, so +it is not used when computing LD among samples 0 and 1: + +```{code-cell} ipython3 +import tskit + +tables = tskit.Tree.generate_star(3).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") +example_ts = tables.tree_sequence() +print(example_ts.ld_matrix(sample_sets=[0, 1])) +print(example_ts.simplify([0, 1]).ld_matrix()) +``` -For some statistics, it is possible to observe `nan` entries in the LD matrix, -which can be surprising and may numerically impact downstream analyses. A `nan` -entry occurs if the denominator of a ratio statistic (including {math}`r` and -{math}`r^2`) is zero, indicating that one or both of the alleles in the pair is -fixed or absent in the given sample set(s). This can happen for +In the `"site"` mode, we only use alleles that are carried by at least one +sample in the sample set (or by both sample sets, for two-way statistics). If +either site is monomorphic in the sample set, ratio statistics (including +{math}`r` and {math}`r^2`) are `nan`, since their denominator is zero, and all +other statistics are zero. A site can be monomorphic in a sample set for a number of reasons: - Some mutation models allow for reversible mutations, so a back mutation at @@ -936,24 +973,12 @@ a number of reasons: - A mutation exists above the root of the local tree, so that all samples carry the mutation, and one or more sites are not variable. -The `branch` mode will also return `nan` values for ratio statistics if there -are branches in either tree on which a mutation would not result in -a polymorphism within a sample set. - -:::{warning} -This means there are two common situations in which many or all LD values will be `nan`. -These are: - -1. A branch-mode ratio statistic computed on less than the full set of samples - will always be `nan`, since part of the trees are ancestral to none of the samples. -2. A site-mode ratio statistic will be `nan` at any sites at which there are alleles found - in the entire set of samples that are not seen in the provided sample set. - -This behavior **may change in the future**, -because possibly more natural behavior not currently implemented -would be to ignore the branches/alleles not ancestral -to any of the provided samples. -::: +In the `"branch"` mode, we only use pairs of branches that could each produce +a polymorphism within the sample set (or within both sample sets, for two-way +statistics), that is, branches that are ancestral to at least one, but not all, +of the samples in the sample set(s). Branch-mode statistics are sums over these +pairs of branches, so if no branch can produce a polymorphism (for instance, +for a sample set containing a single sample), the result is zero. (sec_stats_two_locus_sample_one_way_stats)= @@ -974,7 +999,9 @@ computed from each sample set, indexed by `(i, j)`. These statistics take on a different meaning from their one-way counterparts. For instance `stat="D2"` over a pair of sample sets computes {math}`D_i D_j`, which is the product of the covariance measure of LD within each sample set and is related to the -covariance of {math}`D` between sample sets. +covariance of {math}`D` between sample sets. Only alleles carried by both +sample sets {math}`i` and {math}`j` are used (see +{ref}`sec_stats_two_locus_unobserved`). Only a subset of our summary functions are two-way statistics (see {ref}`sec_two_locus_summary_functions_two_way`). Note that the unbiased two-way @@ -1027,7 +1054,9 @@ allele at either of the two loci. For unpolarised statistics, we compute the summary function over all pairs of alleles. Thus, for polarised statistics, the summary function is called {math}`(n_1-1)\times(n_2-1)` times, where {math}`n_1` and {math}`n_2` -are the total number of alleles at the first and second locus, respectively. +are the number of alleles carried by the sample set at the first and second +locus, respectively (see {ref}`sec_stats_two_locus_computational_details` for +exceptions). For unpolarised statistics, the summary function is called {math}`n_1 n_2` times. The result is then averaged over the results computed for each pair of focal alleles, using the specified weighting approach for a @@ -1043,8 +1072,8 @@ given summary function. : {math}`f(n_{AB}, n_{Ab}, n_{aB}, n) = \frac{D}{D_{\max}}`, where {math}`D_{\max} = \begin{cases} - \min\{p_A (1-p_B), p_B (1-p_B)\} & \textrm{if }D>=0 \\ - \min\{p_A p_B, (1-p_B) (1-p_B)\} & \textrm{if }D<0 + \min\{p_A (1-p_B), (1-p_A) p_B\} & \textrm{if }D>=0 \\ + \min\{p_A p_B, (1-p_A) (1-p_B)\} & \textrm{if }D<0 \end{cases}` and {math}`D` is defined above. Polarised, `total` weighted. diff --git a/python/CHANGELOG.rst b/python/CHANGELOG.rst index 0ad087cfc0..3b8d378628 100644 --- a/python/CHANGELOG.rst +++ b/python/CHANGELOG.rst @@ -18,6 +18,11 @@ In development (:user:`rpinho`, :pr:`3514`) - Preserve edge and migration metadata in ``ltrim`` and ``trim``. (:user:`rpinho`, :pr:`3511`) +- ``TreeSequence.ld_matrix`` now ignores alleles and branches that are not + observed in the sample set(s), so they no longer cause ``nan`` values or + affect the result. Ratio statistics are still ``nan`` at sites that are + monomorphic in the sample set. (:user:`apragsdale`, :issue:`3441`, + :issue:`3474`, :pr:`3515`) -------------------- [1.0.4] - 2026-10-30 From 367f0926d988d1989b768b9876ffd990885deee1 Mon Sep 17 00:00:00 2001 From: Aaron Ragsdale Date: Mon, 23 Nov 2026 12:07:05 -0600 Subject: [PATCH 8/9] Update c code to avoid calcultion when pairs are skipped --- c/tskit/trees.c | 68 +++++++++++++++++++++++----------- python/tests/test_ld_matrix.py | 3 ++ 2 files changed, 49 insertions(+), 22 deletions(-) diff --git a/c/tskit/trees.c b/c/tskit/trees.c index d2b1530487..320a9d84c5 100644 --- a/c/tskit/trees.c +++ b/c/tskit/trees.c @@ -2374,10 +2374,12 @@ typedef struct { double *weights; double *norm; double *result_tmp; - // For each result: whether to skip the ancestral allele, and the total - // weight of the allele pairs used. + // For each result, whether to skip calculation involving the ancestral allele bool *skip_ancestral; + // Running sum of the total weight over the allele pairs used double *weight_sum; + // For each result, whether the current pair of alleles is used + bool *pair_used; tsk_bitset_t AB_samples; } two_locus_work_t; @@ -2393,9 +2395,11 @@ two_locus_work_init(tsk_size_t max_alleles, tsk_size_t num_samples, = tsk_malloc(result_dim * max_alleles * max_alleles * sizeof(*out->result_tmp)); out->skip_ancestral = tsk_malloc(result_dim * sizeof(*out->skip_ancestral)); out->weight_sum = tsk_malloc(result_dim * sizeof(*out->weight_sum)); + out->pair_used = tsk_malloc(result_dim * sizeof(*out->pair_used)); tsk_memset(&out->AB_samples, 0, sizeof(out->AB_samples)); if (out->weights == NULL || out->norm == NULL || out->result_tmp == NULL - || out->skip_ancestral == NULL || out->weight_sum == NULL) { + || out->skip_ancestral == NULL || out->weight_sum == NULL + || out->pair_used == NULL) { ret = tsk_trace_error(TSK_ERR_NO_MEMORY); goto out; } @@ -2415,13 +2419,15 @@ two_locus_work_free(two_locus_work_t *work) tsk_safe_free(work->result_tmp); tsk_safe_free(work->skip_ancestral); tsk_safe_free(work->weight_sum); + tsk_safe_free(work->pair_used); tsk_bitset_free(&work->AB_samples); } -// Returns true if an allele is carried by the sample set(s) used for result k: -// sample set k for one-way statistics, or both sample sets of the k-th index -// pair for two-way statistics. Alleles that are not carried are not used, so -// that samples outside the sample set(s) do not affect the result. +// Returns true if an allele is carried by the sample set(s) used for result +// indexed by k, i.e. whether allele is seen in sample set k for one-way +// statistics or in both sample sets of the k-th index pair for two-way +// statistics. Alleles that are not carried are not used, so that alleles +// carried only by samples outside the sample set(s) do not affect the result. static bool allele_carried(const tsk_size_t *allele_counts, tsk_size_t allele_offset, tsk_size_t k, const tsk_id_t *set_indexes) @@ -2458,14 +2464,16 @@ compute_general_normed_two_site_stat_result(const tsk_bitset_t *state, double *restrict result_tmp = work->result_tmp; bool *restrict skip_ancestral = work->skip_ancestral; double *restrict weight_sum = work->weight_sum; + bool *restrict pair_used = work->pair_used; + bool any_pair_used; tsk_bitset_t AB_samples = work->AB_samples; - // Only alleles carried by the sample set(s) for each result are used (see - // allele_carried). If either site has fewer than two such alleles (e.g., it + // Only alleles carried by the sample set(s) for each result are used (from + // allele_carried). If either site has fewer than two such alleles (i.e., it // is monomorphic in the sample set), we keep the ancestral allele even for // polarised statistics, so that the summary function is evaluated on the - // fixed allele: this gives nan for ratio statistics (0 / 0) and zero for all - // others. + // fixed allele: this gives nan for ratio statistics r2, r and D_prime + // (0 / 0) and zero for all others. for (k = 0; k < result_dim; k++) { skip_ancestral[k] = polarised && num_a_carried[k] >= 2 && num_b_carried[k] >= 2; weight_sum[k] = 0; @@ -2474,6 +2482,26 @@ compute_general_normed_two_site_stat_result(const tsk_bitset_t *state, for (mut_a = 0; mut_a < num_a_alleles; mut_a++) { result_tmp_row = GET_2D_ROW(result_tmp, result_row_len, mut_a); for (mut_b = 0; mut_b < num_b_alleles; mut_b++) { + // For each result, check whether this pair of alleles is used. Both + // alleles must be carried by the sample set(s) for that result, and + // neither can be the ancestral allele if it is skipped for that result. + any_pair_used = false; + for (k = 0; k < result_dim; k++) { + pair_used[k] = allele_carried(allele_counts, a_off + (mut_a * state_dim), + k, set_indexes) + && allele_carried(allele_counts, + b_off + (mut_b * state_dim), k, set_indexes) + && !(skip_ancestral[k] && (mut_a == 0 || mut_b == 0)); + any_pair_used = any_pair_used || pair_used[k]; + } + // The summary function computes all results at once, so we skip + // the haplotype counts and summary function if no result uses this + // pair of alleles, avoiding the bitset operation and summary function + // calculation. + if (!any_pair_used) { + result_tmp_row += result_dim; + continue; + } for (k = 0; k < state_dim; k++) { tsk_bitset_intersect(state, a_off + (mut_a * state_dim) + k, state, b_off + (mut_b * state_dim) + k, &AB_samples); @@ -2494,15 +2522,10 @@ compute_general_normed_two_site_stat_result(const tsk_bitset_t *state, goto out; } for (k = 0; k < result_dim; k++) { - if (!allele_carried( - allele_counts, a_off + (mut_a * state_dim), k, set_indexes) - || !allele_carried( - allele_counts, b_off + (mut_b * state_dim), k, set_indexes) - || (skip_ancestral[k] && (mut_a == 0 || mut_b == 0))) { - continue; + if (pair_used[k]) { + result[k] += result_tmp_row[k] * norm[k]; + weight_sum[k] += norm[k]; } - result[k] += result_tmp_row[k] * norm[k]; - weight_sum[k] += norm[k]; } result_tmp_row += result_dim; // Advance to the next column } @@ -3237,9 +3260,10 @@ compute_two_tree_branch_state_update(const tsk_treeseq_t *ts, tsk_id_t c, goto out; } for (k = 0; k < result_dim; k++) { - // Only pairs of branches that can produce polymorphism in the sample - // set(s) for result k contribute: sample set k for one-way statistics, - // or both sample sets of the k-th index pair for two-way statistics. + // Only pairs of branches that can produce polymorphism in the + // sample set(s) for result k contribute, where k indexes a single + // sample set for one-way statistics, or k indexes a pair of sample + // sets for two-way statistics. if (set_indexes == NULL) { varies = branches_vary_in_set(weights, k, sample_set_sizes); } else { diff --git a/python/tests/test_ld_matrix.py b/python/tests/test_ld_matrix.py index 827b1afe15..081ecde261 100644 --- a/python/tests/test_ld_matrix.py +++ b/python/tests/test_ld_matrix.py @@ -586,6 +586,9 @@ def compute_general_two_site_stat_result( for mut_a in range(num_row_alleles): a = int(mut_a + row_site_offset) for mut_b in range(num_col_alleles): + # Following the C code, skip pairs of alleles that no result uses. + if not np.any(use_row[mut_a] & use_col[mut_b]): + continue b = int(mut_b + col_site_offset) allele_samples.intersect(a, allele_samples, b, AB_samples) for k in range(state_dim): From 8849821951c64128be901227040224706cb9d547 Mon Sep 17 00:00:00 2001 From: Aaron Ragsdale Date: Mon, 23 Nov 2026 12:16:56 -0600 Subject: [PATCH 9/9] Small tweaks to two-locus docs --- docs/stats.md | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/docs/stats.md b/docs/stats.md index c0bfa7101b..4e915831f6 100644 --- a/docs/stats.md +++ b/docs/stats.md @@ -940,11 +940,13 @@ ts.ld_matrix(sample_sets=[[0, 1, 2, 3], [4, 5, 6, 7]], indexes=[(0, 1)]) # -> 3 #### Alleles and branches not seen in a sample set -Alleles and branches that are not observed in a sample set do not affect the LD -computed for that sample set. For example, LD computed for a subset of samples -gives the same values as LD computed after simplifying the tree sequence to -those samples. In the next example, allele `T` is carried only by sample 2, so -it is not used when computing LD among samples 0 and 1: +Alleles that are not observed in a sample set (or branches on which mutation +would produce such alleles) should not affect the LD computed for that sample +set. For example, we expect LD computed for a subset of samples to give the +same value as LD computed after simplifying the tree sequence to those samples. +As shown in the next example, allele `T` is carried only by sample 2, so it is +not used when computing LD among samples 0 and 1, and we expect equivalent +results: ```{code-cell} ipython3 import tskit @@ -959,11 +961,11 @@ print(example_ts.simplify([0, 1]).ld_matrix()) ``` In the `"site"` mode, we only use alleles that are carried by at least one -sample in the sample set (or by both sample sets, for two-way statistics). If +sample in the sample set (or in both sample sets, for two-way statistics). If either site is monomorphic in the sample set, ratio statistics (including -{math}`r` and {math}`r^2`) are `nan`, since their denominator is zero, and all -other statistics are zero. A site can be monomorphic in a sample set for -a number of reasons: +{math}`r` and {math}`r^2`) are `nan`, since their denominator is zero. All +non-ratio statistics are zero with a monomorphic site. A site can be +monomorphic in a sample set for a number of reasons, including: - Some mutation models allow for reversible mutations, so a back mutation at a site can result in a single allele despite multiple mutations in the