Ptychography phase retrieval#

Ptychography is a coherent imaging technique for recovering a complex-valued object, including both its amplitude and phase, from intensity-only measurements. A localized illumination, called the probe, is scanned across overlapping regions of the object. At each position, a detector records the intensity after the exit wave has propagated from the object plane. The overlap provides redundant measurements of the same object regions, making it possible to recover phase information that is not measured directly by the detector.

Under the far-field (Fraunhofer) approximation, propagation to the detector is described by the 2D Fourier transform \(F\). For a known probe \(p\), the noiseless measurement at scan position \(l\) is

\[y_l = \left| B_l x \right|^2, \quad B_l = F \text{diag}(p) T_l, \quad l = 1, \dots, n_{\text{img}},\]

where \(T_l\) selects the probe-sized region of the complex object \(x\) at scan position \(l\), and \(\text{diag}(p) T_l x\) is the exit wave leaving the object.

In this example, we use as ground truth a complex object reconstructed from experimental ptychography data of an unstained histological cross-section of a mouse [1]. We then build a complex probe, set up the far-field geometry, and simulate diffraction patterns with deepinv.physics.Ptychography. Finally, we reconstruct the object from these measurements.

General setup#

Imports the necessary libraries and modules, including ptychography phase retrieval function from deepinv. It sets the device to GPU if available, otherwise uses the CPU.

import matplotlib.pyplot as plt
import torch

import deepinv as dinv
from deepinv.optim.data_fidelity import AmplitudeLoss
from deepinv.optim.phase_retrieval import correct_global_phase
from deepinv.physics import FarFieldPtychographyGeometry, Ptychography

device = dinv.utils.get_device()
Selected GPU 0 with 28959.3125 MiB free memory

Load the complex object#

We load a complex-valued image of an unstained histological cross-section of a mouse.

x = dinv.utils.load_example(
    "mouse_histology_complex_image.pt", device=device
).unsqueeze(0)
x_amplitude = x.abs()
x_phase = x.angle()

# Show the amplitude between its 5th and 95th percentiles for better contrast,
# and the phase in radians with the cyclic hsv colormap.
amp_low, amp_high = torch.quantile(
    x_amplitude, torch.tensor([0.05, 0.95], device=device)
).tolist()

fig, axs = plt.subplots(1, 2, figsize=(10, 4.5), squeeze=False, layout="tight")
dinv.utils.plot(
    x_amplitude,
    titles="Object amplitude",
    rescale_mode="clip",
    vmin=amp_low,
    vmax=amp_high,
    cbar=True,
    fig=fig,
    axs=axs[:, :1],
    show=False,
)
dinv.utils.plot(
    x_phase,
    titles="Object phase (rad)",
    cmap="hsv",
    rescale_mode="clip",
    vmin=-torch.pi,
    vmax=torch.pi,
    cbar=True,
    fig=fig,
    axs=axs[:, 1:],
)
Object amplitude, Object phase (rad)
/local/pberna03/actions-runner/_work/deepinv/deepinv/deepinv/utils/plotting.py:550: UserWarning: set_ticklabels() should only be used with a fixed number of ticks, i.e. after set_ticks() or using a FixedLocator. Otherwise, ticks may be mislabeled.
  colbar.set_ticklabels(true_labels)
/local/pberna03/actions-runner/_work/deepinv/deepinv/deepinv/utils/plotting.py:550: UserWarning: set_ticklabels() should only be used with a fixed number of ticks, i.e. after set_ticks() or using a FixedLocator. Otherwise, ticks may be mislabeled.
  colbar.set_ticklabels(true_labels)

Set up the physical geometry#

We define the far-field geometry using the illumination wavelength, the object-to-detector distance, and the detector pixel size after binning. Together with the detector shape, these determine the object-plane pixel size through the Fraunhofer relation. We use this pixel size to convert physical distances to pixels.

size = x.shape[-1]
img_size = (1, size, size)
probe_size = 64  # detector and diffraction-pattern shape, in pixels
probe_shape = (1, probe_size, probe_size)
native_detector_pixel_size = 4.5e-6
detector_binning = 8
effective_detector_pixel_size = detector_binning * native_detector_pixel_size

geometry = FarFieldPtychographyGeometry(
    wavelength=632.8e-9,  # visible light
    object_detector_distance=5e-2,
    detector_shape=probe_shape[-2:],
    detector_pixel_size=(
        effective_detector_pixel_size,
        effective_detector_pixel_size,
    ),
)
object_dy, object_dx = geometry.object_pixel_size
object_fov = torch.tensor(geometry.object_extent(img_size[-2:]))  # (height, width)
print(f"Object-plane pixel size: ({object_dy * 1e6:.2f}, {object_dx * 1e6:.2f}) um")
print(
    f"Object field of view: ({object_fov[0] * 1e6:.1f}, {object_fov[1] * 1e6:.1f}) um"
)
Object-plane pixel size: (13.73, 13.73) um
Object field of view: (3515.6, 3515.6) um

Build the probe#

We specify the probe radius in metres and convert it to pixels using the object-plane pixel size. We then create a circular probe with deepinv.physics.phase_retrieval.build_probe() and add a quadratic phase profile to model a curved wavefront, as produced by a thin lens. The phase increases from \(-\pi\) at the centre to \(\pi\) at the edge of the aperture.

probe_radius_m = 4e-4  # illuminated radius on the object
probe_radius = round(probe_radius_m / object_dx)  # in pixels (isotropic geometry)
print(f"Probe radius: {probe_radius_m * 1e6:.1f} um = {probe_radius} pixels")

probe = dinv.physics.phase_retrieval.build_probe(
    probe_shape, type="disk", probe_radius=probe_radius, device=device
)
# Centre the phase profile on the disk so its phase ranges from -pi to pi.
coordinates = torch.arange(probe_size, device=device) - probe_size // 2
yy, xx = torch.meshgrid(coordinates, coordinates, indexing="ij")
lens_phase = 2 * torch.pi * (xx**2 + yy**2) / probe_radius**2 - torch.pi
lens_phase = torch.where(probe.abs() > 0, lens_phase, 0)  # zero phase outside the disk
probe = probe.to(torch.complex64) * torch.exp(1j * lens_phase)

# Show the magnitude in gray and the phase in radians with the cyclic hsv colormap.
fig, axs = plt.subplots(1, 2, figsize=(7, 3), squeeze=False, layout="tight")
dinv.utils.plot(
    probe.abs(),
    titles="Probe magnitude",
    rescale_mode=None,
    cbar=True,
    fig=fig,
    axs=axs[:, :1],
    show=False,
)
dinv.utils.plot(
    probe.angle(),
    titles="Probe phase (rad)",
    cmap="hsv",
    rescale_mode="clip",
    vmin=-torch.pi,
    vmax=torch.pi,
    cbar=True,
    fig=fig,
    axs=axs[:, 1:],
)
Probe magnitude, Probe phase (rad)
Probe radius: 400.0 um = 29 pixels
/local/pberna03/actions-runner/_work/deepinv/deepinv/deepinv/utils/plotting.py:550: UserWarning: set_ticklabels() should only be used with a fixed number of ticks, i.e. after set_ticks() or using a FixedLocator. Otherwise, ticks may be mislabeled.
  colbar.set_ticklabels(true_labels)

Define the scanning grid in physical units#

We choose the scan spacing from the desired overlap between neighbouring probe positions. For a probe of diameter \(d\) and an overlap fraction \(o\), the spacing is \((1 - o) d\). The overlap provides the redundant measurements needed for phase retrieval. We define the grid in metres and extend it far enough for the probe to reach the object corners.

For experimental data, replace this grid with the stage positions from the scan file, stored as an (N, 2) array in metres, in (row, column) order.

target_overlap = 0.7
scan_step = (1 - target_overlap) * 2 * probe_radius_m
scan_span = object_fov - torch.sqrt(torch.tensor(2.0)) * probe_radius_m

side_n_img = int(torch.ceil(scan_span / scan_step).max()) + 1
scan_rows = torch.linspace(-scan_span[0] / 2, scan_span[0] / 2, side_n_img)
scan_cols = torch.linspace(-scan_span[1] / 2, scan_span[1] / 2, side_n_img)
positions = torch.cartesian_prod(scan_rows, scan_cols)
print(
    f"Scan: {len(positions)} positions, {scan_step * 1e6:.1f} um apart, "
    f"spanning {scan_span[0] * 1e6:.1f} um"
)
Scan: 196 positions, 240.0 um apart, spanning 2949.9 um

Convert the scan to pixel shifts and build the operator#

deepinv.physics.PtychographyGeometry.positions_to_shifts() divides the stage positions by the object-plane pixel size and rounds to the nearest pixel to obtain the shifts used by the operator.

Scan step: 240.0 um = 17 pixels

Display probe overlap#

We display the overlap for two consecutive probe positions and for the full scan to see how the probes cover the object.

overlap_img = physics.B.get_overlap_img(physics.B.shifts).cpu()
probe_index = n_img // 2
overlap2probe = physics.B.get_overlap_img(
    physics.B.shifts[probe_index : probe_index + 2]
).cpu()
dinv.utils.plot(
    [overlap2probe.unsqueeze(0), overlap_img.unsqueeze(0)],
    titles=["Overlap 2 probe", "Overlap images"],
)
Overlap 2 probe, Overlap images

Simulate the measurements#

Applying the operator gives one diffraction pattern per scan position. We show the first four patterns, which come from the first row of the scan grid. Neighbouring probes illuminate overlapping regions, so the speckle pattern changes gradually between positions.

y = physics(x)
print(f"Measurements: {tuple(y.shape)} (batch, positions, detector rows, columns)")

# ``fftshift`` to move the zero frequency from the corner to the centre of each image and
# log scale for clearly showing the range of intensities
patterns = torch.fft.fftshift(y[0, :4], dim=(-2, -1)).log()
dinv.utils.plot(
    list(patterns.unsqueeze(1)),
    titles=[f"Position {i + 1} (log)" for i in range(len(patterns))],
    figsize=(10, 3),
)
Position 1 (log), Position 2 (log), Position 3 (log), Position 4 (log)
Measurements: (1, 196, 64, 64) (batch, positions, detector rows, columns)

Optimize the amplitude loss#

We start with an object of uniform amplitude and zero phase, then use Adam to minimize the amplitude loss. Both the object’s amplitude and phase are free to vary during reconstruction. Note that one could also extend the current demo to the blind ptychography case of reconstructing the probe simultaneously.

data_fidelity = AmplitudeLoss()
n_iter = 350
x_est = torch.ones_like(x, requires_grad=True)
optimizer = torch.optim.Adam([x_est], lr=0.05)
loss_hist = []

for i in range(n_iter):
    optimizer.zero_grad()
    loss = data_fidelity(x_est, y, physics).mean()
    loss.backward()
    optimizer.step()
    loss_hist.append(loss.detach().cpu())
    if i % 10 == 0:
        print(f"Iter {i}, loss: {loss.item():.2e}")

# Plot the loss curve
plt.plot(loss_hist)
plt.yscale("log")
plt.title("Amplitude loss")
plt.show()
Amplitude loss
Iter 0, loss: 2.15e+04
Iter 10, loss: 2.57e+03
Iter 20, loss: 1.39e+03
Iter 30, loss: 8.03e+02
Iter 40, loss: 3.70e+02
Iter 50, loss: 1.80e+02
Iter 60, loss: 9.72e+01
Iter 70, loss: 5.59e+01
Iter 80, loss: 3.37e+01
Iter 90, loss: 2.22e+01
Iter 100, loss: 1.65e+01
Iter 110, loss: 1.35e+01
Iter 120, loss: 1.14e+01
Iter 130, loss: 9.82e+00
Iter 140, loss: 8.55e+00
Iter 150, loss: 7.36e+00
Iter 160, loss: 6.27e+00
Iter 170, loss: 5.01e+00
Iter 180, loss: 3.99e+00
Iter 190, loss: 3.49e+00
Iter 200, loss: 3.06e+00
Iter 210, loss: 2.70e+00
Iter 220, loss: 2.38e+00
Iter 230, loss: 2.09e+00
Iter 240, loss: 1.83e+00
Iter 250, loss: 1.60e+00
Iter 260, loss: 1.40e+00
Iter 270, loss: 1.21e+00
Iter 280, loss: 1.05e+00
Iter 290, loss: 9.07e-01
Iter 300, loss: 7.80e-01
Iter 310, loss: 6.69e-01
Iter 320, loss: 5.73e-01
Iter 330, loss: 4.88e-01
Iter 340, loss: 4.15e-01

Compare the reconstruction with the original object#

Correct the global phase offset and compare the ground-truth and estimated amplitude and phase.

x_est = x_est.detach().cpu()
final_est = correct_global_phase(x_est, x.cpu())

# Use the same display ranges for both, so their colours can be compared directly.
fig, axs = plt.subplots(1, 2, figsize=(10, 4.5), squeeze=False, layout="tight")
dinv.utils.plot(
    {"Ground-truth amplitude": x_amplitude, "Estimated amplitude": final_est.abs()},
    rescale_mode="clip",
    vmin=amp_low,
    vmax=amp_high,
    cbar=True,
    fig=fig,
    axs=axs,
)

fig, axs = plt.subplots(1, 2, figsize=(10, 4.5), squeeze=False, layout="tight")
dinv.utils.plot(
    {
        "Ground-truth phase (rad)": x_phase,
        "Estimated phase (rad)": torch.angle(final_est),
    },
    cmap="hsv",
    rescale_mode="clip",
    vmin=-torch.pi,
    vmax=torch.pi,
    cbar=True,
    fig=fig,
    axs=axs,
)
  • Ground-truth amplitude, Estimated amplitude
  • Ground-truth phase (rad), Estimated phase (rad)
/local/pberna03/actions-runner/_work/deepinv/deepinv/deepinv/utils/plotting.py:550: UserWarning: set_ticklabels() should only be used with a fixed number of ticks, i.e. after set_ticks() or using a FixedLocator. Otherwise, ticks may be mislabeled.
  colbar.set_ticklabels(true_labels)
/local/pberna03/actions-runner/_work/deepinv/deepinv/deepinv/utils/plotting.py:550: UserWarning: set_ticklabels() should only be used with a fixed number of ticks, i.e. after set_ticks() or using a FixedLocator. Otherwise, ticks may be mislabeled.
  colbar.set_ticklabels(true_labels)
/local/pberna03/actions-runner/_work/deepinv/deepinv/deepinv/utils/plotting.py:550: UserWarning: set_ticklabels() should only be used with a fixed number of ticks, i.e. after set_ticks() or using a FixedLocator. Otherwise, ticks may be mislabeled.
  colbar.set_ticklabels(true_labels)
/local/pberna03/actions-runner/_work/deepinv/deepinv/deepinv/utils/plotting.py:550: UserWarning: set_ticklabels() should only be used with a fixed number of ticks, i.e. after set_ticks() or using a FixedLocator. Otherwise, ticks may be mislabeled.
  colbar.set_ticklabels(true_labels)
References:

Total running time of the script: (0 minutes 1.447 seconds)

🏷 Tags: Ptychography, Phase-retrieval

Gallery generated by Sphinx-Gallery