---
title: Electromagnetics lab
heading: A one-dimensional FDTD simulator in Python
eyebrow: C10 · Lesson 50 · Electromagnetics lab
xp: 50
---

::: hook
In this lab you'll build the simulator from lesson 49 and use it as a virtual test bench. A few lines of NumPy step Maxwell's equations across a thousand cells; a Gaussian pulse launched into the grid travels, meets a block of dielectric, and splits into a reflected and a transmitted pulse. Measuring them gives the reflection coefficient, which you can compare with the formula from lesson 31, and timing the pulse inside the dielectric gives its speed. When the simulation and the theory agree to a percent, you have a tool you can trust on problems that have no formula.
:::

::: play
- The analytic version of what your simulator will show: a pulse arrives from the left at a dielectric starting at z = 0. Drag t to watch it hit.
- After the hit, a reflected pulse of Γ times the height heads back (inverted, for a denser medium), and a transmitted pulse of τ times the height continues, narrower and slower by the refractive index n.
- Change $\varepsilon_r$ and watch the split change. Your FDTD run should reproduce Γ to about 1%.
:::
:::

```sim plot
view: graph
x: z = -200..200
y: E = -1.1..1.4
slider: er = 1..16 = 4 step 0.25
slider: t = 0..300 = 60 step 1
plot: (exp(-((z - t + 150)/12)^2) + (1 - sqrt(er))/(1 + sqrt(er))*exp(-((-z - t + 150)/12)^2))*step(-z) + 2/(1 + sqrt(er))*exp(-((sqrt(er)*z - t + 150)/12)^2)*step(z) | samples: 3000 | label: E
marker: x = 0 | label: dielectric starts
readout: Γ = (1 - sqrt(er))/(1 + sqrt(er)) | digits: 3
readout: τ = 2/(1 + sqrt(er)) | digits: 3
```

::: predict
## A pulse in vacuum hits a dielectric with $\varepsilon_r$ = 4. What is the transmitted pulse's peak, relative to the incident one?

- [ ] 1
- [ ] 0.33
- [x] 0.67
- [ ] 1.33

::: reveal
0.67: τ = 1 + Γ = 1 − 1/3 = 2/3. The transmitted pulse carries less field, but in a medium with lower impedance, so its power is $\tau^2 \times n = (4/9) \times 2 = 8/9$ of the incident, and the reflected 1/9 makes up the rest.
:::
:::

::: nameit
## The simulator

In normalized units (c = 1, cells of size 1, fields scaled so that E and H have the same size in a vacuum wave), one Yee step with Courant number S is

```
H[k] += S * (E[k+1] - E[k])          for k = 0 .. N-2
E[k] += S / eps[k] * (H[k] - H[k-1]) for k = 1 .. N-2
```

leaving E[0] and E[N−1] at zero (metal walls). In NumPy each line is one slice operation. A **soft source** adds a Gaussian to E at one cell each step, $e^{-((n - 40)/12)^2}$, which launches a pulse each way; recording E at a **probe** cell gives a time trace.

## Measuring

- **Reflection:** put the dielectric's edge to the right of the source and a probe between them. The probe sees the incident pulse pass, then the reflection come back; Γ is the ratio of their peaks (with sign).
- **Speed:** fill the grid with the dielectric, and time the pulse's peak between two probes a known distance apart: speed = distance / steps × S, in units of c.

Make the grid long enough that pulses bouncing off the end walls don't reach the probes during the measurement.
:::

::: example
## The probe sees an incident peak of 0.98 and, later, a reflected peak of −0.33. What is the medium?

::: solution
1. **Reflection coefficient.**
   $$\begin{aligned} \Gamma &= \frac{-0.33}{0.98} \\ &= -0.337 \end{aligned}$$
2. **Refractive index.**
   $$\begin{aligned} n &= \frac{1 - \Gamma}{1 + \Gamma} \\ &= \frac{1.337}{0.663} \\ &= 2.02 \end{aligned}$$
3. **Permittivity.**
   $$\begin{aligned} \varepsilon_r &= n^2 \\ &\approx 4.1 \end{aligned}$$
   The simulator's slightly slow waves inside the dielectric blur the last digit.

**Answer:** a dielectric with n ≈ 2.02 and $\varepsilon_r$ ≈ 4.1.
:::
:::

::: example
## A pulse's peak passes probes 200 cells apart 400 steps apart, at S = 1. How fast is it?

::: solution
1. **Speed.** At S = 1 a wave in free space moves one cell per step, so 200 cells in 400 steps is 0.5c.
2. **The medium.**
   $$n = 2$$
   $$\begin{aligned} \varepsilon_r &= n^2 \\ &= 4 \end{aligned}$$

**Answer:** it travels at 0.5c, so the medium has n = 2 and $\varepsilon_r$ = 4.
:::
:::

::: check
given: er = 2.25 | 4 | 9 | 16
answer: 2/(1 + sqrt(er))
tolerance: 0.5%

## A pulse in vacuum enters a dielectric with $\varepsilon_r$ = {er}. What is the transmitted peak relative to the incident peak?

::: right
Right. τ = 1 + Γ = {answer}.
:::

::: misses
- [(1 - sqrt(er))/(1 + sqrt(er))] That's Γ, the reflected part.
- [any] Not yet. τ = 2/(1 + n).
:::
:::

::: check
given: d = 100 | 300; n = 200 | 600; S = 0.8 | 0.5
answer: d/(n*S)
tolerance: 0.5%

## A pulse's peak takes {n} steps to travel {d} cells at Courant number {S}. What is its speed, as a fraction of c?

::: right
Right. Distance over (steps × S): {answer}.
:::

::: misses
- [d/n] Each step is S time units.
- [any] Not yet. $d/(nS)$.
:::
:::

::: check
kind: python

## Write `step(E, H, eps, S=1.0)`: one Yee update of the NumPy arrays E and H in place (H first, then E, with E[0] and E[-1] left at zero), returning them.

```python starter
import numpy as np

def step(E, H, eps, S=1.0):
    return E, H
```

```python solution
import numpy as np

def step(E, H, eps, S=1.0):
    H[:-1] += S * (E[1:] - E[:-1])
    E[1:-1] += S / eps[1:-1] * (H[1:-1] - H[:-2])
    return E, H
```

```python tests
import numpy as np
N = 800; E = np.zeros(N); H = np.zeros(N); eps = np.ones(N); trace = []
for n in range(400):
    step(E, H, eps, 1.0)
    E[100] += np.exp(-((n - 40) / 12.0) ** 2)
    trace.append(E[300])
arrive = int(np.argmax(trace))
assert abs(arrive - 240) <= 2, f"A pulse launched at cell 100 should peak at cell 300 about 200 steps after the source peaks (step 240); it peaked at step {arrive}."
assert E[0] == 0 and E[-1] == 0, "The end cells are metal walls: E stays zero there."
E = np.zeros(10); H = np.zeros(10); E[5] = 1.0
step(E, H, np.ones(10), 0.5)
assert abs(H[4] - 0.5) < 1e-12 and abs(H[5] + 0.5) < 1e-12, f"H updates from the E difference: H[4] should be 0.5 and H[5] -0.5, got {H[4]}, {H[5]}."
assert abs(E[5] - 0.5) < 1e-12, f"Then E[5] updates from the new H: 1 + 0.5*(H[5] - H[4]) = 0.5, got {E[5]}."
```

::: right
Right. Two vectorized lines are the whole of Maxwell's equations in one dimension.
:::
:::

::: check
kind: python

## Write `reflection(er)`: simulate a 1000-cell grid, vacuum up to cell 600 and $\varepsilon_r$ = er from there, with a soft Gaussian source at cell 400 (centered at step 40, width 12) and a probe at cell 500, for 700 steps at S = 1. Return the reflected peak divided by the incident peak (the largest-magnitude values in the first 200 and the remaining steps, with their signs).

```python starter
def reflection(er):
    return 0.0
```

```python solution
import numpy as np

def step(E, H, eps, S=1.0):
    H[:-1] += S * (E[1:] - E[:-1])
    E[1:-1] += S / eps[1:-1] * (H[1:-1] - H[:-2])
    return E, H

def reflection(er):
    N = 1000
    eps = np.ones(N); eps[600:] = er
    E = np.zeros(N); H = np.zeros(N); trace = []
    for n in range(700):
        step(E, H, eps, 1.0)
        E[400] += np.exp(-((n - 40) / 12.0) ** 2)
        trace.append(E[500])
    tr = np.array(trace)
    inc, ref = tr[:200], tr[200:]
    return ref[np.argmax(np.abs(ref))] / inc[np.argmax(np.abs(inc))]
```

```python tests
for er in (2.25, 4.0, 9.0):
    n = er ** 0.5
    want = (1 - n) / (1 + n)
    got = reflection(er)
    assert abs(got - want) < 0.02, f"For er = {er} the measured reflection should be close to (1 - n)/(1 + n) = {want:.3f}; got {got:.3f}."
assert abs(reflection(1.0)) < 0.01, "With no dielectric there should be essentially no reflection."
```

::: right
Right. The simulation reproduces the boundary formula to about a percent, from nothing but local updates.
:::
:::

::: check
kind: python

## Write `wave_speed(er)`: fill an 1000-cell grid with $\varepsilon_r$ = er, launch the same Gaussian at cell 200 (S = 1), record E at probes at cells 400 and 600 for 900 steps, and return the speed as a fraction of c from the steps between the two probes' peaks.

```python starter
def wave_speed(er):
    return 1.0
```

```python solution
import numpy as np

def step(E, H, eps, S=1.0):
    H[:-1] += S * (E[1:] - E[:-1])
    E[1:-1] += S / eps[1:-1] * (H[1:-1] - H[:-2])
    return E, H

def wave_speed(er):
    N = 1000
    eps = np.full(N, float(er))
    E = np.zeros(N); H = np.zeros(N); a = []; b = []
    for n in range(900):
        step(E, H, eps, 1.0)
        E[200] += np.exp(-((n - 40) / 12.0) ** 2)
        a.append(E[400]); b.append(E[600])
    return 200 / (np.argmax(b) - np.argmax(a))
```

```python tests
for er in (1.0, 2.25, 4.0):
    got = wave_speed(er)
    want = 1 / er ** 0.5
    assert abs(got - want) < 0.03 * want, f"In er = {er} waves should travel at about 1/sqrt(er) = {want:.3f} c; got {got:.3f}."
```

::: right
Right. The grid's waves slow by the refractive index, with a small extra lag from numerical dispersion.
:::
:::

::: explain
## Why does a soft source launch pulses in both directions, and why does the measurement need a long grid?

::: model
A soft source adds to the electric field at one cell, which is like injecting a current sheet there; the fields it creates spread symmetrically, one pulse each way, because nothing in the update prefers a direction. The left-going pulse travels to the metal wall at cell 0, reflects, and comes back past the probe; the transmitted pulse reflects from the far wall too. If either arrived at the probe before the measurement window ended, it would be mistaken for part of the reflection. Making the grid long enough that those stray pulses arrive late, or adding absorbing boundaries, keeps the measurement clean.
:::
:::

::: practice

::: check
given: er = 2 | 3 | 4 | 6 | 9 | 12 | 16
answer: (1 - sqrt(er))/(1 + sqrt(er))
tolerance: 0.5%

## What Γ should the simulator measure for $\varepsilon_r$ = {er}?

::: misses
- [any] $(1 - n)/(1 + n)$.
:::
:::

::: check
given: d = 150 | 400; n = 300 | 400
answer: d/n
tolerance: 0.5%

## {d} cells in {n} steps at S = 1: speed as a fraction of c?

::: misses
- [any] d/n.
:::
:::

::: check
given: g = -0.1 | -0.2 | -0.3 | -0.4 | -0.5 | -0.6
answer: ((1 - g)/(1 + g))^2
tolerance: 0.5%

## A measured Γ of {g}: what $\varepsilon_r$ does it imply?

::: misses
- [any] $n = (1 - \Gamma)/(1 + \Gamma)$, then $n^2$.
:::
:::
:::
