# Graphene JoFET compact model in JAX and VACASK

A Josephson field-effect transistor (JoFET) is a superconductor-graphene-
superconductor junction with a gate. The gate sets the carrier density of the
graphene, which tunes the normal-state resistance $R_\text{n}$ and the
critical current $I_\text{c}$. This notebook uses the compact model of
Gamaethige *et al.* [[GLB+26](#id34)] in two forms:

- `qpdk.models.jofet` gives $R_\text{n}(V_\text{g})$ and
  $I_\text{c}(V_\text{g})$ as differentiable JAX functions.
- `jofet.va` puts the same equations into a resistively and capacitively
  shunted junction (RCSJ) for VACASK.

The notebook compares the static curves with device data, then checks the
VACASK transient against an independent Runge-Kutta integration in JAX.

```ipython3
import sys

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

    print("Running in Google Colab. Installing dependencies...")
    subprocess.check_call([
        sys.executable,
        "-m",
        "pip",
        "install",
        "-q",
        "qpdk[models] @ git+https://github.com/gdsfactory/quantum-rf-pdk.git",
    ])
```

```ipython3
import csv
import os
from pathlib import Path

import jax
import jax.numpy as jnp
import numpy as np
from matplotlib import font_manager, pyplot as plt

import qpdk.colormaps  # ruff: ignore[unused-import] - registers the style colormap
from qpdk.config import PATH
from qpdk.models.constants import e, ħ
from qpdk.models.jofet import (
    JofetParameters,
    jofet_critical_current,
    jofet_normal_resistance,
    jofet_stewart_mccumber,
    rsj_mean_voltage,
)
from qpdk.simulation.vacask import Netlist, Vacask, VacaskError

# Agg suppresses notebook figure outputs in headless CI.
if "ipykernel" in sys.modules:
    from IPython import get_ipython
    from matplotlib_inline.backend_inline import set_matplotlib_formats

    if (ipython := get_ipython()) is not None:
        ipython.run_line_magic("matplotlib", "inline")
        set_matplotlib_formats("png", "svg")

jax.config.update("jax_enable_x64", True)

# The checkout stylesheet is absent from installed wheels.
for _style in (PATH.docs / "qpdk.mplstyle", "qpdk"):
    try:
        plt.style.use(_style)
    except OSError:
        continue
    break

# The stylesheet names fonts that only the docs build ships; register them so
# they resolve without docs/ipython_config.py.
_font_dir = os.environ.get("QPDK_DOCS_FONTS_DIR")
for _fonts in (Path(_font_dir) if _font_dir else None, PATH.repo / "build/docs-fonts"):
    if _fonts is not None and _fonts.is_dir():
        for _font in sorted(_fonts.iterdir()):
            if _font.suffix in {".otf", ".ttf"}:
                font_manager.fontManager.addfont(str(_font))
        break


def show_plot() -> None:
    """Show the current figure with Outfit titles, as the docs config does."""
    fig = plt.gcf()
    for text in [ax.title for ax in fig.axes] + list(fig.texts):
        if text.get_text():
            text.set_fontfamily("Outfit")
            text.set_fontweight("bold")
    plt.show()
```

## Gate dependence

The gate induces the sheet density
$n = \varepsilon_\text{r}\varepsilon_0 (V_\text{g} - V_\text{Dir}) / (t e)$
on top of a residual density $n_\text{r}$. The channel is a Drude resistor in
series with the contacts, and the $I_\text{c} R_\text{n}$ product is fixed by
the induced gap:

$$
R_\text{n} = R_\text{c} + \frac{L_\text{g}}{W e \mu \sqrt{n_\text{r}^2 + n^2}},
\qquad
I_\text{c} = \frac{\alpha \Delta_\text{ind}}{e R_\text{n}}.
$$

The geometry, gate stack and induced gap are the 350 nm device of
Gamaethige *et al.* [[GLB+26](#id34)]. Its width and length match
device TG#2 of Generalov *et al.* [[GVS+24](#id38)]. The plot
overlays the finite-bias resistance digitized from Fig. 2(b) and the critical
current digitized from Fig. 3(c), which the authors extracted from the
differential-resistance map in Fig. 3(b).
The defaults of $\mu$, $R_\text{c}$, $n_\text{r}$, $V_\text{Dir}$ and $\alpha$
jointly fit these same points, using the model’s intrinsic $I_\text{c}$ for
the extracted critical current. The CSV ships with the repository tests.

```ipython3
P = JofetParameters()
vg = jnp.linspace(-16.0, 12.0, 561)
data_file = PATH.repo / "tests/models/data/jofet_arxiv2401_05089_tg2_digitized.csv"
data: dict[str, tuple[np.ndarray, np.ndarray]] = {}
# A checkout without Git LFS holds a pointer file instead of the CSV.
if data_file.is_file() and not data_file.read_text().startswith("version https"):
    with data_file.open(newline="") as handle:
        rows = list(csv.DictReader(handle))
    for quantity in ("Rn_ohm", "Ic_A"):
        selected = [row for row in rows if row["quantity"] == quantity]
        data[quantity] = (
            np.array([float(row["vg_V"]) for row in selected]),
            np.array([float(row["value"]) for row in selected]),
        )

fig, (ax_rn, ax_ic) = plt.subplots(1, 2, figsize=(10, 3.8), layout="constrained")
ax_rn.plot(vg, jofet_normal_resistance(vg), label="model")
ax_ic.plot(vg, 1e9 * jofet_critical_current(vg), label="model")
if data:
    ax_rn.plot(*data["Rn_ohm"], ".", ms=4, label="TG#2, digitized")
    ax_ic.plot(
        data["Ic_A"][0], 1e9 * data["Ic_A"][1], ".", ms=4, label="TG#2, digitized"
    )
for ax in (ax_rn, ax_ic):
    ax.axvline(P.dirac_voltage, color="0.6", lw=0.8, ls="--")
    ax.set_xlabel(r"Gate voltage $V_\text{g}$ (V)")
    ax.legend()
ax_rn.set_ylabel(r"$R_\text{n}$ (Ω)")
ax_ic.set_ylabel(r"$I_\text{c}$ (nA)")
fig.suptitle("JoFET normal resistance and critical current")
show_plot()

beta = jofet_stewart_mccumber(vg)
print(
    f"Ic Rn = {1e6 * P.alpha * P.induced_gap / e:.1f} µV at every gate voltage; "
    f"β_c = {float(beta.min()):.2f} to {float(beta.max()):.2f}"
)
```

```myst-ansi
findfont: Failed to find font weight bold, now using 400.
```

```myst-ansi
<Figure size 1000x380 with 2 Axes>
```

```myst-ansi
Ic Rn = 21.7 µV at every gate voltage; β_c = 0.14 to 0.89
```

The model is symmetric about the Dirac point $V_\text{Dir}$ (dashed). The
device is not: the fit puts $V_\text{Dir}$ at the resistance peak, but the
critical-current minimum sits 0.5 V lower. The in-sample RMS relative error
is 5.4 % for the resistance and 7.0 % for the critical current; the largest
errors, 14 % and 24 %, are near the Dirac point. With the default $C_\text{j} = 100\,\text{fF}$,
the Stewart-McCumber parameter
$\beta_\text{c} = 2 e I_\text{c} R_\text{n}^2 C_\text{j} / \hbar$ peaks near
the Dirac point and stays below 0.9 over the plotted gate range
[[McC68](#id82), [Ste68](#id114)].

## Transient current-voltage curve

A current source ramps the bias to $I$ over 2 ns and holds it. The phase
obeys the RCSJ equations

$$
\dot\varphi = \frac{2e}{\hbar} V, \qquad
C_\text{j} \dot V = I(t) - I_\text{c} \sin\varphi
    - \left(\frac{1}{R_\text{n}} + g_\text{min}\right) V,
$$

starting from $\varphi = V = 0$. A DC voltmeter sees the mean voltage
$\bar V = \hbar \Delta\varphi / (2 e T_\text{w})$ over the last
$T_\text{w} = 10\,\text{ns}$. Two gate voltages give two values of
$\beta_\text{c}$: $0.16$ at 0 V and $0.89$ at the Dirac point.

The reference is a fixed-step fourth-order Runge-Kutta integration written
here in JAX. It shares no code with VACASK, and `vmap` runs every bias at
once.

```ipython3
G_MIN = 1e-15  # convergence conductance of jofet.va, S
T_RISE, T_STOP, WINDOW = 2e-9, 14e-9, 10e-9
DT, SAVE_EVERY = 0.25e-12, 20

GATES = [0.0, P.dirac_voltage]
RATIOS = np.round(np.linspace(0.0, 3.0, 31), 2)
gate = np.repeat(GATES, RATIOS.size)
ic = np.asarray(jofet_critical_current(gate))
rn = np.asarray(jofet_normal_resistance(gate))
bias = np.tile(RATIOS, len(GATES)) * ic


def rcsj_rk4(bias: float, ic: float, rn: float) -> jax.Array:
    """Phase and voltage of a current-ramped RCSJ, RK4 with a fixed step.

    Returns:
        Array of shape ``(2, n)``: phase in rad and voltage in V, every
        ``SAVE_EVERY`` steps from t = 0.
    """

    def rhs(t: jax.Array, y: jax.Array) -> jax.Array:
        phi, v = y
        current = bias * jnp.minimum(t / T_RISE, 1.0)
        dv = (current - ic * jnp.sin(phi) - (1 / rn + G_MIN) * v) / P.capacitance
        return jnp.stack([2 * e / ħ * v, dv])

    def step(y: jax.Array, n: jax.Array) -> tuple[jax.Array, None]:
        t = n * DT
        k1 = rhs(t, y)
        k2 = rhs(t + DT / 2, y + DT / 2 * k1)
        k3 = rhs(t + DT / 2, y + DT / 2 * k2)
        k4 = rhs(t + DT, y + DT * k3)
        return y + DT / 6 * (k1 + 2 * k2 + 2 * k3 + k4), None

    def block(y: jax.Array, j: jax.Array) -> tuple[jax.Array, jax.Array]:
        y, _ = jax.lax.scan(step, y, j * SAVE_EVERY + jnp.arange(SAVE_EVERY))
        return y, y

    n_saved = round(T_STOP / (DT * SAVE_EVERY))
    _, saved = jax.lax.scan(block, jnp.zeros(2), jnp.arange(n_saved))
    return jnp.concatenate([jnp.zeros((1, 2)), saved]).T


phi_rk4, v_rk4 = np.moveaxis(
    np.asarray(jax.jit(jax.vmap(rcsj_rk4))(bias, ic, rn)), 1, 0
)
t = np.arange(phi_rk4.shape[1]) * DT * SAVE_EVERY
n_window = round(WINDOW / (DT * SAVE_EVERY))


def mean_voltage(phi: np.ndarray) -> np.ndarray:
    """Mean voltage over the last ``WINDOW`` from the phase, in V."""
    return ħ / (2 * e) * (phi[:, -1] - phi[:, -1 - n_window]) / WINDOW


vbar_rk4 = mean_voltage(phi_rk4)
```

## The same circuit in VACASK

The netlist holds one current source and one `jofet` instance per bias, with
a voltage source on each gate. `jofet.va` keeps the phase as the voltage of
its internal node `ph` (1 V = 1 rad), so VACASK reports it as `x<k>:ph`. The
transient starts from the DC operating point at zero bias.

```ipython3
try:
    vacask = Vacask.find()
except VacaskError as error:
    print(error)
    raise SystemExit(
        "VACASK is not installed; skipping the rest of this notebook."
    ) from None
print(f"Using VACASK at {vacask.binary.name}")
```

```myst-ansi
Using VACASK at vacask
```

```ipython3
lines = ["model isource isource", "model vsource vsource", "model jofet jofet"]
lines += [f"vg{k} (g{k} 0) vsource dc={vg_k!r}" for k, vg_k in enumerate(GATES)]
for k, (i_k, vg_k) in enumerate(zip(bias.tolist(), gate.tolist(), strict=True)):
    wave = f"[0, 0, {T_RISE!r}, {i_k!r}, {T_STOP!r}, {i_k!r}]"
    lines.append(f'ib{k} (0 d{k}) isource type="pwl" wave={wave}')
    lines.append(f"x{k} (d{k} 0 g{GATES.index(vg_k)}) jofet")
netlist = Netlist(
    "JoFET current ramps",
    loads=["jofet.va"],
    circuit="\n".join(lines),
    control=f"""
        options tolscale=1e-6 reltol=1e-6
        analysis tran1 tran stop={T_STOP!r} step={DT!r} maxstep={DT!r} icmode="op"
    """,
)
tran = vacask.run(netlist)["tran1"]
t_va = tran["time"].real
phi_va = np.array([np.interp(t, t_va, tran[f"x{k}:ph"].real) for k in range(bias.size)])
vbar_va = mean_voltage(phi_va)
```

## Agreement

The left panel shows the mean voltage in units of $I_\text{c} R_\text{n}$.
The overdamped RSJ result
$\bar V = R_\text{n}\sqrt{I^2 - I_\text{c}^2}$ (`rsj_mean_voltage()`)
is the $\beta_\text{c} \to 0$ limit; the capacitance lifts both curves
towards $I R_\text{n}$, more so at the Dirac point. The right panel overlays
the voltage just above $I_\text{c}$ at the Dirac point, where each $2\pi$
phase slip is a voltage pulse.

```ipython3
icrn = ic * rn
fig, (ax_iv, ax_t) = plt.subplots(1, 2, figsize=(10, 3.8), layout="constrained")
ratio = np.linspace(0, 3, 301)
ax_iv.plot(
    ratio,
    rsj_mean_voltage(ratio, 1.0, 1.0),
    "k:",
    zorder=3,
    label=r"RSJ, $\beta_\text{c} \to 0$",
)
ax_iv.plot(ratio, ratio, color="0.8", ls="--", label=r"$I R_\text{n}$")
for vg_k in GATES:
    sel = gate == vg_k
    beta_k = float(jofet_stewart_mccumber(vg_k))
    label = rf"$V_\text{{g}}$ = {vg_k:g} V, $\beta_\text{{c}} = {beta_k:.2f}$"
    (line,) = ax_iv.plot(RATIOS, vbar_rk4[sel] / icrn[sel], label=f"RK4, {label}")
    ax_iv.plot(
        RATIOS,
        vbar_va[sel] / icrn[sel],
        "o",
        mfc="none",
        color=line.get_color(),
        label=f"VACASK, {label}",
    )
ax_iv.set_xlabel(r"Bias $I / I_\text{c}$")
ax_iv.set_ylabel(r"Mean voltage $\bar V / I_\text{c} R_\text{n}$")
ax_iv.legend(fontsize="small")

k = int(np.flatnonzero((gate == P.dirac_voltage) & np.isclose(bias / ic, 1.1))[0])
shown = (t > 12.6e-9) & (t < 13e-9)
ax_t.plot(1e9 * t[shown], 1e6 * v_rk4[k, shown], lw=2.5, label="RK4")
shown_va = np.flatnonzero((t_va > 12.6e-9) & (t_va < 13e-9))[::25]
ax_t.plot(
    1e9 * t_va[shown_va], 1e6 * tran[f"d{k}"].real[shown_va], "o", ms=3, label="VACASK"
)
ax_t.set_xlabel("Time (ns)")
ax_t.set_ylabel(r"$V(\text{d}, \text{s})$ (µV)")
ax_t.set_title(r"$I = 1.1\,I_\text{c}$ at $V_\text{g} = V_\text{Dir}$")
ax_t.legend(loc="upper right", framealpha=0.9)
ax_t.set_ylim(top=1.3 * ax_t.get_ylim()[1])
fig.suptitle("JoFET transient: JAX RK4 against VACASK")
show_plot()

running = bias > 1.01 * ic
print(
    f"max |mean-voltage difference| = {np.max(np.abs(vbar_va - vbar_rk4) / icrn):.1e} Ic Rn\n"
    f"max |phase difference| over {1e9 * T_STOP:g} ns = "
    f"{np.max(np.abs(phi_va - phi_rk4)):.3f} rad, after up to "
    f"{np.max(phi_rk4[running, -1]) / (2 * np.pi):.0f} phase slips"
)
```

```myst-ansi
<Figure size 1000x380 with 2 Axes>
```

```myst-ansi
max |mean-voltage difference| = 5.3e-05 Ic Rn
max |phase difference| over 14 ns = 0.042 rad, after up to 400 phase slips
```

At the two fixed gate biases, the VACASK transient and the notebook’s RK4
integration differed by at most $5.3 \times 10^{-5}\,I_\text{c} R_\text{n}$
in mean voltage and 0.042 rad in phase over 14 ns. The comparison covers
current ramps at fixed gate bias. Slow-ramp switching and retrapping,
temperature and noise remain outside its scope.

## References
