File size: 4,794 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
"""
test_dynamic_deutan_separation.py
---------------------------------
Unit and regression tests for Tier 3 Dynamic Separation of Conflicting Colors
in Deutans (severity-adaptive gaps, headroom allocation, and orthogonal chroma shifts).
"""

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 delta_e_ciede2000, detect_conflicts
from pipeline.cvd_simulation import get_simulation_matrix
from pipeline.reencoding import (
    _effective_target_gap,
    _simulate_lab_center,
    reencode,
    enforce_rg_separation,
    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_effective_target_gap_scaling():
    """Verify that effective target gap scales monotonically with severity."""
    # Deutan scaling
    gap_mild = _effective_target_gap(0.4, "deutan", base_target=30.0)
    gap_mod = _effective_target_gap(0.7, "deutan", base_target=30.0)
    gap_full = _effective_target_gap(1.0, "deutan", base_target=30.0)

    assert 20.0 < gap_mild < 21.0, f"Expected gap ~20.4 at s=0.4, got {gap_mild}"
    assert gap_mild < gap_mod < gap_full, "Gap must increase monotonically with severity"
    assert np.isclose(gap_full, 30.0), f"Expected gap 30.0 at s=1.0, got {gap_full}"

    # Protan baseline is higher to account for L-cone loss
    gap_protan_mild = _effective_target_gap(0.4, "protan", base_target=30.0)
    assert gap_protan_mild > gap_mild, "Protan must maintain a higher baseline lightness gap"


def test_headroom_aware_allocation_high_green():
    """Green near the ceiling (L*=86) must not be pushed past l_max (90)."""
    # Create red at 45 and green at 86 (shortfall = 30 - (86 - 45) = -11 -> already separated,
    # let's set red at 70 and green at 86, gap = 16, shortfall = 14)
    centers = np.array([
        [70.0, 35.0, 20.0],   # red
        [86.0, -35.0, 25.0],  # green near ceiling
    ])
    out = enforce_rg_separation(centers, target_gap=30.0, l_min=2.0, l_max=90.0, severity=1.0, cvd_type="deutan")
    green_new = out[1, 0]
    red_new = out[0, 0]

    assert green_new <= 90.0, f"Green must not clip past l_max (90.0), got {green_new}"
    assert (green_new - red_new) >= 29.9, f"Total gap must reach target ~30, got {green_new - red_new}"
    assert red_new < 60.0, f"Red should absorb the majority of the downward shift, got {red_new}"


def test_headroom_aware_allocation_dark_red():
    """Red near the floor (L*=6) must not be pushed below l_min (2.0)."""
    centers = np.array([
        [6.0, 15.0, 10.0],    # dark red
        [20.0, -18.0, 15.0],  # dark green
    ])
    out = enforce_rg_separation(centers, target_gap=30.0, l_min=2.0, l_max=90.0, severity=1.0, cvd_type="deutan")
    red_new = out[0, 0]
    green_new = out[1, 0]

    assert red_new >= 2.0, f"Red must not drop below l_min (2.0), got {red_new}"
    assert (green_new - red_new) >= 29.9, f"Total gap must reach target ~30, got {green_new - red_new}"
    assert green_new > 30.0, f"Green should absorb the majority of the upward shift, got {green_new}"


def test_deutan_orthogonal_chroma_shift():
    """Verify that the deutan orthogonal vector produces significant separation."""
    v_ortho = ORTHOGONAL_DIRECTIONS["deutan"]
    sim_m = get_simulation_matrix(1.0, "deutan")

    red = _srgb_to_lab([180, 50, 50])
    green = _srgb_to_lab([50, 140, 50])
    centers = np.array([red, green])

    conflicts = detect_conflicts(centers, _simulate_lab_center(centers, sim_m), "deutan")
    assert len(conflicts) > 0, f"Expected conflict between red and green, got {conflicts}"

    reenc = reencode(centers, conflicts, 1.0, "deutan", allow_chroma_shift=True)
    sim_reenc = _simulate_lab_center(reenc, sim_m)
    de_post = delta_e_ciede2000(sim_reenc[0], sim_reenc[1])

    assert de_post > 20.0, f"Re-encoded simulated difference must be suprathreshold (>20.0), got {de_post}"


def test_mild_deutan_naturalness_advantage():
    """Mild deuteranomaly (s=0.4) should achieve lower naturalness drift than severe (s=1.0)."""
    img = np.zeros((100, 100, 3), dtype=np.uint8)
    img[:50, :] = [200, 50, 50]
    img[50:, :] = [50, 200, 50]

    _, m_mild = run_full_pipeline(img, 0.4, "deutan", use_segmentation=False)
    _, m_severe = run_full_pipeline(img, 1.0, "deutan", use_segmentation=False)

    nat_mild = m_mild.get("naturalness_preservation", 999.0)
    nat_severe = m_severe.get("naturalness_preservation", 999.0)

    assert nat_mild < nat_severe, f"Mild deutan naturalness ({nat_mild:.2f}) must be better than severe ({nat_severe:.2f})"
    assert m_mild.get("conflict_resolution_rate", 0) == 1.0, "Mild deutan must achieve 100% resolution rate"