# Transient Dispersive Readout with Dynamiqs

A dispersive readout pulse builds up a different cavity field for each qubit
state. We use a QPDK quarter-wave coplanar waveguide (CPW) resonator and a
transmon model to estimate the two cavity frequencies. We then use the
[Dynamiqs](https://www.dynamiqs.org/) Lindblad solver to compare field
separation and residual photons at two loaded quality factors. The solver
batches the fixed qubit states $|g\rangle$ and $|e\rangle$. The cavity amplitudes follow
[[GBS+06](#id35)] (Eqs. 5.17 and 5.18).
We use the transmon conventions of [[KYG+07](#id59)].

#### NOTE
The Josephson energy, charging energy, coupling, and loaded quality factors
are illustrative inputs. The model assumes vacuum loss and a fixed qubit state.
The plotted field is the intracavity amplitude in the drive frame. A detector
signal would also depend on the output coupling and the receiver.

```ipython3
import sys

if "google.colab" in sys.modules:
    import subprocess

    print("Running in Google Colab. Installing QPDK and Dynamiqs...")
    subprocess.check_call([
        sys.executable,
        "-m",
        "pip",
        "install",
        "-q",
        "qpdk[models] @ git+https://github.com/gdsfactory/quantum-rf-pdk.git",
        "dynamiqs>=0.3.7,<0.4",
    ])
```

```ipython3
import dynamiqs as dq
import jax
import jax.numpy as jnp
import matplotlib.pyplot as plt
from dynamiqs.method import Tsit5

from qpdk import PDK, logger

dq.set_precision("double")
PDK.activate()

from qpdk.cells.resonator import resonator_quarter_wave
from qpdk.models.perturbation import (
    dispersive_shift,
    ej_ec_to_frequency_and_anharmonicity,
)
from qpdk.models.resonator import resonator_frequency
```

## Bare CPW design

We estimate the bare resonance frequency from the path length and cross section
of the QPDK resonator. The cell stores the path length in `info["length"]`.

```ipython3
resonator = resonator_quarter_wave(length=4300.0)
length_um = float(resonator.info["length"])
f_bare_ghz = float(
    resonator_frequency(
        length=length_um,
        cross_section=resonator.info["cross_section_name"],
        is_quarter_wave=True,
    )
    / 1e9
)
logger.info("Bare CPW: f_r = {:.6f} GHz", f_bare_ghz)
```

```myst-ansi
[32m2026-12-05 02:35:31.396[0m | [1mINFO    [0m | [36m__main__[0m:[36m<module>[0m:[36m11[0m - [1mBare CPW: f_r = 7.077339 GHz[0m
```

## Dressed midpoint from second order

Define $e_\text{J} = E_\text{J}/h = 18\,\text{GHz}$,
$e_\text{C} = E_\text{C}/h = 0.24\,\text{GHz}$, and
$g_f = g/(2\pi) = 0.12\,\text{GHz}$. The QPDK helper returns
$f_\text{q} \approx \sqrt{8 e_\text{J} e_\text{C}} - e_\text{C}$ and
the qubit anharmonicity $\alpha_\text{q} \approx -e_\text{C}$.

The transmon and cavity annihilation operators are $b$ and $a$. For
$H_\text{int}/h = g_f\,(b+b^\dagger)(a+a^\dagger)$, virtual transitions
through $|e,n-1\rangle$ and $|e,n+1\rangle$ shift the ground-conditioned
cavity frequency by

<a id="equation-eq-ground-shift"></a>
$$
\delta_\text{ground} = -g_f^2\left(\frac{1}{f_\text{q}-f_\text{r}}
+ \frac{1}{f_\text{q}+f_\text{r}}\right).
$$

QPDK returns the full signed cavity splitting, $(E_{11}-E_{10}-E_{01}+E_{00})/h$,
where $E_{ij}$ is the dressed energy associated with transmon level $i$ and
cavity occupation $j$. At second order,

$$
F(f) = \frac{1}{f-f_\text{r}} + \frac{1}{f+f_\text{r}}, \qquad
\chi_f = 2g_f^2\left[F(f_\text{q})-F(f_\text{q}+\alpha_\text{q})\right].
$$

The sum-frequency denominators retain the counter-rotating terms that
Koch *et al.* [[KYG+07](#id59)] omit in their rotating-wave
derivation. Koch et al. write the splitting as $2\chi$ in angular-frequency
units. We place the drive at the midpoint.

<a id="equation-eq-midpoint"></a>
$$
f_\text{mid} = f_\text{r} + \delta_\text{ground} + \chi_f/2.
$$

The midpoint correction can exceed the linewidth. For the dispersive
approximation, the magnitudes of $\Delta_{01} = f_\text{q}-f_\text{r}$ and
$\Delta_{12} = f_\text{q}+\alpha_\text{q}-f_\text{r}$ must be much larger than the
photon-enhanced couplings $g_f\sqrt{n+1}$ and $g_f\sqrt{2(n+1)}$ over the
occupied photon levels.

```ipython3
# e_J = E_J/h, e_C = E_C/h, g_f = g/(2pi), all in GHz.
e_J_ghz, e_C_ghz, g_f_ghz = 18.0, 0.24, 0.12

f_q_ghz, alpha_ghz = ej_ec_to_frequency_and_anharmonicity(e_J_ghz, e_C_ghz)
chi_f_ghz = dispersive_shift(f_q_ghz, f_bare_ghz, alpha_ghz, g_f_ghz)
ground_shift_ghz = -(g_f_ghz**2) * (
    1 / (f_q_ghz - f_bare_ghz) + 1 / (f_q_ghz + f_bare_ghz)
)
f_mid_ghz = f_bare_ghz + ground_shift_ghz + chi_f_ghz / 2

logger.info(
    "QPDK second order: ground shift = {:+.3f} MHz, chi_f = {:.4f} MHz, "
    "f_mid = {:.6f} GHz ({:+.3f} MHz vs bare)",
    float(ground_shift_ghz * 1e3),
    float(chi_f_ghz * 1e3),
    float(f_mid_ghz),
    float((f_mid_ghz - f_bare_ghz) * 1e3),
)
logger.info(
    "|Delta_01|/g_f = {:.1f}; |Delta_12|/(sqrt(2) g_f) = {:.1f}",
    float(jnp.abs(f_q_ghz - f_bare_ghz) / g_f_ghz),
    float(jnp.abs(f_q_ghz + alpha_ghz - f_bare_ghz) / (jnp.sqrt(2.0) * g_f_ghz)),
)
```

```myst-ansi
[32m2026-12-05 02:35:31.515[0m | [1mINFO    [0m | [36m__main__[0m:[36m<module>[0m:[36m11[0m - [1mQPDK second order: ground shift = +8.878 MHz, chi_f = -2.9060 MHz, f_mid = 7.084764 GHz (+7.425 MHz vs bare)[0m
```

```myst-ansi
[32m2026-12-05 02:35:31.532[0m | [1mINFO    [0m | [36m__main__[0m:[36m<module>[0m:[36m19[0m - [1m|Delta_01|/g_f = 12.0; |Delta_12|/(sqrt(2) g_f) = 9.9[0m
```

## Readout drive and conditional detunings

We drive at $f_\text{mid}$. The solver uses angular detunings
$\delta_g = -\pi\chi_f$ and $\delta_e = +\pi\chi_f$ in rad/ns.

<a id="equation-eq-conditional-hamiltonian"></a>
$$
H_s/\hbar = \delta_s\, a^\dagger a + \epsilon(t)\,(a+a^\dagger).
$$

With $f_\text{mid}$ in GHz, the energy decay rate
$\kappa = 2\pi f_\text{mid}/Q_\text{L}$ is in ns$^{-1}$.
The linewidth is $\kappa/(2\pi)$ in GHz. The collapse operator is
$\sqrt{\kappa}\,a$. After switch-off, the energy decays as $e^{-\kappa t}$
and the field magnitude as $e^{-\kappa t/2}$.

We drive the cavity for 225 ns, then let it decay for 275 ns. For each
loaded quality factor we set the drive amplitude to reach the same photon
population at switch-off, $n(T_\text{on}) = 0.8$. The analytic solution gives
$\epsilon = \sqrt{n(T_\text{on})}\,|\lambda_s|/|1-e^{-\lambda_s T_\text{on}}|$
with $\lambda_s = \kappa/2 + i\delta_s$.

```ipython3
Q_LOADED = jnp.array([2000.0, 4000.0])
KAPPA_INV_NS = 2 * jnp.pi * f_mid_ghz / Q_LOADED

DELTA_G = -jnp.pi * chi_f_ghz
DELTA_E = +jnp.pi * chi_f_ghz
DELTA_TABLE = jnp.broadcast_to(jnp.stack([DELTA_G, DELTA_E]), (Q_LOADED.size, 2))

N_MATCHED, T_ON, T_STOP, N_FOCK = 0.8, 225.0, 500.0, 16


def matched_epsilon(kappa: jax.Array, delta: jax.Array) -> jax.Array:
    """Return the drive amplitude for matched pulse-end population."""
    lambda_s = kappa / 2 + 1j * delta
    return (
        jnp.sqrt(N_MATCHED) * jnp.abs(lambda_s) / jnp.abs(1 - jnp.exp(-lambda_s * T_ON))
    )


EPSILON = matched_epsilon(KAPPA_INV_NS, DELTA_G)

for q_loaded, kappa, epsilon in zip(Q_LOADED, KAPPA_INV_NS, EPSILON, strict=True):
    logger.info(
        "Q_L = {:.0f}: kappa = {:.4f} ns^-1, linewidth = {:.2f} MHz, "
        "matched epsilon = {:.4f} rad/ns",
        float(q_loaded),
        float(kappa),
        float(f_mid_ghz * 1e3 / q_loaded),
        float(epsilon),
    )
```

```myst-ansi
[32m2026-12-05 02:35:31.782[0m | [1mINFO    [0m | [36m__main__[0m:[36m<module>[0m:[36m22[0m - [1mQ_L = 2000: kappa = 0.0223 ns^-1, linewidth = 3.54 MHz, matched epsilon = 0.0124 rad/ns[0m
```

```myst-ansi
[32m2026-12-05 02:35:31.783[0m | [1mINFO    [0m | [36m__main__[0m:[36m<module>[0m:[36m22[0m - [1mQ_L = 4000: kappa = 0.0111 ns^-1, linewidth = 1.77 MHz, matched epsilon = 0.0082 rad/ns[0m
```

## Batch the cavity simulations

For each loaded quality factor, both qubit states share the drive and loss.
Only the detuning $\delta_s$ depends on the qubit state. With
`cartesian_batching=False`, Dynamiqs broadcasts the operators over the
quality-factor and qubit-state axes. The expectation values have axes
`(Q, qubit state, operator, time)`.

```ipython3
a = dq.destroy(N_FOCK)
n_op = a.dag() @ a
TIMES = jnp.array([0.0, T_ON, T_STOP + 1.0])

detuning_values = jnp.stack([DELTA_TABLE, DELTA_TABLE], axis=-1)
drive_values = jnp.stack(
    [
        jnp.broadcast_to(EPSILON[:, None], DELTA_TABLE.shape),
        jnp.zeros_like(DELTA_TABLE),
    ],
    axis=-1,
)
H = dq.pwc(TIMES, detuning_values, n_op) + dq.pwc(TIMES, drive_values, a + a.dag())

tsave = jnp.linspace(0.0, T_STOP, 501)
result = dq.mesolve(
    H,
    [jnp.sqrt(KAPPA_INV_NS)[:, None, None, None] * a],
    dq.fock(N_FOCK, 0),
    tsave,
    exp_ops=[a, n_op],
    method=Tsit5(rtol=1e-8, atol=1e-10),
    save_states=False,
    cartesian_batching=False,
    progress_meter=False,
)
expects = result.expects
assert expects is not None
alpha = expects[..., 0, :]
photons = jnp.real(expects[..., 1, :])
assert alpha.shape == (Q_LOADED.size, 2, tsave.size)
assert photons.shape == alpha.shape
```

## Analytic benchmark

Starting from vacuum, the cavity stays in a coherent state under linear drive
and loss. The master equation gives the exact single-mode solution.

<a id="equation-eq-coherent-solution"></a>
$$
\alpha_\text{on}(t) = -\frac{i\epsilon}{\lambda_s}(1-e^{-\lambda_s t}),
\qquad
\alpha(t>T_\text{on}) =
\alpha(T_\text{on})\,e^{-\lambda_s(t-T_\text{on})}.
$$

We check the field and photon number in double precision with 16 Fock levels.

```ipython3
def coherent_alpha(
    t: jax.Array,
    delta: jax.Array,
    kappa: jax.Array,
    epsilon: jax.Array,
    t_on: float,
) -> jax.Array:
    """Return the exact rotating-frame cavity amplitude for a square drive."""
    lambda_s = kappa / 2 + 1j * delta
    alpha_drive = -1j * epsilon * (1 - jnp.exp(-lambda_s * t)) / lambda_s
    alpha_switch = -1j * epsilon * (1 - jnp.exp(-lambda_s * t_on)) / lambda_s
    return jnp.where(
        t <= t_on, alpha_drive, alpha_switch * jnp.exp(-lambda_s * (t - t_on))
    )


alpha_analytic = coherent_alpha(
    tsave,
    DELTA_TABLE[..., None],
    KAPPA_INV_NS[:, None, None],
    EPSILON[:, None, None],
    T_ON,
)
photons_analytic = jnp.abs(alpha_analytic) ** 2
err_alpha = float(jnp.max(jnp.abs(alpha - alpha_analytic)))
err_photons = float(jnp.max(jnp.abs(photons - photons_analytic)))
reverse_photons = float(jnp.max(jnp.abs(photons[:, 0, :] - photons[:, 1, :])))

assert err_alpha < 3e-4
assert err_photons < 3e-4
assert reverse_photons < 3e-4
logger.info("max |<a> - alpha| = {:.2e}", err_alpha)
logger.info("max |n - |alpha|^2| = {:.2e}", err_photons)
logger.info("max n(g) - n(e) = {:.2e}", reverse_photons)
```

```myst-ansi
[32m2026-12-05 02:35:36.437[0m | [1mINFO    [0m | [36m__main__[0m:[36m<module>[0m:[36m32[0m - [1mmax |<a> - alpha| = 2.91e-10[0m
```

```myst-ansi
[32m2026-12-05 02:35:36.438[0m | [1mINFO    [0m | [36m__main__[0m:[36m<module>[0m:[36m33[0m - [1mmax |n - |alpha|^2| = 3.24e-10[0m
```

```myst-ansi
[32m2026-12-05 02:35:36.439[0m | [1mINFO    [0m | [36m__main__[0m:[36m<module>[0m:[36m34[0m - [1mmax n(g) - n(e) = 0.00e+00[0m
```

## Conditional trajectories and ringdown

```ipython3
fig, axes = plt.subplots(1, 3, figsize=(13, 3.8), constrained_layout=True)
colors = ("C0", "C1")
i_on = int(jnp.argmin(jnp.abs(tsave - T_ON)))
for iq, q_loaded in enumerate(Q_LOADED):
    for isec, (name, linestyle) in enumerate((("g", "-"), ("e", "--"))):
        amplitude = alpha[iq, isec]
        axes[0].plot(
            jnp.real(amplitude),
            jnp.imag(amplitude),
            linestyle,
            color=colors[iq],
            label=rf"$Q_\text{{L}}={q_loaded:.0f}$, $|{name}\rangle$",
        )
        axes[0].plot(
            jnp.real(amplitude[i_on]),
            jnp.imag(amplitude[i_on]),
            "o",
            color=colors[iq],
            ms=4,
        )
    separation = jnp.abs(alpha[iq, 1, :] - alpha[iq, 0, :])
    axes[1].plot(
        tsave, separation, color=colors[iq], label=rf"$Q_\text{{L}}={q_loaded:.0f}$"
    )
    axes[2].semilogy(
        tsave,
        photons[iq, 0, :],
        color=colors[iq],
        label=rf"$Q_\text{{L}}={q_loaded:.0f}$",
    )
    axes[2].plot(T_STOP, float(photons[iq, 0, -1]), "o", color=colors[iq])
    axes[2].annotate(
        f"{photons[iq, 0, -1]:.1e}",
        (T_STOP, float(photons[iq, 0, -1])),
        textcoords="offset points",
        xytext=(4, 4),
        fontsize=7,
        color=colors[iq],
    )

for ax in axes[1:]:
    ax.axvspan(0, T_ON, color="0.92", zorder=0)
    ax.axvline(T_ON, color="0.4", linestyle=":", lw=1)

axes[0].annotate(
    "switch-off",
    (float(jnp.real(alpha[0, 0, i_on])), float(jnp.imag(alpha[0, 0, i_on]))),
    textcoords="offset points",
    xytext=(6, -10),
    fontsize=7,
)
axes[0].set_xlabel(r"$\text{Re}\,\alpha$")
axes[0].set_ylabel(r"$\text{Im}\,\alpha$")
axes[0].set_aspect("equal")
axes[0].legend(fontsize=7)
axes[1].set_xlabel("Time (ns)")
axes[1].set_ylabel(r"$|\alpha_e-\alpha_g|$")
axes[1].legend(fontsize=8)
axes[2].set_xlabel("Time (ns)")
axes[2].set_ylabel(r"$\langle n\rangle$")
axes[2].axhline(N_MATCHED, color="0.5", linestyle=":", lw=1)
axes[2].legend(fontsize=8)
fig.suptitle("Conditional response at matched pulse-end population")
plt.show()
```

```myst-ansi
<Figure size 3900x1140 with 3 Axes>
```

At switch-off, the higher-$Q$ cavity has greater field separation at the same
photon population. It also takes longer to reach the same residual population. The midpoint
drive gives both qubit states the same photon population at each time. After
switch-off, the fields keep rotating in opposite directions, so their
separation can grow briefly while the photon population falls.

## Gradient at matched pulse-end population

We differentiate the squared field separation $|\alpha_e-\alpha_g|^2$ at
switch-off with respect to $Q_\text{L}$. We adjust $\epsilon$ as $Q_\text{L}$
varies to hold the switch-off population at $n(T_\text{on})=0.8$.
A centered finite difference checks the derivative through `mesolve`.

```ipython3
def separation_sq(q_loaded: jax.Array | float) -> jax.Array:
    """Return |alpha_e - alpha_g|^2 at the matched pulse end."""
    kappa = 2 * jnp.pi * f_mid_ghz / q_loaded
    epsilon = matched_epsilon(kappa, DELTA_G)
    detuning_values = jnp.stack([DELTA_G, DELTA_E])[:, None]
    drive_values = jnp.full((2, 1), epsilon)
    hamiltonian = dq.pwc(jnp.array([0.0, T_ON + 1.0]), detuning_values, n_op) + dq.pwc(
        jnp.array([0.0, T_ON + 1.0]), drive_values, a + a.dag()
    )
    result = dq.mesolve(
        hamiltonian,
        [jnp.sqrt(kappa) * a],
        dq.fock(N_FOCK, 0),
        jnp.array([0.0, T_ON]),
        exp_ops=[a],
        method=Tsit5(rtol=1e-8, atol=1e-10),
        save_states=False,
        cartesian_batching=False,
        progress_meter=False,
    )
    expects = result.expects
    assert expects is not None
    final_alpha = expects[:, 0, -1]
    return jnp.abs(final_alpha[1] - final_alpha[0]) ** 2


Q_GRAD = 4000.0
grad_q = jax.grad(separation_sq)(Q_GRAD)
step = 10.0
finite_difference = (separation_sq(Q_GRAD + step) - separation_sq(Q_GRAD - step)) / (
    2 * step
)
relative_difference = float(jnp.abs(grad_q - finite_difference) / jnp.abs(grad_q))
assert relative_difference < 1e-2
logger.info(
    "At Q = {:.0f}, matched epsilon = {:.4f} rad/ns; d|alpha_e-alpha_g|^2/dQ "
    "= {:.3e} per unit Q; centered FD = {:.3e}; relative difference = {:.1e}",
    Q_GRAD,
    float(matched_epsilon(2 * jnp.pi * f_mid_ghz / Q_GRAD, DELTA_G)),
    float(grad_q),
    float(finite_difference),
    relative_difference,
)
```

```myst-ansi
[32m2026-12-05 02:35:47.463[0m | [1mINFO    [0m | [36m__main__[0m:[36m<module>[0m:[36m35[0m - [1mAt Q = 4000, matched epsilon = 0.0082 rad/ns; d|alpha_e-alpha_g|^2/dQ = 1.672e-04 per unit Q; centered FD = 1.672e-04; relative difference = 4.8e-06[0m
```

## References
