{
 "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": [
    "# Effective B-H curve: harmonic model against transient saturation\n",
    "\n",
    "A time-harmonic model assumes that every field varies as $e^{j\\omega t}$; a saturating core does not:\n",
    "its flux density flattens at the peaks of the current and the winding voltage carries harmonics.\n",
    "A harmonic model can still give the fundamental closely if each point of the steel gets an\n",
    "**effective** permeability that stores the same cycle-average magnetic energy as the nonlinear\n",
    "material at the local field amplitude. OneSimulation does this when `EddyCurrents` has a frequency\n",
    "and a `BHCurve` as magnetic response.\n",
    "\n",
    "The core is a square frame of 100 mm with 20 mm legs of laminated steel (no eddy currents in the\n",
    "laminations); a winding of $N=100$ turns around its left leg carries $i(t)=\\hat I\\sin\\omega t$ at\n",
    "50 Hz with $\\hat I=4$ A, which drives the steel to about 1.6 T. In the plane the vector potential\n",
    "$A_z$ solves\n",
    "\n",
    "$$\\nabla\\cdot\\big(\\nu(|\\mathbf B|)\\,\\nabla A_z\\big)=-J_z,\\qquad \\mathbf H=\\nu(|\\mathbf B|)\\,\\mathbf B,$$\n",
    "\n",
    "with $\\nu$ from the B-H curve of the steel (points from 0.5 T at 80 A/m to 2 T at 40 kA/m).\n",
    "\n",
    "| model | steel | time |\n",
    "|---|---|---|\n",
    "| transient | nonlinear B-H curve, Newton in each BDF2 step | two periods, 80 steps each |\n",
    "| harmonic, effective | energy-equivalent effective curve | phasor at 50 Hz |\n",
    "| harmonic, linear | initial permeability of the curve | phasor at 50 Hz |\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| outer edges of the 300 mm air square | $A_z=0$ |\n",
    "\n",
    "Air, core and winding come from the CAD files `effective_bh_curve_frequency_domain*.step`; the script\n",
    "`effective_bh_curve_frequency_domain_geometry.py` builds them with the CAD objects of OneSimulation.\n",
    "The two-dimensional model is their mid-plane section.\n",
    "\n",
    "**Reference.** The transient solution with the nonlinear curve is exact up to discretization; the\n",
    "fundamental of its winding voltage over the second period,\n",
    "$V_1=\\frac{2}{T}\\int_T v(t)\\,e^{-j\\omega t}\\,\\mathrm{d}t$, defines the inductance\n",
    "$L_1=\\operatorname{Im}(V_1/I_1)/\\omega$ that a harmonic model should reproduce (Lederer, Igarashi,\n",
    "Kost and Honma, *IEEE Trans. Magn.* 35, 1999, 1214, on effective reluctivities for harmonic analysis)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import VacuumPermeability, regionwise\n",
    "from onesim.meshing import TriangularMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange\n",
    "from onesim.numerics.linear import ComplexSparseDirect, SparseDirect\n",
    "from onesim.numerics.nonlinear import DampedNewton\n",
    "from onesim.numerics.time import BDF\n",
    "from onesim.physics.magnetostatics import (\n",
    "    BHCurve,\n",
    "    Coil,\n",
    "    EddyCurrents,\n",
    "    MagneticInsulation,\n",
    "    coil_current,\n",
    "    coil_impedance,\n",
    "    coil_voltage,\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",
    "`load` returns each part, `section` its mid-plane. Core and winding sides are embedded regions\n",
    "with triangles of 2 mm, the air grows to 15 mm."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "name = \"effective_bh_curve_frequency_domain\"\n",
    "cut = lambda part: load(f\"{name}{part}.step\").section((0, 0, 1), origin=(0, 0, 0.005))\n",
    "air, core, go, back = (\n",
    "    cut(\"\"),\n",
    "    cut(\"_core\").named(\"core\"),\n",
    "    cut(\"_go\").named(\"go\"),\n",
    "    cut(\"_return\").named(\"back\"),\n",
    ")\n",
    "mesh = TriangularMesher(\n",
    "    target_size=0.015,\n",
    "    embedded_regions=(core, go, back),\n",
    "    region_sizes={\"core\": 0.002, \"go\": 0.002, \"back\": 0.002},\n",
    ").generate(air)\n",
    "\n",
    "fig = plots.figure(1, 2, size=(14, 6))\n",
    "plots.geometry(\n",
    "    [\n",
    "        load(f\"{name}_{part}.step\").named(label)\n",
    "        for part, label in (\n",
    "            (\"core\", \"steel core\"),\n",
    "            (\"go\", \"winding, go side\"),\n",
    "            (\"return\", \"winding, return side\"),\n",
    "        )\n",
    "    ],\n",
    "    camera=plots.Camera(elevation=60, azimuth=-70),\n",
    "    title=\"Core and winding\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Mid-plane section: {mesh.cell_count} triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Three models\n",
    "\n",
    "`BHCurve(region=core)` holds the steel curve inside the core and vacuum outside. The laminations\n",
    "leave the core a tiny effective conductivity of 100 S/m (penetration depth 0.1 m, no eddy-current\n",
    "effect on a 20 mm leg). The winding is a stranded `Coil` with its return side; the transient model\n",
    "feeds it with a function of time."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "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",
    "mu0, turns, amplitude, frequency = (\n",
    "    float(VacuumPermeability().evaluate()),\n",
    "    100,\n",
    "    4.0,\n",
    "    50.0,\n",
    ")\n",
    "omega = 2 * np.pi * frequency\n",
    "initial = 0.5 / (80 * mu0)\n",
    "conditions = lambda model: (\n",
    "    MagneticInsulation(boundary=air.boundaries.all, physics=model),\n",
    ")\n",
    "solver = SparseDirect()\n",
    "transient_coil = Coil(\n",
    "    go, return_region=back, turns=turns, current=lambda t: amplitude * np.sin(omega * t)\n",
    ")\n",
    "laminated = regionwise({\"core\": 100.0}, default=0.0, unit=\"S/m\")\n",
    "transient = EddyCurrents(\n",
    "    domain=air.domain(),\n",
    "    permeability=VacuumPermeability(),\n",
    "    magnetic_response=steel,\n",
    "    coils=(transient_coil,),\n",
    "    conductivity=laminated,\n",
    ")\n",
    "period, steps = 1 / frequency, 80\n",
    "history = Simulation(\n",
    "    problem=Problem(\n",
    "        name=\"Core, transient\",\n",
    "        geometry=air,\n",
    "        physics=(transient,),\n",
    "        boundary_conditions=conditions(transient),\n",
    "    ),\n",
    "    mesh=mesh,\n",
    "    numerics=Numerics(\n",
    "        spatial=FiniteElement(element=Lagrange(order=2), quadrature_order=4),\n",
    "        linear_solver=solver,\n",
    "        time_integrator=BDF(order=2),\n",
    "        nonlinear_solver=DampedNewton(\n",
    "            linear_solver=solver,\n",
    "            relative_tolerance=1e-7,\n",
    "            absolute_tolerance=1e-9,\n",
    "            maximum_iterations=60,\n",
    "        ),\n",
    "    ),\n",
    ").run(start_time=0.0, end_time=2 * period, time_step=period / steps)\n",
    "harmonic = {}\n",
    "for label, response, permeability in (\n",
    "    (\"effective\", steel, VacuumPermeability()),\n",
    "    (\"linear\", None, regionwise({\"core\": initial * mu0}, default=mu0, unit=\"H/m\")),\n",
    "):\n",
    "    coil = Coil(go, return_region=back, turns=turns, current=amplitude)\n",
    "    model = EddyCurrents(\n",
    "        domain=air.domain(),\n",
    "        permeability=permeability,\n",
    "        magnetic_response=response,\n",
    "        frequency=frequency,\n",
    "        coils=(coil,),\n",
    "        conductivity=laminated,\n",
    "    )\n",
    "    result = Simulation(\n",
    "        problem=Problem(\n",
    "            name=f\"Core, harmonic {label}\",\n",
    "            geometry=air,\n",
    "            physics=(model,),\n",
    "            boundary_conditions=conditions(model),\n",
    "        ),\n",
    "        mesh=mesh,\n",
    "        numerics=Numerics(\n",
    "            spatial=FiniteElement(element=Lagrange(order=2), quadrature_order=4),\n",
    "            linear_solver=ComplexSparseDirect(),\n",
    "        ),\n",
    "    ).solve_stationary()\n",
    "    harmonic[label] = (result, model, coil, coil_impedance(result, model, coil))"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The fundamental of the transient voltage over the second period against the two harmonic models,\n",
    "as inductance per metre of depth and as amplitude of the winding voltage."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "times = np.array(history.times)\n",
    "last = times[times > period - 1e-12][1:]\n",
    "voltage = np.array(\n",
    "    [coil_voltage(history, transient, transient_coil, time=t) for t in last]\n",
    ").real\n",
    "current = np.array(\n",
    "    [coil_current(history, transient, transient_coil, time=t) for t in last]\n",
    ").real\n",
    "fundamental = lambda signal: 2 / len(last) * np.sum(signal * np.exp(-1j * omega * last))\n",
    "V1, I1 = fundamental(voltage), fundamental(current)\n",
    "L1 = (V1 / I1).imag / omega\n",
    "print(\n",
    "    f\"initial relative permeability of the steel {initial:.0f}; peak current {amplitude:.1f} A\"\n",
    ")\n",
    "print(\n",
    "    f\"transient, nonlinear: fundamental of the voltage {abs(V1):.4f} V/m, L1 = {1e3 * L1:.4f} mH/m, \"\n",
    "    f\"third harmonic {100 * abs(2 / len(last) * np.sum(voltage * np.exp(-3j * omega * last))) / abs(V1):.1f} % of the fundamental\"\n",
    ")\n",
    "print(\"harmonic model     L [mH/m]   against the transient fundamental   |V| [V/m]\")\n",
    "for label, (result, model, coil, impedance) in harmonic.items():\n",
    "    inductance = impedance.imag / omega\n",
    "    print(\n",
    "        f\"{label:17s} {1e3 * inductance:9.4f} {100 * (inductance / L1 - 1):+30.2f} % {abs(impedance) * amplitude:12.4f}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With the effective curve the harmonic model gives the inductance of the saturated core within a\n",
    "few percent, at the cost of one linear-sized solve; with the initial permeability it overestimates\n",
    "it several times, because it does not see the saturation at all.\n",
    "\n",
    "## Figure\n",
    "\n",
    "The winding voltage over the second period from the transient model with the sine of each\n",
    "harmonic model, and the flux density in the core at the current peak of the transient model."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "phase = np.exp(1j * omega * last)\n",
    "fig = plots.figure(1, 2, size=(15, 6))\n",
    "plots.line(\n",
    "    x=1e3 * (last - period),\n",
    "    y={\"transient, nonlinear B-H curve\": voltage},\n",
    "    reference={\n",
    "        f\"harmonic, {label}\": (\n",
    "            1e3 * (last - period),\n",
    "            np.real(impedance * amplitude * phase / 1j),\n",
    "        )\n",
    "        for label, (_, _, _, impedance) in harmonic.items()\n",
    "    },\n",
    "    xlabel=\"time in the second period [ms]\",\n",
    "    ylabel=\"winding voltage [V/m]\",\n",
    "    title=\"Winding voltage\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.surface(\n",
    "    history.field(transient.magnetic_flux_density),\n",
    "    time=period * 1.25,\n",
    "    component=lambda B, position: np.linalg.norm(B[:, :2], axis=1),\n",
    "    limits=(0, 2.0),\n",
    "    contours=11,\n",
    "    subdivisions=2,\n",
    "    xlimits=(-0.07, 0.07),\n",
    "    ylimits=(-0.07, 0.07),\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"y [m]\",\n",
    "    label=\"|B| [T]\",\n",
    "    title=\"Flux density at the current peak (transient)\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Add a small air gap in the right leg in `effective_bh_curve_frequency_domain_geometry.py`: the gap\n",
    "linearizes the core and the effective and linear models move closer together."
   ]
  }
 ]
}
