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); diff --git a/c/tskit/trees.c b/c/tskit/trees.c index 2fcf399e20..320a9d84c5 100644 --- a/c/tskit/trees.c +++ b/c/tskit/trees.c @@ -2374,6 +2374,12 @@ typedef struct { double *weights; double *norm; double *result_tmp; + // 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; @@ -2387,8 +2393,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->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) { + if (out->weights == NULL || out->norm == NULL || out->result_tmp == NULL + || out->skip_ancestral == NULL || out->weight_sum == NULL + || out->pair_used == NULL) { ret = tsk_trace_error(TSK_ERR_NO_MEMORY); goto out; } @@ -2406,15 +2417,38 @@ 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->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 +// 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) +{ + 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, - 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 +2457,51 @@ 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; - uint8_t is_polarised = polarised ? 1 : 0; + 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; + 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; - for (mut_a = is_polarised; mut_a < num_a_alleles; mut_a++) { + // 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 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; + } + + 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 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); @@ -2447,17 +2516,26 @@ 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); + 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++) { - result[k] += result_tmp_row[k] * norm[k]; + if (pair_used[k]) { + 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; } @@ -2651,6 +2729,29 @@ get_mutation_sample_sets(const tsk_bitset_t *allele_samples, tsk_size_t num_samp } } +// 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 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 < 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]++; + } + } + } + } +} + 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 +2768,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 +2788,8 @@ 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 * 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; } @@ -2726,6 +2829,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, 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); @@ -2740,7 +2845,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] * 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])); } @@ -2757,6 +2864,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); @@ -3088,6 +3196,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, @@ -3100,6 +3223,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; @@ -3134,7 +3260,21 @@ 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, 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 { + 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/docs/stats.md b/docs/stats.md index 61c9cf29b4..4e915831f6 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,14 +936,36 @@ 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 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 + +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 -a number of reasons: +In the `"site"` mode, we only use alleles that are carried by at least one +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. 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 @@ -936,24 +975,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 +1001,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 +1056,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 +1074,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 diff --git a/python/tests/test_ld_matrix.py b/python/tests/test_ld_matrix.py index 4d6e47ddcc..081ecde261 100644 --- a/python/tests/test_ld_matrix.py +++ b/python/tests/test_ld_matrix.py @@ -552,10 +552,43 @@ 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): + 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. 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 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 + + 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): + # 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): @@ -574,16 +607,18 @@ 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, + result_dim, weights, num_row_alleles, num_col_alleles, 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]: + 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( @@ -1938,8 +1973,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( @@ -2398,3 +2444,199 @@ 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)) + + +@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 + ) + # 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_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(ld == 0)) + + +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)))