"""Unit tests for the standalone paper-support analyses: - src/causal_difficulty/eval/deconfound.py (D^perp cross-fitted residualization) - scripts/prop2_quant.py (Proposition 2 master-form fit + critical-scale crossing) These are pure additions -- none of this exercises or changes ``causal_difficulty.eval.reports.evaluate()`` or any existing run output. """ from __future__ import annotations import sys from pathlib import Path import numpy as np from causal_difficulty.eval.deconfound import ( cross_fitted_m, cross_fitted_residual, explained_variance_drop, null_head_negative_control, orthogonality_diagnostics, predict_m, stratified_rank_correlation, ) SCRIPTS_DIR = Path(__file__).resolve().parents[1] / "scripts" if str(SCRIPTS_DIR) not in sys.path: sys.path.insert(0, str(SCRIPTS_DIR)) def _synthetic_tau_c(n=400, b=0.6, noise_std=0.05, seed=0): rng = np.random.RandomState(seed) c = rng.uniform(0.0, 1.0, size=n) tau = b * c + rng.normal(0.0, noise_std, size=n) return c, tau def test_predict_m_train_holdout_reduces_correlation_with_C(): c, tau = _synthetic_tau_c(n=600, seed=1) c_train, tau_train = c[:400], tau[:400] c_hold, tau_hold = c[400:], tau[400:] m_hat = predict_m(c_train, tau_train, c_hold, method="isotonic") residual = tau_hold - m_hat raw_corr = abs(np.corrcoef(tau_hold, c_hold)[0, 1]) resid_corr = abs(np.corrcoef(residual, c_hold)[0, 1]) # D^perp should be far less correlated with C than the raw tau was. assert resid_corr < raw_corr assert resid_corr < 0.25 def test_cross_fitted_residual_is_orthogonal_to_C(): c, tau = _synthetic_tau_c(n=500, b=0.8, noise_std=0.05, seed=2) residual, m_hat = cross_fitted_residual(c, tau, n_folds=5, method="isotonic", seed=2) assert np.all(np.isfinite(m_hat)) diag = orthogonality_diagnostics(residual, c) assert abs(diag["mean_D_perp"]) < 0.05 assert abs(diag["corr_D_perp_C"]) < 0.2 assert abs(diag["corr_D_perp_C2"]) < 0.2 def test_cross_fitted_m_uses_out_of_fold_predictions(): c, tau = _synthetic_tau_c(n=200, seed=3) m_hat = cross_fitted_m(c, tau, n_folds=4, method="isotonic", seed=3) assert m_hat.shape == tau.shape assert np.all(np.isfinite(m_hat)) # out-of-fold predictions should not perfectly memorize the noisy target assert not np.allclose(m_hat, tau) def test_fit_m_of_c_handles_degenerate_input(): from causal_difficulty.eval.deconfound import fit_m_of_c predict_fn = fit_m_of_c(np.array([0.5]), np.array([0.3])) out = predict_fn(np.array([0.1, 0.9])) assert out.shape == (2,) assert np.allclose(out, 0.3) def test_orthogonality_diagnostics_nan_on_constant_input(): diag = orthogonality_diagnostics(np.zeros(10), np.linspace(0, 1, 10)) assert np.isnan(diag["corr_D_perp_C"]) def test_null_head_control_collapses_to_zero_for_a_genuinely_good_predictor(): """A predictor that is highly correlated with the real D^perp target should NOT let a constant/shuffled null-head version of itself inherit that correlation -- otherwise the reported D^perp_hat Spearman would be an artifact of the shared m_pred(C) subtraction, not of the head. """ rng = np.random.RandomState(11) n = 400 c = rng.uniform(0.0, 1.0, size=n) tau = 0.6 * c + rng.normal(0.0, 0.05, size=n) pred = tau + rng.normal(0.0, 0.02, size=n) # genuinely informative predictor c_train, c_hold = c[:250], c[250:] tau_train, tau_hold = tau[:250], tau[250:] pred_train, pred_hold = pred[:250], pred[250:] m_hat_hold = predict_m(c_train, tau_train, c_hold) d_perp_hold = tau_hold - m_hat_hold m_pred_hold = predict_m(c_train, pred_train, c_hold) d_perp_hat_hold = pred_hold - m_pred_hold real_rho_s = abs(np.corrcoef( np.argsort(np.argsort(d_perp_hat_hold)), np.argsort(np.argsort(d_perp_hold)))[0, 1]) assert real_rho_s > 0.5 # sanity: the real predictor is genuinely good result = null_head_negative_control( pred_train, pred_hold, c_train, c_hold, d_perp_hold, seed=3, n_shuffle_repeats=15, ) assert np.isnan(result["rho_S_constant_head"]) or abs(result["rho_S_constant_head"]) < 0.3 assert abs(result["rho_S_shuffled_head_mean"]) < 0.3 # the null-head controls must be far weaker than the real predictor. assert result["rho_S_shuffled_head_abs_mean"] < real_rho_s def test_explained_variance_drop_detects_genuine_complexity_leakage(): """App. dperp-controls (b): a prediction that strongly tracks C should show a high before-residualization R^2 and a much lower after- residualization R^2 once the C-tracking component is removed. """ rng = np.random.RandomState(5) n = 250 c = rng.uniform(0.0, 1.0, size=n) pred_before = 2.0 * c + rng.normal(0.0, 0.05, size=n) pred_after = rng.normal(0.0, 0.05, size=n) # no C signal left result = explained_variance_drop(pred_before, pred_after, c, n_folds=5, seed=5) assert result["r2_before"] > 0.7 assert result["r2_after"] < result["r2_before"] assert result["r2_drop"] > 0.5 def test_explained_variance_drop_small_when_nothing_to_remove(): """A prediction with no C-tracking to begin with should show a small (near-zero or negative) before-R^2, hence a small drop -- the honest reading when the complexity proxy carries little signal to start with. """ rng = np.random.RandomState(6) n = 250 c = rng.uniform(0.0, 1.0, size=n) pred_before = rng.normal(0.0, 0.05, size=n) pred_after = pred_before.copy() result = explained_variance_drop(pred_before, pred_after, c, n_folds=5, seed=6) assert result["r2_before"] < 0.3 assert abs(result["r2_drop"]) < 0.3 def test_stratified_rank_correlation_survives_within_narrow_strata(): """App. dperp-controls (c): if pred and target are genuinely correlated independent of C, the within-stratum Spearman should stay strong even though C itself carries no information within a narrow stratum. """ rng = np.random.RandomState(7) n = 300 c = rng.uniform(0.0, 1.0, size=n) target = rng.normal(0.0, 1.0, size=n) pred = target + rng.normal(0.0, 0.1, size=n) # correlated w/ target, indep of C result = stratified_rank_correlation(pred, target, c, n_strata=5) assert result["n_strata_used"] == 5 assert result["weighted_mean_spearman"] > 0.8 def test_stratified_rank_correlation_nan_when_no_real_signal(): """If pred carries no genuine per-job signal (pure noise), the within-stratum Spearman should collapse toward ~0, not spuriously inherit correlation from the shared C trend.""" rng = np.random.RandomState(8) n = 300 c = rng.uniform(0.0, 1.0, size=n) target = rng.normal(0.0, 1.0, size=n) pred = rng.normal(0.0, 1.0, size=n) # independent noise result = stratified_rank_correlation(pred, target, c, n_strata=5) assert abs(result["weighted_mean_spearman"]) < 0.3 def test_master_form_fit_recovers_known_parameters(): from prop2_quant import _fit_master_form, _master_form sigmas = np.array([0.0, 0.005, 0.01, 0.02, 0.04, 0.06, 0.10]) true_rho0, true_sigma_star = 0.9, 0.015 clean_curve = _master_form(sigmas, true_rho0, true_sigma_star) fit = _fit_master_form(sigmas, clean_curve) assert fit["rho0"] is not None assert abs(fit["rho0"] - true_rho0) < 0.05 assert abs(fit["sigma_star"] - true_sigma_star) < 0.01 assert fit["r2"] > 0.99 def test_master_form_fit_flags_too_few_points(): from prop2_quant import _fit_master_form fit = _fit_master_form(np.array([0.0, 0.01]), np.array([0.8, 0.6])) assert fit["rho0"] is None assert "error" in fit def test_crossing_sigma_finds_half_value_crossing(): from prop2_quant import _crossing_sigma sigmas = np.array([0.0, 0.01, 0.02, 0.04]) rho_c = np.array([0.8, 0.6, 0.3, 0.1]) # clean=0.8, half=0.4, crosses between 0.01 and 0.02 sigma_star, clean, max_sigma = _crossing_sigma(sigmas, rho_c) assert clean == 0.8 assert sigma_star is not None assert 0.01 < sigma_star < 0.02 def test_crossing_sigma_returns_none_when_never_crosses(): from prop2_quant import _crossing_sigma sigmas = np.array([0.0, 0.01, 0.02, 0.04]) rho_c = np.array([0.9, 0.89, 0.88, 0.87]) # stays near clean value, never halves sigma_star, clean, max_sigma = _crossing_sigma(sigmas, rho_c) assert sigma_star is None assert clean == 0.9 assert max_sigma == 0.04