JAX backend
With the jax extra, JaxModel runs the rate evaluation, the population equations and the quasi-static reduction on JAX: jitted, vectorised with vmap, and differentiable. See Backends for what it covers and how it differs from the reference.
import jaximport numpy as npimport plasma_plots
import opencrfrom opencr.backends.jax_backend import JaxModel
plasma_plots.set_backend("plotly") # interactive figures, embedded in the docsplasma_plots.set_math("latex") # formulas in the figures typeset as LaTeX
model = opencr.load_model("hydrogen/atomic/basic", n_max=10)conditions = opencr.Conditions(1.0, 1e18, densities={"H(n=1)": 1e19, "H+": 1e18})jm = JaxModel(model, conditions)Jitted rates and a vmapped scan
Section titled “Jitted rates and a vmapped scan”The first call compiles; the second runs the compiled code:
temperatures = np.geomspace(0.5, 100.0, 30)densities = np.geomspace(1e16, 1e22, 5)grid_t, grid_n = np.meshgrid(temperatures, densities, indexing="ij")reduction = jm.reduction(grid_t, grid_n) # compilesreduction = jm.reduction(grid_t, grid_n)s_cr = reduction.effective_rate("H(n=1)", "H+").reshape(grid_t.shape)with plasma_plots.figure(title="Effective ionization coefficient (JAX)") as fig: for j, density in enumerate(densities): mantissa, exponent = f"{density:.1e}".split("e") label = rf"$n_e = {mantissa} \times 10^{{{int(exponent)}}}$ m$^{{-3}}$" fig[0].loglog(temperatures, s_cr[:, j], label=label) fig[0].set_xlabel("$T_e$ [eV]") fig[0].set_ylabel(r"$S_\mathrm{CR}$ [m$^3$/s]") fig[0].legend()Loading figure…
Automatic differentiation
Section titled “Automatic differentiation”The Jacobian of the population equations by forward-mode AD agrees with the analytic sparse one, and jax.grad of an effective coefficient gives its sensitivity to the conditions, here :
system = model.system(conditions)n = np.geomspace(1e10, 1e15, system.size)analytic = system.jacobian(n).toarray()print( f"Jacobian: largest difference {np.abs(np.asarray(jm.jacobian(n, 1.0, 1e18)) - analytic).max() / np.abs(analytic).max():.1e} of the largest entry")
def log_s_cr(log_t): return jax.numpy.log(jm.effective_rate("H(n=1)", "H+", jax.numpy.exp(log_t), 1e18))
slope = jax.jit(jax.grad(log_s_cr))for t in (1.0, 3.0, 10.0, 30.0): print(f"T_e = {t:5.1f} eV: d ln S_CR / d ln T_e = {float(slope(np.log(t))):.2f}")Jacobian: largest difference 7.2e-15 of the largest entryT_e = 1.0 eV: d ln S_CR / d ln T_e = 13.81T_e = 3.0 eV: d ln S_CR / d ln T_e = 4.87T_e = 10.0 eV: d ln S_CR / d ln T_e = 1.69T_e = 30.0 eV: d ln S_CR / d ln T_e = 0.65