Skip to content

Measure and plot a reconstruction

This tutorial measures one real lattice SIM data set and its reconstructions with pysrx.metrics: how fine the detail is, how sharp and how thin the result is, and how far two methods agree; then it plots them. Every number and figure below was made with the code on this page.

The data. A ZEISS Elyra lattice SIM crop of mitochondria (MT-CO1, 488 nm): 13 raw phases, 32 planes at 120 nm, 256 x 256 camera pixels of 62.6 nm. The reconstructions (ZEN SIM, Richardson-Lucy and the Lattice SIM NeRF) live on the 31.3 nm object grid; they are the ones on the lattice SIM page. Imaging: Robert Mitchell, Clarke Group, KIR, Oxford.

The middle plane of the Elyra crop: the pseudo-widefield image, ZEN SIM, Poisson Richardson-Lucy and the Lattice SIM NeRF

The plane measured below, 10 x 10 µm around the cell. Each panel on its own range; the widefield is on the camera grid, shown at the object grid's size.

import numpy as np
from pysrx import metrics as M

raw = np.load("raw.npy").astype(float) - 92.0     # (13, Z, Y, X) counts above the camera offset
wf = np.clip(raw, 0, None).mean(0)                 # pseudo-widefield: the mean of the 13 phases
zen, rl, nerf = (np.load(f) for f in ("zen.npy", "rl.npy", "nerf.npy"))   # as in Getting started

px_cam, px_obj, dz = 0.0626, 0.0313, 0.12          # µm: camera pixel, object pixel, plane step
z = wf.shape[0] // 2                               # the middle plane (2 z on the 60 nm object grid)
planes = {"widefield": (wf[z], px_cam), "zen": (zen[z], px_obj),
          "rl": (rl[2 * z], px_obj), "nerf": (nerf[2 * z], px_obj)}

Every function takes the pixel size in µm, so results come out in µm and compare across grids: the widefield plane is on the camera grid, the reconstructions on a grid twice as fine.

1. What to expect: the textbook limits

M.theoretical(na=1.4, ex_nm=488, em_nm=525, n=1.518)
µm
lateral_widefield 0.229
axial_widefield 0.813

Lattice SIM can at best double the lateral widefield limit, so about 115 nm is the target. A measured value well below that is a warning sign, not a success.

2. Resolution without a reference: decorrelation

Decorrelation analysis (Descloux et al., Nat. Methods 2019) finds the finest detail that still carries signal above the noise, from one image, with no reference and no second acquisition.

for name, (plane, px) in planes.items():
    print(name, M.decorrelation_resolution(plane, px))
Pseudo-widefield ZEN SIM Poisson RL Lattice SIM NeRF
277 nm 123 nm 155 nm 143 nm

Lower is not always better

Decorrelation is also lowered by artefacts and fixed-pattern noise: any sharp, high-frequency pattern looks like detail. Read it together with the other measures below, and look at the images.

3. Resolution from two halves: FRC

Fourier ring correlation compares two independent images of the same object and reports where they stop agreeing (the 1/7 threshold). With photon counts you do not need a second acquisition: binomial_split thins every pixel's count into two independent Poisson halves.

counts = np.rint(np.clip(raw, 0, None)).sum(0)[z]   # all 13 phases at one plane, in counts
a, b = M.binomial_split(counts, seed=0)
res = M.frc(a, b, px_um=px_cam)
res.resolution_um, res.k_cross                     # 0.125 µm, 1.0

Here the answer is 125 nm, at k = 1.0: the camera Nyquist. That is not a resolution, it is the pitfall this measure is known for: an sCMOS camera adds the same fixed pattern (pixel and column offsets) to every frame, and a binomial split cannot separate it, so both halves share it and their FRC never falls below 1/7. Remove the fixed pattern before splitting (pysrx.camera has remove_fixed_pattern), or split with Gaussian data fission (fission_split, with the variance from poisson_gauss_var) once the camera gain is known. A split FRC that lands exactly at Nyquist always deserves this check.

Self-FRC needs only one image: it splits the image into its two diagonal pixel-interleaved halves, as SR-Metrics did.

for name, (plane, px) in planes.items():
    print(name, M.self_frc(plane, px).resolution_um)
Pseudo-widefield ZEN SIM Poisson RL Lattice SIM NeRF
353 nm 132 nm 176 nm 155 nm

Plot the curves to see where each crosses the threshold:

import matplotlib.pyplot as plt

label = {"widefield": "Pseudo-widefield", "zen": "ZEN SIM", "rl": "Poisson RL", "nerf": "Lattice SIM NeRF"}
fig, ax = plt.subplots(figsize=(5.5, 3.2))
for name, (plane, px) in planes.items():
    r = M.self_frc(plane, px)
    ax.plot(r.k / (4 * px), r.curve, label=f"{label[name]}: {r.resolution_um * 1000:.0f} nm")   # k -> cycles per µm
ax.axhline(r.threshold, color="k", ls="--", lw=0.8)
ax.set(xlabel="spatial frequency (1/µm)", ylabel="FRC", ylim=(-0.1, 1.05))
ax.legend(frameon=False)
fig.savefig("frc.png", dpi=160, bbox_inches="tight")

Self-FRC curves against spatial frequency for the pseudo-widefield, ZEN SIM, Poisson RL and the Lattice SIM NeRF, with the 1/7 threshold

Each curve falls as the detail gets finer; the resolution is where it crosses 1/7. r.k is in units of the half-image Nyquist, so k / (4 px) converts it to cycles per µm.

The ranking agrees with decorrelation. The values are in physical units: the interleaved halves have pixels twice the size, and pySRX accounts for that (SR-Metrics reported half these values; see Coming from SR-Metrics).

Up-sampled images: reduce before splitting

Classic SIM doubles the spatial-frequency support, so the reconstruction lives on a grid with half the camera pixel size. An image that was only up-sampled onto that finer grid, such as the widefield put on the SIM grid to sit next to it, has no real content above its own Nyquist. Its interleaved halves are then not independent: with pixel repetition each 2 x 2 block holds four copies of one camera pixel, the two diagonal halves are identical, the FRC is 1 everywhere and the resolution is NaN. Reduce the image back to its own grid first, with sampling=2 and one of three methods:

w2 = np.kron(wf[z], np.ones((2, 2)))               # the widefield plane up-sampled onto the object grid
M.self_frc(wf[z], px_cam).resolution_um            # 0.353 µm, on its own grid
M.self_frc(w2, px_obj).resolution_um               # nan: identical halves
for method in ("max", "fourier", "skipping"):
    print(method, M.self_frc(w2, px_obj, sampling=2, method=method).resolution_um)
Pseudo-widefield sampling method Self-FRC
camera grid 1 353 nm
up-sampled x 2 1 NaN (identical halves)
up-sampled x 2 2 "max": 2 x 2 max pooling 338 nm
up-sampled x 2 2 "fourier": keep the central half of the spectrum 358 nm
up-sampled x 2 2 "skipping": split with a step of 4 pixels 338 nm

The checkerboard split of self-FRC, 2 x 2 max pooling and pixel skipping

Left: the self-FRC split, two diagonal pairs of half-images whose FRC curves are averaged (after Koho et al., Nat. Commun. 10, 3103 (2019), CC BY 4.0). Middle: 2 x 2 max pooling (method="max"). Right: pixel skipping (method="skipping").

All three land within 20 nm of the value on the camera grid, so use the image on its own grid when you have it. The reconstructions need no reduction: their finer grid carries the doubled support, and sampling=1 is right for them.

4. Local resolution: rolling FRC maps

One FRC number averages over the whole field: background, cell and structure alike. A rolling FRC map (rFRC; Zhao et al., Light Sci. Appl. 12, 298 (2023)) computes the self-FRC in small windows across the image, so it shows where a method resolves more, not just one number.

for name, (plane, px) in planes.items():
    w = round(32 * px_obj / px)                    # 2 µm windows on both grids (in half-image pixels)
    m = M.self_rolling_frc_map(plane, px, window=w, stride=w // 2, n_bins=w // 2,
                               min_mean=0.1 * np.percentile(plane, 99.8))
    print(name, np.nanmedian(m.resolution_um), (~m.masked).sum(), "of", m.masked.size, "windows kept")

cmap = plt.get_cmap("viridis_r").copy()
cmap.set_bad("0.75")                               # masked windows (NaN) in grey
plt.imshow(m.resolution_um * 1000, cmap=cmap, vmin=110, vmax=200)   # the last map; the figure shows all four

Three settings matter:

  • Flip tiling (flip_tile=True, the default) mirror-tiles each window 2 x 2 before the FFT, so the window edges do not add a cross of false high frequencies.
  • Rings (n_bins=w // 2, rings two pixels wide). With the default 50 rings a small window has rings that hold only a few frequencies; they can score -1 and end the curve early (here some windows on a mitochondrion came out at 2.5 µm).
  • The signal mask (min_mean). Windows on the background hold no structure: their FRC measures noise, their crossing means nothing, and in a sparse field they are most of the map. min_mean drops every window whose mean intensity is below it (here 10 % of the 99.8th percentile); dropped windows are NaN in the map and m.masked marks them.
Pseudo-widefield ZEN SIM Poisson RL Lattice SIM NeRF
windows with signal (of 225) 86 20 17 17
median local resolution 374 nm 129 nm 138 nm 134 nm

The four planes and their rolling self-FRC maps; background windows grey

Top: the plane of each method. Bottom: local self-FRC resolution in 2 µm windows (the widefield on its own scale). Grey: windows without signal, masked. Red: windows with signal whose FRC never drops below 1/7, so the crossing lies beyond the half-image Nyquist (125 nm on the object grid); treat them like a low decorrelation value, as fine detail or as a pattern both halves share.

The widefield map separates the haze over the cell (above 400 nm) from the mitochondria (250 to 350 nm). Among the reconstructions ZEN SIM is the most uniform; Poisson RL and the NeRF are coarser in a few windows at the top of the network. The same caution as for decorrelation applies: an artefact that both halves share looks like resolution.

5. 3D: Fourier shell correlation

A stack is 3D, and so is its resolution. Fourier shell correlation (FSC) is FRC one dimension up: it correlates two volumes in spherical shells of spatial frequency. The single-image version (after Koho et al. 2019) splits one stack the way self-FRC splits a plane: in every 2 x 2 x 2 cube of voxels, the two ends of each of the four body diagonals, (000)-(111), (100)-(011), (001)-(110) and (010)-(101), go to two sub-volumes. The four FSC curves are averaged and the resolution is the 1/7 crossing.

Single-image FRC of one plane and single-image FSC of the stack for raw, ACsN, RL and ACsN + RL light-sheet data, and the four diagonals of the 3D split

CD40 T cells, 488 nm, ZEISS Lightsheet 7: raw, ACsN denoising, Richardson-Lucy (10 iterations) and ACsN + RL; the legends give the resolution in pixels (voxels). Left: single-image FRC of one XY plane. Middle: single-image FSC of the stack. Right: the four diagonals of the 3D split. RL's curves turn up again at high frequency: the iterations amplify something both halves share, so a curve that rises again is a warning, not resolution. Images courtesy Narain Karedla, University of Oxford; method after Koho et al., *Nat. Commun.* 10, 3103 (2019).

self_fsc takes the voxel spacing per axis, (dz, dy, dx) in µm. The shells are spherical in physical frequency (cycles per µm), so a coarser z only means fewer shells along kz: the half-volumes reach \( 1/(4\,\Delta z) \) along z, 2.1 µm⁻¹ for 120 nm planes and 4.2 µm⁻¹ for 60 nm. resolution_axial_um and resolution_lateral_um repeat the analysis in a 30° cone around kz and a 30° wedge around the xy plane (cone_deg).

vols = {"widefield": (wf, (dz, px_cam, px_cam)), "zen": (zen, (dz, px_obj, px_obj)),
        "rl": (rl, (dz / 2, px_obj, px_obj)), "nerf": (nerf, (dz / 2, px_obj, px_obj))}
for name, (vol, spacing) in vols.items():
    r = M.self_fsc(vol, spacing)
    print(name, r.resolution_um, r.resolution_lateral_um, r.resolution_axial_um)
Pseudo-widefield ZEN SIM Poisson RL Lattice SIM NeRF
stack 32 x 256 x 256 32 x 512 x 512 63 x 512 x 512 63 x 512 x 512
self-FSC, all shells 358 nm 136 nm 127 nm 142 nm
lateral wedge 358 nm 136 nm 127 nm 142 nm
axial cone NaN NaN NaN NaN
self-FRC, middle plane (section 3) 353 nm 132 nm 176 nm 155 nm

For the widefield and ZEN SIM the FSC agrees with the self-FRC of one plane; Poisson RL and the NeRF come out finer in 3D. The split assumes that neighbouring voxels carry independent noise, and a volume on 60 nm planes, far finer than its axial resolution, does not: whatever neighbouring planes share holds the curve up. The axial cone shows it plainly: it stays above 1/7 up to the edge of its band in all four stacks (NaN), even for the widefield, whose axial limit is 813 nm. So compare FSC values only between volumes on the same grid, and measure thickness with axial_fwhm (section 7).

6. Sharpness on a fixed physical grid

tenengrad measures gradient energy at a fixed physical scale on a common grid, normalised by the mean intensity squared, so neither the pixel size nor the brightness decides the number.

for name, (plane, px) in planes.items():
    print(name, M.tenengrad(plane, px, grid_um=0.03, sigma_um=0.06))
Pseudo-widefield ZEN SIM Poisson RL Lattice SIM NeRF
3.6 695 647 671

Use the same grid_um and sigma_um for every image you compare. On a stack, best_plane(vol, px_um) returns the sharpest plane.

7. Axial extent

axial_fwhm fits a Gaussian along z through bright, isolated 3D maxima and returns one FWHM per peak, in µm: the apparent thickness of bright structures.

M.axial_fwhm(rl, (dz / 2, px_obj, px_obj), n_peaks=200, min_dist_um=0.5)
ZEN SIM Poisson RL Lattice SIM NeRF
median axial FWHM 1574 nm 1180 nm 1229 nm
peaks used 4 7 7

Give each volume its own spacing (ZEN keeps the 120 nm planes, ours are on 60 nm). A 3.8 µm crop holds only a few isolated peaks, so treat a median of 4 to 7 as indicative; the pseudo-widefield found none, because its structures extend beyond the crop in z.

8. Agreement between two images

Fidelity metrics compare a test image with a reference. Without ground truth, they measure agreement, not accuracy: here ZEN SIM as the reference.

ref = planes["zen"][0]
for name in ("rl", "nerf"):
    t = planes[name][0]
    print(name, M.nmse(ref, t), M.psnr(ref, t), M.ssim_global(ref, t), M.pcc(ref, t))
against ZEN SIM nMSE PSNR SSIM PCC
Poisson RL 0.486 28.5 dB 0.551 0.891
Lattice SIM NeRF 0.315 30.4 dB 0.748 0.899

Every fidelity metric first min-max normalises each image by its own range, so an offset or a gain does not count as a difference:

M.nmse(x, x + 100.0), M.pcc(x, x + 100.0)          # 1.8e-11, 1.0

(SR-Metrics scaled the first image by the minimum of the second, which biased every fidelity metric whenever the two minima differed.) With a real reference of the same object, such as a registered confocal stack, the same functions measure accuracy; the light field page does that against an LSM 980.

Not every agreement metric looks at the content:

Metric pySRX Content-aware What it compares
SSIM ssim_global ✅ perceptual: structure, contrast, luminance
PCC pcc ❌ pixel intensity correlation only
MI mutual_info ⚠️ partly statistical dependency (the measure used for registration)
FRC frc, rolling_frc_map ✅ frequency-based similarity, e.g. sharpness

nMSE and PSNR, like PCC, compare pixel by pixel. In the table above PCC barely separates Poisson RL from the NeRF (0.891 and 0.899) where SSIM does (0.551 and 0.748). FRC between two images, M.frc(ref, t, px_obj), asks at what detail they stop agreeing, and rolling_frc_map(ref, t, px_obj) maps it.

9. Plot the result

Measurements need pictures next to them. Show the same plane of each method side by side, with one line drawn across a mitochondrion, and plot the intensity along that line:

y0, x0, x1 = 272, 250, 370                       # the profile: one row of the object grid, 3.8 µm long
crop = np.s_[128:448, 160:480]                   # 10 x 10 µm around the cell
panels = {"Pseudo-widefield": np.kron(wf[z], np.ones((2, 2))),   # camera grid -> object grid, for display
          "Poisson RL": rl[2 * z], "Lattice SIM NeRF": nerf[2 * z]}

fig, axs = plt.subplots(1, 4, figsize=(12, 3), gridspec_kw={"width_ratios": [1, 1, 1, 1.4], "wspace": 0.4})
for ax, (name, im) in zip(axs, panels.items()):
    ax.imshow(im[crop], cmap="gray", vmin=0, vmax=np.percentile(im[crop], 99.8))
    ax.plot([x0 - 160, x1 - 160], [y0 - 128] * 2, color="orange", lw=1)
    ax.set_title(name); ax.set_axis_off()
    prof = im[y0, x0:x1] / im[y0, x0:x1].max()
    axs[3].plot((np.arange(x0, x1) - x0) * px_obj, prof, label=name)
axs[3].set(xlabel="position along the line (µm)", ylabel="intensity (normalised)", title="Line profile")
axs[3].legend(frameon=False, loc="upper left", bbox_to_anchor=(1.0, 1.0))
fig.savefig("compare.png", dpi=150, bbox_inches="tight")

The pseudo-widefield, Poisson RL and Lattice SIM NeRF planes with an orange line across a mitochondrion, and the intensity profiles along it

The widefield profile is one broad hump; both reconstructions split it into narrow peaks a few hundred nanometres apart. Show each panel on its own range (here 0 to its 99.8th percentile) and say so in the caption.

10. How well does the model predict unseen data?

The strongest test of a reconstruction is to leave one raw phase out of the fit and ask how well the result predicts it: heldout_deviance(op_h, x, y_h) takes an operator that renders only the held-out phase. It needs the forward model, so it is run where the operator is built (Elyra-SIM-Recon); its values for this crop are in the results table.

Coming from SR-Metrics

SRMetric and calculate_metrics keep the SR-Metrics interface, and python -m pysrx.metrics replaces the benchmark-sr command, so old notebooks and scripts run unchanged. The differences are listed, each with its test, in Coming from SR-Metrics.