{
 "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": [
    "# Laser beam absorbed in a silica glass rod\n",
    "\n",
    "A laser beam (power $P=5$ W, Gaussian radius $w=1.5$ mm) enters a glass rod along its axis. The\n",
    "glass absorbs the light weakly, $\\alpha=100$ 1/m, so the intensity decays slowly along the 20 mm\n",
    "rod (86 % is absorbed):\n",
    "\n",
    "$$I(r,z)=\\frac{2P}{\\pi w^2}\\,e^{-2r^2/w^2}\\,e^{-\\alpha z},\\qquad\n",
    "  \\rho c\\,\\frac{\\partial T}{\\partial t}=\\nabla\\cdot(k\\nabla T)+\\alpha I(r,z).$$\n",
    "\n",
    "Fused silica: $k=1.38$ W/(m K), $\\rho=2200$ kg/m³, $c=740$ J/(kg K). All faces are taken as\n",
    "insulated for the 10 s of heating, so every absorbed joule stays in the rod.\n",
    "\n",
    "| face | condition |\n",
    "|---|---|\n",
    "| `entrance`, `exit`, `mantle` | insulated |\n",
    "| initial state | 20 °C |\n",
    "\n",
    "The rod (30 mm diameter) comes from the CAD file `laser_absorption_silica_rod.step`; the script\n",
    "`laser_absorption_silica_rod_geometry.py` builds it with the CAD objects of OneSimulation.\n",
    "\n",
    "**Reference.** (1) Energy: the heat stored in the rod is $P(1-e^{-\\alpha L})\\,t$. (2) Away from\n",
    "the end faces and the mantle the rod acts as an infinite medium. Each instant of the Gaussian\n",
    "source then spreads as a Gaussian, and the exponential axial profile grows by $e^{\\kappa\\alpha^2s}$,\n",
    "so on the axis (Carslaw and Jaeger, *Conduction of Heat in Solids*, ch. 10)\n",
    "\n",
    "$$T(0,z,t)-T_0=\\frac{\\alpha I_0e^{-\\alpha z}}{\\rho c}\\int_0^t\\frac{e^{\\kappa\\alpha^2 s}}{1+8\\kappa s/w^2}\\,ds,\n",
    "  \\qquad \\kappa=\\frac{k}{\\rho c},\\quad I_0=\\frac{2P}{\\pi w^2}.$$"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.d2 import Plane\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import IsotropicSolid\n",
    "from onesim.meshing import Geometric, disc_blocks, extrude, merge_blocks\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.numerics.time import BDF, BackwardEuler\n",
    "from onesim.physics.heat_transfer import HeatConduction, HeatFlux\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.simulation.initial_conditions import InitialValue\n",
    "from onesim.visualization import plots, theme\n",
    "from scipy.integrate import quad\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`load` returns the rod with its named faces. `disc_blocks` meshes the cross-section with a centre\n",
    "block, a ring out to twice the beam radius and an outer ring graded towards the beam; `extrude`\n",
    "carries the cells along the rod and `geometry=rod` binds them to its faces."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "rod = load(\"laser_absorption_silica_rod.step\")\n",
    "faces = rod.boundaries\n",
    "radius, length, beam = rod.size[0] / 2, rod.size[2], 0.0015\n",
    "blocks = disc_blocks(\n",
    "    (0, 0),\n",
    "    (2 * beam, radius),\n",
    "    4,\n",
    "    (4, 8),\n",
    "    core=0.5,\n",
    "    gradings=(Geometric(4, ratio=1.0), Geometric(8, ratio=5.0)),\n",
    ")\n",
    "mesh = extrude(\n",
    "    merge_blocks(blocks, order=2), length, Geometric(10, ratio=1.0), geometry=rod\n",
    ")\n",
    "\n",
    "view = plots.Camera(elevation=25, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(14, 5.5))\n",
    "plots.geometry(\n",
    "    rod,\n",
    "    selection={\n",
    "        \"beam entrance\": faces.entrance,\n",
    "        \"exit\": faces.exit,\n",
    "        \"mantle\": faces.mantle,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Glass rod with its named faces\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"{mesh.cell_count} quadratic hexahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "The Beer-Lambert source is the heating density of the model. Quadratic elements and the\n",
    "second-order BDF integrator with 40 steps of 0.25 s."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "power, absorption, initial = 5.0, 100.0, 293.15\n",
    "peak = 2 * power / (np.pi * beam**2)\n",
    "silica = IsotropicSolid(\n",
    "    density=2200.0,\n",
    "    specific_heat_capacity=740.0,\n",
    "    thermal_conductivity=1.38,\n",
    "    youngs_modulus=7.3e10,\n",
    "    poisson_ratio=0.17,\n",
    "    thermal_expansion_coefficient=5.5e-7,\n",
    ")\n",
    "model = HeatConduction(\n",
    "    domain=rod.volume,\n",
    "    material=silica,\n",
    "    heating=lambda x, y, z: absorption\n",
    "    * peak\n",
    "    * np.exp(-2 * (x**2 + y**2) / beam**2 - absorption * z),\n",
    ")\n",
    "problem = Problem(\n",
    "    name=\"Laser absorption in silica\",\n",
    "    geometry=rod,\n",
    "    physics=(model,),\n",
    "    boundary_conditions=(HeatFlux(boundary=faces.all, physics=model, value=0.0),),\n",
    "    initial_conditions=(InitialValue(model.temperature, initial),),\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)),\n",
    "    linear_solver=SparseDirect(),\n",
    "    time_integrator=BDF(order=2, startup=BackwardEuler()),\n",
    ")\n",
    "temperature = (\n",
    "    Simulation(problem=problem, mesh=mesh, numerics=numerics)\n",
    "    .run(start_time=0.0, end_time=10.0, time_step=0.25)\n",
    "    .field(model.temperature)\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The stored heat against the absorbed energy, and the axis temperature in the middle of the rod\n",
    "against the diffusing-Gaussian solution."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "capacity = silica.density * silica.specific_heat_capacity\n",
    "kappa = silica.thermal_conductivity / capacity\n",
    "absorbed = power * (1 - np.exp(-absorption * length))\n",
    "axis = (\n",
    "    lambda z, t: absorption\n",
    "    * peak\n",
    "    * np.exp(-absorption * z)\n",
    "    / capacity\n",
    "    * quad(\n",
    "        lambda s: np.exp(kappa * absorption**2 * s) / (1 + 8 * kappa * s / beam**2),\n",
    "        0,\n",
    "        t,\n",
    "    )[0]\n",
    ")\n",
    "times, middle = temperature.time_series([[0.0, 0.0, length / 2]])\n",
    "middle = np.ravel(middle)\n",
    "print(\n",
    "    \"time [s]   stored heat [J]   absorbed energy [J]   axis rise at z = 10 mm: simulation [K]   exact [K]\"\n",
    ")\n",
    "for index in (4, 8, 20, 40):\n",
    "    stored = capacity * (\n",
    "        temperature.integrate(time=times[index]).value\n",
    "        - initial * np.pi * radius**2 * length\n",
    "    )\n",
    "    print(\n",
    "        f\"{times[index]:8.2f} {stored:17.4f} {absorbed * times[index]:21.4f} {middle[index] - initial:38.4f} \"\n",
    "        f\"{axis(length / 2, times[index]):11.4f}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The temperature in a section through the axis after 10 s, and the rise on the axis over time at\n",
    "three depths with the exact solution."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 2, size=(16, 6))\n",
    "plots.section(\n",
    "    temperature,\n",
    "    time=10.0,\n",
    "    plane=Plane(origin=(0, 0, 0), normal=(0, 1, 0)),\n",
    "    component=lambda T, position: T - 273.15,\n",
    "    contours=12,\n",
    "    subdivisions=3,\n",
    "    xlimits=(-0.008, 0.008),\n",
    "    label=\"T [°C]\",\n",
    "    title=\"Section through the beam axis after 10 s (central 16 mm)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "depths = {f\"z = {1e3 * z:.1f} mm\": z for z in (0.0075, 0.010, 0.0125)}\n",
    "plots.line(\n",
    "    y={\n",
    "        name: (times, temperature.time_series([[0.0, 0.0, z]])[1].ravel() - initial)\n",
    "        for name, z in depths.items()\n",
    "    },\n",
    "    reference={\n",
    "        name: (times[::2], [axis(z, t) for t in times[::2]])\n",
    "        for name, z in depths.items()\n",
    "    },\n",
    "    xlabel=\"time [s]\",\n",
    "    ylabel=\"temperature rise on the axis [K]\",\n",
    "    title=\"Simulation (lines), exact (dashed)\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Let the faces lose heat by convection and radiation and run until the steady state, or raise the\n",
    "absorption coefficient towards the values of silica at 10.6 µm, where the beam is absorbed within\n",
    "a fraction of a millimetre and the rod heats from its entrance face."
   ]
  }
 ]
}
