---
title: Matrix mechanics lab
heading: Spin operators, measurement, precession and Rabi oscillation as matrices in code
eyebrow: B10 · Lesson 18 · Matrix mechanics lab
xp: 50
---

::: hook
Lessons 15 to 17 put quantum mechanics in the language of vectors and operators. For a spin or a qubit the vectors have just two components and the operators are 2 × 2 matrices, so everything can be computed exactly with a few lines of NumPy: commutators, the probabilities of measuring along any axis, time evolution by a matrix exponential, and the Rabi oscillation that drives every qubit gate. In this lab you'll build those tools and check each against the formulas, then use the same machinery on a chain of coupled wells. Units are those where ħ = 1.
:::

::: play
- A two-level system is driven with Rabi frequency Ω and detuning Δ. The curve is the population of the upper level against time, from Rabi's formula.
- On resonance the population swings fully between 0 and 1; off resonance it swings faster and never fully flips.
- Step 4 reproduces this curve by exponentiating the 2 × 2 Hamiltonian, with no formula at all.
:::

```sim plot
view: graph
x: t = 0..3
y: P = 0..1
slider: W = 0.5..3 step 0.1 = 1
slider: D = 0..3 step 0.1 = 1
plot: W^2/(W^2 + D^2)*sin(2*pi*sqrt(W^2 + D^2)*t/2)^2 | label: upper-level population | samples: 600
readout: largest population = W^2/(W^2 + D^2) | digits: 3
```

::: predict
## A spin points up along z and is measured along an axis tilted 60° toward x. What is the chance of getting "up" along that axis?

- [ ] 50%
- [x] 75%
- [ ] 87%
- [ ] 100%

::: reveal
75%, which is $\cos^2 30°$. In matrix language, it's the squared overlap of the state $(1, 0)$ with the eigenvector of $\sin 60°\,S_x + \cos 60°\,S_z$ that has the larger eigenvalue. Step 2 computes it for any axis.
:::
:::

::: nameit
## Spin as matrices

With ħ = 1, $S_i = \frac12\sigma_i$ with the Pauli matrices

$$\sigma_x = \begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix}, \quad \sigma_y = \begin{pmatrix} 0 & -i \\ i & 0 \end{pmatrix}, \quad \sigma_z = \begin{pmatrix} 1 & 0 \\ 0 & -1 \end{pmatrix},$$

which obey $[S_x, S_y] = iS_z$ and its cyclic versions.

## Measurement

The spin along a unit vector **n** is $\mathbf n \cdot \mathbf S$. Its eigenvectors are the possible outcomes, and the chance of each is the squared size of the state's overlap with it: `np.linalg.eigh` gives both eigenvalues and eigenvectors.

## Time evolution

For a time-independent Hamiltonian, $|\psi(t)\rangle = e^{-iHt}|\psi(0)\rangle$. With $H = V\,\text{diag}(w)\,V^\dagger$ from `eigh`, $e^{-iHt} = V\,\text{diag}(e^{-iwt})\,V^\dagger$. A spin in a field along z, $H = \omega S_z$, precesses about z at ω.

## Rabi oscillation

In the frame rotating with the drive, a two-level system with Rabi frequency Ω and detuning Δ has $H = \frac12\begin{pmatrix} \Delta & \Omega \\ \Omega & -\Delta \end{pmatrix}$, and exponentiating it reproduces Rabi's formula, $P = \frac{\Omega^2}{\Omega^2 + \Delta^2}\sin^2\frac{\sqrt{\Omega^2 + \Delta^2}\,t}{2}$.

## Larger matrices

The same code handles N coupled wells: the tight-binding matrix with $-t$ beside the diagonal has eigenvalues $-2t\cos\frac{j\pi}{N + 1}$, the beginnings of a band.
:::

::: example
## A spin-½ points along +x and sits in a field that makes it precess about z at 1 cycle per unit time. What is ⟨S_x⟩ after a quarter and a half cycle?

::: solution
1. **Evolve the state.** With $H = 2\pi S_z$, evolve the state $\frac{1}{\sqrt2}(1, 1)$ by the matrix exponential.
2. **Read off ⟨S_x⟩.** It's 0.5 at t = 0, 0 at t = 0.25 (the spin points along y) and −0.5 at t = 0.5.
3. **Compare with a classical moment.** The expectation values precess exactly like a classical magnetic moment, which is Ehrenfest's theorem for spin: the averages obey the classical equations even though each measurement gives only ±½.

**Answer:** ⟨S_x⟩ is 0 after a quarter cycle and −0.5 after a half cycle.
:::
:::

::: example
## A qubit is driven with Ω = Δ = 2π × 1 (frequencies in cycles per unit time). What is its upper population at t = 0.3, and what's the most it ever reaches?

::: solution
1. **Exponentiate the Hamiltonian.** Exponentiate this for t = 0.3, apply it to the state, and square the second component:
   $$H = \frac12\begin{pmatrix} \Delta & \Omega \\ \Omega & -\Delta \end{pmatrix}$$
   That gives 0.4722.
2. **Check with Rabi's formula.**
   $$\begin{aligned} P &= \frac12\sin^2\left(\frac{\sqrt2 \times 2\pi \times 0.3}{2}\right) \\ &= 0.4722 \end{aligned}$$
3. **The most it reaches.** With equal detuning and drive, the population never exceeds ½. Detuning tilts the rotation axis on the Bloch sphere away from the equator, so the state circles without reaching the south pole.

**Answer:** the upper population is 0.4722 at t = 0.3, and it never exceeds ½.
:::
:::

::: example
## Eight identical wells in a row are coupled to their neighbors by t = 1. What are the lowest three levels?

::: solution
1. **The levels.** The matrix with −1 beside the diagonal has eigenvalues
   $$-2\cos\frac{j\pi}{9}$$
   which are −1.879, −1.532 and −1.000 for j = 1, 2, 3.
2. **Check numerically.** `eigvalsh` reproduces them to rounding.
3. **The band.** All eight levels lie between −2 and +2, the band of width 4t of lesson 31. With more wells the levels fill the band densely: a crystal's band is the limit of this matrix as N grows.

**Answer:** the lowest three levels are −1.879, −1.532 and −1.000.
:::
:::

::: check
kind: python

## Step 1. Write `spin_ops()` returning the three spin matrices $S_x, S_y, S_z$ (ħ = 1), and `commutator(A, B)`.

```python starter
import numpy as np

def spin_ops():
    I = np.eye(2)
    return I, I, I

def commutator(A, B):
    return A @ B

Sx, Sy, Sz = spin_ops()
print(commutator(Sx, Sy))
```

```python solution
import numpy as np

def spin_ops():
    Sx = np.array([[0, 1], [1, 0]], dtype=complex) / 2
    Sy = np.array([[0, -1j], [1j, 0]], dtype=complex) / 2
    Sz = np.array([[1, 0], [0, -1]], dtype=complex) / 2
    return Sx, Sy, Sz

def commutator(A, B):
    return A @ B - B @ A

Sx, Sy, Sz = spin_ops()
print(commutator(Sx, Sy))
```

```python tests
import numpy as np
Sx, Sy, Sz = spin_ops()
assert np.allclose(commutator(Sx, Sy), 1j * Sz), "[Sx, Sy] = i Sz."
assert np.allclose(commutator(Sy, Sz), 1j * Sx) and np.allclose(commutator(Sz, Sx), 1j * Sy), "And cyclically."
assert np.allclose(Sx @ Sx + Sy @ Sy + Sz @ Sz, 0.75 * np.eye(2)), "S² = s(s + 1) = 3/4 for spin ½."
```

::: right
Right. $S^2 = \frac34$ for every state: spin ½ is a fixed amount of angular momentum, never fully along any axis.
:::
:::

::: check
kind: python

## Step 2. Write `prob_up(state, n)` returning the chance that a spin in `state` (a 2-component array) is found "up" along the unit vector n, using the eigenvectors of $\mathbf n \cdot \mathbf S$. `spin_ops` is included.

```python starter
import numpy as np

def spin_ops():
    Sx = np.array([[0, 1], [1, 0]], dtype=complex) / 2
    Sy = np.array([[0, -1j], [1j, 0]], dtype=complex) / 2
    Sz = np.array([[1, 0], [0, -1]], dtype=complex) / 2
    return Sx, Sy, Sz

def prob_up(state, n):
    return abs(state[0])**2

print(prob_up(np.array([1, 0]), [np.sin(np.pi / 3), 0, np.cos(np.pi / 3)]))
```

```python solution
import numpy as np

def spin_ops():
    Sx = np.array([[0, 1], [1, 0]], dtype=complex) / 2
    Sy = np.array([[0, -1j], [1j, 0]], dtype=complex) / 2
    Sz = np.array([[1, 0], [0, -1]], dtype=complex) / 2
    return Sx, Sy, Sz

def prob_up(state, n):
    Sx, Sy, Sz = spin_ops()
    S = n[0] * Sx + n[1] * Sy + n[2] * Sz
    w, v = np.linalg.eigh(S)
    up = v[:, np.argmax(w)]
    return float(abs(np.vdot(up, state))**2)

print(prob_up(np.array([1, 0]), [np.sin(np.pi / 3), 0, np.cos(np.pi / 3)]))
```

```python tests
import numpy as np
assert abs(prob_up(np.array([1, 0]), [np.sin(np.pi / 3), 0, np.cos(np.pi / 3)]) - 0.75) < 1e-12, "Tilted 60°: 75%."
assert abs(prob_up(np.array([1, 1]) / np.sqrt(2), [0, 1, 0]) - 0.5) < 1e-12, "+x measured along y: 50%."
assert abs(prob_up(np.array([1, 1j]) / np.sqrt(2), [0, 1, 0]) - 1) < 1e-12, "The state (1, i)/√2 points along +y."
```

::: right
Right. Complex amplitudes matter: $(1, i)/\sqrt2$ points along +y, while $(1, 1)/\sqrt2$ points along +x.
:::
:::

::: check
kind: python

## Step 3. Write `evolve(H, psi, t)` returning $e^{-iHt}\psi$ through the eigendecomposition of the Hermitian matrix H, and `sx_mean(psi)` returning ⟨S_x⟩. `spin_ops` is included.

```python starter
import numpy as np

def spin_ops():
    Sx = np.array([[0, 1], [1, 0]], dtype=complex) / 2
    Sy = np.array([[0, -1j], [1j, 0]], dtype=complex) / 2
    Sz = np.array([[1, 0], [0, -1]], dtype=complex) / 2
    return Sx, Sy, Sz

def evolve(H, psi, t):
    return psi

def sx_mean(psi):
    return 0.0

Sx, Sy, Sz = spin_ops()
psi = np.array([1, 1]) / np.sqrt(2)
print([sx_mean(evolve(2 * np.pi * Sz, psi, t)) for t in (0, 0.25, 0.5)])
```

```python solution
import numpy as np

def spin_ops():
    Sx = np.array([[0, 1], [1, 0]], dtype=complex) / 2
    Sy = np.array([[0, -1j], [1j, 0]], dtype=complex) / 2
    Sz = np.array([[1, 0], [0, -1]], dtype=complex) / 2
    return Sx, Sy, Sz

def evolve(H, psi, t):
    w, v = np.linalg.eigh(H)
    return v @ np.diag(np.exp(-1j * w * t)) @ v.conj().T @ psi

def sx_mean(psi):
    Sx, _, _ = spin_ops()
    return float(np.real(np.vdot(psi, Sx @ psi)))

Sx, Sy, Sz = spin_ops()
psi = np.array([1, 1]) / np.sqrt(2)
print([sx_mean(evolve(2 * np.pi * Sz, psi, t)) for t in (0, 0.25, 0.5)])
```

```python tests
import numpy as np
Sx, Sy, Sz = spin_ops()
psi = np.array([1, 1]) / np.sqrt(2)
vals = [sx_mean(evolve(2 * np.pi * Sz, psi, t)) for t in (0, 0.25, 0.5, 1.0)]
assert np.allclose(vals, [0.5, 0, -0.5, 0.5], atol=1e-12), f"⟨Sx⟩ should precess 0.5, 0, -0.5, 0.5; got {vals}."
assert abs(np.linalg.norm(evolve(2 * np.pi * Sz, psi, 0.37)) - 1) < 1e-12, "Evolution is unitary."
```

::: right
Right. One cycle returns ⟨S_x⟩ to 0.5, while the state itself has picked up a sign: a spin-½ needs two full turns to return exactly.
:::
:::

::: check
kind: python

## Step 4. Write `rabi_numeric(W, D, t)` that exponentiates the rotating-frame Hamiltonian $\frac12\begin{pmatrix} D & W \\ W & -D \end{pmatrix}$ (W and D in rad per unit time) from the state (1, 0) and returns the upper population. `evolve` is included.

```python starter
import numpy as np

def evolve(H, psi, t):
    w, v = np.linalg.eigh(H)
    return v @ np.diag(np.exp(-1j * w * t)) @ v.conj().T @ psi

def rabi_numeric(W, D, t):
    return 0.0

print(rabi_numeric(2 * np.pi, 2 * np.pi, 0.3))
```

```python solution
import numpy as np

def evolve(H, psi, t):
    w, v = np.linalg.eigh(H)
    return v @ np.diag(np.exp(-1j * w * t)) @ v.conj().T @ psi

def rabi_numeric(W, D, t):
    H = 0.5 * np.array([[D, W], [W, -D]], dtype=complex)
    psi = evolve(H, np.array([1, 0], dtype=complex), t)
    return float(abs(psi[1])**2)

print(rabi_numeric(2 * np.pi, 2 * np.pi, 0.3))
```

```python tests
import numpy as np
for W, D, t in ((2 * np.pi, 2 * np.pi, 0.3), (2 * np.pi, 0.0, 0.5), (3.0, 1.5, 0.8)):
    G = np.sqrt(W * W + D * D)
    want = W * W / (G * G) * np.sin(G * t / 2)**2
    assert abs(rabi_numeric(W, D, t) - want) < 1e-12, f"For W = {W:.3f}, D = {D:.3f}, t = {t}: Rabi's formula gives {want:.6f}."
```

::: right
Right. The matrix exponential reproduces Rabi's formula exactly, and it keeps working for multilevel systems, pulses with changing phase, and anything else where no formula exists.
:::
:::

::: check
kind: python

## Step 5. Write `chain_levels(n, t)` returning the sorted eigenvalues of n identical wells coupled to neighbors by t, the matrix with −t beside the diagonal.

```python starter
import numpy as np

def chain_levels(n, t):
    return np.zeros(n)

print(chain_levels(8, 1.0)[:3])
```

```python solution
import numpy as np

def chain_levels(n, t):
    H = -t * (np.eye(n, k=1) + np.eye(n, k=-1))
    return np.linalg.eigvalsh(H)

print(chain_levels(8, 1.0)[:3])
```

```python tests
import numpy as np
w = chain_levels(8, 1.0)
exact = np.sort([-2 * np.cos(j * np.pi / 9) for j in range(1, 9)])
assert np.allclose(w, exact), f"Expect -2t cos(jπ/(N + 1)); got {w}."
assert np.all(np.abs(chain_levels(50, 0.5)) < 1.0), "All levels lie within the band from -2t to 2t."
```

::: right
Right. The levels fill the band from −2t to 2t, closer together near its edges, where the band is flat.
:::
:::

::: check
given: t = 30 | 60 | 100
answer: cos(t*pi/360)^2
tolerance: 0.5%

## A spin up along z is measured along an axis tilted {t}°. What is the chance of "up"?

::: right
Right. $\cos^2\frac\theta2$.
:::

::: misses
- [cos(t*pi/180)^2] Spin uses half angles.
- [any] The overlap with the tilted axis's up state.
:::
:::

::: check
given: W = 1 | 2; D = 0.5 | 3
answer: W^2/(W^2 + D^2)
tolerance: 0.5%

## A two-level system is driven with Rabi frequency {W} and detuning {D} (same units). What is the largest upper population it reaches?

::: right
Right. $\frac{\Omega^2}{\Omega^2 + \Delta^2}$.
:::

::: misses
- [W/(W + D)] Rabi's formula has squares.
- [any] The amplitude of Rabi's formula.
:::
:::

::: explain
## Why does computing $e^{-iHt}$ through the eigenvectors of H give the exact time evolution?

::: model
In the basis of H's eigenvectors, the Hamiltonian is diagonal, and each eigenvector simply picks up the phase $e^{-iE_nt}$ as time passes, without mixing with the others. So to evolve any state, you write it in that basis, multiply each component by its phase, and transform back: that's $V\,\text{diag}(e^{-iE_nt})\,V^\dagger$. Nothing is approximated, and no time steps are needed, because a time-independent Hamiltonian's evolution is completely determined by its eigenvalues and eigenvectors. The same reasoning is why stationary states are the natural building blocks of every solution.
:::
:::

::: practice

::: check
given: n = 4 | 10; j = 1 | 2
answer: -2*cos(j*pi/(n + 1))
tolerance: 0.5%

## Level j = {j} of {n} coupled wells with t = 1?

::: misses
- [any] $-2t\cos\frac{j\pi}{N + 1}$.
:::
:::

::: check
given: t = 0.1 | 0.4; w = 1 | 3
answer: 0.5*cos(w*t)
tolerance: 0.5%

## A spin starts along +x and precesses about z at {w} rad per unit time. What is ⟨S_x⟩ at t = {t}?

::: misses
- [any] $\frac12\cos\omega t$.
:::
:::
:::
