Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
207 changes: 207 additions & 0 deletions tests/models/test_isotropic_thin_3d_singular_system.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,207 @@
"""The closed-form singular system of the 2D phase transfer function: values, vectors, inverse and gradients.

The reference is ``torch.linalg.svd`` of each frequency's 2 x Z matrix, in double precision on the CPU.
"""

import warnings

import pytest
import torch

from waveorder.models import isotropic_thin_3d
from waveorder.reconstruct import tikhonov_regularized_inverse_filter

Z_POSITIONS = [-1.5, -0.75, 0.0, 0.75, 1.5]


def _transfer_functions(tilt_zenith=0.2, tilt_azimuth=1.0, shape=(32, 32), **kwargs):
return isotropic_thin_3d.calculate_transfer_function(
yx_shape=shape,
yx_pixel_size=6.5 / 40,
z_position_list=Z_POSITIONS,
wavelength_illumination=0.532,
index_of_refraction_media=1.3,
numerical_aperture_illumination=0.5,
numerical_aperture_detection=1.2,
tilt_angle_zenith=tilt_zenith,
tilt_angle_azimuth=tilt_azimuth,
**kwargs,
)


def _svd_reference(absorption_tf, phase_tf):
"""``torch.linalg.svd`` of every frequency's 2 x Z matrix, in the layout of ``calculate_singular_system``."""
matrix = torch.stack((absorption_tf, phase_tf), 0).permute(2, 3, 0, 1).to(torch.complex128)
U, S, Vh = torch.linalg.svd(matrix, full_matrices=False)
return U.permute(2, 3, 0, 1), S.permute(2, 0, 1), Vh.permute(2, 3, 0, 1)


def _inverse_filter(singular_system, regularization_strength=1e-3):
U, S, Vh = singular_system
S_reg = tikhonov_regularized_inverse_filter(S, regularization_strength)
return torch.einsum("sj...,j...,jf...->fs...", torch.conj(U), S_reg, torch.conj(Vh))


def test_singular_values_and_inverse_match_the_svd():
absorption_tf, phase_tf = _transfer_functions()
U, S, Vh = isotropic_thin_3d.calculate_singular_system(absorption_tf, phase_tf)
U_ref, S_ref, Vh_ref = _svd_reference(absorption_tf, phase_tf)
assert U.dtype == absorption_tf.dtype and S.dtype == torch.float32 and Vh.dtype == absorption_tf.dtype
assert U.shape == (2, 2, 32, 32) and S.shape == (2, 32, 32) and Vh.shape == (2, len(Z_POSITIONS), 32, 32)
assert torch.allclose(S.double(), S_ref, atol=1e-6 * float(S_ref.max()))
assert (S[0] >= S[1]).all()
ours = _inverse_filter((U, S, Vh))
reference = _inverse_filter((U_ref, S_ref, Vh_ref))
assert torch.allclose(ours.to(torch.complex128), reference, atol=1e-5 * float(reference.abs().max()))


def test_the_system_is_orthonormal_and_reproduces_the_transfer_function():
absorption_tf, phase_tf = _transfer_functions(tilt_zenith=0.3)
U, S, Vh = (x.to(torch.complex128) for x in isotropic_thin_3d.calculate_singular_system(absorption_tf, phase_tf))
eye = torch.eye(2, dtype=torch.complex128)[..., None, None]
assert torch.allclose(torch.einsum("ik...,il...->kl...", U.conj(), U), eye, atol=1e-6)
rebuilt = torch.einsum("sk...,k...,kz...->sz...", U, S.to(torch.complex128), Vh)
original = torch.stack((absorption_tf, phase_tf), 0).to(torch.complex128)
assert torch.allclose(rebuilt, original, atol=1e-6 * float(original.abs().max()))
inside = S[1].real > 1e-3 * float(S.real.max()) # the rows of Vh are orthonormal where both values are nonzero
gram = torch.einsum("kz...,lz...->kl...", Vh, Vh.conj())
assert torch.allclose(gram[..., inside], eye.expand_as(gram)[..., inside], atol=1e-5)


def test_batched_input_equals_each_item():
tfs = [_transfer_functions(tilt_zenith=zenith) for zenith in (0.0, 0.25)]
batched = isotropic_thin_3d.calculate_singular_system(
torch.stack([a for a, _ in tfs]), torch.stack([p for _, p in tfs])
)
for index, (absorption_tf, phase_tf) in enumerate(tfs):
single = isotropic_thin_3d.calculate_singular_system(absorption_tf, phase_tf)
for ours, theirs in zip(batched, single):
assert torch.equal(ours[index], theirs)


@pytest.mark.parametrize(
"case",
["zero", "multiple_of_identity", "rank_one", "absorption_only"],
)
def test_degenerate_frequencies(case):
"""Frequencies outside the pupil, equal singular values, and a rank-one matrix give a valid, finite system."""
rng = torch.Generator().manual_seed(0)
row = torch.randn(len(Z_POSITIONS), 1, 1, dtype=torch.complex64, generator=rng)
other = torch.randn(len(Z_POSITIONS), 1, 1, dtype=torch.complex64, generator=rng)
if case == "zero":
absorption_tf, phase_tf = torch.zeros_like(row), torch.zeros_like(row)
elif case == "multiple_of_identity": # orthogonal rows of equal norm: A A^H = c I
other = other - (row.conj() * other).sum(0) / (row.conj() * row).sum(0) * row
other = other * torch.linalg.vector_norm(row) / torch.linalg.vector_norm(other)
absorption_tf, phase_tf = row, other
elif case == "rank_one":
absorption_tf, phase_tf = row, (0.5 - 0.25j) * row
else:
absorption_tf, phase_tf = row, torch.zeros_like(row)
U, S, Vh = isotropic_thin_3d.calculate_singular_system(absorption_tf, phase_tf)
assert all(torch.isfinite(torch.view_as_real(x) if x.is_complex() else x).all() for x in (U, S, Vh))
_, S_ref, _ = _svd_reference(absorption_tf, phase_tf)
assert torch.allclose(S.double(), S_ref, atol=1e-5 * max(float(S_ref.max()), 1.0))
eye = torch.eye(2, dtype=U.dtype)[..., None, None]
assert torch.allclose(torch.einsum("ik...,il...->kl...", U.conj(), U), eye, atol=1e-6)
rebuilt = torch.einsum("sk...,k...,kz...->sz...", U, S.to(U.dtype), Vh)
assert torch.allclose(rebuilt, torch.stack((absorption_tf, phase_tf), 0), atol=1e-5)


def test_gradcheck_of_the_singular_values_and_the_inverse():
"""Analytic gradients equal finite differences, in double precision, for a phase-invariant use of the system."""
rng = torch.Generator().manual_seed(1)
absorption_tf = torch.randn(4, 3, 3, dtype=torch.complex128, generator=rng, requires_grad=True)
phase_tf = torch.randn(4, 3, 3, dtype=torch.complex128, generator=rng, requires_grad=True)
data = torch.randn(4, 3, 3, dtype=torch.complex128, generator=rng)

def values(a, p):
return isotropic_thin_3d.calculate_singular_system(a, p)[1]

def inverse(a, p):
return torch.einsum("zsyx,zyx->syx", _inverse_filter(isotropic_thin_3d.calculate_singular_system(a, p)), data)

assert torch.autograd.gradcheck(values, (absorption_tf, phase_tf))
assert torch.autograd.gradcheck(inverse, (absorption_tf, phase_tf))


def test_gradients_match_the_svds_where_it_has_them():
"""On frequencies with distinct, nonzero singular values the gradients equal torch.linalg.svd's."""
tilt = torch.tensor(0.2, dtype=torch.float64, requires_grad=True)
data = torch.randn(len(Z_POSITIONS), 32, 32, dtype=torch.float64, generator=torch.Generator().manual_seed(2))
grads = {}
for name in ("closed_form", "svd"):
absorption_tf, phase_tf = _transfer_functions(tilt_zenith=tilt, pupil_steepness=100.0)
absorption_tf, phase_tf = absorption_tf.to(torch.complex128), phase_tf.to(torch.complex128)
if name == "closed_form":
system = isotropic_thin_3d.calculate_singular_system(absorption_tf, phase_tf)
else:
system = _svd_reference(absorption_tf, phase_tf)
# a phase-invariant loss: the Tikhonov reconstruction of fixed data
filtered = torch.einsum("zsyx,zyx->syx", _inverse_filter(system), torch.fft.fft2(data).to(torch.complex128))
loss = (filtered.abs() ** 2).sum() + system[1].sum()
(grads[name],) = torch.autograd.grad(loss, tilt)
assert torch.isfinite(grads["closed_form"])
assert grads["closed_form"] == pytest.approx(float(grads["svd"]), rel=1e-6)


def test_gradient_through_reconstruct_is_finite_and_matches_finite_differences():
"""The exact system now backs gradient-based fits: d(loss)/d(tilt) through ``reconstruct``.

``reconstruct`` computes the transfer function in single precision, so the analytic gradient agrees with finite
differences to about 1e-3 (5e-4 here); the double-precision comparison is
``test_gradients_match_the_svds_where_it_has_them``.
"""
generator = torch.Generator().manual_seed(3)
data = 10.0 + torch.rand(len(Z_POSITIONS), 32, 32, generator=generator, dtype=torch.float64)

def loss(zenith):
_, phase = isotropic_thin_3d.reconstruct(
data,
yx_pixel_size=6.5 / 40,
z_position_list=Z_POSITIONS,
wavelength_illumination=0.532,
index_of_refraction_media=1.3,
numerical_aperture_illumination=0.5,
numerical_aperture_detection=1.2,
tilt_angle_zenith=zenith,
tilt_angle_azimuth=1.0,
pupil_steepness=100.0,
)
return (phase**2).sum()

zenith = torch.tensor(0.2, dtype=torch.float64, requires_grad=True)
(gradient,) = torch.autograd.grad(loss(zenith), zenith)
step = 1e-4
with torch.no_grad():
numeric = (
loss(torch.tensor(0.2 + step, dtype=torch.float64)) - loss(torch.tensor(0.2 - step, dtype=torch.float64))
) / (2 * step)
assert torch.isfinite(gradient)
assert float(gradient) == pytest.approx(float(numeric), rel=5e-3)


def test_decomposition_auto_is_svd_with_or_without_gradients():
data = 10.0 + torch.rand(len(Z_POSITIONS), 32, 32, generator=torch.Generator().manual_seed(4))
common = dict(
yx_pixel_size=6.5 / 40,
z_position_list=Z_POSITIONS,
wavelength_illumination=0.532,
index_of_refraction_media=1.3,
numerical_aperture_illumination=0.5,
numerical_aperture_detection=1.2,
tilt_angle_azimuth=1.0,
)
zenith = torch.tensor(0.2, requires_grad=True)
with warnings.catch_warnings():
warnings.simplefilter("error") # neither "auto" nor "svd" warns
_, auto = isotropic_thin_3d.reconstruct(data, tilt_angle_zenith=zenith, decomposition="auto", **common)
_, svd = isotropic_thin_3d.reconstruct(data, tilt_angle_zenith=0.2, decomposition="svd", **common)
assert torch.allclose(auto.detach(), svd, atol=1e-6 * float(svd.abs().max()))


def test_per_channel_still_works_and_is_deprecated():
absorption_tf, phase_tf = _transfer_functions()
with pytest.warns(DeprecationWarning, match="per_channel"):
U, S, Vh = isotropic_thin_3d.calculate_singular_system(absorption_tf, phase_tf, use_svd=False)
assert torch.equal(U[0, 1], torch.zeros_like(U[0, 1])) and torch.equal(U[0, 0], torch.ones_like(U[0, 0]))
Loading
Loading