pysrx.optics¶
pysrx.optics
¶
Optical models: light-field sub-aperture PSFs, widefield / confocal PSFs and lattice SIM patterns.
LightfieldCalib
dataclass
¶
pupil_centres()
¶
(V, 2) lenslet centres in units of the objective pupil radius (ky, kx), rotation applied.
pupil_radius()
¶
Lenslet sub-aperture radius in units of the objective pupil radius.
from_acquisition(acq, **overrides)
classmethod
¶
Build from tanoa's normalised acquisition dict (attributes.tanoa.acquisition).
Taken from the CZI: NA / immersion, MLA rotation, and each view's focal group (rank of its lenslet's MLA defocus, e.g. -0.33 / 0 / +0.33 mm -> 0 / 1 / 2). NOT in the CZI, so still placeholders to calibrate (scripts/01_calibrate.py): lenslet centres in the pupil (hex layout), pitch_frac, lens_radius_frac, group_dz_um (object-space focal shift per group), and the unit of the vendor's per-lens OffsetX/Y.
LatticeSIM
dataclass
¶
Pattern
dataclass
¶
Estimated lattice pattern. k in cycles / px (y, x); inactive orders: k = nan, amplitude 0.
confocal_psf(opt, pinhole_au, shape_zyx, dx_um, dz_um, device='cuda', oversample=2)
¶
h_ex x (h_em (*) pinhole); pinhole_au None -> widefield h_em. Normalised to sum 1. FFT order.
pinhole_disk(diameter_um, shape_yx, dx_um, device='cuda', sub=8)
¶
Area-weighted disk, origin at (0, 0) (FFT order), normalised to sum 1.
render(vol, psf)
¶
Circular 3D convolution vol (*) psf (both (Z, Y, X), psf in FFT order). Pad vol beforehand as needed.
sectioning_curve(psf)
¶
Response to a thin uniform fluorescent sheet vs defocus: sum over each plane (FFT-ordered z), peak 1.
widefield_psf(opt, lam_um, shape_zyx, dx_um, dz_um, device='cuda', oversample=1)
¶
(Z, Y, X) intensity PSF, origin at index 0 (FFT order) in every axis; each plane sums to 1 (energy).
default_groups(centres)
¶
Placeholder focal-group assignment (0/1/2), interleaved so each group covers the whole pupil.
fourier_shift(h, shift_yx)
¶
Shift h[v, z] by shift_yx[v] (V, 2) or shift_yx[v, z] (V, Z, 2) pixels (circular, sub-pixel).
hex_layout(rings=3)
¶
Lenslet centres of a hex grid (unit pitch), ring 0..rings -> 1, 7, 19, 37 lenses. (V, 2) as (ky, kx).
load_calib(path)
¶
(calib, z_um of the reconstruction grid) from scripts/01_calibrate.py's JSON.
psf_model(cal, z_um, size=48, device='cuda', dtype=torch.float32, centres=None, radius=None, group_dz=None, edge=0.0, views=None, offsets=None)
¶
Centred PSFs and parallax shifts.
Returns psf (V, Z, size, size) -- each (v, z) slice the blur of view v at depth z with its linear (shift) part removed, normalised so a point emits unit total energy into all views at every depth -- and shift_px (V, Z, 2) = z . k_c / kz(k_c) / pixel (+ per-view offsets), the (dy, dx) displacement of that blur.
centres (V, 2) pupil-radius units, radius and group_dz (G,) may be tensors with requires_grad
(calibration); edge > 0 softens the lenslet aperture edge (pupil-radius units) so centres get gradients.
views restricts to a subset (then centres / offsets are given for that subset only); offsets (V, 2) px
overrides cal.offsets_px (tensor allowed).
psf_stack(cal, z_um, size=64, device='cuda', dtype=torch.float32)
¶
Full PSFs H[v, z, y, x] with the parallax baked in (window must hold the shifted spots; small grids/tests). For real data use psf_model + Projector(shift_px=...), which applies the shift exactly on the full grid.
estimate_pattern(raw, lat, cutoff, *, device='cuda', seed_basis=None, snr_min=40.0, q_min=0.02, apod=0.1, tol=2.0)
¶
Fit the lattice pattern to raw phases (H, Y, X) or (H, Z, Y, X), offset already subtracted.
cutoff: detection OTF cutoff 2 NA / lambda_em in cycles / px (bounds the peak search and the amplitude OTF).
snr_min: spectral peak / band median for a blind detection. Noise alone peaks at ~ln(N_band) / ln 2 (16 at
256^2, 23 at 1280^2) times the median, hence 40; a seeded order (one location) needs snr_min / 4.
seed_basis: (2, 2) rows k_a, k_b to refine locally instead of the blind search. tol: max misfit of a detected
peak to the fitted lattice, in FFT bins. Returns a Pattern (all arrays numpy).
lattice_snr_map(raw, pattern, lat, tile=32, scales=(0.8, 0.9), angles_deg=(22.5, 45.0, 67.5))
¶
Where is the lattice measurable? Per-tile SNR (Y // tile, X // tile) of raw phases (H, Y, X), offset removed.
Signal: sum over the active non-zero orders of |sum_tile d_o e^{-2 pi i k_o . r} conj(d_0)|^2 (the demodulated
cross-power at the fitted frequencies). Noise: the same in the same tile at off-lattice frequencies (each k_o
rotated by angles_deg and scaled by scales, averaged). Background tiles sit near 1 (power ratio; 10 log10 for
dB).
otf2d(shape, cutoff, shift=(0.0, 0.0), device='cpu')
¶
In-focus incoherent OTF of a circular pupil, (Y, X) FFT order, cutoff in cycles / px; evaluated at f + shift.
separate(raw, lat)
¶
(H, ...) raw phases -> (O, ...) complex order components.
confocal
¶
Digital confocal: render optical sections of a continuous fluorescence field as a point-scanning confocal would.
h_conf(r, z) = h_ex(r, z) [ h_em(., z) (*)_2D D_P ](r) (D_P: pinhole disk of P Airy units, object space)
widefield: h_wf(r, z) = h_em(r, z) (uniform illumination, no pinhole)
image: I = x (*)_3D h_conf (x = emission density, e.g. the NeRF field)
h_ex / h_em are scalar Debye widefield PSFs of the full objective aperture (NA, immersion index n) at the excitation / emission wavelengths, built by angular spectrum on the sampling grid: h(r, z) = | F^-1{ P(k) exp(i 2 pi z kz) } |^2, P the pupil |k| <= NA / lambda (optionally aplanatic-apodised). 1 AU = 1.22 lambda_em / NA (diameter). Parameters cover the 40x/1.1 W AF568 set (561 / 603 nm, n 1.333) and the 20x/0.8 air Convallaria set (488 / 560).
widefield_psf(opt, lam_um, shape_zyx, dx_um, dz_um, device='cuda', oversample=1)
¶
(Z, Y, X) intensity PSF, origin at index 0 (FFT order) in every axis; each plane sums to 1 (energy).
pinhole_disk(diameter_um, shape_yx, dx_um, device='cuda', sub=8)
¶
Area-weighted disk, origin at (0, 0) (FFT order), normalised to sum 1.
confocal_psf(opt, pinhole_au, shape_zyx, dx_um, dz_um, device='cuda', oversample=2)
¶
h_ex x (h_em (*) pinhole); pinhole_au None -> widefield h_em. Normalised to sum 1. FFT order.
render(vol, psf)
¶
Circular 3D convolution vol (*) psf (both (Z, Y, X), psf in FFT order). Pad vol beforehand as needed.
sectioning_curve(psf)
¶
Response to a thin uniform fluorescent sheet vs defocus: sum over each plane (FFT-ordered z), peak 1.
lightfield
¶
Wave-optics forward model of the ZEISS Lightfield 4D (multifocal Fourier light field microscope).
Picture: the micro-lens array (MLA) sits in a plane conjugate to the objective pupil. Each of the 37 lenslets crops a small sub-aperture of the pupil and forms its own low-NA image ("view") of the whole field. A point at depth z puts a defocus phase across the pupil; through an off-axis sub-aperture that phase acts like a tilt, so the spot shifts laterally in proportion to z and to the lenslet's distance from the pupil centre (parallax). The 3 focal groups add a fixed extra defocus per lenslet so different groups are sharp at different depths.
PSF of view v at depth z (scalar Debye, object-space units): h_v(r; z) = | F{ A_v(k) . P(k) . exp(i 2 pi (z + dz_g(v)) sqrt((n/lam)^2 - |k|^2)) } |^2 with P the objective pupil (|k| <= NA/lam) and A_v the lenslet sub-aperture.
The views in the raw CZI are already rectified and registered at the native focal plane by ZEN, so a source at z = 0 projects to the same pixel in every view: PSFs are built centred, and parallax comes out of the physics.
Implementation: the defocus phase through a sub-aperture centred at k_c is split into its linear part (a pure lateral shift, z . k_c / kz(k_c), applied exactly as a Fourier phase ramp in the projector) and the remainder (the blur, computed on a small window). Only the object depth z shifts a view -- ZEN registered the views at the native plane -- while the focal-group defocus dz_g only blurs. Everything is torch, so the calibration (scripts/01_calibrate.py) can fit lenslet centres, lenslet radius, dz_g and per-view offsets by gradient descent.
LightfieldCalib
dataclass
¶
pupil_centres()
¶
(V, 2) lenslet centres in units of the objective pupil radius (ky, kx), rotation applied.
pupil_radius()
¶
Lenslet sub-aperture radius in units of the objective pupil radius.
from_acquisition(acq, **overrides)
classmethod
¶
Build from tanoa's normalised acquisition dict (attributes.tanoa.acquisition).
Taken from the CZI: NA / immersion, MLA rotation, and each view's focal group (rank of its lenslet's MLA defocus, e.g. -0.33 / 0 / +0.33 mm -> 0 / 1 / 2). NOT in the CZI, so still placeholders to calibrate (scripts/01_calibrate.py): lenslet centres in the pupil (hex layout), pitch_frac, lens_radius_frac, group_dz_um (object-space focal shift per group), and the unit of the vendor's per-lens OffsetX/Y.
hex_layout(rings=3)
¶
Lenslet centres of a hex grid (unit pitch), ring 0..rings -> 1, 7, 19, 37 lenses. (V, 2) as (ky, kx).
default_groups(centres)
¶
Placeholder focal-group assignment (0/1/2), interleaved so each group covers the whole pupil.
psf_model(cal, z_um, size=48, device='cuda', dtype=torch.float32, centres=None, radius=None, group_dz=None, edge=0.0, views=None, offsets=None)
¶
Centred PSFs and parallax shifts.
Returns psf (V, Z, size, size) -- each (v, z) slice the blur of view v at depth z with its linear (shift) part removed, normalised so a point emits unit total energy into all views at every depth -- and shift_px (V, Z, 2) = z . k_c / kz(k_c) / pixel (+ per-view offsets), the (dy, dx) displacement of that blur.
centres (V, 2) pupil-radius units, radius and group_dz (G,) may be tensors with requires_grad
(calibration); edge > 0 softens the lenslet aperture edge (pupil-radius units) so centres get gradients.
views restricts to a subset (then centres / offsets are given for that subset only); offsets (V, 2) px
overrides cal.offsets_px (tensor allowed).
psf_stack(cal, z_um, size=64, device='cuda', dtype=torch.float32)
¶
Full PSFs H[v, z, y, x] with the parallax baked in (window must hold the shifted spots; small grids/tests). For real data use psf_model + Projector(shift_px=...), which applies the shift exactly on the full grid.
fourier_shift(h, shift_yx)
¶
Shift h[v, z] by shift_yx[v] (V, 2) or shift_yx[v, z] (V, Z, 2) pixels (circular, sub-pixel).
load_calib(path)
¶
(calib, z_um of the reconstruction grid) from scripts/01_calibrate.py's JSON.
sim
¶
Lattice SIM illumination: phase-step model, order separation and pattern estimation from raw phase images.
Model (ZEISS Elyra 7 Lattice SIM, 13 phases). The illumination is a 2D lattice with basis wavevectors k_a, k_b
(cycles / px, (y, x)); phase step h shifts it by (phi_a,h, phi_b,h) along the two axes (phases_deg of tanoa's
structured_illumination block). Order o = (m, n) has wavevector k_o = m k_a + n k_b and phase m phi_a + n phi_b:
I_h(r) = sum_o c_o exp(i (2 pi k_o . r + m phi_a,h + n phi_b,h)) (c_-o = conj(c_o), c_0 = 1)
raw_h(r) = sum_o exp(i (m phi_a,h + n phi_b,h)) d_o(r), d_o = h (*) (c_o e^{2 pi i k_o . r} s)
The Elyra steps are phi_a = 3 h (2 pi / 13), phi_b = -2 h (2 pi / 13), so order (m, n) carries residue 3m - 2n
(mod 13). DEFAULT_ORDERS (0, +-a, +-b, +-(a+b), +-(a-b), +-2a, +-2b) hits all 13 residues once: the phase matrix
is a 13-point DFT and the separation is exact and perfectly conditioned. (Any other lattice order aliases onto the
component with the same residue.)
Estimation (estimate_pattern), per z plane and accumulated over planes:
1. separate the orders d_o (apodised edges);
2. for o != 0, p_o = d_o conj(d_0) has a spectral peak at k_o (sum_f D_o(f) conj(D_0(f - q)) is maximal at q = k_o);
a coarse peak search per order, with SNR = peak / median power over the band q_min <= |q| <= cutoff;
3. least-squares fit of the basis to the orders above snr_min (orders outside the span of the detected ones are
flagged inactive, e.g. one lattice direction only), then a joint sub-pixel refinement of the basis maximising
sum_o w_o sum_z |P_o,z(k_o)|^2 on demodulated, block-binned p_o (cheap, exact for sub-bin offsets);
4. complex order amplitude c_o / c_0 from the OTF-weighted overlap of the shifted order with the zero order
(Gustafsson / Wicker), with the in-focus 2D OTF otf2d (defocus ignored).
With seed_basis (e.g. the 488 fit for a fainter channel: the lattice is the image of one grating) step 2-3 skip
the blind search and refine locally around the seed.
LatticeSIM
dataclass
¶
Pattern
dataclass
¶
Estimated lattice pattern. k in cycles / px (y, x); inactive orders: k = nan, amplitude 0.
separate(raw, lat)
¶
(H, ...) raw phases -> (O, ...) complex order components.
otf2d(shape, cutoff, shift=(0.0, 0.0), device='cpu')
¶
In-focus incoherent OTF of a circular pupil, (Y, X) FFT order, cutoff in cycles / px; evaluated at f + shift.
estimate_pattern(raw, lat, cutoff, *, device='cuda', seed_basis=None, snr_min=40.0, q_min=0.02, apod=0.1, tol=2.0)
¶
Fit the lattice pattern to raw phases (H, Y, X) or (H, Z, Y, X), offset already subtracted.
cutoff: detection OTF cutoff 2 NA / lambda_em in cycles / px (bounds the peak search and the amplitude OTF).
snr_min: spectral peak / band median for a blind detection. Noise alone peaks at ~ln(N_band) / ln 2 (16 at
256^2, 23 at 1280^2) times the median, hence 40; a seeded order (one location) needs snr_min / 4.
seed_basis: (2, 2) rows k_a, k_b to refine locally instead of the blind search. tol: max misfit of a detected
peak to the fitted lattice, in FFT bins. Returns a Pattern (all arrays numpy).
lattice_snr_map(raw, pattern, lat, tile=32, scales=(0.8, 0.9), angles_deg=(22.5, 45.0, 67.5))
¶
Where is the lattice measurable? Per-tile SNR (Y // tile, X // tile) of raw phases (H, Y, X), offset removed.
Signal: sum over the active non-zero orders of |sum_tile d_o e^{-2 pi i k_o . r} conj(d_0)|^2 (the demodulated
cross-power at the fitted frequencies). Noise: the same in the same tile at off-lattice frequencies (each k_o
rotated by angles_deg and scaled by scales, averaged). Background tiles sit near 1 (power ratio; 10 log10 for
dB).