{
 "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": [
    "# Gaussian pulse and perfectly matched layers\n",
    "\n",
    "A Gaussian pressure pulse of half-width 30 mm is released at rest in air. It spreads as a\n",
    "cylindrical wave. To imitate open space, the computational square ends in **perfectly matched\n",
    "layers** (PML): strips in which the wave is damped without being reflected at their entrance.\n",
    "\n",
    "The acoustic equations for pressure and velocity are solved with staggered finite differences\n",
    "and the classical Runge-Kutta method. By symmetry one quarter of the square is computed, with\n",
    "reflecting walls on the two symmetry lines.\n",
    "\n",
    "The quarter of the air volume comes from the CAD file `gaussian_pulse_pml.step`, written by\n",
    "`gaussian_pulse_pml_geometry.py` with the CAD objects of OneSimulation. The model lives on its\n",
    "cross-section, a square of 0.36 m whose sides keep the names `x_min`, `x_max`, `y_min`, `y_max`.\n",
    "\n",
    "**Reference.** In free space the pulse $p_0e^{-\\beta r^2}$ evolves as the Hankel integral\n",
    "\n",
    "$$p(r,t)=\\frac{p_0}{2\\beta}\\int_0^\\infty e^{-k^2/4\\beta}\\,\\cos(ckt)\\,J_0(kr)\\,k\\,\\mathrm dk .$$"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.meshing import cartesian\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.time import ClassicalRungeKutta4\n",
    "from onesim.physics.acoustics import (\n",
    "    AcousticPML,\n",
    "    LinearAcoustics,\n",
    "    StaggeredAcousticDifference,\n",
    ")\n",
    "from onesim.simulation import Problem, ReflectingWall, Simulation\n",
    "from onesim.simulation.initial_conditions import InitialValue\n",
    "from onesim.visualization import plots, theme\n",
    "from scipy.special import j0, roots_legendre\n",
    "\n",
    "theme.set()\n",
    "\n",
    "sound_speed, half_width, inner, spacing = 343.0, 0.030, 0.30, 0.003\n",
    "beta = np.log(2) / half_width**2"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`section` cuts the loaded solid at half thickness. The square is 0.36 m wide; the inner 0.30 m\n",
    "are evaluated, and the outer cells hold the layer."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "air_volume = load(\"gaussian_pulse_pml.step\")\n",
    "square = air_volume.section((0, 0, 1), origin=(0, 0, 0.005))\n",
    "side = square.size[0]\n",
    "cells = round(side / spacing)\n",
    "mesh = cartesian(\n",
    "    shape=(cells, cells),\n",
    "    extents=(side, side),\n",
    "    geometry=square,\n",
    "    periodic=False,\n",
    "    max_candidate_cells=10**6,\n",
    ")\n",
    "\n",
    "fig = plots.figure(1, 2, size=(13, 4.5))\n",
    "plots.geometry(air_volume, labels=False, title=\"Quarter of the air volume\", ax=fig[0])\n",
    "plots.geometry(square, title=\"Cross-section with its named sides\", ax=fig[1])\n",
    "plots.show()\n",
    "\n",
    "\n",
    "def exact_pressure(r, t):\n",
    "    \"\"\"Free-space pressure of the pulse at the radii r and the time t.\"\"\"\n",
    "    nodes, weights = roots_legendre(1600)\n",
    "    k = 0.5 * np.sqrt(160 * beta) * (nodes + 1)\n",
    "    amplitude = (\n",
    "        np.exp(-(k**2) / (4 * beta))\n",
    "        * k\n",
    "        * 0.5\n",
    "        * np.sqrt(160 * beta)\n",
    "        * weights\n",
    "        / (2 * beta)\n",
    "    )\n",
    "    return j0(np.outer(np.ravel(r), k)) @ (amplitude * np.cos(sound_speed * k * t))"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Simulation\n",
    "\n",
    "The outermost `layer` cells on the two outer sides are PML; without a layer the outer sides are\n",
    "plain reflecting walls."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "def simulate(layer):\n",
    "    \"\"\"Pressure history of the pulse with a PML of `layer` cells (0: reflecting walls).\"\"\"\n",
    "    air = LinearAcoustics(\n",
    "        domain=square.domain(), density=1.204, sound_speed=sound_speed\n",
    "    )\n",
    "    problem = Problem(\n",
    "        name=\"Gaussian pulse\",\n",
    "        geometry=square,\n",
    "        physics=(air,),\n",
    "        boundary_conditions=(\n",
    "            ReflectingWall(boundary=square.boundaries.all, physics=air),\n",
    "        ),\n",
    "        initial_conditions=(\n",
    "            InitialValue(air.pressure, lambda x, y: np.exp(-beta * (x**2 + y**2))),\n",
    "            InitialValue(air.velocity, (0.0, 0.0)),\n",
    "        ),\n",
    "    )\n",
    "    pml = (\n",
    "        AcousticPML(((0, layer), (0, layer)), target_reflection=1e-4) if layer else None\n",
    "    )\n",
    "    numerics = Numerics(\n",
    "        spatial=StaggeredAcousticDifference(pml=pml),\n",
    "        time_integrator=ClassicalRungeKutta4(),\n",
    "    )\n",
    "    step = 0.25 * spacing / sound_speed\n",
    "    return (\n",
    "        Simulation(problem=problem, mesh=mesh, numerics=numerics)\n",
    "        .run(start_time=0.0, end_time=1200 * step, time_step=step)\n",
    "        .field(air.pressure)\n",
    "    )\n",
    "\n",
    "\n",
    "runs = {layer: simulate(layer) for layer in (0, 5, 10, 20)}\n",
    "pressure = runs[20]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "While the pulse crosses the square, the field with the 20-cell layer is compared with the\n",
    "exact solution. After 2 ms the pulse has left; any difference to the free-space solution in the\n",
    "inner 0.30 m was reflected by the outer sides."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "axis = (np.arange(round(inner / spacing)) + 0.5) * spacing\n",
    "grid = np.array([[x, y] for x in axis for y in axis])\n",
    "radius = np.hypot(*grid.T)\n",
    "times = pressure.times\n",
    "nearest = lambda field, t: float(field.times[np.argmin(np.abs(field.times - t))])\n",
    "snapshot = lambda field, t: field.evaluate(grid, time=nearest(field, t))\n",
    "for t in (0.5e-3, 0.8e-3):\n",
    "    deviation = np.abs(\n",
    "        snapshot(pressure, t) - exact_pressure(radius, nearest(pressure, t))\n",
    "    ).max()\n",
    "    print(\n",
    "        f\"t = {1e3 * t:.1f} ms: largest deviation from the exact solution {deviation:.4f} of the initial peak\"\n",
    "    )\n",
    "reflected = {\n",
    "    layer: np.abs(\n",
    "        snapshot(field, 2.0e-3) - exact_pressure(radius, nearest(field, 2.0e-3))\n",
    "    ).max()\n",
    "    for layer, field in runs.items()\n",
    "}\n",
    "for layer, value in reflected.items():\n",
    "    print(\n",
    "        f\"{'reflecting walls' if layer == 0 else f'PML of {layer:2d} cells':17s} largest deviation from free space after 2 ms: {value:.1e}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The pulse inside the square and while it leaves through the layer, the pressure at a point near\n",
    "the layer over time, and the reflected pressure against the layer thickness."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "probe = [[0.27, 0.0015]]\n",
    "signals = {\n",
    "    (\"reflecting walls\" if layer == 0 else f\"PML, {layer} cells\"): (\n",
    "        1e3 * times,\n",
    "        field.time_series(probe)[1].ravel(),\n",
    "    )\n",
    "    for layer, field in runs.items()\n",
    "    if layer in (0, 20)\n",
    "}\n",
    "free_space = np.array([exact_pressure(np.hypot(*probe[0]), t)[0] for t in times[::10]])\n",
    "\n",
    "fig = plots.figure(2, 2, size=(13, 11))\n",
    "for panel, t in zip((fig[0], fig[1]), (0.5e-3, 0.8e-3)):\n",
    "    plots.heatmap(\n",
    "        axis,\n",
    "        axis,\n",
    "        snapshot(pressure, t).reshape(len(axis), len(axis)).T,\n",
    "        colormap=\"diverging\",\n",
    "        centre=0.0,\n",
    "        label=\"pressure / initial peak\",\n",
    "        xlabel=\"x [m]\",\n",
    "        ylabel=\"y [m]\",\n",
    "        title=f\"Pressure after {1e3 * t:.1f} ms\",\n",
    "        ax=panel,\n",
    "    )\n",
    "plots.line(\n",
    "    y=signals,\n",
    "    reference={\"exact, free space\": (1e3 * times[::10], free_space)},\n",
    "    xlabel=\"time [ms]\",\n",
    "    ylabel=\"pressure at 0.27 m / initial peak\",\n",
    "    title=\"Near the outer side: the wall reflects, the layer does not\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.bars(\n",
    "    [(\"walls\" if layer == 0 else f\"{layer} cells\") for layer in reflected],\n",
    "    list(reflected.values()),\n",
    "    scale=\"log\",\n",
    "    ylabel=\"reflected pressure after 2 ms / initial peak\",\n",
    "    title=\"Reflection against the layer thickness\",\n",
    "    ax=fig[3],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Lower the target reflection of the layer or make it thinner than five cells to see where it\n",
    "stops working; release the pulse off centre, so that the wave meets the layer at a shallow\n",
    "angle."
   ]
  }
 ]
}
