{
 "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": [
    "# Inductive heating of a copper cylinder\n",
    "\n",
    "A long coil (inner radius 15 mm, outer radius 17 mm, 5000 turns per metre) carries an alternating\n",
    "current of 15 A amplitude at 2 kHz around a copper cylinder of radius $a=10$ mm. The eddy\n",
    "currents heat the cylinder; the conductivity of copper falls with temperature,\n",
    "$\\sigma(T)=\\sigma_{20}/(1+\\alpha(T-T_{20}))$ with $\\sigma_{20}=5.8\\cdot10^7$ S/m and\n",
    "$\\alpha=0.0039$ 1/K, which changes the skin depth and the induced power while the cylinder warms\n",
    "up.\n",
    "\n",
    "Two models are coupled. The time-harmonic eddy-current model (`EddyCurrents`) gives the\n",
    "time-averaged loss density $q=|\\mathbf J|^2/(2\\sigma)$ for the present temperature; heat\n",
    "conduction (`HeatConduction`) takes $q$ as its source,\n",
    "\n",
    "$$\\rho c\\,\\frac{\\partial T}{\\partial t}=\\nabla\\cdot(\\lambda\\nabla T)+q,$$\n",
    "\n",
    "and returns the temperature to the conductivity. The electromagnetic field settles within\n",
    "microseconds, the temperature within seconds, so `QuasiStationaryCoupling` solves the field as\n",
    "stationary in every time step of the heat equation and iterates both until they agree.\n",
    "\n",
    "The domain is the meridian section of `inductive_heating_copper_cylinder.step`, a 10 mm slice of\n",
    "the long coil; the cylinder and the winding are the sections of `_cylinder.step` and\n",
    "`_winding.step`, which the mesh follows. The script `inductive_heating_copper_cylinder_geometry.py`\n",
    "builds them with the CAD objects of OneSimulation. The slice is thermally insulated, so all\n",
    "induced heat stays in it.\n",
    "\n",
    "| edge | electromagnetic | thermal |\n",
    "|---|---|---|\n",
    "| axis $r=0$ | axis of the revolved space | axis |\n",
    "| top, bottom, $r=20$ mm | field normal (`MagneticSymmetry`) | no heat flux |\n",
    "\n",
    "**Reference.** At the start (uniform 20 °C) the loss per metre is the Bessel result for a long\n",
    "cylinder in a long coil (Lammeraner and Štafl, *Eddy Currents*, 1966),\n",
    "$P/\\ell=\\int_0^a|nI\\,kJ_1(kr)/J_0(ka)|^2/(2\\sigma)\\,2\\pi r\\,\\mathrm dr$, $k=\\sqrt{-\\mathrm j\\omega\\mu_0\\sigma}$.\n",
    "With insulated walls the heat stored in the slice must grow in every step by the time step times\n",
    "the induced power (backward Euler)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import (\n",
    "    IsotropicSolid,\n",
    "    TabulatedLaw,\n",
    "    VacuumPermeability,\n",
    "    regionwise,\n",
    ")\n",
    "from onesim.meshing import TriangularMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.coupled_systems import QuasiStationaryCoupling\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange, RevolvedH1SpaceFactory\n",
    "from onesim.numerics.field_transfer import FiniteElementEvaluation\n",
    "from onesim.numerics.linear import ComplexSparseDirect, SparseDirect\n",
    "from onesim.numerics.nonlinear import FixedPoint\n",
    "from onesim.numerics.time import BackwardEuler\n",
    "from onesim.physics.heat_transfer import HeatConduction, HeatFlux\n",
    "from onesim.physics.magnetostatics import (\n",
    "    Coil,\n",
    "    EddyCurrents,\n",
    "    MagneticSymmetry,\n",
    "    joule_losses,\n",
    ")\n",
    "from onesim.results.integration import mean_value\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.simulation.field_connections import FieldCoupling\n",
    "from onesim.simulation.initial_conditions import InitialValue\n",
    "from onesim.visualization import plots, theme\n",
    "from scipy.integrate import quad\n",
    "from scipy.special import jv\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`section` cuts the parts in the plane $y=0$; the section coordinates are $(r, z)$. The mesh follows\n",
    "the surfaces of the cylinder and the winding and resolves the skin depth (1.5 mm at 2 kHz)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "meridian = lambda name: load(f\"inductive_heating_copper_cylinder{name}.step\").section(\n",
    "    (0, 1, 0)\n",
    ")\n",
    "domain, cylinder, winding = meridian(\"\"), meridian(\"_cylinder\"), meridian(\"_winding\")\n",
    "axis = domain.select(\n",
    "    edges=lambda edge: all(abs(point[0]) < 1e-12 for point in edge.points)\n",
    ")\n",
    "height, radius = domain.size[1], cylinder.size[0]\n",
    "mesh = TriangularMesher(\n",
    "    target_size=0.0008,\n",
    "    embedded_regions=(cylinder.named(\"cylinder\"), winding.named(\"winding\")),\n",
    ").generate(domain)\n",
    "\n",
    "fig = plots.figure(1, 2, size=(14, 6))\n",
    "plots.geometry(\n",
    "    [\n",
    "        load(f\"inductive_heating_copper_cylinder{name}.step\").named(label)\n",
    "        for name, label in ((\"_cylinder\", \"copper cylinder\"), (\"_winding\", \"winding\"))\n",
    "    ],\n",
    "    camera=plots.Camera(elevation=30, azimuth=-60),\n",
    "    title=\"Slice of the cylinder and the coil (x > 0)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Meridian section: {mesh.cell_count} triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "Copper properties in the cylinder, air elsewhere; the conductivity is a table over temperature."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "frequency, per_metre, current, t20 = 2000.0, 5000, 15.0, 293.15\n",
    "turns = int(round(per_metre * height))\n",
    "mu0 = float(VacuumPermeability().evaluate())\n",
    "table = np.linspace(t20, t20 + 1000.0, 11)\n",
    "copper = TabulatedLaw(\n",
    "    points=tuple(table), values=tuple(5.8e7 / (1 + 0.0039 * (table - t20))), unit=\"S/m\"\n",
    ")\n",
    "eddy = EddyCurrents(\n",
    "    domain=domain.domain(),\n",
    "    permeability=VacuumPermeability(),\n",
    "    frequency=frequency,\n",
    "    conductivity=regionwise({\"cylinder\": copper}, default=0.0, unit=\"S/m\"),\n",
    "    coils=(Coil(winding, turns=turns, current=current),),\n",
    ")\n",
    "heat = HeatConduction(\n",
    "    domain=domain.domain(),\n",
    "    material=IsotropicSolid(\n",
    "        density=regionwise({\"cylinder\": 8960.0}, default=1.2, unit=\"kg/m^3\"),\n",
    "        specific_heat_capacity=regionwise(\n",
    "            {\"cylinder\": 385.0}, default=1005.0, unit=\"J/kg/K\"\n",
    "        ),\n",
    "        thermal_conductivity=regionwise(\n",
    "            {\"cylinder\": 400.0}, default=0.026, unit=\"W/m/K\"\n",
    "        ),\n",
    "        youngs_modulus=1.0,\n",
    "        poisson_ratio=0.3,\n",
    "        thermal_expansion_coefficient=0.0,\n",
    "    ),\n",
    ")\n",
    "problem = Problem(\n",
    "    name=\"Inductive heating\",\n",
    "    geometry=domain,\n",
    "    physics=(heat, eddy),\n",
    "    boundary_conditions=(\n",
    "        MagneticSymmetry(boundary=domain.boundaries.all - axis, physics=eddy),\n",
    "        HeatFlux(boundary=domain.boundaries.all, physics=heat, value=0.0),\n",
    "    ),\n",
    "    initial_conditions=(InitialValue(heat.temperature, t20),),\n",
    "    couplings=(\n",
    "        FieldCoupling(\n",
    "            source=eddy.loss_density,\n",
    "            target=heat.heating,\n",
    "            transfer=FiniteElementEvaluation(),\n",
    "        ),\n",
    "        FieldCoupling(\n",
    "            source=heat.temperature,\n",
    "            target=eddy.temperature,\n",
    "            transfer=FiniteElementEvaluation(),\n",
    "        ),\n",
    "    ),\n",
    ")\n",
    "revolved = lambda: FiniteElement(\n",
    "    element=Lagrange(order=2), quadrature_order=4, provider=RevolvedH1SpaceFactory()\n",
    ")\n",
    "step, end = 20.0, 120.0\n",
    "result = Simulation(\n",
    "    problem=problem,\n",
    "    mesh={heat: mesh, eddy: mesh},\n",
    "    numerics={\n",
    "        heat: Numerics(\n",
    "            spatial=revolved(),\n",
    "            linear_solver=SparseDirect(),\n",
    "            time_integrator=BackwardEuler(),\n",
    "        ),\n",
    "        eddy: Numerics(spatial=revolved(), linear_solver=ComplexSparseDirect()),\n",
    "    },\n",
    "    coupling_solver=QuasiStationaryCoupling(\n",
    "        transient_systems=(heat,),\n",
    "        stationary_systems=(eddy,),\n",
    "        iteration=FixedPoint(\n",
    "            relative_tolerance=1e-8, absolute_tolerance=0.0, maximum_iterations=20\n",
    "        ),\n",
    "    ),\n",
    ").run(start_time=0.0, end_time=end, time_step=step)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "Induced power and mean cylinder temperature over time, the heat stored in the cylinder in every\n",
    "step against the time step times the induced power, and the starting power against Bessel. The\n",
    "air holds less than 0.04 % of the heat and is left out of the balance."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "times = np.array(result.times)\n",
    "temperature = result.field(heat.temperature)\n",
    "losses = np.array([joule_losses(result, eddy, time=t) for t in times])\n",
    "mean_temperature = np.array(\n",
    "    [float(mean_value(temperature, region=cylinder, time=t)) for t in times]\n",
    ")\n",
    "heat_capacity = 8960.0 * 385.0 * np.pi * radius**2 * height\n",
    "k = np.sqrt(-1j * 2 * np.pi * frequency * mu0 * 5.8e7)\n",
    "bessel = quad(\n",
    "    lambda s: abs(per_metre * current * k * jv(1, k * s) / jv(0, k * radius)) ** 2\n",
    "    / (2 * 5.8e7)\n",
    "    * 2\n",
    "    * np.pi\n",
    "    * s,\n",
    "    0,\n",
    "    radius,\n",
    "    limit=200,\n",
    ")[0]\n",
    "print(\n",
    "    f\"induced power at 20 °C: {losses[0] / height:.3f} W/m, Bessel {bessel:.3f} W/m ({100 * (losses[0] / height / bessel - 1):+.3f} %)\"\n",
    ")\n",
    "print(\n",
    "    \"time [s]   power [W]   mean cylinder temperature [°C]   stored heat of the step / (dt * power)\"\n",
    ")\n",
    "for n, (t, p, T) in enumerate(zip(times, losses, mean_temperature)):\n",
    "    balance = (\n",
    "        heat_capacity * (T - mean_temperature[n - 1]) / (step * p)\n",
    "        if n\n",
    "        else float(\"nan\")\n",
    "    )\n",
    "    print(f\"{t:8.0f} {p:11.4f} {T - 273.15:28.2f} {balance:24.5f}\")\n",
    "print(\n",
    "    f\"after {times[-1]:.0f} s the power has risen by {100 * (losses[-1] / losses[0] - 1):.1f} % because the conductivity fell\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The temperature in the meridian plane at the end, and the induced power and mean temperature over\n",
    "time."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 2, size=(15, 6))\n",
    "plots.surface(\n",
    "    temperature,\n",
    "    time=times[-1],\n",
    "    component=lambda T, position: np.ravel(T) - 273.15,\n",
    "    contours=10,\n",
    "    subdivisions=2,\n",
    "    label=\"temperature [°C]\",\n",
    "    title=f\"Temperature after {times[-1]:.0f} s\",\n",
    "    xlabel=\"r [m]\",\n",
    "    ylabel=\"z [m]\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    times,\n",
    "    {\"induced power [W]\": losses},\n",
    "    right={\"mean cylinder temperature [°C]\": mean_temperature - 273.15},\n",
    "    markers=True,\n",
    "    xlabel=\"time [s]\",\n",
    "    ylabel=\"induced power [W]\",\n",
    "    right_label=\"temperature [°C]\",\n",
    "    title=\"Heating history\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Let the cylinder lose heat to the air (a convective `HeatFlux` on its surface or heat conduction\n",
    "through a thicker air gap), raise the frequency to concentrate the heating in a thinner skin, or\n",
    "replace copper by steel with its own temperature-dependent conductivity and permeability."
   ]
  }
 ]
}
