{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "fa790599",
   "metadata": {},
   "source": [
    "# Capacitor discharge through a series RLC circuit\n",
    "\n",
    "A capacitor $C$, initially charged to the voltage $U_0$, is connected at $t=0$ to\n",
    "a resistor $R$ and an inductor $L$ in series. There is no source in the loop.\n",
    "Kirchhoff's voltage law, with the capacitor charge $q$ and the loop current\n",
    "$i=\\dot q$, gives the familiar second-order system\n",
    "\n",
    "$$\\dot q = i,\\qquad L\\,\\frac{di}{dt}+R\\,i+\\frac{q}{C}=0.$$\n",
    "\n",
    "OneSimulation treats the circuit as a zero-dimensional (lumped) model with two\n",
    "differential states, the charge and the current, and integrates them with the\n",
    "classical fourth-order Runge-Kutta method.\n",
    "\n",
    "**Reference.** With $\\omega_0=1/\\sqrt{LC}$, $\\alpha=R/(2L)$ and, for the\n",
    "underdamped case $\\alpha<\\omega_0$, $\\omega_d=\\sqrt{\\omega_0^2-\\alpha^2}$, the\n",
    "charge and the current are\n",
    "\n",
    "$$q(t)=q_0\\,e^{-\\alpha t}\\left(\\cos\\omega_d t+\\frac{\\alpha}{\\omega_d}\\sin\\omega_d t\\right),\n",
    "\\qquad i(t)=-q_0\\,\\frac{\\omega_0^2}{\\omega_d}\\,e^{-\\alpha t}\\sin\\omega_d t,$$\n",
    "\n",
    "with $q_0=C\\,U_0$. The current vanishes exactly at $t_n=n\\pi/\\omega_d$, where the\n",
    "charge takes the values $q_0 e^{-\\alpha t_n}(-1)^n$. We use these facts to check\n",
    "not only the time series but also the damped angular frequency and the decay rate."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "6565f364",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "FigureTheme(name='onesimulation', paper='#F7F2E7', panel='#FFFAF2', ink='#223D35', frame='#9FA593', grid='#D5D7C8', cycle=('#336B57', '#B66E43', '#5F9175', '#A85539', '#214D43', '#CD9561', '#8B9A8D'), field_scale=ColorScale(name='onesimulation', stops=('#052C1F', '#0E4C2F', '#407243', '#77985C', '#B2B679', '#EDDCA2', '#FFD29A', '#EEA674', '#CB774F', '#9F4C36', '#6E2A23'), diverging=False), diverging_scale=ColorScale(name='onesimulation_diverging', stops=('#00474A', '#007372', '#579E98', '#A3C8C0', '#F6F0E5', '#E3B89A', '#C9805C', '#9E5136', '#6A291D'), diverging=True), style=mappingproxy({}))"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import numpy as np\n",
    "from onesim.cad.geometry import LumpedDomain\n",
    "from onesim.meshing import LumpedMesh\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.discretization import LumpedParameters\n",
    "from onesim.numerics.time import ClassicalRungeKutta4\n",
    "from onesim.physics.electromagnetics import SeriesRLC\n",
    "from onesim.results.storage import MemoryOutputSink, Output\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.simulation.initial_conditions import InitialValue\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8b4c24bc",
   "metadata": {},
   "source": [
    "## Parameters and model\n",
    "\n",
    "The parameters can be changed. The reference formula below stays valid as long\n",
    "as the circuit remains underdamped, $R<2\\sqrt{L/C}$. The values describe a\n",
    "small laboratory circuit: a 100 µF capacitor charged to 10 V discharging\n",
    "through 2 Ω and 10 mH."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "cd456aad",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "omega_0 = 1000.0 rad/s,  alpha = 100.0 1/s,  omega_d = 995.0 rad/s\n",
      "damped period = 6.315 ms,  decay time 1/alpha = 10.0 ms\n"
     ]
    }
   ],
   "source": [
    "resistance = 2.0\n",
    "inductance = 10.0e-3\n",
    "capacitance = 100.0e-6\n",
    "initial_voltage = 10.0\n",
    "initial_current = 0.0\n",
    "\n",
    "omega_0 = 1.0 / np.sqrt(inductance * capacitance)\n",
    "alpha = resistance / (2 * inductance)\n",
    "omega_d = np.sqrt(omega_0**2 - alpha**2)\n",
    "initial_charge = capacitance * initial_voltage\n",
    "damped_period = 2 * np.pi / omega_d\n",
    "end_time = 5.0 / alpha\n",
    "time_step = damped_period / 200.0\n",
    "print(\n",
    "    f\"omega_0 = {omega_0:.1f} rad/s,  alpha = {alpha:.1f} 1/s,  omega_d = {omega_d:.1f} rad/s\"\n",
    ")\n",
    "print(\n",
    "    f\"damped period = {damped_period * 1e3:.3f} ms,  decay time 1/alpha = {1e3 / alpha:.1f} ms\"\n",
    ")\n",
    "\n",
    "domain = LumpedDomain()\n",
    "model = SeriesRLC(\n",
    "    domain=domain.system,\n",
    "    resistance=resistance,\n",
    "    inductance=inductance,\n",
    "    capacitance=capacitance,\n",
    "    source_voltage=0.0,\n",
    ")\n",
    "simulation = Simulation(\n",
    "    problem=Problem(\n",
    "        name=\"Series RLC capacitor discharge\",\n",
    "        geometry=domain,\n",
    "        physics=(model,),\n",
    "        initial_conditions=(\n",
    "            InitialValue(model.charge, initial_charge),\n",
    "            InitialValue(model.current, initial_current),\n",
    "        ),\n",
    "    ),\n",
    "    mesh=LumpedMesh(domain),\n",
    "    numerics=Numerics(\n",
    "        spatial=LumpedParameters(),\n",
    "        time_integrator=ClassicalRungeKutta4(),\n",
    "    ),\n",
    ")\n",
    "simulation.validate().require_valid()\n",
    "\n",
    "sink = MemoryOutputSink()\n",
    "result = simulation.run(\n",
    "    start_time=0.0,\n",
    "    end_time=end_time,\n",
    "    time_step=time_step,\n",
    "    output=Output(\n",
    "        fields=(model.charge, model.current, model.capacitor_voltage),\n",
    "        interval=time_step,\n",
    "        sink=sink,\n",
    "    ),\n",
    ")\n",
    "times = sink.times\n",
    "\n",
    "\n",
    "charges = sink.time_series(model.charge)[1]\n",
    "currents = sink.time_series(model.current)[1]\n",
    "capacitor_voltages = sink.time_series(model.capacitor_voltage)[1]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7f0f0a7b",
   "metadata": {},
   "source": [
    "## Comparison with the closed-form solution\n",
    "\n",
    "We evaluate the reference charge and current at every stored time. In addition\n",
    "we read the damped frequency off the zero crossings of the current and the decay\n",
    "rate off the charge values at those crossings, exactly as one would from an\n",
    "oscilloscope trace. A passing check shows that this numerical example agrees\n",
    "with the linear circuit equations; it is not a measurement of a real circuit."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "822ea57b",
   "metadata": {},
   "outputs": [],
   "source": [
    "envelope = initial_charge * np.exp(-alpha * times)\n",
    "reference_charge = envelope * (\n",
    "    np.cos(omega_d * times) + (alpha / omega_d) * np.sin(omega_d * times)\n",
    ")\n",
    "reference_current = (\n",
    "    -initial_charge\n",
    "    * (omega_0**2 / omega_d)\n",
    "    * np.exp(-alpha * times)\n",
    "    * np.sin(omega_d * times)\n",
    ")\n",
    "\n",
    "max_charge_error = float(np.max(np.abs(charges - reference_charge)))\n",
    "max_current_error = float(np.max(np.abs(currents - reference_current)))\n",
    "print(f\"Maximum charge error:  {max_charge_error:.3e} C  (q0 = {initial_charge:.1e} C)\")\n",
    "print(\n",
    "    f\"Maximum current error: {max_current_error:.3e} A  (peak current ~ {initial_charge * omega_0:.2f} A)\"\n",
    ")\n",
    "\n",
    "sign_change = np.where(np.sign(currents[:-1]) * np.sign(currents[1:]) < 0)[0]\n",
    "crossing_times = times[sign_change] - currents[sign_change] * (\n",
    "    (times[sign_change + 1] - times[sign_change])\n",
    "    / (currents[sign_change + 1] - currents[sign_change])\n",
    ")\n",
    "measured_omega_d = np.pi / np.mean(np.diff(crossing_times))\n",
    "charge_at_crossings = np.interp(crossing_times, times, charges)\n",
    "measured_alpha = -np.polyfit(crossing_times, np.log(np.abs(charge_at_crossings)), 1)[0]\n",
    "print(\n",
    "    f\"Damped angular frequency: measured {measured_omega_d:.2f} rad/s, exact {omega_d:.2f} rad/s\"\n",
    ")\n",
    "print(\n",
    "    f\"Decay rate:               measured {measured_alpha:.3f} 1/s,  exact {alpha:.3f} 1/s\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a182813d",
   "metadata": {},
   "source": [
    "## Figure"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e6f5235c",
   "metadata": {},
   "outputs": [],
   "source": [
    "dense_t = np.linspace(0.0, end_time, 2000)\n",
    "dense_env = initial_voltage * np.exp(-alpha * dense_t)\n",
    "dense_voltage = dense_env * (\n",
    "    np.cos(omega_d * dense_t) + (alpha / omega_d) * np.sin(omega_d * dense_t)\n",
    ")\n",
    "fig = plots.figure(2, 1, size=(8, 7))\n",
    "plots.line(\n",
    "    points={\"OneSimulation RK4\": (times[::10] * 1e3, capacitor_voltages[::10])},\n",
    "    reference={\"closed-form solution\": (dense_t * 1e3, dense_voltage)},\n",
    "    band={\n",
    "        \"decay envelope\": (\n",
    "            -np.interp(times[::10], dense_t, dense_env),\n",
    "            np.interp(times[::10], dense_t, dense_env),\n",
    "        )\n",
    "    },\n",
    "    x=times[::10] * 1e3,\n",
    "    ylabel=\"capacitor voltage [V]\",\n",
    "    title=\"Series RLC capacitor discharge\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    times * 1e3,\n",
    "    {\"loop current\": currents},\n",
    "    points={\"zero crossings\": (crossing_times * 1e3, np.zeros_like(crossing_times))},\n",
    "    xlabel=\"time [ms]\",\n",
    "    ylabel=\"current [A]\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dd87b1b8",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Raise the resistance towards the critical value $2\\sqrt{L/C}$ and watch the\n",
    "oscillation disappear; beyond it the circuit is overdamped and the reference\n",
    "formula must be replaced by the sum of two real exponentials. A constant\n",
    "`source_voltage` turns the discharge into a step response that settles at the\n",
    "charge $C\\,U_\\mathrm{s}$ with the same $\\alpha$ and $\\omega_d$. Halving the time step\n",
    "should shrink the time-series errors by about a factor of sixteen."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "OneSimulation (venv)",
   "language": "python",
   "name": "onesim"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
