Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions c/tests/test_stats.c
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down Expand Up @@ -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);
}
Expand Down
137 changes: 99 additions & 38 deletions c/tskit/trees.c
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand All @@ -3997,29 +4001,52 @@ 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]);
}
}
}

ret = tsk_treeseq_general_stat(self, num_weights, new_weights, 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;
}
Expand Down Expand Up @@ -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;
}
Expand All @@ -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;
Expand Down
38 changes: 38 additions & 0 deletions python/tests/test_tree_stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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(
Expand Down
3 changes: 1 addition & 2 deletions python/tskit/trees.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."
)
Expand Down