---
title: Diffraction lab
heading: Computing diffraction patterns in NumPy
eyebrow: B8 · Lesson 25 · Diffraction lab
xp: 50
---

::: hook
The sinc² pattern of a slit and the sharp lines of a grating came from formulas (lessons 10 and 11). Real apertures, like a lens with a central obstruction, a grating with uneven lines or a phased array with a dead element, rarely have tidy formulas. But Huygens's principle gives a recipe a computer can follow for any shape: treat each point of the opening as a source, add up their waves with the right phases, and square. In this lab you'll do exactly that, check it against the formulas, and then do it much faster with the FFT.
:::

::: play
- The dashed curve is a slit's exact pattern, $\text{sinc}^2(a\sin\theta/\lambda)$. The solid one adds up $m$ point sources spread evenly across the slit.
- With a few sources the sum looks right near the center but grows false peaks farther out: evenly spaced sources are a grating.
- Raise $m$ until the false peaks leave the range $-1 \le \sin\theta \le 1$. How does that $m$ compare with $a/\lambda$?
:::
:::

```sim plot
view: graph
x: s = -1..1
y: I = 0..1
slider: m = 2..60 step 1 = 8
slider: r = 1..20 step 0.5 = 10
plot: (sin(m*pi*r/m*s + 1e-9)/(m*sin(pi*r/m*s + 1e-9)))^2 | label: m sources | samples: 2000
plot: (sin(pi*r*s + 1e-9)/(pi*r*s + 1e-9))^2 | label: exact | dashed | color: ch2 | samples: 2000
readout: slit width in wavelengths = r | digits: 3
readout: first false peak at sin θ = m/r | digits: 3
```

::: predict
## You model a slit 20 wavelengths wide with 10 point sources. Where does the first false peak appear?

- [ ] Nowhere: 10 sources is plenty
- [x] At $\sin\theta = 0.5$, well inside the visible range
- [ ] At $\sin\theta = 2$, outside the visible range
- [ ] Right at the center

::: reveal
At $\sin\theta = 0.5$. Ten sources across 20 wavelengths are 2 wavelengths apart, a grating with $d = 2\lambda$, which has a first-order peak at $\sin\theta = \lambda/d = 0.5$. To push it past $\sin\theta = 1$ the sources must be less than a wavelength apart: more than 20 of them.
:::
:::

::: nameit
## Huygens's principle as a sum

Put $m$ point sources at positions $y_j$ across the opening, each with the opening's transmission $t_j$. In direction θ, the source at $y_j$ is ahead by a path $y_j\sin\theta$, so the far field is

$$E(\theta) \propto \sum_j t_je^{i2\pi y_j\sin\theta/\lambda}$$

and the intensity is $|E|^2$, normalized to 1 straight ahead. The sources must be closer than a wavelength, or the sum itself becomes a grating with false orders at $\sin\theta = \lambda/\Delta y$.

## In NumPy

```python
import numpy as np
s = np.linspace(-0.3, 0.3, 601)          # sin(theta) values
y = np.linspace(-1e-5, 1e-5, 200)        # source positions (m)
phase = 2 * np.pi / 0.5e-6 * np.outer(s, y)   # one row per angle, one column per source
E = np.exp(1j * phase).sum(axis=1)       # add the sources for every angle at once
I = np.abs(E) ** 2 / np.abs(E).max() ** 2
```

`np.outer` builds the whole table of phases at once, so no Python loop is needed. NumPy's `np.sinc(x)` is $\frac{\sin\pi x}{\pi x}$, so a slit's exact pattern is `np.sinc(a * s / lam) ** 2`.

## With the FFT

The sum has the form of a Fourier transform: the far field is the transform of the aperture's transmission, evaluated at spatial frequency $f_x = \sin\theta/\lambda$. Sample the aperture at spacing $\Delta x$ over $n$ points and the FFT (A10) computes the sum for $n$ directions at once:

- spatial frequencies from `np.fft.fftfreq(n, dx)`, so $\sin\theta = \lambda f_x$;
- steps of $\Delta(\sin\theta) = \frac{\lambda}{n\Delta x}$, so a wider window gives finer angles;
- `np.fft.fftshift` puts the zero frequency in the middle, in increasing order.

This is how optics software computes far fields for arbitrary apertures, and how antenna engineers compute the patterns of phased arrays.
:::

::: example
## How many Huygens sources does a 20 µm slit need at 0.5 µm? What happens with 200?

::: solution
1. **How many sources.** The sources must be less than a wavelength apart, so
   $$m > \frac{a}{\lambda} = 40$$
2. **With 200 sources.** They're 0.1 µm apart, so the first false peak would be at
   $$\begin{aligned} \sin\theta &= \frac{0.5}{0.1} \\ &= 5 \end{aligned}$$
   far outside the range.
3. **Accuracy.** The sum matches $\text{sinc}^2$ to within about $10^{-5}$ for $|\sin\theta| \le 0.3$.

**Answer:** it needs more than 40 sources. With 200 there's no false peak in range, and the sum matches $\text{sinc}^2$ to within about $10^{-5}$.
:::
:::

::: example
## An aperture is sampled at 0.5 µm over 4096 points and transformed with the FFT, at λ = 0.5 µm. What directions does the result cover, and how finely?

::: solution
1. **Window width.**
   $$4096 \times 0.5\ \mu\text{m} = 2048\ \mu\text{m}$$
2. **Angular step.**
   $$\begin{aligned} \Delta(\sin\theta) &= \frac{0.5}{2048} \\ &= 2.4 \times 10^{-4} \end{aligned}$$
3. **Range.** The highest frequency is $\frac{1}{2\Delta x}$, so $\sin\theta$ runs to
   $$\pm\frac{\lambda}{2\Delta x} = \pm0.5$$
4. **A 20 µm slit.** Its first null, at $\sin\theta = 0.025$, sits 102 steps out from the center, so the main lobe is well resolved.

**Answer:** the result covers $\sin\theta$ from −0.5 to +0.5, in steps of $2.4 \times 10^{-4}$.
:::
:::

::: check
given: m = 5 | 10 | 20; a = 40 | 100; lam = 0.5 | 0.633
answer: asin(m*lam/a)*180/pi
unit: °
tolerance: 0.5%

## A slit {a} µm wide is modeled with {m} evenly spaced sources at {lam} µm. At what angle is the first false peak?

::: right
Right. The sources form a grating with $d = a/m$: $\sin\theta = m\lambda/a$, giving {answer}.
:::

::: misses
- [asin(lam/a)*180/pi] That's the slit's own first null; the false peak comes from the source spacing $a/m$.
- [any] Not yet. Treat the sources as a grating of spacing $a/m$.
:::
:::

::: check
given: a = 20 | 50; lam = 0.45 | 0.65
answer: floor(a/lam) + 1
tolerance: 0.1%

## What is the fewest evenly spaced sources that model a slit {a} µm wide at {lam} µm without any false peak in the range $|\sin\theta| \le 1$?

::: right
Right. The spacing $a/m$ must be less than λ, so $m > a/\lambda$: {answer}.
:::

::: misses
- [any] Not yet. Keep the source spacing below one wavelength.
:::
:::

::: check
given: n = 1024 | 4096; dx = 0.25 | 1; lam = 0.5 | 1.55
answer: lam/(n*dx)
tolerance: 0.5%

## An aperture sampled at {dx} µm over {n} points is transformed at {lam} µm. How big is each step in $\sin\theta$?

::: right
Right. $\frac{\lambda}{n\Delta x}$ = {answer}.
:::

::: misses
- [1/(n*dx)] Multiply the frequency step $1/(n\Delta x)$ by λ to get $\sin\theta$.
- [any] Not yet. Frequency step $1/(n\Delta x)$, then $\sin\theta = \lambda f_x$.
:::
:::

::: check
given: n = 2048 | 8192; dx = 0.5 | 1; a = 10 | 40
answer: n*dx/a
tolerance: 0.5%

## A slit {a} µm wide is sampled at {dx} µm over {n} points. How many FFT steps lie between the center and the first null?

::: right
Right. The null is at $\lambda/a$ and the step is $\lambda/(n\Delta x)$: $n\Delta x/a$ = {answer}.
:::

::: misses
- [any] Not yet. Divide the null's position by the step size.
:::
:::

::: check
kind: python

## Write `slit_pattern(s, a, lam, m=200)`: the intensity at each $\sin\theta$ in the array `s` from `m` sources spread evenly across a slit of width `a`, at the centers of `m` equal strips, normalized to 1 straight ahead. The test compares it with $\text{sinc}^2$.

```python starter
import numpy as np

def slit_pattern(s, a, lam, m=200):
    return np.ones_like(s)

s = np.linspace(-0.3, 0.3, 7)
print(slit_pattern(s, 20e-6, 0.5e-6))
```

```python solution
import numpy as np

def slit_pattern(s, a, lam, m=200):
    y = (np.arange(m) + 0.5) * a / m - a / 2
    E = np.exp(2j * np.pi / lam * np.outer(s, y)).sum(axis=1) / m
    return np.abs(E) ** 2

s = np.linspace(-0.3, 0.3, 7)
print(slit_pattern(s, 20e-6, 0.5e-6))
```

```python tests
import numpy as np
s = np.linspace(-0.3, 0.3, 601)
I = slit_pattern(s, 20e-6, 0.5e-6)
assert np.shape(I) == s.shape, "Return one intensity per value of s."
assert abs(I[300] - 1) < 1e-9, f"Straight ahead (s = 0) should be 1; got {I[300]:.4f}."
ref = np.sinc(20e-6 * s / 0.5e-6) ** 2
err = np.max(np.abs(I - ref))
assert err < 1e-3, f"The pattern should match sinc² within 0.001; the largest difference is {err:.4f}."
```

::: right
Right. Try `m=10`: a false peak appears at $\sin\theta = 0.25$, just as the grating rule predicts.
:::
:::

::: check
kind: python

## Write `grating_pattern(s, N, d, a, lam)`: $N$ slits of width `a`, centers `d` apart. Add the $N$ slits' phasors $e^{i2\pi nd\sin\theta/\lambda}$, divide by $N$, square, and multiply by one slit's envelope $\text{sinc}^2(a\sin\theta/\lambda)$.

```python starter
import numpy as np

def grating_pattern(s, N, d, a, lam):
    return np.sinc(a * s / lam) ** 2

s = np.array([0.0, 0.1, 0.25])
print(grating_pattern(s, 5, 2e-6, 0.6e-6, 0.5e-6))
```

```python solution
import numpy as np

def grating_pattern(s, N, d, a, lam):
    n = np.arange(N)
    arr = np.exp(2j * np.pi * d / lam * np.outer(s, n)).sum(axis=1) / N
    return np.sinc(a * s / lam) ** 2 * np.abs(arr) ** 2

s = np.array([0.0, 0.1, 0.25])
print(grating_pattern(s, 5, 2e-6, 0.6e-6, 0.5e-6))
```

```python tests
import numpy as np
s = np.linspace(-0.3, 0.3, 600)
N, d, a, lam = 5, 2e-6, 0.6e-6, 0.5e-6
G = grating_pattern(s, N, d, a, lam)
assert np.shape(G) == s.shape, "Return one intensity per value of s."
b = np.pi * d * s / lam
ref = np.sinc(a * s / lam) ** 2 * (np.sin(N * b) / (N * np.sin(b))) ** 2
err = np.max(np.abs(G - ref))
assert err < 1e-6, f"The pattern should match the grating formula; the largest difference is {err:.3g}."
peak = grating_pattern(np.array([0.25]), N, d, a, lam)[0]
assert abs(peak - np.sinc(a * 0.25 / lam) ** 2) < 1e-9, "The first order, at sin θ = λ/d, should reach the envelope's height."
```

::: right
Right. Set `a = d / 2`: the second order vanishes, because it falls on the envelope's first zero, a "missing order".
:::
:::

::: check
kind: python

## Write `fft_pattern(aperture, dx, lam)`: given an aperture's transmission sampled at spacing `dx`, return `(s, I)`, the values of $\sin\theta$ in increasing order and the intensity normalized to 1 at $\sin\theta = 0$. Use `np.fft.fft`, `np.fft.fftfreq` and `np.fft.fftshift`.

```python starter
import numpy as np

def fft_pattern(aperture, dx, lam):
    n = len(aperture)
    return np.zeros(n), np.zeros(n)

n = 4096
slit = np.zeros(n); slit[n // 2 - 20:n // 2 + 20] = 1.0
s, I = fft_pattern(slit, 0.5e-6, 0.5e-6)
print(s[n // 2], I[n // 2])
```

```python solution
import numpy as np

def fft_pattern(aperture, dx, lam):
    n = len(aperture)
    F = np.fft.fftshift(np.fft.fft(aperture))
    s = np.fft.fftshift(np.fft.fftfreq(n, dx)) * lam
    I = np.abs(F) ** 2
    return s, I / I[n // 2]

n = 4096
slit = np.zeros(n); slit[n // 2 - 20:n // 2 + 20] = 1.0
s, I = fft_pattern(slit, 0.5e-6, 0.5e-6)
print(s[n // 2], I[n // 2])
```

```python tests
import numpy as np
n = 4096
slit = np.zeros(n); slit[n // 2 - 20:n // 2 + 20] = 1.0
s, I = fft_pattern(slit, 0.5e-6, 0.5e-6)
assert len(s) == n and len(I) == n, "Return one value of s and one intensity per FFT bin."
assert np.all(np.diff(s) > 0), "The values of sin θ should increase; fftshift both the frequencies and the transform."
assert abs(s[n // 2]) < 1e-12 and abs(I[n // 2] - 1) < 1e-9, "The center bin should be sin θ = 0 with intensity 1."
assert np.interp(0.025, s, I) < 1e-3, "A 20 µm slit at 0.5 µm should have its first null at sin θ = 0.025."
m = np.abs(s) < 0.1
err = np.max(np.abs(I[m] - np.sinc(20e-6 * s[m] / 0.5e-6) ** 2))
assert err < 2e-3, f"Near the center the pattern should match sinc²; the largest difference is {err:.4f}."
```

::: right
Right. Make a double slit, two 40-sample slits 200 samples apart, and you'll see the fringes inside the sinc² envelope, computed for 4096 directions in a fraction of a millisecond.
:::
:::

::: explain
## Why can the FFT compute a diffraction pattern, and what limits the directions it covers?

::: model
The far field is a sum over the aperture of each point's transmission times a phase that grows linearly with the point's position, which has the same form as a discrete Fourier transform, with the spatial frequency $\sin\theta/\lambda$ playing the role of frequency. The FFT computes that sum for $n$ evenly spaced spatial frequencies at once. The sample spacing sets the highest frequency it can represent, so $\sin\theta$ only reaches $\pm\lambda/2\Delta x$; the total window width sets how finely those directions are spaced, $\lambda/(n\Delta x)$. Finer sampling covers wider angles, and a longer window gives finer angular detail.
:::
:::

::: practice

::: check
given: a = 0.5 | 1; d = 2 | 3
answer: (sin(pi*a/d)/(pi*a/d))^2
tolerance: 0.5%

## A grating has slits {a} µm wide, {d} µm apart. How bright is its first order, as a fraction of the center?

::: misses
- [any] The envelope at $\sin\theta = \lambda/d$: $\text{sinc}^2(a/d)$.
:::
:::

::: check
given: dx = 0.25 | 0.5 | 1; lam = 0.5 | 1
answer: lam/(2*dx)
tolerance: 0.5%

## An aperture is sampled every {dx} µm and transformed at {lam} µm. Up to what $\sin\theta$ does the FFT reach? (Above 1, it covers every direction.)

::: misses
- [any] $\lambda/(2\Delta x)$.
:::
:::

::: check
given: d = 2 | 3 | 4
answer: d
tolerance: 0.5%

## A grating's slits are 1 µm wide and {d} µm apart. Which order is the first one missing?

::: misses
- [any] The order that lands on the envelope's first zero: $m = d/a$.
:::
:::
:::
