From 313e2464c18a093561266210f17300864c9adef0 Mon Sep 17 00:00:00 2001 From: Chen-Yang Su Date: Sun, 29 Nov 2026 14:47:25 -0800 Subject: [PATCH] Use scaled shifted two-pass centering in trait_covariance and trait_correlation --- c/tests/test_stats.c | 31 ++++++++ c/tskit/trees.c | 137 +++++++++++++++++++++++--------- python/tests/test_tree_stats.py | 38 +++++++++ python/tskit/trees.py | 3 +- 4 files changed, 169 insertions(+), 40 deletions(-) diff --git a/c/tests/test_stats.c b/c/tests/test_stats.c index 50a1c84417..7e7092a116 100644 --- a/c/tests/test_stats.c +++ b/c/tests/test_stats.c @@ -1779,6 +1779,14 @@ test_paper_ex_trait_covariance(void) CU_ASSERT_EQUAL_FATAL(ret, 0); CU_ASSERT_DOUBLE_EQUAL_FATAL(result, 0.0, 1e-6); + /* large constant weights should not overflow during mean calculation */ + for (j = 0; j < 4; j++) { + weights[j] = 1e308; + } + ret = tsk_treeseq_trait_covariance(&ts, 1, weights, 0, NULL, TSK_STAT_SITE, &result); + CU_ASSERT_EQUAL_FATAL(ret, 0); + CU_ASSERT_DOUBLE_EQUAL_FATAL(result, 0.0, 1e-6); + tsk_treeseq_free(&ts); free(weights); } @@ -1813,6 +1821,29 @@ test_paper_ex_trait_correlation(void) CU_ASSERT_EQUAL_FATAL(ret, 0); CU_ASSERT_DOUBLE_EQUAL_FATAL(result, 1.0, 1e-6); + /* large offset should not suffer catastrophic cancellation */ + weights[0] = weights[1] = 1e9; + weights[2] = weights[3] = 1e9 + 1.0; + ret = tsk_treeseq_trait_correlation( + &ts, 1, weights, 0, NULL, TSK_STAT_SITE, &result); + CU_ASSERT_EQUAL_FATAL(ret, 0); + CU_ASSERT_DOUBLE_EQUAL_FATAL(result, 1.0, 1e-6); + + /* large and tiny scales should not overflow or underflow */ + weights[0] = weights[1] = 0.0; + weights[2] = weights[3] = 1e200; + ret = tsk_treeseq_trait_correlation( + &ts, 1, weights, 0, NULL, TSK_STAT_SITE, &result); + CU_ASSERT_EQUAL_FATAL(ret, 0); + CU_ASSERT_DOUBLE_EQUAL_FATAL(result, 1.0, 1e-6); + + weights[0] = weights[1] = 0.0; + weights[2] = weights[3] = 1e-200; + ret = tsk_treeseq_trait_correlation( + &ts, 1, weights, 0, NULL, TSK_STAT_SITE, &result); + CU_ASSERT_EQUAL_FATAL(ret, 0); + CU_ASSERT_DOUBLE_EQUAL_FATAL(result, 1.0, 1e-6); + tsk_treeseq_free(&ts); free(weights); } diff --git a/c/tskit/trees.c b/c/tskit/trees.c index 2fcf399e20..8dfd5a04cf 100644 --- a/c/tskit/trees.c +++ b/c/tskit/trees.c @@ -3984,11 +3984,15 @@ tsk_treeseq_trait_covariance(const tsk_treeseq_t *self, tsk_size_t num_weights, int ret; const double *row; double *new_row; - double *means = tsk_calloc(num_weights, sizeof(double)); + double *max_abs = tsk_calloc(num_weights, sizeof(double)); + int *exps = tsk_calloc(num_weights, sizeof(int)); + double *u0 = tsk_calloc(num_weights, sizeof(double)); + double *shifted_means = tsk_calloc(num_weights, sizeof(double)); double *new_weights = tsk_malloc((num_weights + 1) * num_samples * sizeof(double)); weight_stat_params_t args = { num_samples = self->num_samples }; - if (new_weights == NULL || means == NULL) { + if (new_weights == NULL || max_abs == NULL || exps == NULL || u0 == NULL + || shifted_means == NULL) { ret = tsk_trace_error(TSK_ERR_NO_MEMORY); goto out; } @@ -3997,21 +4001,41 @@ tsk_treeseq_trait_covariance(const tsk_treeseq_t *self, tsk_size_t num_weights, goto out; } - // center weights - for (j = 0; j < num_samples; j++) { - row = GET_2D_ROW(weights, num_weights, j); + if (num_samples > 0) { + // Scale by an exact power of 2 and shift by the first sample so that + // centering neither overflows nor loses precision on large offsets. + for (j = 0; j < num_samples; j++) { + row = GET_2D_ROW(weights, num_weights, j); + for (k = 0; k < num_weights; k++) { + double a = fabs(row[k]); + if (a > max_abs[k]) { + max_abs[k] = a; + } + } + } + row = GET_2D_ROW(weights, num_weights, 0); for (k = 0; k < num_weights; k++) { - means[k] += row[k]; + if (max_abs[k] > 0.0 && tsk_isfinite(max_abs[k])) { + frexp(max_abs[k], &exps[k]); + } + u0[k] = ldexp(row[k], -exps[k]); + } + for (j = 0; j < num_samples; j++) { + row = GET_2D_ROW(weights, num_weights, j); + for (k = 0; k < num_weights; k++) { + shifted_means[k] += ldexp(row[k], -exps[k]) - u0[k]; + } } - } - for (k = 0; k < num_weights; k++) { - means[k] /= (double) num_samples; - } - for (j = 0; j < num_samples; j++) { - row = GET_2D_ROW(weights, num_weights, j); - new_row = GET_2D_ROW(new_weights, num_weights, j); for (k = 0; k < num_weights; k++) { - new_row[k] = row[k] - means[k]; + shifted_means[k] /= (double) num_samples; + } + for (j = 0; j < num_samples; j++) { + row = GET_2D_ROW(weights, num_weights, j); + new_row = GET_2D_ROW(new_weights, num_weights, j); + for (k = 0; k < num_weights; k++) { + new_row[k] = ldexp( + (ldexp(row[k], -exps[k]) - u0[k]) - shifted_means[k], exps[k]); + } } } @@ -4019,7 +4043,10 @@ tsk_treeseq_trait_covariance(const tsk_treeseq_t *self, tsk_size_t num_weights, trait_covariance_summary_func, &args, num_windows, windows, options, result); out: - tsk_safe_free(means); + tsk_safe_free(max_abs); + tsk_safe_free(exps); + tsk_safe_free(u0); + tsk_safe_free(shifted_means); tsk_safe_free(new_weights); return ret; } @@ -4053,15 +4080,19 @@ tsk_treeseq_trait_correlation(const tsk_treeseq_t *self, tsk_size_t num_weights, tsk_size_t num_samples = self->num_samples; tsk_size_t j, k; int ret; - double *means = tsk_calloc(num_weights, sizeof(double)); - double *meansqs = tsk_calloc(num_weights, sizeof(double)); + double *max_abs = tsk_calloc(num_weights, sizeof(double)); + int *exps = tsk_calloc(num_weights, sizeof(int)); + double *u0 = tsk_calloc(num_weights, sizeof(double)); + double *shifted_means = tsk_calloc(num_weights, sizeof(double)); + double *sum_sq = tsk_calloc(num_weights, sizeof(double)); double *sds = tsk_calloc(num_weights, sizeof(double)); const double *row; double *new_row; double *new_weights = tsk_malloc((num_weights + 1) * num_samples * sizeof(double)); weight_stat_params_t args = { num_samples = self->num_samples }; - if (new_weights == NULL || means == NULL || meansqs == NULL || sds == NULL) { + if (new_weights == NULL || max_abs == NULL || exps == NULL || u0 == NULL + || shifted_means == NULL || sum_sq == NULL || sds == NULL) { ret = tsk_trace_error(TSK_ERR_NO_MEMORY); goto out; } @@ -4071,36 +4102,66 @@ tsk_treeseq_trait_correlation(const tsk_treeseq_t *self, tsk_size_t num_weights, goto out; } - // center and scale weights - for (j = 0; j < num_samples; j++) { - row = GET_2D_ROW(weights, num_weights, j); + if (num_samples > 0) { + // Scale by an exact power of 2, shift by the first sample, and use a + // two-pass sum of squared deviations so centering and scaling neither + // overflow/underflow nor suffer catastrophic cancellation. + for (j = 0; j < num_samples; j++) { + row = GET_2D_ROW(weights, num_weights, j); + for (k = 0; k < num_weights; k++) { + double a = fabs(row[k]); + if (a > max_abs[k]) { + max_abs[k] = a; + } + } + } + row = GET_2D_ROW(weights, num_weights, 0); for (k = 0; k < num_weights; k++) { - means[k] += row[k]; - meansqs[k] += row[k] * row[k]; + if (max_abs[k] > 0.0 && tsk_isfinite(max_abs[k])) { + frexp(max_abs[k], &exps[k]); + } + u0[k] = ldexp(row[k], -exps[k]); + } + for (j = 0; j < num_samples; j++) { + row = GET_2D_ROW(weights, num_weights, j); + for (k = 0; k < num_weights; k++) { + shifted_means[k] += ldexp(row[k], -exps[k]) - u0[k]; + } } - } - for (k = 0; k < num_weights; k++) { - means[k] /= (double) num_samples; - meansqs[k] -= means[k] * means[k] * (double) num_samples; - meansqs[k] /= (double) (num_samples - 1); - sds[k] = sqrt(meansqs[k]); - } - for (j = 0; j < num_samples; j++) { - row = GET_2D_ROW(weights, num_weights, j); - new_row = GET_2D_ROW(new_weights, num_weights + 1, j); for (k = 0; k < num_weights; k++) { - new_row[k] = (row[k] - means[k]) / sds[k]; + shifted_means[k] /= (double) num_samples; + } + for (j = 0; j < num_samples; j++) { + row = GET_2D_ROW(weights, num_weights, j); + new_row = GET_2D_ROW(new_weights, num_weights + 1, j); + for (k = 0; k < num_weights; k++) { + double d = (ldexp(row[k], -exps[k]) - u0[k]) - shifted_means[k]; + new_row[k] = d; + sum_sq[k] += d * d; + } + // set final row to 1/n to compute frequency + new_row[num_weights] = 1.0 / (double) num_samples; + } + for (k = 0; k < num_weights; k++) { + sds[k] = sqrt(sum_sq[k] / (double) (num_samples - 1)); + } + for (j = 0; j < num_samples; j++) { + new_row = GET_2D_ROW(new_weights, num_weights + 1, j); + for (k = 0; k < num_weights; k++) { + new_row[k] /= sds[k]; + } } - // set final row to 1/n to compute frequency - new_row[num_weights] = 1.0 / (double) num_samples; } ret = tsk_treeseq_general_stat(self, num_weights + 1, new_weights, num_weights, trait_correlation_summary_func, &args, num_windows, windows, options, result); out: - tsk_safe_free(means); - tsk_safe_free(meansqs); + tsk_safe_free(max_abs); + tsk_safe_free(exps); + tsk_safe_free(u0); + tsk_safe_free(shifted_means); + tsk_safe_free(sum_sq); tsk_safe_free(sds); tsk_safe_free(new_weights); return ret; diff --git a/python/tests/test_tree_stats.py b/python/tests/test_tree_stats.py index 7f1db699d0..668a835fc5 100644 --- a/python/tests/test_tree_stats.py +++ b/python/tests/test_tree_stats.py @@ -5385,6 +5385,22 @@ def test_errors(self, ts_10_mut_recomb_fixture): with pytest.raises(ValueError): ts.trait_correlation(W[1:, :]) + def test_numerical_stability(self, ts_10_mut_recomb_fixture): + ts = self.get_example_ts(ts_10_mut_recomb_fixture) + W = np.column_stack( + [ + np.arange(ts.num_samples, dtype=float), + (np.arange(ts.num_samples) % 2).astype(float), + ] + ) + base = ts.trait_covariance(W, mode=self.mode) + self.assertArrayAlmostEqual( + base, ts.trait_covariance(W + 1e14, mode=self.mode), rtol=1e-6 + ) + huge_const = np.full((ts.num_samples, 1), 1e308) + res = ts.trait_covariance(huge_const, mode=self.mode) + self.assertArrayAlmostEqual(res, np.zeros_like(res)) + @pytest.mark.slow class TestBranchTraitCovariance( @@ -5609,6 +5625,28 @@ def test_normalisation(self, ts_10_mut_recomb_fixture): self.verify_centering(ts, trait_correlation, ts.trait_correlation) self.verify_standardising(ts, trait_correlation, ts.trait_correlation) + def test_numerical_stability(self, ts_10_mut_recomb_fixture): + ts = self.get_example_ts(ts_10_mut_recomb_fixture) + W = np.column_stack( + [ + np.arange(ts.num_samples, dtype=float), + (np.arange(ts.num_samples) % 2).astype(float), + ] + ) + base = ts.trait_correlation(W, mode=self.mode) + for shifted in [W + 1e9, W + 1e12]: + self.assertArrayAlmostEqual( + base, ts.trait_correlation(shifted, mode=self.mode), rtol=1e-6 + ) + for scale in [1e200, 1e300, 1e-200, 1e-300]: + self.assertArrayAlmostEqual( + base, ts.trait_correlation(W * scale, mode=self.mode) + ) + extreme = np.where(W[:, 1:2] > 0, 1e308, -1e308) + self.assertArrayAlmostEqual( + base[..., 1:2], ts.trait_correlation(extreme, mode=self.mode) + ) + @pytest.mark.slow class TestBranchTraitCorrelation( diff --git a/python/tskit/trees.py b/python/tskit/trees.py index 168cead7e0..cd754cecd6 100644 --- a/python/tskit/trees.py +++ b/python/tskit/trees.py @@ -9692,8 +9692,7 @@ def trait_correlation(self, W, windows=None, mode="site", span_normalise=True): """ if W.shape[0] != self.num_samples: raise ValueError("First trait dimension must be equal to number of samples.") - sds = np.std(W, axis=0) - if np.any(sds == 0): + if W.shape[0] > 0 and np.any(np.all((W == W[0]) & np.isfinite(W), axis=0)): raise ValueError( "Weight columns must have positive variance", "to compute correlation." )