{
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "display_name": "OneSimulation (venv)",
   "language": "python",
   "name": "onesim"
  },
  "language_info": {
   "name": "python"
  }
 },
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Small-signal inductance of an inductor with a nonlinear core\n",
    "\n",
    "An inductor in a power converter carries a large direct current with a small ripple on top. The\n",
    "ripple sees the *small-signal* (incremental) inductance $L_\\mathrm{ss}=\\mathrm d\\Psi/\\mathrm dI$ at\n",
    "the operating point, which falls as the steel saturates. The inductor here is a pot core of steel\n",
    "(radius 30 mm, height 40 mm) with a 1 mm air gap in its centre post and a winding of $N=200$ turns\n",
    "in the window; the steel follows a measured $B$-$H$ curve.\n",
    "\n",
    "Everything is symmetric about the axis. OneSimulation first solves the nonlinear magnetostatic\n",
    "field of the bias current; `EddyCurrents` with a `DCOperatingPoint` then solves the harmonic\n",
    "field of a small current using the differential reluctivity $\\mathrm dH/\\mathrm dB$ of every\n",
    "point, and `coil_impedance` returns $j\\omega L_\\mathrm{ss}$.\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| axis and outer walls of the air region | magnetic insulation, $A_\\varphi=0$ |\n",
    "\n",
    "| region | material |\n",
    "|---|---|\n",
    "| core | steel, $B$-$H$ curve below |\n",
    "| winding, air | $\\mu_0$ |\n",
    "\n",
    "The air region comes from `inductor_small_signal_axisymmetric.step`, the core and the winding from\n",
    "`inductor_small_signal_axisymmetric_core.step` and `..._winding.step`; the script\n",
    "`inductor_small_signal_axisymmetric_geometry.py` builds them with the CAD objects of OneSimulation.\n",
    "\n",
    "**Reference.** (i) The differential inductance from two DC solutions at $I\\pm\\Delta I$,\n",
    "$L_\\mathrm{diff}=(\\Psi(I+\\Delta I)-\\Psi(I-\\Delta I))/2\\Delta I$, with the flux linkage of the\n",
    "winding; the small-signal analysis must reproduce it. (ii) At low bias the steel is far from\n",
    "saturation and the gap dominates: $L\\approx\\mu_0N^2A_\\mathrm{post}/g$ with the cross-section\n",
    "$A_\\mathrm{post}$ of the centre post (magnetic circuit, fringing neglected; Kazimierczuk,\n",
    "*High-Frequency Magnetic Components*, 2nd ed., ch. 2)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import VacuumPermeability\n",
    "from onesim.meshing import TriangularMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange, RevolvedH1SpaceFactory\n",
    "from onesim.numerics.linear import ComplexSparseDirect, SparseDirect\n",
    "from onesim.numerics.nonlinear import DampedNewton\n",
    "from onesim.physics.magnetostatics import (\n",
    "    BHCurve,\n",
    "    Coil,\n",
    "    DCOperatingPoint,\n",
    "    EddyCurrents,\n",
    "    MagneticInsulation,\n",
    "    Magnetostatics,\n",
    "    RegionCurrent,\n",
    "    coil_impedance,\n",
    "    flux_linkage,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`section` with the plane $y=0$ gives the meridian plane ($x=r$). Quadratic triangles of 1 mm in\n",
    "the core and the winding, 0.25 mm in the gap region, growing to 8 mm outside."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "plates = {\n",
    "    name: load(f\"inductor_small_signal_axisymmetric{suffix}.step\")\n",
    "    for name, suffix in ((\"air\", \"\"), (\"core\", \"_core\"), (\"winding\", \"_winding\"))\n",
    "}\n",
    "meridian = plates[\"air\"].section((0, 1, 0))\n",
    "core, winding = plates[\"core\"].section((0, 1, 0)).named(\"core\"), plates[\n",
    "    \"winding\"\n",
    "].section((0, 1, 0)).named(\"winding\")\n",
    "mesh = TriangularMesher(\n",
    "    target_size=0.008,\n",
    "    embedded_regions=(core, winding),\n",
    "    region_sizes={\"core\": 0.001, \"winding\": 0.001},\n",
    "    grading=0.25,\n",
    ").generate(meridian)\n",
    "\n",
    "fig = plots.figure(1, 2, size=(14, 6))\n",
    "plots.geometry(\n",
    "    [plates[\"core\"].named(\"steel core\"), plates[\"winding\"].named(\"winding\")],\n",
    "    camera=plots.Camera(elevation=10, azimuth=-90),\n",
    "    title=\"Meridian plates of core and winding (STEP)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Meridian plane: {mesh.cell_count} quadratic triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Models\n",
    "\n",
    "`linkage` solves the nonlinear DC field of a winding current and returns the flux linkage;\n",
    "`small_signal` solves the harmonic field of 1 mA at 1 kHz around a DC bias and returns\n",
    "$L_\\mathrm{ss}=\\mathrm{Im}\\,Z/\\omega$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "turns, frequency, area = 200, 1e3, winding.measure\n",
    "steel = BHCurve(\n",
    "    flux_density=(0.5, 1.0, 1.3, 1.5, 1.6, 1.7, 1.8, 2.0),\n",
    "    field_strength=(80, 150, 300, 700, 1500, 3500, 8000, 40000),\n",
    "    region=\"core\",\n",
    ")\n",
    "numerics = lambda solver: Numerics(\n",
    "    spatial=FiniteElement(\n",
    "        element=Lagrange(order=2), quadrature_order=4, provider=RevolvedH1SpaceFactory()\n",
    "    ),\n",
    "    linear_solver=solver,\n",
    "    **(\n",
    "        {\n",
    "            \"nonlinear_solver\": DampedNewton(\n",
    "                linear_solver=solver, relative_tolerance=1e-10, absolute_tolerance=1e-14\n",
    "            )\n",
    "        }\n",
    "        if isinstance(solver, SparseDirect)\n",
    "        else {}\n",
    "    )\n",
    ")\n",
    "source = lambda current: (\n",
    "    RegionCurrent.coil(winding, turns=turns, current=current, cross_section=area),\n",
    ")\n",
    "insulated = lambda m: (MagneticInsulation(boundary=meridian.boundaries.all, physics=m),)\n",
    "linkage = lambda current: (\n",
    "    lambda m: flux_linkage(\n",
    "        Simulation(\n",
    "            problem=Problem(\n",
    "                name=\"DC field\",\n",
    "                geometry=meridian,\n",
    "                physics=(m,),\n",
    "                boundary_conditions=insulated(m),\n",
    "            ),\n",
    "            mesh=mesh,\n",
    "            numerics=numerics(SparseDirect()),\n",
    "        ).solve_stationary(),\n",
    "        m,\n",
    "        m.current_sources[0],\n",
    "    )\n",
    ")(\n",
    "    Magnetostatics(\n",
    "        domain=meridian.domain(),\n",
    "        permeability=VacuumPermeability(),\n",
    "        current_sources=source(current),\n",
    "        magnetic_response=steel,\n",
    "    )\n",
    ")\n",
    "small_signal = lambda bias: (\n",
    "    lambda coil: (\n",
    "        lambda m: coil_impedance(\n",
    "            Simulation(\n",
    "                problem=Problem(\n",
    "                    name=\"Small signal\",\n",
    "                    geometry=meridian,\n",
    "                    physics=(m,),\n",
    "                    boundary_conditions=insulated(m),\n",
    "                ),\n",
    "                mesh=mesh,\n",
    "                numerics=numerics(ComplexSparseDirect()),\n",
    "            ).solve_stationary(),\n",
    "            m,\n",
    "            coil,\n",
    "        ).imag\n",
    "        / (2 * np.pi * frequency)\n",
    "    )(\n",
    "        EddyCurrents(\n",
    "            domain=meridian.domain(),\n",
    "            permeability=VacuumPermeability(),\n",
    "            frequency=frequency,\n",
    "            coils=(coil,),\n",
    "            magnetic_response=steel,\n",
    "            operating_point=DCOperatingPoint(source(bias)),\n",
    "        )\n",
    "    )\n",
    ")(Coil(winding, turns=turns, current=1e-3))\n",
    "\n",
    "biases, delta = np.array((0.25, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 8.0)), 0.02\n",
    "differential = np.array(\n",
    "    [(linkage(i + delta) - linkage(i - delta)) / (2 * delta) for i in biases]\n",
    ")\n",
    "incremental = np.array([small_signal(i) for i in biases])"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The small-signal inductance against the differential inductance of the DC field, and the\n",
    "low-bias value against the magnetic circuit."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "post = np.pi * 0.010**2\n",
    "circuit = float(VacuumPermeability().evaluate()) * turns**2 * post / 0.001\n",
    "print(\"bias [A]   L small-signal [mH]   L differential [mH]   relative difference\")\n",
    "for i, ss, dd in zip(biases, incremental, differential):\n",
    "    print(f\"{i:8.2f} {1e3 * ss:19.4f} {1e3 * dd:21.4f} {ss / dd - 1:+20.1e}\")\n",
    "print(\n",
    "    f\"magnetic circuit, gap only: {1e3 * circuit:.3f} mH; small-signal inductance at 0.25 A: {1e3 * incremental[0]:.3f} mH \"\n",
    "    f\"({incremental[0] / circuit - 1:+.1%}, fringing at the gap raises it)\"\n",
    ")\n",
    "print(\n",
    "    f\"saturation: the inductance falls to {incremental[-1] / incremental[0]:.1%} of its low-bias value at {biases[-1]:.0f} A\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Left: the inductance against the bias current. Right: the DC flux density in the meridian plane at\n",
    "6 A, where the centre post saturates."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "field = (\n",
    "    lambda m: Simulation(\n",
    "        problem=Problem(\n",
    "            name=\"DC field\",\n",
    "            geometry=meridian,\n",
    "            physics=(m,),\n",
    "            boundary_conditions=insulated(m),\n",
    "        ),\n",
    "        mesh=mesh,\n",
    "        numerics=numerics(SparseDirect()),\n",
    "    )\n",
    "    .solve_stationary()\n",
    "    .field(m.magnetic_flux_density)\n",
    ")(\n",
    "    Magnetostatics(\n",
    "        domain=meridian.domain(),\n",
    "        permeability=VacuumPermeability(),\n",
    "        current_sources=source(6.0),\n",
    "        magnetic_response=steel,\n",
    "    )\n",
    ")\n",
    "r, z = np.asarray(mesh.coordinates).T\n",
    "inside = (r < 0.04) & (np.abs(z) < 0.03)\n",
    "values = np.linalg.norm(np.abs(field.evaluate(np.column_stack((r, z)))), axis=1)\n",
    "fig = plots.figure(1, 2, size=(16, 6))\n",
    "plots.line(\n",
    "    points={\"small-signal analysis\": (biases, 1e3 * incremental)},\n",
    "    reference={\"differential, from DC solutions\": (biases, 1e3 * differential)},\n",
    "    hlines={\"magnetic circuit (gap)\": 1e3 * circuit},\n",
    "    ylimits=(0, None),\n",
    "    xlabel=\"DC bias current [A]\",\n",
    "    ylabel=\"inductance [mH]\",\n",
    "    title=\"Small-signal inductance\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.heatmap(\n",
    "    1e3 * r,\n",
    "    1e3 * z,\n",
    "    values,\n",
    "    triangles=np.asarray(mesh.cells),\n",
    "    limits=(0, 2.0),\n",
    "    label=\"|B| [T]\",\n",
    "    xlimits=(0, 40),\n",
    "    ylimits=(-30, 30),\n",
    "    xlabel=\"r [mm]\",\n",
    "    ylabel=\"z [mm]\",\n",
    "    title=\"DC flux density at 6 A\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Widen the gap in `inductor_small_signal_axisymmetric_geometry.py`: the inductance drops, but it\n",
    "holds up to a higher current. Give the core a conductivity in `EddyCurrents` to see the eddy-current\n",
    "loss of the ripple as the real part of the impedance."
   ]
  }
 ]
}
