Skip to content

pysrx.metrics

One metrics library for super-resolution and reconstruction benchmarks. It absorbs SR-Metrics and the LF4D benchmark metrics (lf4d.metrics); the public API is flat (from pysrx import metrics as M; M.frc(...)).

Family Functions
Resolution frc (+ FRC_SR_METRICS preset), frc_resolution, self_frc, decorrelation_resolution, theoretical
Resolution maps (rFRC) rolling_frc_map (two images), self_rolling_frc_map (one image), result FRCMap
Fidelity nmse, psnr, ssim_global, pcc, mutual_info, pearson_fg, normalise
Spectrum spectral_anisotropy
Sharpness, noise, axial tenengrad, tenengrad_profile, best_plane, noise_signal, axial_fwhm
SR-Metrics API SRMetric, calculate_metrics, CLI python -m pysrx.metrics

Coming from SR-Metrics

SR-Metrics pysrx.metrics Parity
SRMetric.compute_nMSE/PSNR/SSIM/PCC/mutual_info nmse, psnr, ssim_global, pcc, mutual_info identical when the two images' minima agree (see below)
SRMetric.compute_frc frc(a, b, px, **FRC_SR_METRICS) identical
SRMetric.compute_self_frc self_frc(img, px, sampling=, method=), one image per call curves identical; resolution x 2 (physical units)
ResolutionMap.compute_rrFRC_map (notebook) rolling_frc_map(a, b, px, window=, stride=) per-window curves identical; resolution x 2
ResolutionMap.compute_srFRC_map (notebook) self_rolling_frc_map(img, px, window=, stride=, sampling=) weights identical; resolution x 2
compute_anisotropy (angular notebook) spectral_anisotropy(img, n_bins=num_bins - 1, exclude_dc=False) identical
benchmark.py (benchmark-sr) python -m pysrx.metrics --raw ... --reconstructed ... same output file
calculate_metrics calculate_metrics fixed normalisation

SRMetric keeps the SR-Metrics return values (including compute_self_frc in SR-Metrics units), so old notebooks run unchanged. Golden-parity data: tests/golden/golden_v0.npz and tests/golden/golden_sr_v1.npz.

Deliberate differences, each covered by a test:

  • Normalisation. SR-Metrics scaled img1 by max(img1) - min(img2); every fidelity metric here min-max normalises each image by its own range, so an offset copy is a perfect match.
  • Resolution units. The self-FRC half-images have pixel 2 x sampling x px, so self_frc and self_rolling_frc_map report 4 sampling px / k; a window pair in rolling_frc_map reports 2 px / k. SR-Metrics reported half of both; the values here agree with the two-image frc of the same band limit.
  • Windows without a crossing are skipped in the maps (the notebook added NaN to the rrFRC map); uncovered pixels are NaN and FRCMap.weight counts the windows used.
  • Spectral anisotropy drops the zero frequency by default (the notebook kept it in the sector at pi).

Speed

The rolling maps batch the windows into FFTs (CuPy through pysrx.gpu when a GPU is present). A 512 x 512 pair, 32 px windows, stride 4 (14 641 windows): 1.1 s on a Quadro RTX 4000, 4.0 s with NumPy, against about 24 s for the notebook's per-window loop on one core.

pysrx.metrics

One metrics library for super-resolution and reconstruction benchmarks (absorbs SR-Metrics and lf4d.metrics).

  • resolution: frc (+ FRC_SR_METRICS preset), frc_resolution, self_frc, decorrelation_resolution, theoretical
  • rfrc: rolling_frc_map, self_rolling_frc_map (rFRC resolution maps, FRCMap)
  • spectral: spectral_anisotropy
  • fidelity: nmse, psnr, ssim_global, pcc, mutual_info, pearson_fg, normalise
  • sharpness: tenengrad, tenengrad_profile, best_plane
  • noise: noise_signal
  • axial: axial_fwhm
  • sim: bin_volume, binomial_split, fission_split, poisson_gauss_var, xz_section, decorrelation_xz, heldout_deviance, heldout_deviance_fit, modulation_ncc (structured-illumination evaluation)
  • compat: SRMetric, calculate_metrics (SR-Metrics API)
  • CLI: python -m pysrx.metrics (SR-Metrics benchmark-sr)

SRMetric

Bases: SRMetric

compute_self_frc(num_bins=50, resolution_limit=1 / 7, sampling_rate=(1, 1), sampling_method='max', flip_tile=True, plot=False)

SR-Metrics return values (lists per image; resolution in SR-Metrics units, i.e. half of self_frc(...).resolution_um; None without a crossing). plot=True runs the original plotting code.

axial_fwhm(vol, spacing, n_peaks=200, min_dist_um=5.0, seed=0)

FWHM (um) of Gaussian fits to axial profiles through bright local 3D maxima.

The section is thin, so this reports apparent axial extent = PSF axial width convolved with the structure's own depth; it is comparable across systems, not a pure PSF FWHM.

calculate_metrics(raw_image, reconstructed_image, metrics=None)

SR-Metrics calculate_metrics: metric name -> value.

mutual_info(ref, test, bins=256)

Mutual information (nats) from the joint histogram of the normalised images.

nmse(ref, test)

sum (r - t)^2 / sum r^2 on normalised images.

normalise(a)

Min-max scale to [0, 1] (float64); a constant image maps to zeros.

pcc(ref, test)

Pearson correlation over all pixels.

pearson_fg(a, b)

Pearson correlation restricted to the joint foreground (Otsu on the smoothed sum), as lf4d.metrics.

psnr(ref, test)

Peak SNR (dB) on normalised images (peak 1); inf for identical images.

ssim_global(ref, test, c1=0.0001, c2=0.0009)

Single-window (whole-image) SSIM on normalised images, as SR-Metrics.

decorrelation_resolution(img, px_um, n_r=200, n_g=25)

Lateral resolution (um) by decorrelation analysis (Descloux 2019). 1 = Nyquist frequency.

frc(a, b, px_um, *, threshold=1 / 7, n_bins=None, square=True, apodize=True, subtract_mean=True, smooth=3, k_min=0.05, on_no_crossing='nyquist', flip_tile=False)

FRC of two independent images of the same object (e.g. split acquisitions or binomial photon splits).

frc_resolution(a, b, px_um, thresh=1 / 7)

lf4d.metrics signature: (resolution um, k, curve).

self_frc(img, px_um, *, sampling=1, method='max', flip_tile=True, n_bins=50, threshold=1 / 7)

Single-image (self) FRC (SR-Metrics compute_self_frc): the image is split into its two diagonal pixel-interleaved pairs, the FRC of each pair is computed and the two curves are averaged.

sampling > 1 first reduces an up-sampled image by method ('max' pooling, 'fourier' spectrum crop, or 'skipping' straight into the split); flip_tile mirror-tiles the image before the split; n_bins // sampling rings. k is in units of the half-image Nyquist and the resolution is physical: the half-images have pixel 2 x sampling x px_um, so resolution = 4 sampling px_um / k_cross (SR-Metrics reported half of it, which disagrees with the two-image FRC of the same band limit). NaN if the curve never drops below threshold.

theoretical(na, ex_nm, em_nm, n=1.0)

Textbook resolution limits (um).

rolling_frc_map(a, b, px_um, *, window=32, stride=16, n_bins=50, threshold=1 / 7, flip_tile=True, batch=None)

Relative rolling FRC (rrFRC) between two images of the same field (e.g. two acquisitions, or a raw and a reconstruction on the same grid): FRC of every window x window patch pair, stepped by stride.

n_bins rings per window (the notebook default 50; fewer for small windows avoids empty rings, which score 0 and end the curve early), flip_tile mirror-tiles each window before the FFT, batch caps the windows per FFT batch (default ~128 MB of spectra).

self_rolling_frc_map(img, px_um, *, window=32, stride=16, sampling=1, method='max', n_bins=50, threshold=1 / 7, flip_tile=True, batch=None)

Self rolling FRC (srFRC) of one image: the image (reduced by sampling with method if it was up-sampled) is split into its two diagonal pixel-interleaved pairs; per window the two FRC curves are averaged.

window and stride are in half-image pixels (as in the notebook); the returned window/stride and the map are on the input grid (x 2 sampling). n_bins // sampling rings.

best_plane(vol, px_um)

Best-focus plane: max raw gradient energy at 1 um scale (robust to noise and dim planes).

tenengrad(plane, px_um, grid_um=0.25, sigma_um=0.4, normalize=True)

Gaussian-derivative gradient energy at a fixed physical scale (sigma_um) on a common grid, so neither pixel size nor pixel noise dominates. Normalised by mean^2 -> intensity-invariant.

bin_volume(vol, factors)

Mean-bin a (Z, Y, X) volume by integer factors (bz, by, bx), cropping the remainder. Use it to compare reconstructions on the data grid: detail finer than the camera pixel / z step is not constrained by the data, and two reconstructions of independent halves share whatever their solver puts there.

binomial_split(counts, seed=0, p=0.5)

Integer counts -> (a, b) with a ~ Binomial(counts, p), b = counts - a (independent Poisson halves).

decorrelation_xz(vol, row, spacing)

Decorrelation resolution (um) of the isotropic XZ section through row (pixel = the z step, so the Nyquist floor is 2 dz).

fission_split(y, var, seed=0)

Gaussian data fission: y1 = y + z, y2 = y - z, z ~ N(0, var) (var = Var(y), e.g. poisson_gauss_var).

For y with (approximately) Gaussian noise of variance var, y1 and y2 are independent, each with the same expectation as y and twice its noise variance. Unlike binomial thinning it does not assume one count per photon, so it holds for gained sCMOS counts with read noise (where binomial halves share shot and read noise).

heldout_deviance(op_h, x, y_h, background=0.0)

Mean Poisson deviance of y_h against op_h.forward(x) + background (op_h renders only the held-out phase).

heldout_deviance_fit(pred, raw, holdout, return_fit=False)

pred, raw (H, ...): fit raw ~ g pred + o on all phases but holdout, then the deviance of the held-out phase.

modulation_ncc(raw, pred)

NCC of (raw_h - mean_h raw) vs (pred_h - mean_h pred) over all phases and pixels (pattern term only).

poisson_gauss_var(mean, gain, read_var)

Variance (counts^2) of sCMOS counts with expectation mean: gain x mean (shot noise) + read variance.

xz_section(vol, row, spacing, isotropic=True)

(Z, Y, X) -> the (Z, X') section at y = row. With isotropic, x is resampled (Fourier, band-limited) DOWN to the z step so the pixels are square at the z pitch. Upsampling z instead would leave an empty axial frequency band (no data, not even noise) that decorrelation / FRC read as content at Nyquist.

spectral_anisotropy(img, n_bins=359, *, exclude_dc=True, k_range=None)

(anisotropy, angular power): power |F|^2 summed in n_bins equal angular sectors over [0, 2 pi), and anisotropy = std / (mean + 1e-6) of those sums (0 for an isotropic spectrum).

k_range = (lo, hi) keeps lo <= |k| < hi in units of Nyquist. exclude_dc drops the zero frequency, which the notebook kept (it lands in the sector at pi and dominates it); exclude_dc=False, n_bins=num_bins - 1 reproduces the notebook's compute_anisotropy(fftshift(fft2(img)), num_bins).

axial

Apparent axial extent from Gaussian fits through bright 3D maxima (from lf4d.metrics).

axial_fwhm(vol, spacing, n_peaks=200, min_dist_um=5.0, seed=0)

FWHM (um) of Gaussian fits to axial profiles through bright local 3D maxima.

The section is thin, so this reports apparent axial extent = PSF axial width convolved with the structure's own depth; it is comparable across systems, not a pure PSF FWHM.

compat

SR-Metrics compatible API (SRMetric, calculate_metrics) on top of the unified functions.

Note: SR-Metrics normalised img1 by max(img1) - min(img2); this wrapper uses the fixed normalisation, so values differ from SR-Metrics when the two images' minima differ.

SRMetric

Bases: SRMetric

compute_self_frc(num_bins=50, resolution_limit=1 / 7, sampling_rate=(1, 1), sampling_method='max', flip_tile=True, plot=False)

SR-Metrics return values (lists per image; resolution in SR-Metrics units, i.e. half of self_frc(...).resolution_um; None without a crossing). plot=True runs the original plotting code.

calculate_metrics(raw_image, reconstructed_image, metrics=None)

SR-Metrics calculate_metrics: metric name -> value.

fidelity

Content fidelity between a reference and a test image: nMSE, PSNR, global SSIM, PCC, mutual information.

Unified from SR-Metrics and lf4d.metrics. Each image is min-max normalised on its OWN range (SR-Metrics normalised the first image by max(img1) - min(img2), so every metric shifted when the two minima differed; fixed here).

normalise(a)

Min-max scale to [0, 1] (float64); a constant image maps to zeros.

nmse(ref, test)

sum (r - t)^2 / sum r^2 on normalised images.

psnr(ref, test)

Peak SNR (dB) on normalised images (peak 1); inf for identical images.

ssim_global(ref, test, c1=0.0001, c2=0.0009)

Single-window (whole-image) SSIM on normalised images, as SR-Metrics.

pcc(ref, test)

Pearson correlation over all pixels.

mutual_info(ref, test, bins=256)

Mutual information (nats) from the joint histogram of the normalised images.

pearson_fg(a, b)

Pearson correlation restricted to the joint foreground (Otsu on the smoothed sum), as lf4d.metrics.

noise

Noise, SNR, CNR and dynamic range of one plane (from lf4d.metrics).

resolution

Resolution: Fourier ring correlation (one implementation, two presets), decorrelation analysis, self-FRC (one image), textbook limits.

frc defaults reproduce lf4d.metrics.frc_resolution (square crop, apodised, mean-subtracted, 3-bin smoothed crossing above 0.05 Nyquist, Nyquist fallback); frc(..., **FRC_SR_METRICS) reproduces SR-Metrics compute_frc (50 raw bins, raise without a crossing). Frequencies are in units of Nyquist (1 = 1 / (2 px)).

decorrelation_resolution(img, px_um, n_r=200, n_g=25)

Lateral resolution (um) by decorrelation analysis (Descloux 2019). 1 = Nyquist frequency.

theoretical(na, ex_nm, em_nm, n=1.0)

Textbook resolution limits (um).

frc(a, b, px_um, *, threshold=1 / 7, n_bins=None, square=True, apodize=True, subtract_mean=True, smooth=3, k_min=0.05, on_no_crossing='nyquist', flip_tile=False)

FRC of two independent images of the same object (e.g. split acquisitions or binomial photon splits).

frc_resolution(a, b, px_um, thresh=1 / 7)

lf4d.metrics signature: (resolution um, k, curve).

self_frc(img, px_um, *, sampling=1, method='max', flip_tile=True, n_bins=50, threshold=1 / 7)

Single-image (self) FRC (SR-Metrics compute_self_frc): the image is split into its two diagonal pixel-interleaved pairs, the FRC of each pair is computed and the two curves are averaged.

sampling > 1 first reduces an up-sampled image by method ('max' pooling, 'fourier' spectrum crop, or 'skipping' straight into the split); flip_tile mirror-tiles the image before the split; n_bins // sampling rings. k is in units of the half-image Nyquist and the resolution is physical: the half-images have pixel 2 x sampling x px_um, so resolution = 4 sampling px_um / k_cross (SR-Metrics reported half of it, which disagrees with the two-image FRC of the same band limit). NaN if the curve never drops below threshold.

rfrc

Rolling FRC resolution maps (rFRC; Zhao et al. 2023, Light Sci Appl 12, 298), ported from the SR-Metrics notebook res_map.ipynb (ResolutionMap.compute_rrFRC_map / compute_srFRC_map).

Windows are processed in batched FFTs, whole window rows at a time (CuPy through pysrx.gpu when a GPU is present, NumPy otherwise) and the map is the mean resolution of the windows covering each pixel. Differences from the notebook (all tested): - resolution in physical units, 2 px / k for a window pair and 4 sampling px / k for the self (half-image) map; the notebook reported half of both (its rrFRC map disagreed with its own compute_frc by that factor); - windows whose FRC never drops below the threshold are skipped (the notebook added NaN to the rrFRC map); - pixels no window covers are NaN, not 0; the weight map counts the windows used.

rolling_frc_map(a, b, px_um, *, window=32, stride=16, n_bins=50, threshold=1 / 7, flip_tile=True, batch=None)

Relative rolling FRC (rrFRC) between two images of the same field (e.g. two acquisitions, or a raw and a reconstruction on the same grid): FRC of every window x window patch pair, stepped by stride.

n_bins rings per window (the notebook default 50; fewer for small windows avoids empty rings, which score 0 and end the curve early), flip_tile mirror-tiles each window before the FFT, batch caps the windows per FFT batch (default ~128 MB of spectra).

self_rolling_frc_map(img, px_um, *, window=32, stride=16, sampling=1, method='max', n_bins=50, threshold=1 / 7, flip_tile=True, batch=None)

Self rolling FRC (srFRC) of one image: the image (reduced by sampling with method if it was up-sampled) is split into its two diagonal pixel-interleaved pairs; per window the two FRC curves are averaged.

window and stride are in half-image pixels (as in the notebook); the returned window/stride and the map are on the input grid (x 2 sampling). n_bins // sampling rings.

sharpness

Focus / sharpness: Gaussian-derivative gradient energy at a fixed physical scale (from lf4d.metrics).

tenengrad(plane, px_um, grid_um=0.25, sigma_um=0.4, normalize=True)

Gaussian-derivative gradient energy at a fixed physical scale (sigma_um) on a common grid, so neither pixel size nor pixel noise dominates. Normalised by mean^2 -> intensity-invariant.

best_plane(vol, px_um)

Best-focus plane: max raw gradient energy at 1 um scale (robust to noise and dim planes).

sim

Reference-free evaluation for structured-illumination reconstructions (moved from Elyra-SIM-Recon).

  • binomial_split two statistically independent halves of Poisson counts (for split FRC: two reconstructions from half the photons). Caveat: only valid for pure photon counts; a camera fixed pattern (offset / column noise) is split into both halves and correlates them, so remove it first.
  • bin_volume mean-bin a volume to the data grid before comparing reconstructions (split FRC).
  • fission_split independent halves of gained sCMOS counts (Gaussian data fission, needs Var(y): poisson_gauss_var with the gain and read noise from pysrx.camera.photon_transfer).
  • xz_section the XZ section through one row, x resampled (Fourier) down to the z step: square pixels at the z pitch (upsampling z would fake content at Nyquist).
  • decorrelation_xz decorrelation resolution (um) of that section: a mixed x / z measure, dominated by the poorer axis; floor 2 dz.
  • heldout_deviance mean Poisson deviance of a held-out phase predicted through an operator (fit on the other phases); lower is better.
  • heldout_deviance_fit the same for an external volume's prediction (e.g. ZEN pushed through the model): one gain and offset fitted on the training phases, then the held-out phase predicted.
  • modulation_ncc NCC of the pattern-dependent part (each phase minus the phase mean) of data vs prediction.

binomial_split(counts, seed=0, p=0.5)

Integer counts -> (a, b) with a ~ Binomial(counts, p), b = counts - a (independent Poisson halves).

bin_volume(vol, factors)

Mean-bin a (Z, Y, X) volume by integer factors (bz, by, bx), cropping the remainder. Use it to compare reconstructions on the data grid: detail finer than the camera pixel / z step is not constrained by the data, and two reconstructions of independent halves share whatever their solver puts there.

poisson_gauss_var(mean, gain, read_var)

Variance (counts^2) of sCMOS counts with expectation mean: gain x mean (shot noise) + read variance.

fission_split(y, var, seed=0)

Gaussian data fission: y1 = y + z, y2 = y - z, z ~ N(0, var) (var = Var(y), e.g. poisson_gauss_var).

For y with (approximately) Gaussian noise of variance var, y1 and y2 are independent, each with the same expectation as y and twice its noise variance. Unlike binomial thinning it does not assume one count per photon, so it holds for gained sCMOS counts with read noise (where binomial halves share shot and read noise).

xz_section(vol, row, spacing, isotropic=True)

(Z, Y, X) -> the (Z, X') section at y = row. With isotropic, x is resampled (Fourier, band-limited) DOWN to the z step so the pixels are square at the z pitch. Upsampling z instead would leave an empty axial frequency band (no data, not even noise) that decorrelation / FRC read as content at Nyquist.

decorrelation_xz(vol, row, spacing)

Decorrelation resolution (um) of the isotropic XZ section through row (pixel = the z step, so the Nyquist floor is 2 dz).

heldout_deviance(op_h, x, y_h, background=0.0)

Mean Poisson deviance of y_h against op_h.forward(x) + background (op_h renders only the held-out phase).

heldout_deviance_fit(pred, raw, holdout, return_fit=False)

pred, raw (H, ...): fit raw ~ g pred + o on all phases but holdout, then the deviance of the held-out phase.

modulation_ncc(raw, pred)

NCC of (raw_h - mean_h raw) vs (pred_h - mean_h pred) over all phases and pixels (pattern term only).

spectral

Spectral anisotropy: angular distribution of the power spectrum (from the SR-Metrics notebook angular.ipynb).

Useful for SIM, where missing or weak pattern orientations show up as angular gaps in the spectrum.

spectral_anisotropy(img, n_bins=359, *, exclude_dc=True, k_range=None)

(anisotropy, angular power): power |F|^2 summed in n_bins equal angular sectors over [0, 2 pi), and anisotropy = std / (mean + 1e-6) of those sums (0 for an isotropic spectrum).

k_range = (lo, hi) keeps lo <= |k| < hi in units of Nyquist. exclude_dc drops the zero frequency, which the notebook kept (it lands in the sector at pi and dominates it); exclude_dc=False, n_bins=num_bins - 1 reproduces the notebook's compute_anisotropy(fftshift(fft2(img)), num_bins).