File size: 5,722 Bytes
78661be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cbfe96
 
 
 
 
 
 
 
78661be
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
import numpy as np
import pytest
from pipeline.cvd_simulation import (
    get_simulation_matrix,
    simulate_cvd,
    simulate_cvd_machado2009,
    simulate_cvd_brettel1997,
    simulate_cvd_vienot1999,
    MACHADO_MATRICES,
)


def test_white_point_preservation():
    """White [1, 1, 1] must map to [1, 1, 1] under all severities and CVD types."""
    for cvd in ("deutan", "protan"):
        for sev in (0.0, 0.3, 0.5, 0.8, 1.0):
            M = get_simulation_matrix(sev, cvd)
            white_sim = np.array([1.0, 1.0, 1.0]) @ M.T
            np.testing.assert_allclose(
                white_sim, [1.0, 1.0, 1.0], atol=1e-3,
                err_msg=f"White point not preserved for {cvd} at sev={sev}"
            )


def test_machado2009_daltonlens_exact_parity():
    """Our vectorized Machado 2009 implementation must match DaltonLens reference perfectly."""
    try:
        import daltonlens.simulate as dl_sim
    except ImportError:
        pytest.skip("daltonlens library not available")

    ref_sim = dl_sim.Simulator_Machado2009()

    np.random.seed(42)
    test_img = np.random.rand(16, 16, 3).astype(np.float32)

    for cvd, dl_deficiency in [("deutan", dl_sim.Deficiency.DEUTAN), ("protan", dl_sim.Deficiency.PROTAN)]:
        for sev in [0.0, 0.2, 0.5, 0.8, 1.0]:
            our_out = simulate_cvd_machado2009(test_img, sev, cvd)
            ref_out = ref_sim._simulate_cvd_linear_rgb(test_img, dl_deficiency, sev)

            # Check exact match (< 1e-6)
            max_diff = np.max(np.abs(our_out - ref_out))
            assert max_diff < 1e-6, f"Discrepancy with DaltonLens Machado for {cvd} at s={sev}: {max_diff}"


def test_brettel1997_white_point_preservation():
    """Brettel 1997 must preserve white [1, 1, 1] across all severities."""
    white = np.array([[[1.0, 1.0, 1.0]]], dtype=np.float32)
    for cvd in ("deutan", "protan"):
        for sev in (0.0, 0.3, 0.7, 1.0):
            out = simulate_cvd_brettel1997(white, sev, cvd)
            np.testing.assert_allclose(
                out[0, 0], [1.0, 1.0, 1.0], atol=1e-3,
                err_msg=f"Brettel white point drift for {cvd} at sev={sev}"
            )


def test_brettel1997_daltonlens_exact_parity():
    """Our vectorized Brettel 1997 implementation must match DaltonLens reference perfectly."""
    try:
        import daltonlens.simulate as dl_sim
    except ImportError:
        pytest.skip("daltonlens library not available")

    ref_sim = dl_sim.Simulator_Brettel1997()

    np.random.seed(123)
    test_img = np.random.rand(16, 16, 3).astype(np.float32)

    for cvd, dl_deficiency in [("deutan", dl_sim.Deficiency.DEUTAN), ("protan", dl_sim.Deficiency.PROTAN)]:
        for sev in [0.5, 1.0]:
            our_out = simulate_cvd_brettel1997(test_img, sev, cvd)
            ref_out = ref_sim._simulate_cvd_linear_rgb(test_img, dl_deficiency, sev)

            # Both unclipped or clipped should match to within float precision (< 1e-5)
            max_diff = np.max(np.abs(our_out - ref_out))
            assert max_diff < 1e-5, f"Discrepancy with DaltonLens reference for {cvd} at s={sev}: {max_diff}"


def test_brettel1997_confusion_line_collapse():
    """Under deuteranopia, two colors along a deutan confusion line must collapse to the same simulated color."""
    lms1 = np.array([0.2, 0.1, 0.01])
    lms2 = np.array([0.2, 0.3, 0.01])

    from pipeline.cvd_simulation import LINEAR_RGB_FROM_LMS
    rgb1 = (lms1 @ LINEAR_RGB_FROM_LMS.T).reshape(1, 1, 3).astype(np.float32)
    rgb2 = (lms2 @ LINEAR_RGB_FROM_LMS.T).reshape(1, 1, 3).astype(np.float32)

    sim1 = simulate_cvd_brettel1997(rgb1, 1.0, "deutan")
    sim2 = simulate_cvd_brettel1997(rgb2, 1.0, "deutan")

    np.testing.assert_allclose(sim1, sim2, atol=1e-5)


def test_vienot1999_red_green_collapse():
    """Under Viénot 1999 full dichromacy, Row 0 and Row 1 are identical."""
    for cvd in ("deutan", "protan"):
        M = get_simulation_matrix(1.0, cvd, model="vienot1999")
        np.testing.assert_allclose(M[0], M[1], atol=1e-4)


def test_severity_interpolation():
    """Severity 0.0 must be identity; intermediate values match DaltonLens Machado tables."""
    for cvd in ("deutan", "protan"):
        M_0 = get_simulation_matrix(0.0, cvd)
        np.testing.assert_allclose(M_0, np.eye(3), atol=1e-6)

        M_half = get_simulation_matrix(0.5, cvd)
        np.testing.assert_allclose(M_half, MACHADO_MATRICES[cvd][5], atol=1e-6)

        M_full = get_simulation_matrix(1.0, cvd)
        np.testing.assert_allclose(M_full, MACHADO_MATRICES[cvd][10], atol=1e-6)

        # A severity BETWEEN two table steps. 0.0, 0.5 and 1.0 all land on a
        # multiple of 0.1, where the old divide-first alpha happened to be
        # correct, so they could never catch it. 0.35 sits halfway between
        # table rows 3 and 4 and fails outright if alpha is wrong.
        M_035 = get_simulation_matrix(0.35, cvd)
        expected = 0.5 * MACHADO_MATRICES[cvd][3] + 0.5 * MACHADO_MATRICES[cvd][4]
        np.testing.assert_allclose(M_035, expected, atol=1e-6)

        # Brettel model still linearly interpolates
        M_brettel_half = get_simulation_matrix(0.5, cvd, model="brettel1997")
        M_brettel_full = get_simulation_matrix(1.0, cvd, model="brettel1997")
        np.testing.assert_allclose(M_brettel_half, 0.5 * np.eye(3) + 0.5 * M_brettel_full, atol=1e-6)


def test_simulate_cvd_output_format():
    """simulate_cvd should return sRGB values in [0, 1]."""
    test_img = np.array([[[0.5, 0.2, 0.8]]], dtype=np.float32)
    srgb_out = simulate_cvd(test_img, 0.8, "deutan")
    assert srgb_out.shape == test_img.shape
    assert srgb_out.dtype == np.float32
    assert 0.0 <= srgb_out.min() and srgb_out.max() <= 1.0