File size: 6,329 Bytes
1d21e88
 
 
 
 
 
 
 
 
f65c627
1d21e88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f65c627
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import cv2
import numpy as np
import pytest
from backend.experimental.segmentation import IrisGeometry, detect_geometry, adaptive_mask
from backend.experimental.radial import radial_vectors, fit_radial_mesh
from backend.experimental.native_refinement import refine_native
from backend.experimental.patch_validation import validate_patches
from backend.experimental.mesh import dense_mesh
from backend.experimental.evaluation import predict_points
from backend.experimental.settings import LearnedSettings


def test_uncertain_segmentation_falls_back_without_inventing_geometry():
    image = np.full((600, 600, 3), 100, np.uint8)
    mask, geometry = adaptive_mask(image)
    assert geometry is None
    assert mask.dtype == bool
    assert not mask[300, 300]


def test_detect_offcenter_pupil_and_limbus():
    image = np.full((600, 600, 3), 210, np.uint8)
    cv2.circle(image, (325, 280), 230, (85, 100, 120), -1)
    cv2.circle(image, (325, 280), 65, (15, 15, 15), -1)
    geometry = detect_geometry(image)
    assert geometry is not None
    assert np.linalg.norm(np.array(geometry.center)-[325, 280]) < 5
    assert abs(geometry.pupil_radius-65) < 5
    assert abs(geometry.iris_radius-230) < 8


def test_radial_fit_recovers_unseen_dilation():
    geometry = IrisGeometry((300, 300), 80, 250, 1)
    y, x = np.mgrid[60:540:12, 60:540:12]
    a = np.column_stack([x.ravel(), y.ravel()]).astype(np.float32)
    radius = np.linalg.norm(a-300, axis=1)
    a = a[(radius>90)&(radius<240)]
    b = a+8*radial_vectors(a, np.eye(3), geometry)
    train = np.arange(len(a))%5 != 0
    model = fit_radial_mesh(a[train], b[train], (600, 600), geometry)
    error = np.linalg.norm(model.predict(a[~train])-b[~train], axis=1)
    assert np.percentile(error, 95) < 1


def test_radial_prior_zero_at_limbus_and_center():
    geometry = IrisGeometry((300, 300), 80, 250, 1)
    p = np.float32([[300, 300], [550, 300], [580, 300], [380, 300]])
    v = radial_vectors(p, np.eye(3), geometry)
    assert np.allclose(v[:3], 0)
    assert np.allclose(v[3], [1, 0])


def test_native_flow_without_support_preserves_map():
    rng = np.random.default_rng(1)
    im = rng.integers(0, 180, (160, 160, 3), dtype=np.uint8)
    y, x = np.indices(im.shape[:2], dtype=np.float32)
    mapping = np.stack([x, y], -1)
    result, metrics = refine_native(im, np.roll(im, 2, axis=1), mapping, np.zeros(im.shape[:2], bool))
    assert not metrics['applied']
    assert np.array_equal(result, mapping)


def test_multiscale_preserves_identity_and_rejects_borders():
    rng = np.random.default_rng(2)
    im = rng.integers(0, 200, (200, 200, 3), dtype=np.uint8)
    points = np.float32([[80, 80], [120, 120], [5, 5]])
    p, q = validate_patches(im, im, points, points, multiscale=True)
    assert len(p) == 2
    assert np.allclose(p, q, atol=.01)


def test_dense_mesh_matches_evaluated_coordinates_without_grid_quantization():
    y,x=np.mgrid[:9,:9]
    coefficients=np.stack([20*np.sin(y/3),15*np.cos(x/3)],-1).astype(np.float32)
    mapping,valid,_=dense_mesh(coefficients,np.eye(3),(600,600))
    py,px=np.mgrid[40:560:7,40:560:11]
    points=np.stack([px.ravel(),py.ravel()],-1).astype(np.float32)
    expected=predict_points(points,np.eye(3),coefficients,(600,600))
    assert np.max(np.linalg.norm(expected-mapping[py.ravel(),px.ravel()],axis=1))<.0001
    assert valid[40:560,40:560].all()


@pytest.mark.parametrize('key,value', [('IRIS_MATCHER','unknown'), ('IRIS_MATCH_MAX_SIZE','9999'),
                                     ('IRIS_MATCH_MAX_SIZE','bad'), ('IRIS_ADAPTIVE_MASK','yes'),
                                     ('IRIS_PATCH_VALIDATION','unchecked')])
def test_invalid_server_settings_fail_explicitly(monkeypatch,key,value):
    monkeypatch.setenv(key,value)
    with pytest.raises(RuntimeError):
        LearnedSettings.from_env()


def test_pupil_only_mask_reports_assumed_outer_boundary():
    geometry=IrisGeometry((310,290),60,240,0,False)
    mask,measured=adaptive_mask(np.full((600,600,3),100,np.uint8),geometry)
    assert not measured.limbus_detected
    assert not mask[290,310]
    assert mask[290,410]


def test_geometry_patch_analysis_returns_original_moving_coordinates():
    from backend.experimental.patch_validation import validate_geometry_patches
    rng=np.random.default_rng(4)
    image=rng.integers(0,220,(600,600,3),dtype=np.uint8)
    image=cv2.GaussianBlur(image,(5,5),1)
    affine=cv2.getRotationMatrix2D((300,300),12,1)
    moving=cv2.warpAffine(image,affine,(600,600))
    y,x=np.mgrid[100:510:35,100:510:35]
    reference_points=np.stack([x.ravel(),y.ravel()],-1).astype(np.float32)
    moving_points=cv2.transform(reference_points[None],affine)[0]
    p,q=validate_geometry_patches(image,moving,reference_points,moving_points)
    expected=cv2.transform(p[None],affine)[0]
    assert len(p)>.9*len(reference_points)
    assert np.percentile(np.linalg.norm(q-expected,axis=1),95)<.3


def test_candidate_selection_cannot_win_by_dropping_hard_points():
    from backend.experimental.selection import improves
    baseline=dict(count=100,scored_count=100,p95_px=5.,median_px=1.)
    candidate=dict(count=70,scored_count=70,p95_px=1.,median_px=.5)
    assert not improves(baseline,candidate)
    candidate.update(count=100,scored_count=90)
    assert not improves(baseline,candidate)
    candidate.update(scored_count=100,median_px=2.)
    assert not improves(baseline,candidate)
    candidate.update(median_px=.8)
    assert improves(baseline,candidate)


def test_candidate_selection_preserves_insufficient_evidence():
    from backend.experimental.selection import select_correspondences
    a=np.zeros((29,2),np.float32)
    p,q,evaluation,selection=select_correspondences((a,a),(a,a),(600,600))
    assert selection['selected']=='single'
    assert evaluation['p95_px'] is None


def test_native_refinement_recovers_known_small_translation():
    rng=np.random.default_rng(4)
    image=cv2.GaussianBlur(rng.integers(0,200,(400,400,3),dtype=np.uint8),(7,7),1.5)
    moving=np.roll(image,2,axis=1)
    y,x=np.indices((400,400),dtype=np.float32)
    mapping=np.stack([x,y],-1)
    support=(x>40)&(x<360)&(y>40)&(y<360)
    refined,metrics=refine_native(image,moving,mapping,support)
    assert metrics['applied']
    assert np.median(np.linalg.norm(refined[support]-mapping[support]-[2,0],axis=1))<.2