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