{
 "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 heating of an absorbing slab (Beer-Lambert law)\n",
    "\n",
    "A laser beam (power $P=10$ W, Gaussian radius $w=10$ mm) falls on the front of a glass slab 1 mm\n",
    "thick. The glass absorbs the light gradually: the intensity decays along the beam as\n",
    "\n",
    "$$I(r,z)=I_0\\,e^{-2r^2/w^2}\\,e^{-\\alpha z},\\qquad I_0=\\frac{2P}{\\pi w^2},$$\n",
    "\n",
    "with the absorption coefficient $\\alpha=2000$ 1/m ($\\alpha d=2$, so 86 % of the light is\n",
    "absorbed). The absorbed light is a heat source $\\dot q=-\\partial I/\\partial z=\\alpha I$ in the\n",
    "steady heat equation\n",
    "\n",
    "$$-\\nabla\\cdot(k\\nabla T)=\\alpha I(r,z),\\qquad k=1.4\\ \\mathrm{W/(m\\,K)}.$$\n",
    "\n",
    "| face | condition |\n",
    "|---|---|\n",
    "| `front`, $z=0$ | insulated (the light passes it; convection to air neglected) |\n",
    "| `back`, $z=1$ mm | on a heat sink at 20 °C |\n",
    "| `edges` | insulated |\n",
    "\n",
    "The slab (60 mm × 60 mm) comes from the CAD file `beer_lambert_slab_heating.step`; the script\n",
    "`beer_lambert_slab_heating_geometry.py` builds it with the CAD objects of OneSimulation.\n",
    "\n",
    "**Reference.** All absorbed power must reach the heat sink:\n",
    "$P_{abs}=P\\,(1-e^{-\\alpha d})$ (the beam is much narrower than the slab). On the beam axis the\n",
    "beam is 20 times wider than the slab is thick, so the heat flows almost straight to the back,\n",
    "and the one-dimensional solution of $-kT''=\\alpha I_0e^{-\\alpha z}$ with $T'(0)=0$, $T(d)=T_s$,\n",
    "\n",
    "$$T(z)=T_s+\\frac{I_0}{k}\\Big[(d-z)-\\frac{e^{-\\alpha z}-e^{-\\alpha d}}{\\alpha}\\Big],$$\n",
    "\n",
    "holds up to the small sideways conduction, of relative order $2d^2/w^2=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, Piecewise, StructuredHexahedralMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.physics.heat_transfer import FixedTemperature, HeatConduction, HeatFlux\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 the slab with its named faces. The hexahedra are 1.5 mm wide under the beam and\n",
    "grow towards the edges; six layers through the thickness, finer at the front, resolve the\n",
    "exponential absorption."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "slab = load(\"beer_lambert_slab_heating.step\")\n",
    "faces = slab.boundaries\n",
    "(x0, _, _), (x1, _, thickness) = slab.bounding_box\n",
    "across = Piecewise(\n",
    "    (\n",
    "        (-0.015 - x0, Geometric(5, first=0.0015, toward=\"end\")),\n",
    "        (0.03, Geometric(20, ratio=1.0)),\n",
    "        (x1 - 0.015, Geometric(5, first=0.0015)),\n",
    "    )\n",
    ")\n",
    "grading = (across, across, Piecewise(((thickness, Geometric(6, ratio=3.0)),)))\n",
    "mesh = StructuredHexahedralMesher(\n",
    "    cells=tuple(g.cells for g in grading), grading=grading\n",
    ").generate(slab)\n",
    "\n",
    "view = plots.Camera(elevation=35, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(15, 5.5))\n",
    "plots.geometry(\n",
    "    slab,\n",
    "    selection={\n",
    "        \"irradiated front\": faces.front,\n",
    "        \"back on the heat sink\": faces.back,\n",
    "        \"edges\": faces.edges,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Slab 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, a function of position."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "power, beam, absorption, sink = 10.0, 0.010, 2000.0, 293.15\n",
    "peak = 2 * power / (np.pi * beam**2)\n",
    "glass = IsotropicSolid(\n",
    "    density=2500.0,\n",
    "    specific_heat_capacity=800.0,\n",
    "    thermal_conductivity=1.4,\n",
    "    youngs_modulus=7e10,\n",
    "    poisson_ratio=0.22,\n",
    "    thermal_expansion_coefficient=9e-6,\n",
    ")\n",
    "model = HeatConduction(\n",
    "    domain=slab.volume,\n",
    "    material=glass,\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=\"Beer-Lambert heating\",\n",
    "    geometry=slab,\n",
    "    physics=(model,),\n",
    "    boundary_conditions=(\n",
    "        FixedTemperature(boundary=faces.back, physics=model, value=sink),\n",
    "        HeatFlux(boundary=faces.front | faces.edges, physics=model, value=0.0),\n",
    "    ),\n",
    ")\n",
    "temperature = (\n",
    "    Simulation(\n",
    "        problem=problem,\n",
    "        mesh=mesh,\n",
    "        numerics=Numerics(\n",
    "            spatial=FiniteElement(element=Lagrange(order=2)),\n",
    "            linear_solver=SparseDirect(),\n",
    "        ),\n",
    "    )\n",
    "    .solve_stationary()\n",
    "    .field(model.temperature)\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "absorbed = power * (1 - np.exp(-absorption * thickness))\n",
    "k = glass.thermal_conductivity\n",
    "axis_exact = lambda z: sink + peak / k * (\n",
    "    (thickness - z)\n",
    "    - (np.exp(-absorption * z) - np.exp(-absorption * thickness)) / absorption\n",
    ")\n",
    "z = np.linspace(0, thickness, 101)\n",
    "axis = temperature.evaluate(\n",
    "    np.column_stack((np.zeros_like(z), np.zeros_like(z), z))\n",
    ").ravel()\n",
    "print(\n",
    "    f\"absorbed power: Beer-Lambert {absorbed:.4f} W, heat into the sink {temperature.boundary_flux(faces.back):.4f} W\"\n",
    ")\n",
    "print(\n",
    "    f\"front temperature on the axis: simulation {axis[0] - 273.15:.3f} °C, one-dimensional solution {axis_exact(0.0) - 273.15:.3f} °C \"\n",
    "    f\"({100 * (axis[0] - axis_exact(0.0)) / (axis_exact(0.0) - sink):+.2f} % of the rise)\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The temperature of the front face, a section through the beam axis (thickness drawn ten times\n",
    "enlarged), and the temperature through the slab on the axis."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "celsius = lambda T, position: T - 273.15\n",
    "r = np.linspace(-0.03, 0.03, 301)\n",
    "fig = plots.figure(layout=[[\"front\", \"axis\"], [\"section\", \"section\"]], size=(16, 10))\n",
    "plots.surface(\n",
    "    temperature,\n",
    "    boundary=faces.front,\n",
    "    component=celsius,\n",
    "    limits=(20, 50),\n",
    "    contours=7,\n",
    "    subdivisions=2,\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"y [m]\",\n",
    "    label=\"T [°C]\",\n",
    "    title=\"Front face under the beam\",\n",
    "    ax=fig[\"front\"],\n",
    ")\n",
    "plots.line(\n",
    "    points={\"simulation\": (1e3 * z[::5], axis[::5] - 273.15)},\n",
    "    reference={\"one-dimensional solution\": (1e3 * z, axis_exact(z) - 273.15)},\n",
    "    xlabel=\"depth z [mm]\",\n",
    "    ylabel=\"T on the beam axis [°C]\",\n",
    "    title=\"Through the slab on the axis\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[\"axis\"],\n",
    ")\n",
    "plots.section(\n",
    "    temperature,\n",
    "    plane=Plane(origin=(0, 0, 0), normal=(0, 1, 0)),\n",
    "    component=celsius,\n",
    "    limits=(20, 50),\n",
    "    contours=16,\n",
    "    subdivisions=2,\n",
    "    aspect=10.0,\n",
    "    xlimits=(-0.025, 0.025),\n",
    "    label=\"T [°C]\",\n",
    "    title=\"Section through the beam axis (thickness drawn ten times enlarged)\",\n",
    "    ax=fig[\"section\"],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Raise the absorption coefficient: the heat is released ever closer to the front and the slab\n",
    "behaves like a surface-heated plate. Or let the front lose heat by convection to air\n",
    "(`ConvectiveHeatFlux`) and narrow the beam, so that sideways conduction takes over."
   ]
  }
 ]
}
