Electrical circuit¶
This example solves a DAE: a low-pass LRC filter driven by a sinusoidal voltage source. The circuit gives two differential equations (the inductor and the capacitor) and two purely algebraic ones (Ohm's law for the resistor, and Kirchhoff's current law), so the system cannot be written as an ODE without eliminating variables by hand.
import jax
import jax.numpy as jnp
import matplotlib.pyplot as plt
from diffsol_jax import ODEProblem, solve
jax.config.update("jax_enable_x64", True)
The state is [i_r, i_l, i_c, v]: the three branch currents and the voltage
over the resistor-capacitor pair. The two algebraic equations are written as
rows of rhs like any other, returning the residual that must be zero.
def rhs(x, p, t):
i_r, i_l, i_c, v = x
r, l_, c, v0, omega = p
vs = v0 * jnp.sin(omega * t)
return jnp.array(
[
v - r * i_r, # 0 = v - R i_R
(vs - v) / l_, # d i_L / dt
i_l - i_r - i_c, # 0 = i_L - i_R - i_C
i_c / c, # d v / dt
]
)
algebraic= marks which rows are constraints. A DAE needs an implicit
solver; bdf is the default.
The initial state only needs its differential entries (i_l and v) to be
meaningful: the algebraic entries are projected onto the constraints before
the solve, so zeros are a fine starting guess.
R, L, C, V0, OMEGA = 100.0, 1.0, 1e-3, 10.0, 100.0
params = jnp.array([R, L, C, V0, OMEGA])
t_eval = jnp.linspace(0.0, 1.0, 2000)
y0 = jnp.zeros(4)
ys = solve(problem, y0, params, t_eval[0], t_eval[-1], saveat=t_eval)
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(t_eval, ys[:, 0], label="$i_R$")
ax.set_xlabel("t")
ax.set_ylabel("current")
ax.set_title("Low-pass LRC filter")
ax.legend()
fig.tight_layout()
fig.savefig("electrical-circuit.png")
