{
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "name": "python3",
   "language": "python",
   "display_name": "Python 3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Measuring thermal conductivity with a laser flash\n",
    "\n",
    "Heat the front of a thin disc, then watch the back. For an insulated specimen after an instantaneous flash, the rear face reaches half of its final rise at $t_{1/2}=0.1388 L^2/\\alpha$. This experiment uses a finite pulse. We compare a freely suspended sample with a disc in thermal contact with a cold ring, then infer conductivity from their rear-centre signals."
   ],
   "id": "markdown-01"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.d3 import Box\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import IsotropicSolid\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 SparseDirect\n",
    "from onesim.numerics.time import BDF, BackwardEuler\n",
    "from onesim.physics.heat_transfer import ConvectiveHeatFlux, 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",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "code-02"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The specimen and its meridian\n",
    "\n",
    "A radial half-section of the STEP disc gives the computational domain. Rotating this section about the vertical axis weights each element by $2\\pi r$."
   ],
   "id": "markdown-03"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "disc = load(\"flash_method_axisymmetric.step\")\n",
    "radius, thickness = disc.size[0] / 2, disc.size[2]\n",
    "half = disc & Box(length=radius, width=2*radius, height=thickness, origin=(0, -radius, 0))\n",
    "plane = half.section((0, 1, 0), origin=(0, 0, 0))\n",
    "front = plane.select(edges=lambda e: all(abs(p[1]) < 1e-8 for p in e.points))\n",
    "rim = plane.select(edges=lambda e: all(abs(p[0] - radius) < 1e-8 for p in e.points))\n",
    "back_and_axis = plane.select(edges=lambda e: all(abs(p[1] - thickness) < 1e-8 for p in e.points) or all(abs(p[0]) < 1e-8 for p in e.points))\n",
    "mesh = TriangularMesher(target_size=thickness / 12).generate(plane)\n",
    "print(f\"Mesh: {len(mesh.coordinates):,} nodes, {mesh.cell_count:,} elements\")\n",
    "fig = plots.figure(1, 2, size=(12, 4.3))\n",
    "plots.geometry(disc, selection={\"flashed face\": disc.boundaries.front, \"observed face\": disc.boundaries.rear},\n",
    "               camera=plots.Camera(elevation=22, azimuth=-52), labels=False, title=\"The 12.7 mm specimen\", ax=fig[0])\n",
    "plots.mesh(mesh, groups=(\"all\",), legend=False, title=\"Axisymmetric meridian mesh\", ax=fig[1])\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "code-04"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Flash the front face\n",
    "\n",
    "A raised-cosine pulse with a duration of 20 ms deposits enough energy for a mean rise of 1 K. In the second mounting, a contact conductance of 6000 W/(m² K) carries heat from the rim into a holder at the initial temperature. The two flat faces are otherwise insulated."
   ],
   "id": "markdown-05"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "rho, cp, conductivity = 2700.0, 900.0, 20.0\n",
    "diffusivity = conductivity / (rho * cp)\n",
    "duration, baseline = 0.020, 295.0\n",
    "fluence = rho * cp * thickness * 1.0\n",
    "def outward_flux(t):\n",
    "    return -2 * fluence / duration * np.sin(np.pi * np.clip(t / duration, 0, 1))**2\n",
    "\n",
    "solid = IsotropicSolid(density=rho, specific_heat_capacity=cp, thermal_conductivity=conductivity,\n",
    "                       youngs_modulus=70e9, poisson_ratio=0.30, thermal_expansion_coefficient=1e-5)\n",
    "heat = HeatConduction(domain=plane.domain(), material=solid)\n",
    "flash = HeatFlux(physics=heat, boundary=front, value=outward_flux)\n",
    "insulation = HeatFlux(physics=heat, boundary=back_and_axis, value=0)\n",
    "insulated_rim = HeatFlux(physics=heat, boundary=rim, value=0)\n",
    "holder = ConvectiveHeatFlux(physics=heat, boundary=rim, heat_transfer_coefficient=6000, ambient_temperature=baseline)\n",
    "numerics = Numerics(spatial=FiniteElement(element=Lagrange(order=2), provider=RevolvedH1SpaceFactory()),\n",
    "                    time_integrator=BDF(order=2, startup=BackwardEuler()), linear_solver=SparseDirect())\n",
    "fields, traces = {}, {}\n",
    "for name, conditions in ((\"Insulated\", (flash, insulation, insulated_rim)), (\"Cold ring\", (flash, insulation, holder))):\n",
    "    problem = Problem(name=name, geometry=plane, physics=(heat,), boundary_conditions=conditions,\n",
    "                      initial_conditions=(InitialValue(heat.temperature, baseline),))\n",
    "    field = Simulation(problem=problem, mesh=mesh, numerics=numerics).run(\n",
    "        start_time=0.0, end_time=0.48, time_step=0.001).field(heat.temperature)\n",
    "    times, rear = field.time_series([[0, thickness]])\n",
    "    fields[name], traces[name] = field, rear.ravel() - baseline"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "code-06"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Read the rear-face trace\n",
    "\n",
    "Compare the insulated solution with the Fourier series of Parker et al. (1961), averaged over the pulse. The inferred conductivity uses the interval from the pulse centroid to half the peak. It assumes negligible heat loss, so the cold-ring trace tests the effect of the fixture."
   ],
   "id": "markdown-07"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "nodes, weights = np.polynomial.legendre.leggauss(24)\n",
    "phase = (1 + nodes) / 2\n",
    "lag = (times[:, None] - duration * phase) * diffusivity / thickness**2\n",
    "modes = np.arange(1, 65)\n",
    "series = 1 + 2 * np.sum((-1.)**modes * np.exp(-np.maximum(lag, 0)[:, :, None] * (np.pi * modes)**2), axis=2)\n",
    "expected = np.where(lag > 0, series, 0) @ (weights * np.sin(np.pi * phase)**2)\n",
    "print(f\"Maximum insulated rear-face error: {np.max(np.abs(traces['Insulated'] - expected)):.4f} K\")\n",
    "for name, rise in traces.items():\n",
    "    peak = np.argmax(rise)\n",
    "    half_time = np.interp(rise[peak] / 2, rise[:peak + 1], times[:peak + 1])\n",
    "    estimate = 0.1388 * rho * cp * thickness**2 / (half_time - duration / 2)\n",
    "    print(f\"{name}: peak {rise[peak]:.4f} K, half-rise {half_time*1000:.2f} ms, conductivity {estimate:.3f} W/(m K)\")\n",
    "\n",
    "fig = plots.figure(1, 2, size=(13, 4.6))\n",
    "plots.surface(fields[\"Cold ring\"], time=0.20, component=lambda value, point: value - baseline,\n",
    "              length_unit=\"mm\", contours=8, label=\"Temperature rise [K]\", title=\"Heat loss at the rim after 200 ms\", ax=fig[0])\n",
    "plots.line(y={k: (times*1000, v) for k, v in traces.items()}, points={\"Parker series + pulse\": (times[::30]*1000, expected[::30])},\n",
    "           xlabel=\"Time [ms]\", ylabel=\"Rear-centre rise [K]\", title=\"Response to a 20 ms flash\", legend=\"lower right\", ax=fig[1])\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "code-08"
  }
 ]
}
