<!-- DO NOT EDIT. -->
<!-- THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. -->
<!-- TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: -->
<!-- "auto_examples/physics/demo_ptychography.py" -->
<!-- LINE NUMBERS ARE GIVEN BELOW. -->

#### NOTE
New to DeepInverse? Get started with the basics with the
[5 minute quickstart tutorial](https://deepinv.org/auto_examples/basics/demo_quickstart.html.md#sphx-glr-auto-examples-basics-demo-quickstart-py)..

<a id="sphx-glr-auto-examples-physics-demo-ptychography-py"></a>

# Ptychography phase retrieval

This example shows how to create a Ptychography phase retrieval operator and generate phaseless measurements from a given image.

<!-- GENERATED FROM PYTHON SOURCE LINES 9-13 -->

## 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.

<!-- GENERATED FROM PYTHON SOURCE LINES 13-28 -->
```Python
import matplotlib.pyplot as plt
import torch
import numpy as np
import deepinv as dinv
from deepinv.utils import load_example
from deepinv.utils.plotting import plot
from deepinv.physics import Ptychography
from deepinv.optim.data_fidelity import L1
from deepinv.optim.phase_retrieval import correct_global_phase

device = dinv.utils.get_device()
```

```none
Selected GPU 0 with 28779.9375 MiB free memory
```

<!-- GENERATED FROM PYTHON SOURCE LINES 30-33 -->

## Load image from the internet

Loads a sample image from a URL, resizes it to 128x128 pixels, and extracts only one color channel.

<!-- GENERATED FROM PYTHON SOURCE LINES 33-42 -->
```Python
size = 128
image = load_example("CBSD_0010.png", grayscale=False, img_size=(size, size))

x = image[:, 0, ...].unsqueeze(1)  # Take only one channel
print(x.shape)
plot([x], figsize=(10, 10))
```

```none
torch.Size([1, 1, 128, 128])
```

<!-- GENERATED FROM PYTHON SOURCE LINES 43-46 -->

## Prepare phase input

We use the original image as the phase information for the complex signal. The original value range is [0, 1], and we map it to the phase range [0, pi].

<!-- GENERATED FROM PYTHON SOURCE LINES 46-51 -->
```Python
phase = x / x.max() * np.pi  # between 0 and pi
input = torch.exp(1j * phase.to(torch.complex64)).to(device)
```

<!-- GENERATED FROM PYTHON SOURCE LINES 52-56 -->

## Set up ptychography physics model

Initializes the ptychography physics model with parameters like the probe and shifts.
This model will be used to simulate ptychography measurements.

<!-- GENERATED FROM PYTHON SOURCE LINES 56-71 -->
```Python
img_size = (1, size, size)
n_img = 10**2
probe = dinv.physics.phase_retrieval.build_probe(
    img_size, type="disk", probe_radius=30, device=device
)
shifts = dinv.physics.phase_retrieval.generate_shifts(img_size, n_img=n_img, fov=170)

physics = Ptychography(
    img_size=img_size,
    probe=probe,
    shifts=shifts,
    device=device,
)
```

<!-- GENERATED FROM PYTHON SOURCE LINES 72-75 -->

## Display probe overlap

Calculates and displays the overlap of probe regions in the image, helping visualize the ptychography pattern.

<!-- GENERATED FROM PYTHON SOURCE LINES 75-84 -->
```Python
overlap_img = physics.B.get_overlap_img(physics.B.shifts).cpu()
overlap2probe = physics.B.get_overlap_img(physics.B.shifts[55:57]).cpu()
plot(
    [overlap2probe.unsqueeze(0), overlap_img.unsqueeze(0)],
    titles=["Overlap 2 probe", "Overlap images"],
)
```

<!-- GENERATED FROM PYTHON SOURCE LINES 85-88 -->

## Generate and visualize probe and measurements

Displays the ptychography probe and a sum of the generated measurement data.

<!-- GENERATED FROM PYTHON SOURCE LINES 88-97 -->
```Python
probe = physics.probe[:, 55].cpu()
y = physics(input)
plot(
    [torch.abs(probe), y[0].sum(dim=0).log().unsqueeze(0)],
    titles=["Probe", "y"],
)
```

<!-- GENERATED FROM PYTHON SOURCE LINES 98-101 -->

## Gradient descent for phase retrieval

Implements a simple gradient descent algorithm to minimize the L1 data fidelity loss for phase retrieval.

<!-- GENERATED FROM PYTHON SOURCE LINES 101-119 -->
```Python
data_fidelity = L1()
lr = 0.1
n_iter = 200
x_est = torch.randn_like(x).to(device)
loss_hist = []

for i in range(n_iter):
    x_est = x_est - lr * data_fidelity.grad(x_est, y, physics)
    loss_hist.append(data_fidelity(x_est, y, physics).cpu())
    if i % 10 == 0:
        print(f"Iter {i}, loss: {loss_hist[i]}")

# Plot the loss curve
plt.plot(loss_hist)
plt.title("loss curve (gradient descent with random initialization)")
plt.show()
```

```none
Iter 0, loss: tensor([23953.7969])
Iter 10, loss: tensor([14560.8633])
Iter 20, loss: tensor([12004.5332])
Iter 30, loss: tensor([7251.1802])
Iter 40, loss: tensor([5526.1528])
Iter 50, loss: tensor([4536.6250])
Iter 60, loss: tensor([3646.8047])
Iter 70, loss: tensor([3813.3425])
Iter 80, loss: tensor([4315.8345])
Iter 90, loss: tensor([4320.2207])
Iter 100, loss: tensor([3790.2324])
Iter 110, loss: tensor([3655.6079])
Iter 120, loss: tensor([4044.2708])
Iter 130, loss: tensor([3791.3345])
Iter 140, loss: tensor([4008.1716])
Iter 150, loss: tensor([4596.6147])
Iter 160, loss: tensor([4131.6675])
Iter 170, loss: tensor([3725.8979])
Iter 180, loss: tensor([4225.5508])
Iter 190, loss: tensor([4318.9380])
```

<!-- GENERATED FROM PYTHON SOURCE LINES 120-124 -->

## Display final estimated phase retrieval

Corrects the global phase of the estimated image to match the original phase and plots the result.
This final visualization shows the original image and the estimated phase after retrieval.

<!-- GENERATED FROM PYTHON SOURCE LINES 124-128 -->
```Python
x_est = x_est.detach().cpu()
final_est = correct_global_phase(x_est, x)
plot([x, torch.angle(final_est)], titles=["x", "Final estimate"])
```

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

🏷 Tags: Ptychography, Phase-retrieval

<a id="sphx-glr-download-auto-examples-physics-demo-ptychography-py"></a>

[`Download Jupyter notebook: demo_ptychography.ipynb`](https://deepinv.org/auto_examples/physics/_downloads/9464f38579ff220e8d6a07bba06944d9/demo_ptychography.ipynb)

[`Download Python source code: demo_ptychography.py`](https://deepinv.org/auto_examples/physics/_downloads/2af06c813c78b76d31aa61b436db646f/demo_ptychography.py)

[`Download zipped: demo_ptychography.zip`](https://deepinv.org/auto_examples/physics/_downloads/a513b24e745042d0e8ca99e5d5dece45/demo_ptychography.zip)

[Gallery generated by Sphinx-Gallery](https://sphinx-gallery.github.io)
