File size: 5,336 Bytes
5999247 | 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 | """explorer.py - the interactive anatomy explainer: click (or choose) a region -> its measurement + an explanation of the anatomy."""
import numpy as np
import measure as M, textgen as T, render as R
DISC_MARGIN = 12 # px either side of the ring that still counts as 'on the ring'
def local_thickness(m, x, y, half=2):
xi, yi = int(round(x)), int(round(y)); n = m.shape[0]
if not (0 <= xi < n and 0 <= yi < n): return None
w = m[max(0, yi - half):yi + half + 1, max(0, xi - half):xi + half + 1].astype(float)
w = w[w > M.INVALID_THR]
return float(w.mean()) if w.size >= 3 else None
def locate(A, mx, my):
cx, cy = A["center"]; r = float(np.hypot(mx - cx, my - cy)); theta = M.angle_deg(mx, my, A["center"])
ring_r = M.RING_RADIUS_PX
zone = "disc" if r <= A["disc_r"] else ("inner" if r < ring_r - DISC_MARGIN else ("ring" if r <= ring_r + DISC_MARGIN else "outer"))
return {"zone": zone, "r": r, "theta": theta, "quad": M.quadrant_of(theta), "hour": M.hour_of(theta),
"local": local_thickness(A["m"], mx, my), "mx": mx, "my": my}
ZONE_TITLE = {"disc": "Optic nerve head (optic disc)", "inner": "Between the optic nerve head and the measurement ring",
"ring": "On the measurement ring", "outer": "Outside the measurement ring"}
def explain(A, ref, loc):
f = A["f"]; z = loc["zone"]; q = loc["quad"]; h = loc["hour"]
L = [f"### {ZONE_TITLE[z]}"]
if z == "disc":
L.append("No nerve-fibre-layer thickness is measured here, because this is where the nerve fibres leave the eye as the optic nerve, so the dark blue is **not** damage. "
"The software finds this region and centres the measurement ring on it. The cup-to-disc ratio is judged from the optic disc itself on a fundus photograph or disc scan, which this map cannot provide.")
L.append(f"*Detected disc region radius: about {A['disc_r']:.0f} px ({A['disc_r'] * M.MM_PER_PX:.2f} mm, assuming the 6 mm map width).*")
return "\n\n".join(L)
here = T.u(loc["local"]) if loc["local"] is not None else "no valid data at this point"
L.append(f"**Thickness at the point you chose:** {here} \n**Direction from the disc:** {h} o'clock, {T.QUAD_LONG[q]} side")
hv = f.get(f"h{h}"); hf = T.flag_of(hv, ref[f"h{h}"]); qv = f.get("q_" + q); qf = T.flag_of(qv, ref["q_" + q])
L.append(f"**{h} o'clock sector (ring average):** {T.u(hv)} - {T.FLAG_WORD[hf]} (reference median {T.u(ref[f'h{h}']['p50'])}) \n"
f"**{T.QUAD_LONG[q].capitalize()} quadrant (ring average):** {T.u(qv)} - {T.FLAG_WORD[qf]} (reference median {T.u(ref['q_' + q]['p50'])})")
if z == "inner": L.append("Nerve fibres converge on the optic nerve head from all directions, so this area is usually thicker than the retina further away. It is **not** part of the standard ring measurement.")
elif z == "ring": L.append("This is the circle (about 3.5 mm across) on which the standard ring measurements are taken.")
else: L.append("This is outside the ring: nerve fibres here are still on their way towards the optic nerve head, and thickness normally falls with distance from the disc. It is not part of the standard ring measurement.")
L.append(T.ANAT[q])
L.append("*A measurement in one sector is not a diagnosis. Only an eye-care professional can interpret it together with other tests.*")
return "\n\n".join(L)
REGION_CHOICES = ["Optic nerve head"] + [f"{h} o'clock" for h in T.HOUR_ORDER] + [f"{T.QUAD_LONG[k].capitalize()} quadrant" for k in T.QUADS]
def choice_to_loc(A, choice):
"""Dropdown fallback (works even if clicking is not available): pick a region by name."""
cx, cy = A["center"]
if choice == "Optic nerve head": return locate(A, cx, cy)
if choice.endswith("quadrant"):
k = {T.QUAD_LONG[x].capitalize() + " quadrant": x for x in T.QUADS}[choice]; th = {"S": 0, "R": 90, "I": 180, "L": 270}[k]
else:
h = int(choice.split()[0]); th = 0 if h == 12 else h * 30
a = np.radians(th); return locate(A, cx + M.RING_RADIUS_PX * np.sin(a), cy - M.RING_RADIUS_PX * np.cos(a))
def profile_figure(A, ref, theta=None):
import matplotlib; matplotlib.use("Agg"); import matplotlib.pyplot as plt
prof, _ = M.ring_profile(A["m"], A["center"])
deg = np.arange(360); p5 = np.array([ref[f"h{M.hour_of(d)}"]["p5"] for d in deg]); p50 = np.array([ref[f"h{M.hour_of(d)}"]["p50"] for d in deg]); p95 = np.array([ref[f"h{M.hour_of(d)}"]["p95"] for d in deg])
fig, ax = plt.subplots(figsize=(7.2, 3.3))
ax.fill_between(deg, p5, p95, color="tab:green", alpha=0.18, label="reference group 5th-95th percentile")
ax.plot(deg, p50, color="tab:green", lw=1, ls="--", label="reference median")
ax.plot(deg, prof, color="black", lw=1.8, label="this map (ring profile)")
if theta is not None: ax.axvline(theta, color="tab:red", lw=1.8, label="selected direction")
ax.set_xticks([0, 90, 180, 270, 360]); ax.set_xticklabels(["0° top\n(superior)", "90°\nimage-right", "180°\n(inferior)", "270°\nimage-left", "360°"])
ax.set_xlim(0, 360); ax.set_ylabel("RNFL thickness (µm)"); ax.set_title("Thickness around the ring vs the reference group", fontsize=10)
ax.legend(fontsize=7, loc="upper center", bbox_to_anchor=(0.5, -0.28), ncol=4, frameon=False)
fig.tight_layout(); return fig
|