r"""
Shapiro steps: the ac Josephson effect under microwaves
=======================================================

A junction at voltage :math:`V` oscillates at the Josephson frequency
:math:`f_J = 2eV/h`, 483.6 MHz per microvolt
(:func:`~physicskit.condensed.josephson.josephson_frequency`). Shapiro
(1963) irradiated junctions with microwaves of frequency :math:`f` and saw
the oscillation lock onto the drive: the current-voltage curve breaks into
flat steps at exactly :math:`V_n = nhf/2e`. In the RCSJ model
:math:`\dot\varphi + \sin\varphi = i_{dc} + i_{ac}\cos\Omega\tau`
(:func:`~physicskit.condensed.josephson.rcsj_iv_curve`) the steps sit at
:math:`\langle\dot\varphi\rangle = n\Omega`. Since the step voltage depends
on nothing but :math:`f` and fundamental constants, arrays of such
junctions now define the volt.
"""

import matplotlib.pyplot as plt
import numpy as np
from scipy.constants import e, h

from physicskit.condensed.josephson import josephson_frequency, rcsj_iv_curve

# %%
# Steps in the overdamped junction
# --------------------------------

omega = 1.0
i_dc = np.linspace(0.0, 3.0, 151)
fig, axes = plt.subplots(1, 2, figsize=(12, 4.5))
curves = {}
for i_ac in [0.0, 1.0, 2.0]:
    curves[i_ac] = rcsj_iv_curve(i_dc, beta_c=0.0, i_ac=i_ac, omega=omega)
    axes[0].plot(curves[i_ac] / omega, i_dc, lw=1.5, label=rf"$i_{{ac}}$ = {i_ac}")
for n in range(4):
    axes[0].axvline(n, color="0.8", lw=0.8)
axes[0].set_xlabel(r"$\langle V\rangle / (\hbar\Omega / 2e)$, i.e. $V / (hf/2e)$")
axes[0].set_ylabel(r"$I_{dc} / I_c$")
axes[0].set_title(r"Shapiro steps, $\Omega = 2eRI_c/\hbar$")
axes[0].legend(fontsize=8)

# %%
# The step voltages in physical units
# -----------------------------------
#
# For a 10 GHz drive the steps are spaced by :math:`hf/2e = 20.7\ \mu V`.

f = 10e9
n_step = np.arange(0, 6)
V_n = n_step * h * f / (2 * e)
axes[1].plot(n_step, V_n * 1e6, "o-", lw=2)
axes[1].set_xlabel("step index n")
axes[1].set_ylabel(r"$V_n$ ($\mu$V)")
axes[1].set_title(r"$V_n = n\,hf/2e$ at f = 10 GHz")
fig.tight_layout()

# %%
# Check
# -----
# K_J = 2e/h = 483.6 MHz/uV; the n-th step voltage oscillates at exactly
# n f; the driven junction locks onto v = n Omega over a finite current
# range for n = 0, 1, 2; the undriven one does not.
assert abs(josephson_frequency(1e-6) / 483.5978484e6 - 1) < 1e-9
np.testing.assert_allclose(josephson_frequency(V_n), n_step * f, rtol=1e-12)
v = curves[1.0]
for n in [0, 1, 2]:
    assert np.sum(np.abs(v - n * omega) < 1e-4) >= 5
v0 = curves[0.0]
assert np.sum(np.abs(v0[i_dc > 1.05] - omega) < 1e-4) <= 1
