import numpy as np import pytest from otfusion import ( FusionConfig, cost_matrix, dynamic_alpha, semantic_cost, sinkhorn_fusion, sinkhorn_log, substitute_missing, to_distribution, ) def random_simplex(n, rng): x = rng.uniform(0.01, 0.99, n) return np.column_stack([1 - x, x]) # --------------------------------------------------------------------------- # Sinkhorn solver (Eq. 18) # --------------------------------------------------------------------------- def test_sinkhorn_satisfies_marginals(): rng = np.random.default_rng(0) a, b = random_simplex(50, rng), random_simplex(50, rng) cost = rng.uniform(0, 2, (50, 2, 2)) res = sinkhorn_log(a, b, cost, reg=0.15) assert res.converged.all() np.testing.assert_allclose(res.plans.sum(axis=2), a, atol=1e-8) np.testing.assert_allclose(res.plans.sum(axis=1), b, atol=1e-8) assert (res.plans >= 0).all() def test_sinkhorn_minimises_entropic_objective(): """For 2x2 problems the feasible set is one-dimensional, so a grid search finds the optimum.""" a, b = np.array([0.3, 0.7]), np.array([0.6, 0.4]) cost = np.array([[0.0, 1.8], [1.2, 0.0]]) reg = 0.15 plan = sinkhorn_log(a, b, cost, reg=reg).plans[0] lo, hi = max(0.0, a[0] - b[1]), min(a[0], b[0]) best, best_val = None, np.inf for t in np.linspace(lo + 1e-9, hi - 1e-9, 200001): T = np.array([[t, a[0] - t], [b[0] - t, a[1] - b[0] + t]]) val = np.sum(T * cost) + reg * np.sum(T * np.log(T)) if val < best_val: best, best_val = T, val np.testing.assert_allclose(plan, best, atol=1e-5) def test_sinkhorn_rejects_bad_reg(): with pytest.raises(ValueError): sinkhorn_log(np.array([0.5, 0.5]), np.array([0.5, 0.5]), np.zeros((2, 2)), reg=0) # --------------------------------------------------------------------------- # Inputs and masking (Eqs. 13-15) # --------------------------------------------------------------------------- def test_to_distribution_shapes(): p = np.array([0.2, 0.9]) expected = np.array([[0.8, 0.2], [0.1, 0.9]]) np.testing.assert_allclose(to_distribution(p), expected) np.testing.assert_allclose(to_distribution(p[:, None]), expected) np.testing.assert_allclose(to_distribution(expected), expected) def test_missing_modality_replaced_by_uniform(): p = np.array([[0.1, 0.9], [0.8, 0.2]]) q = np.array([[0.3, 0.7], [np.nan, np.nan]]) p_t, q_t = substitute_missing(p, q, np.array([False, True]), np.array([True, False])) np.testing.assert_allclose(p_t, [[0.5, 0.5], [0.8, 0.2]]) np.testing.assert_allclose(q_t, [[0.3, 0.7], [0.5, 0.5]]) def test_nan_input_treated_as_missing(): res = sinkhorn_fusion(np.array([np.nan, 0.9]), np.array([0.8, 0.2])) np.testing.assert_allclose(res.p[0], [0.5, 0.5]) assert np.isfinite(res.fused).all() # --------------------------------------------------------------------------- # Alpha and cost matrix (Eqs. 16-17) # --------------------------------------------------------------------------- def test_dynamic_alpha(): p = np.array([[0.05, 0.95], [0.5, 0.5], [0.3, 0.7]]) q = np.array([[0.5, 0.5], [0.05, 0.95], [0.3, 0.7]]) alpha = dynamic_alpha(p, q) assert alpha[0] == pytest.approx(1.0, abs=1e-6) # only histopathology is confident assert alpha[1] == pytest.approx(0.0, abs=1e-6) # only risk is confident assert alpha[2] == pytest.approx(0.5, abs=1e-6) # equally confident def test_cost_matrix_limits(): p = np.array([[0.2, 0.8]]) q = np.array([[0.6, 0.4]]) sem = semantic_cost(fp_weight=1.8, fn_weight=1.2) np.testing.assert_allclose(sem, [[0, 1.8], [1.2, 0]]) np.testing.assert_allclose(cost_matrix(p, q, np.array([0.0]), 1.8, 1.2)[0], sem) divergence = (p[0][:, None] - q[0][None, :]) ** 2 np.testing.assert_allclose(cost_matrix(p, q, np.array([1.0]), 1.8, 1.2)[0], divergence) def test_config_validation(): with pytest.raises(ValueError): FusionConfig(alpha=1.5) with pytest.raises(ValueError): FusionConfig(alpha="adaptive") assert FusionConfig(alpha="dynamic").alpha == "dynamic" # --------------------------------------------------------------------------- # Full fusion (Eq. 19 and fallback) # --------------------------------------------------------------------------- def test_fusion_output_is_a_distribution(): rng = np.random.default_rng(1) for alpha in (0.1, "dynamic"): res = sinkhorn_fusion(rng.uniform(0, 1, 100), rng.uniform(0, 1, 100), FusionConfig(alpha=alpha)) assert res.fused.shape == (100, 2) np.testing.assert_allclose(res.fused.sum(axis=1), 1.0) assert (res.fused >= 0).all() assert not res.fallback.any() def test_eq19_row_marginal_equals_p_under_marginal_constraint(): """Eq. 18 constrains T 1 = p, so the row marginal read out by Eq. 19 equals p.""" rng = np.random.default_rng(2) res = sinkhorn_fusion(rng.uniform(0, 1, 100), rng.uniform(0, 1, 100)) np.testing.assert_allclose(res.fused, res.p, atol=1e-8) def test_fallback_uses_outer_product(): cfg = FusionConfig(max_iter=1, fallback_tol=1e-12) res = sinkhorn_fusion(np.array([0.9, 0.2]), np.array([0.3, 0.6]), cfg) assert res.fallback.all() expected = res.p[:, :, None] * res.q[:, None, :] np.testing.assert_allclose(res.plans, expected)