{
 "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": [
    "# Periodic surface temperature wave in a semi-infinite solid\n",
    "\n",
    "The surface of a thick body, for example the ground under the daily temperature cycle,\n",
    "oscillates about a mean value, $T_s(t)=T_m+A\\sin(\\omega t)$. Heat conduction carries this\n",
    "oscillation into the solid as a **damped thermal wave**: with depth the amplitude decays and the\n",
    "oscillation lags behind the surface.\n",
    "\n",
    "$$\\rho c_p\\,\\frac{\\partial T}{\\partial t}=k\\,\\frac{\\partial^2 T}{\\partial x^2},\\qquad\n",
    "  T(0,t)=T_m+A\\sin(\\omega t),\\qquad T(x\\to\\infty,t)=T_m .$$\n",
    "\n",
    "The soil column comes from the CAD file `periodic_surface_temperature_wave.step`; its surface is\n",
    "named `x_min`, its deep end `x_max`, and the four lateral faces form the group `sides`. The\n",
    "script `periodic_surface_temperature_wave_geometry.py` builds it with the CAD objects of\n",
    "OneSimulation, seven penetration depths long.\n",
    "\n",
    "**Reference.** With the diffusivity $\\alpha=k/(\\rho c_p)$ the periodic solution is\n",
    "\n",
    "$$T(x,t)-T_m=A\\,e^{-x/d}\\,\\sin\\!\\big(\\omega t-x/d\\big),\\qquad d=\\sqrt{\\frac{2\\alpha}{\\omega}} .$$\n",
    "\n",
    "The amplitude falls to $1/e$ and the phase lags by one radian per penetration depth $d$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import IsotropicSolid\n",
    "from onesim.meshing import 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.numerics.time import BDF, BackwardEuler\n",
    "from onesim.physics.heat_transfer import FixedTemperature, 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": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "column = load(\"periodic_surface_temperature_wave.step\")\n",
    "faces = column.boundaries\n",
    "length, cross, _ = column.size\n",
    "mesh = StructuredHexahedralMesher(cells=(64, 1, 1)).generate(column)\n",
    "\n",
    "fig = plots.figure(1, 2, size=(14, 4.5))\n",
    "plots.geometry(\n",
    "    column,\n",
    "    selection={\"surface\": faces.x_min, \"deep end\": faces.x_max},\n",
    "    labels=False,\n",
    "    title=\"Soil column with its surface and deep end\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh, groups=(\"all\",), legend=False, title=f\"{mesh.cell_count} hexahedra\", ax=fig[1]\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "Moist soil under a daily cycle of ±10 K. The surface follows the sinusoid, the deep end stays at\n",
    "the mean temperature and the sides are insulated. Quadratic elements in space, the second-order\n",
    "BDF method with 40 steps per day in time."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "soil = IsotropicSolid(\n",
    "    density=2000.0,\n",
    "    specific_heat_capacity=1000.0,\n",
    "    thermal_conductivity=1.0,\n",
    "    youngs_modulus=1e9,\n",
    "    poisson_ratio=0.3,\n",
    "    thermal_expansion_coefficient=1e-5,\n",
    ")\n",
    "mean, swing, period = 288.0, 10.0, 86400.0\n",
    "omega = 2 * np.pi / period\n",
    "depth = np.sqrt(\n",
    "    2 * soil.thermal_conductivity / (soil.density * soil.specific_heat_capacity) / omega\n",
    ")\n",
    "\n",
    "model = HeatConduction(domain=column.volume, material=soil, heating=0.0)\n",
    "problem = Problem(\n",
    "    name=\"Periodic surface temperature wave\",\n",
    "    geometry=column,\n",
    "    physics=(model,),\n",
    "    boundary_conditions=(\n",
    "        FixedTemperature(\n",
    "            boundary=faces.x_min,\n",
    "            physics=model,\n",
    "            value=lambda t: mean + swing * np.sin(omega * t),\n",
    "        ),\n",
    "        FixedTemperature(boundary=faces.x_max, physics=model, value=mean),\n",
    "        HeatFlux(boundary=faces.sides, physics=model, value=0.0),\n",
    "    ),\n",
    "    initial_conditions=(InitialValue(model.temperature, mean),),\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",
    "result = Simulation(problem=problem, mesh=mesh, numerics=numerics).run(\n",
    "    start_time=0.0, end_time=6 * period, time_step=period / 40\n",
    ")\n",
    "temperature = result.field(model.temperature)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Amplitude and phase lag\n",
    "\n",
    "The temperature along the column is recorded over the sixth day, when the start-up has died\n",
    "out. Projecting each depth's signal onto $e^{-i\\omega t}$ gives its amplitude and phase lag."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "x = np.linspace(0, 4 * depth, 81)\n",
    "times, signals = temperature.time_series(\n",
    "    np.column_stack((x, np.full_like(x, cross / 2), np.full_like(x, cross / 2)))\n",
    ")\n",
    "times, signals = times[-40:], signals[-40:] - mean\n",
    "wave = 2j * np.mean(signals * np.exp(-1j * omega * times)[:, None], axis=0)\n",
    "amplitude, lag = np.abs(wave), -np.unwrap(np.angle(wave))\n",
    "\n",
    "print(\n",
    "    f\"penetration depth d = {100 * depth:.2f} cm, column length {length / depth:.1f} d\"\n",
    ")\n",
    "print(\"depth    amplitude [K]   theory   phase lag [rad]   theory\")\n",
    "for index in (0, 10, 20, 40, 60):\n",
    "    print(\n",
    "        f\"{x[index] / depth:4.1f} d {amplitude[index]:14.3f} {swing * np.exp(-x[index] / depth):8.3f}\"\n",
    "        f\" {lag[index]:17.3f} {x[index] / depth:8.3f}\"\n",
    "    )\n",
    "print(\n",
    "    f\"penetration depth from the amplitude decay: {-100 / np.polyfit(x, np.log(amplitude), 1)[0]:.2f} cm, \"\n",
    "    f\"from the phase lag: {100 / np.polyfit(x, lag, 1)[0]:.2f} cm\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Amplitude and phase lag against depth, and the temperature over the sixth day at four depths."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "hours = (times - times[0]) / 3600\n",
    "picks = {\"surface\": 0, \"x = 0.5 d\": 10, \"x = d\": 20, \"x = 2 d\": 40}\n",
    "theory = {\n",
    "    label: mean + swing * np.exp(-x[i] / depth) * np.sin(omega * times - x[i] / depth)\n",
    "    for label, i in picks.items()\n",
    "}\n",
    "\n",
    "fig = plots.figure(1, 3, size=(16, 4.8))\n",
    "plots.line(\n",
    "    100 * x,\n",
    "    points={\"simulation\": (100 * x[::2], amplitude[::2])},\n",
    "    reference={\"A exp(-x/d)\": swing * np.exp(-x / depth)},\n",
    "    vlines={\"penetration depth d\": 100 * depth},\n",
    "    xlabel=\"depth [cm]\",\n",
    "    ylabel=\"temperature amplitude [K]\",\n",
    "    title=\"Amplitude\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    100 * x,\n",
    "    points={\"simulation\": (100 * x[::2], lag[::2])},\n",
    "    reference={\"x/d\": x / depth},\n",
    "    xlabel=\"depth [cm]\",\n",
    "    ylabel=\"phase lag [rad]\",\n",
    "    title=\"Phase lag\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    hours,\n",
    "    points={label: mean + signals[:, i] for label, i in picks.items()},\n",
    "    reference=theory,\n",
    "    xlabel=\"time within the sixth day [h]\",\n",
    "    ylabel=\"temperature [K]\",\n",
    "    title=\"Simulation (markers) and theory (dashed)\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Use the yearly cycle instead of the daily one: the penetration depth grows by $\\sqrt{365}$ to\n",
    "about two metres, so lengthen the column in `periodic_surface_temperature_wave_geometry.py` and\n",
    "write the STEP file again. Add a second soil layer with a different conductivity, or replace the\n",
    "fixed surface temperature by convection to the air."
   ]
  }
 ]
}
