"""Regression tests for the A1/A2 ellipse-fitting bugfix in ``MedVision_BenchmarkPlannerBiometry_fromSeg.__fit_ellipses``. The biometry planner fits the lesion ellipse in *physical* (real-world) space so the major/minor axes are physically meaningful. Two bugs broke that under anisotropic in-plane spacing: A1 - the contour was scaled with transposed pixel spacing (cv2 points are ``(x=dim1, y=dim0)`` but ``pixel_sizes`` is ``(dim0, dim1)``); A2 - major vs. minor was decided by *pixel* length while reported in *mm*. See ``doc/ellipse-fitting-image-vs-real-space.md`` for the linear algebra. This is a plain-``assert`` script (the repo has no test framework); run with:: python scripts/test_fit_ellipses_anisotropy.py Exit code 0 = all tests passed. """ import os import sys import numpy as np sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src")) from medvision_ds.utils.benchmark_planner import ( # noqa: E402 MedVision_BenchmarkPlannerBiometry_fromSeg as Planner, ) # private method name after Python name-mangling _FIT = "_MedVision_BenchmarkPlannerBiometry_fromSeg__fit_ellipses" def _make_planner(): """Instantiate without the heavy DB-backed ``__init__``; ``__fit_ellipses`` only needs the two bbox-scale attributes. The scales are set wide/narrow so the ``all_within`` acceptance filter never drops a valid landmark, isolating the fitting logic under test.""" obj = Planner.__new__(Planner) obj.enlarged_bbox_scale = 5.0 obj.shrunk_bbox_scale = 0.05 return obj def _rasterize_physical_ellipse(shape, center_idx, s0, s1, A, B, phi_deg): """Binary mask whose TRUE physical fit is an ellipse with semi-axes ``A`` (major) and ``B`` (minor) in mm at angle ``phi_deg`` in physical ``(dim0, dim1)`` space. ``s0, s1`` are the mm spacings of dim0, dim1.""" n0, n1 = shape c0, c1 = center_idx ii, jj = np.meshgrid(np.arange(n0), np.arange(n1), indexing="ij") d0 = (ii - c0) * s0 d1 = (jj - c1) * s1 phi = np.deg2rad(phi_deg) u = d0 * np.cos(phi) + d1 * np.sin(phi) # along physical major v = -d0 * np.sin(phi) + d1 * np.cos(phi) # along physical minor return ((u / A) ** 2 + (v / B) ** 2 <= 1.0).astype(np.uint8) def _fit(planner, mask, pixel_sizes, slice_dim=2, slice_idx=0): return getattr(planner, _FIT)( mask, 1, np.asarray(pixel_sizes, dtype=float), slice_dim, slice_idx ) def _physical_axis(landmark, key_a, key_b, voxel): """Length (mm) and in-plane direction (deg, mod 180) of the landmark axis, mirroring ``_cal_distance`` (``point * voxel_sizes``).""" pa = np.asarray(landmark[key_a], dtype=float) * np.asarray(voxel) pb = np.asarray(landmark[key_b], dtype=float) * np.asarray(voxel) vec = (pa - pb)[:2] length = float(np.linalg.norm(pa - pb)) angle = float(np.degrees(np.arctan2(vec[1], vec[0])) % 180.0) return length, angle def test_anisotropic_recovers_physical_major(): """Discriminating case: the lesion is longest in *physical* mm along dim0 (2A = 160 mm), but because dim1 is finer (0.5 mm) it is longest in *pixels* along dim1. A correct (real-space) fit must report the dim0 axis as major; the pre-fix code either dropped the lesion or labelled the pixel-long axis.""" s0, s1 = 1.0, 0.5 A, B, phi = 80.0, 50.0, 25.0 # physical semi-axes (mm), tilt (deg) mask = _rasterize_physical_ellipse((220, 320), (110, 160), s0, s1, A, B, phi) voxel = (s0, s1, 1.0) # slice_dim=2 -> in-plane (dim0, dim1) landmarks, _, n_clusters = _fit(_make_planner(), mask, (s0, s1)) assert n_clusters == 1, f"expected 1 cluster, got {n_clusters}" assert len(landmarks) == 1, f"expected 1 landmark, got {len(landmarks)}" major_mm, major_dir = _physical_axis(landmarks[0], "P1", "P2", voxel) minor_mm, _ = _physical_axis(landmarks[0], "P3", "P4", voxel) # Recovered physical lengths match the truth (tolerance covers rasterization # + algebraic-conic vs. truth ellipse fit). assert abs(major_mm - 2 * A) < 0.08 * 2 * A, f"major {major_mm:.1f} != ~160 mm" assert abs(minor_mm - 2 * B) < 0.08 * 2 * B, f"minor {minor_mm:.1f} != ~100 mm" # L-1-2 is the physical major (A2): longer than L-3-4. assert major_mm > minor_mm, f"major {major_mm:.1f} !> minor {minor_mm:.1f}" # Major axis points along the PHYSICAL major direction (~25 deg), NOT the # pixel-major direction (~115 deg) the buggy comparison would pick. d_phys = min(abs(major_dir - phi), 180 - abs(major_dir - phi)) assert d_phys < 12.0, f"major_dir {major_dir:.1f} not aligned with {phi} deg" def test_isotropic_is_a_noop(): """With isotropic in-plane spacing the fix is a provable no-op: the four landmark index coordinates must be byte-identical to the released behaviour. Golden captured from the pre-fix code on the same mask.""" GOLDEN = { "P1": [182, 194, 0], "P2": [38, 126, 0], "P3": [131, 115, 0], "P4": [89, 205, 0], } mask = _rasterize_physical_ellipse((220, 320), (110, 160), 1.0, 1.0, 80.0, 50.0, 25.0) landmarks, _, _ = _fit(_make_planner(), mask, (1.0, 1.0)) assert len(landmarks) == 1, f"expected 1 landmark, got {len(landmarks)}" for key, expected in GOLDEN.items(): assert landmarks[0][key] == expected, ( f"{key}: {landmarks[0][key]} != golden {expected} (isotropic must be unchanged)" ) def test_physical_measurement_is_continuous_and_ordered(): """The reported L-1-2 / L-3-4 must be the CONTINUOUS real-space ellipse axes, persisted in ``landmark['measurements']`` — NOT a re-derivation from the rounded landmark points. On near-circular lesions (A ~ B) the rounded points can flip order, but the physical measurement must keep major (L-1-2) >= minor (L-3-4) and must equal the continuous axis (~2A / ~2B), proving the int landmarks are display-only and the rounding never corrupts the measurement.""" planner = _make_planner() # Same well-formed geometry as the other tests, but near-circular (A ~ B) on # a few spacings/angles that would stress a rounding tie-break. for s0, s1, A, B, phi in [ (1.0, 0.7, 60.0, 59.0, 30.0), (0.8, 1.3, 60.0, 59.2, 70.0), (1.0, 1.0, 60.0, 59.0, 15.0), ]: mask = _rasterize_physical_ellipse((220, 320), (110, 160), s0, s1, A, B, phi) landmarks, _, _ = _fit(planner, mask, (s0, s1)) assert len(landmarks) == 1, f"({s0},{s1},{A},{B},{phi}): got {len(landmarks)} landmarks" meas = landmarks[0].get("measurements") assert meas is not None, "fit must persist a physical-space 'measurements' field" # major >= minor on the PHYSICAL measurement (max/min of axes_real). assert meas["L-1-2"] + 1e-9 >= meas["L-3-4"], ( f"({s0},{s1},{A},{B},{phi}): physical major {meas['L-1-2']:.3f} < minor {meas['L-3-4']:.3f}" ) # The measurement is the continuous axis (~2A / ~2B), within fit tolerance. assert abs(meas["L-1-2"] - 2 * A) < 0.08 * 2 * A, f"major {meas['L-1-2']:.2f} != ~{2 * A}" assert abs(meas["L-3-4"] - 2 * B) < 0.08 * 2 * B, f"minor {meas['L-3-4']:.2f} != ~{2 * B}" if __name__ == "__main__": test_anisotropic_recovers_physical_major() test_isotropic_is_a_noop() test_physical_measurement_is_continuous_and_ordered() print("OK: ellipse-fit tests passed (anisotropic recovery + isotropic no-op + physical measurement)")