File size: 9,282 Bytes
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
"""
test_reencoding_review_fixes.py
--------------------------------
Regression tests verifying the 21 findings addressed from the
Re-Encoding Module Review (https://claude.ai/code/artifact/b6cb1d7b-b8cd-4363-8992-e6602e88d670).
"""

import numpy as np
import pytest

from pipeline.__init__ import (
    _linear_to_lab_f32,
    _srgb_to_linear_f32,
    run_full_pipeline,
)
from pipeline.conflict import (
    detect_conflicts,
    _rg_a_min,
    _rg_chroma_min,
)
from pipeline.reencoding import (
    _candidate_center,
    _effective_target_gap,
    _is_red,
    _is_green,
    _classify_pair,
    enforce_rg_separation,
    reencode,
    ORTHOGONAL_DIRECTIONS,
)


def _srgb_to_lab(rgb: list) -> np.ndarray:
    u = np.array([[rgb]], dtype=np.uint8)
    return _linear_to_lab_f32(_srgb_to_linear_f32(u))[0, 0]


def test_r1_saturated_primaries_not_clamped_to_80():
    """R1: Verify saturated colors outside [-80, 80] are not snapped to +-80."""
    # Pure sRGB blue has b* around -107.8
    pure_blue_lab = _srgb_to_lab([0, 0, 255])
    assert pure_blue_lab[2] < -90.0, f"Expected blue b* < -90, got {pure_blue_lab[2]}"

    ortho_dir = ORTHOGONAL_DIRECTIONS["deutan"]
    # Candidate center with small ortho step
    cand = _candidate_center(
        pure_blue_lab,
        delta_l=0.0,
        chroma_scale=1.0,
        max_delta_chroma=10.0,
        ortho_dir=ortho_dir,
        ortho_step=0.5,
    )
    # The b* shift should be small (~2-3), NOT a giant snap to -80
    b_shift = abs(float(cand[2]) - float(pure_blue_lab[2]))
    assert b_shift < 8.0, f"b* must not snap to -80.0! Shift was {b_shift}"
    assert cand[2] < -90.0, f"Expected b* to remain < -90, got {cand[2]}"


def test_r2_enforce_rg_separation_respects_max_delta_l():
    """R2: Safety net enforce_rg_separation must respect max_delta_l from original_centers."""
    orig_centers = np.array([
        [40.0, 30.0, 15.0],   # red
        [42.0, -30.0, 15.0],  # green
    ])
    # Suppose re-encoder already moved red to 35.0 (shift = 5.0) and green to 47.0 (shift = 5.0)
    mod_centers = np.array([
        [35.0, 30.0, 15.0],
        [47.0, -30.0, 15.0],
    ])
    # Gap is 12, target gap is 32 -> shortfall is 20.
    # If max_delta_l is 10.0, red can only go down to 40.0 - 10.0 = 30.0 (headroom 5.0 from 35.0)
    # and green can only go up to 42.0 + 10.0 = 52.0 (headroom 5.0 from 47.0).
    out = enforce_rg_separation(
        mod_centers,
        target_gap=32.0,
        conflict_pairs=[(0, 1)],
        original_centers=orig_centers,
        max_delta_l=10.0,
    )
    red_l = out[0, 0]
    green_l = out[1, 0]

    # Red must not exceed max_delta_l from orig (40.0 - 10.0 = 30.0)
    assert red_l >= 30.0 - 1e-5, f"Red drifted too far: orig=40, out={red_l}, max_delta_l=10"
    # Green must not exceed max_delta_l from orig (42.0 + 10.0 = 52.0)
    assert green_l <= 52.0 + 1e-5, f"Green drifted too far: orig=42, out={green_l}, max_delta_l=10"


def test_r8_effective_target_gap_zero_at_zero_severity():
    """R8: Normal vision (severity=0) must have 0 target gap."""
    gap_deutan = _effective_target_gap(0.0, "deutan")
    gap_protan = _effective_target_gap(0.0, "protan")
    assert gap_deutan == 0.0, f"Expected 0.0 at severity=0, got {gap_deutan}"
    assert gap_protan == 0.0, f"Expected 0.0 at severity=0, got {gap_protan}"


def test_r10_dark_red_green_recognized():
    """R10: Dark red/green at L*=18 must be recognized consistently across modules."""
    dark_red = np.array([18.0, 4.0, 2.0])
    dark_green = np.array([18.0, -4.0, 2.0])

    # In conflict.py:
    a_min = _rg_a_min(18.0)
    c_min = _rg_chroma_min(18.0)
    assert abs(dark_red[1]) > a_min, "Dark red a* should exceed luminance-scaled a_min"
    assert abs(dark_green[1]) > a_min, "Dark green a* should exceed luminance-scaled a_min"

    # In reencoding.py:
    assert _is_red(dark_red), "reencoding._is_red must recognize dark red"
    assert _is_green(dark_green), "reencoding._is_green must recognize dark green"


def test_r11_polarity_preservation_from_original_centers():
    """R11: Polarity in enforce_rg_separation must be dictated by original centers."""
    # Orig: red is darker (35) than green (45)
    orig_centers = np.array([
        [35.0, 30.0, 15.0],   # 0: red
        [45.0, -30.0, 15.0],  # 1: green
    ])
    # Suppose modified centers had an anomalous swap (e.g. green at 38, red at 39)
    mod_centers = np.array([
        [39.0, 30.0, 15.0],
        [38.0, -30.0, 15.0],
    ])
    out = enforce_rg_separation(
        mod_centers,
        target_gap=30.0,
        conflict_pairs=[(0, 1)],
        original_centers=orig_centers,
        max_delta_l=30.0,
    )
    # Red (0) must remain darker than green (1)
    assert out[0, 0] < out[1, 0], f"Expected red < green, got red={out[0, 0]}, green={out[1, 0]}"


def test_r15_centers_delivered_matches_shifts():
    """R15: Metrics receive delivered centers (centers + shifts)."""
    img = np.zeros((60, 60, 3), dtype=np.uint8)
    img[:30, :] = [220, 40, 40]   # red
    img[30:, :] = [40, 200, 40]   # green

    _, metrics = run_full_pipeline(
        img,
        severity=1.0,
        cvd_type="deutan",
        use_segmentation=False,
        compute_validation_metrics=True,
    )
    # The pipeline must complete and metrics should be computed honestly
    assert "de_improvement" in metrics
    assert "conflict_resolution_rate" in metrics
    assert metrics["conflict_resolution_rate"] > 0.5


def test_r16_chromatic_roi_text_not_silently_dropped():
    """R16: Colored text (roi-text with high chroma) is not dropped by conflict detection."""
    red_text = np.array([50.0, 45.0, 20.0])      # colored text
    green_bg = np.array([52.0, -40.0, 25.0])     # colored bg
    centers = np.array([red_text, green_bg])
    sim_centers = np.array([[51.0, 0.0, 15.0], [51.0, 0.0, 15.0]])

    conflicts = detect_conflicts(
        centers,
        sim_centers,
        cvd_type="deutan",
        cluster_labels=["roi-text #1", "roi-color #2"],
    )
    assert (0, 1) in conflicts or (1, 0) in conflicts, (
        f"Chromatic text must be flagged for conflict resolution, got {conflicts}"
    )


def test_r18_subsampling_pinned_indices_remapped():
    """R18: max_clusters subsampling correctly remaps pinned_indices."""
    centers_orig = np.zeros((10, 3))
    centers_orig[:, 0] = np.linspace(10, 90, 10)
    centers_sim = centers_orig.copy()

    # Suppose cluster 9 was pinned
    pinned = {9}
    conflicts = detect_conflicts(
        centers_orig,
        centers_sim,
        cvd_type="deutan",
        max_clusters=5,
        pinned_indices=pinned,
    )
    # Should run without error and not crash on reindexed arrays
    assert isinstance(conflicts, list)


def test_chapter_3_parameter_alignment():
    """Verify all 5 parameters match the locked Chapter 3 manuscript values."""
    import inspect
    from pipeline.__init__ import run_full_pipeline
    from pipeline.conflict import detect_conflicts
    from pipeline.reencoding import reencode
    import pipeline.__init__ as pipe_mod

    # 1. target_de == 24.0
    sig_pipe = inspect.signature(run_full_pipeline)
    sig_reenc = inspect.signature(reencode)
    assert sig_pipe.parameters["target_de"].default == 24.0
    assert sig_reenc.parameters["target_de"].default == 24.0

    # 2. target_rg_l_gap == 30.0
    assert sig_pipe.parameters["target_rg_l_gap"].default == 30.0
    assert sig_reenc.parameters["target_rg_l_gap"].default == 30.0

    # 3. max_delta_l == 38.0
    assert sig_pipe.parameters["max_delta_l"].default == 38.0
    assert sig_reenc.parameters["max_delta_l"].default == 38.0

    # 4. rg_separation_threshold == 35.0
    sig_conf = inspect.signature(detect_conflicts)
    assert sig_conf.parameters["rg_separation_threshold"].default == 35.0

    # 5. Chroma retention == 15%, on the legacy path that reproduces Chapter 3.
    #
    # This assertion used to grep the source for a literal line. It broke on
    # BOTH merges from milder-dynamic-reencoding, because each one moved the
    # constant -- module level, then inline, then module level again under a
    # new name -- while the VALUE never changed once. A text search cannot tell
    # a rename from a regression, so it cries wolf on the refactors and would
    # stay silent if someone assigned 0.15 in dead code.
    #
    # Reading the constants instead ties the test to what Chapter 3 actually
    # claims: the legacy mixer keeps 15% of the chroma shift, and the milder
    # mixer that replaced it as the default keeps 45%.
    from pipeline.__init__ import _CHROMA_SHIFT_RETAIN
    from pipeline.reencoding_mild import MILD_CHROMA_RETAIN

    assert _CHROMA_SHIFT_RETAIN == 0.15, (
        f"Chapter 3 locks legacy chroma retention at 0.15, got {_CHROMA_SHIFT_RETAIN}"
    )
    assert MILD_CHROMA_RETAIN == 0.45, (
        f"the milder mixer is documented at 0.45, got {MILD_CHROMA_RETAIN}"
    )

    # And the legacy branch must actually USE the legacy constant -- the value
    # existing somewhere proves nothing if the code path ignores it.
    with open(pipe_mod.__file__, "r", encoding="utf-8") as f:
        content = f.read()
    assert "chroma_retain = _CHROMA_SHIFT_RETAIN" in content, (
        "the legacy path no longer reads _CHROMA_SHIFT_RETAIN"
    )