{
 "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": [
    "# Double-slit diffraction of sound\n",
    "\n",
    "Young's double-slit experiment with sound: two waveguides of width $w=50$ mm, whose centres are\n",
    "$d=300$ mm apart, carry the same plane wave to two slits in a rigid screen. Behind the screen the\n",
    "two slit waves overlap; where their path difference is a whole number of wavelengths they add,\n",
    "where it is half a wavelength they cancel. The model is two-dimensional (a cut through long\n",
    "slits); the pressure obeys\n",
    "\n",
    "$$\\nabla\\cdot\\Big(\\frac1{\\rho_0}\\nabla p\\Big)+\\frac{\\omega^2}{\\rho_0c^2}\\,p=0 .$$\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| inlets of the two guides | incoming plane wave $p_\\mathrm{in}=1$ Pa, reflected wave absorbed: $v_n=(p-2p_\\mathrm{in})/(\\rho_0c)$ |\n",
    "| guide walls and screen | rigid, $\\partial p/\\partial n=0$ |\n",
    "| half circle of radius $R=1$ m | outgoing cylindrical wave, $v_n=-i\\,\\dfrac{H_1^{(2)}(kR)}{H_0^{(2)}(kR)}\\,\\dfrac{p}{\\rho_0c}$ |\n",
    "\n",
    "The condition on the half circle is exact for the circularly symmetric part of the outgoing\n",
    "wave; the directional part leaves a small reflection of order $1/(kR)^2\\approx10^{-3}$.\n",
    "\n",
    "**Reference.** If each slit moves the air uniformly, Rayleigh's integral gives the field behind\n",
    "the screen exactly (P. M. Morse and K. U. Ingard, *Theoretical Acoustics*, §7.4):\n",
    "\n",
    "$$p(\\mathbf x)\\propto\\int_\\mathrm{slits}H_0^{(2)}\\big(k\\,|\\mathbf x-\\mathbf x'|\\big)\\,\\mathrm dx' ,$$\n",
    "\n",
    "and far away it becomes the Fraunhofer pattern of the double slit (M. Born and E. Wolf,\n",
    "*Principles of Optics*, §8.6),\n",
    "\n",
    "$$\\frac{|p(\\theta)|}{|p(0)|}=\\Big|\\cos\\Big(\\frac{kd\\sin\\theta}{2}\\Big)\\Big|\\,\n",
    "  \\Big|\\frac{\\sin(kw\\sin\\theta/2)}{kw\\sin\\theta/2}\\Big| ,$$\n",
    "\n",
    "with minima at $\\sin\\theta=(m+\\tfrac12)\\lambda/d$. The pattern is computed for $d=2\\lambda$,\n",
    "$3\\lambda$ and $4\\lambda$ (2287, 3430 and 4573 Hz)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.meshing import TriangularMesher\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange\n",
    "from onesim.physics.acoustics import (\n",
    "    AcousticHarmonicPressure,\n",
    "    ComplexPressurePencil,\n",
    "    ConstantPressureForms,\n",
    "    PressureAdmittanceBoundary,\n",
    "    PressureTraceSamples,\n",
    "    SampledPressureAdmittanceForms,\n",
    "    SampledPressureVolumeForms,\n",
    "    pressure_space_volume_samples,\n",
    ")\n",
    "from onesim.visualization import plots, theme\n",
    "from scipy.sparse.linalg import spsolve\n",
    "from scipy.special import hankel2\n",
    "\n",
    "theme.set()\n",
    "\n",
    "c0, rho0, incident = 343.0, 1.204, 1.0\n",
    "impedance = rho0 * c0\n",
    "width, spacing = 0.05, 0.30\n",
    "ratios = np.array([2.0, 3.0, 4.0])\n",
    "frequencies = ratios * c0 / spacing"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`load` reads the plate of air written by `double_slit_diffraction_geometry.py`; `section` cuts it\n",
    "at half thickness and keeps the face names. The triangles are an eighth of the shortest wavelength\n",
    "(9.4 mm) and shrink to 1.5 mm at the four slit edges."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "air = load(\"double_slit_diffraction.step\")\n",
    "plane = air.section((0, 0, 1), origin=(0, 0, 0.005))\n",
    "faces = plane.boundaries\n",
    "outer = plane.size[0] / 2\n",
    "edges = np.array(\n",
    "    [\n",
    "        [x, 0.0]\n",
    "        for x in (\n",
    "            -spacing / 2 - width / 2,\n",
    "            -spacing / 2 + width / 2,\n",
    "            spacing / 2 - width / 2,\n",
    "            spacing / 2 + width / 2,\n",
    "        )\n",
    "    ]\n",
    ")\n",
    "h = c0 / frequencies.max() / 8\n",
    "mesh = TriangularMesher(\n",
    "    target_size=h,\n",
    "    size_field=lambda p: np.minimum(\n",
    "        h,\n",
    "        0.0015 + 0.25 * np.min(np.linalg.norm(p[:, None, :2] - edges, axis=2), axis=1),\n",
    "    ),\n",
    ").generate(plane)\n",
    "\n",
    "view = plots.Camera(elevation=60, azimuth=-90)\n",
    "fig = plots.figure(1, 2, size=(16, 6))\n",
    "plots.geometry(\n",
    "    air,\n",
    "    selection={\n",
    "        \"inlets\": air.boundaries.inlet,\n",
    "        \"guide walls\": air.boundaries.guide,\n",
    "        \"screen\": air.boundaries.screen,\n",
    "        \"outer half circle\": air.boundaries.outer,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Air volume (STEP)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Cross-section: {mesh.cell_count} quadratic triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "Quadratic Lagrange elements; `SampledPressureVolumeForms` integrates the volume forms, and the\n",
    "boundary traces of the inlets and of the half circle come from the space's `trace_data`. The\n",
    "inlets carry the admittance $1/\\rho_0c$ and the load $2i\\omega p_\\mathrm{in}/(\\rho_0c)\\int\\phi_i\\,\n",
    "\\mathrm dS$ of the incoming wave, the half circle the cylindrical-wave admittance.\n",
    "`AcousticHarmonicPressure` solves the three frequencies."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "space = FiniteElement(element=Lagrange(order=2)).bind_space(mesh)\n",
    "volume = ConstantPressureForms(\n",
    "    *SampledPressureVolumeForms(\n",
    "        size=space.dof_count,\n",
    "        samples=lambda: pressure_space_volume_samples(space),\n",
    "        inverse_density=lambda omega, sample: 1 / rho0,\n",
    "        compressibility=lambda omega, sample: 1 / impedance / c0,\n",
    "    )(0.0)\n",
    ")\n",
    "traces = {\n",
    "    face: SampledPressureAdmittanceForms(\n",
    "        size=space.dof_count,\n",
    "        admittance=lambda omega, sample: 1.0,\n",
    "        samples=lambda face=face: iter(\n",
    "            [\n",
    "                PressureTraceSamples(space.cell_dofs[owner], points, weights, basis)\n",
    "                for owner, points, weights, _, basis, _ in map(\n",
    "                    space.trace_data, mesh.facets(getattr(faces, face))\n",
    "                )\n",
    "            ]\n",
    "        ),\n",
    "    )(0.0)\n",
    "    for face in (\"inlet\", \"outer\")\n",
    "}\n",
    "cylindrical = (\n",
    "    lambda omega: -1j\n",
    "    * hankel2(1, omega * outer / c0)\n",
    "    / hankel2(0, omega * outer / c0)\n",
    "    / impedance\n",
    ")\n",
    "boundary = PressureAdmittanceBoundary(\n",
    "    lambda omega: traces[\"inlet\"] / impedance + cylindrical(omega) * traces[\"outer\"]\n",
    ")\n",
    "result = AcousticHarmonicPressure(\n",
    "    operator=ComplexPressurePencil(volume, boundary=boundary),\n",
    "    angular_frequencies=2 * np.pi * frequencies,\n",
    "    load=lambda omega: 2j\n",
    "    * omega\n",
    "    * incident\n",
    "    / impedance\n",
    "    * (traces[\"inlet\"] @ np.ones(space.dof_count)),\n",
    "    linear_solver=spsolve,\n",
    ").run()\n",
    "print(f\"{space.dof_count} pressure unknowns, {mesh.cell_count} triangles\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Reference\n",
    "\n",
    "Rayleigh's integral over the two slits with 64 Gauss points across each slit."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "nodes, weights = np.polynomial.legendre.leggauss(64)\n",
    "sources = np.concatenate(\n",
    "    [centre + width / 2 * nodes for centre in (-spacing / 2, spacing / 2)]\n",
    ")\n",
    "rayleigh = lambda omega, points: hankel2(\n",
    "    0, omega / c0 * np.hypot(points[:, :1] - sources, points[:, 1:])\n",
    ") @ np.tile(weights, 2)\n",
    "fraunhofer = lambda ratio, theta: np.abs(\n",
    "    np.cos(np.pi * ratio * np.sin(theta))\n",
    "    * np.sinc(ratio * width / spacing * np.sin(theta))\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The pressure amplitude on a half circle of radius 0.9 m, normalised by its value straight ahead,\n",
    "against Rayleigh's integral at the same radius; and the angles of the interference minima up to 75°\n",
    "against the Fraunhofer rule. Towards grazing angles the computed field falls below the uniform-slit\n",
    "integral: the real slit velocity is not uniform but peaks at the edges, which matters most along\n",
    "the screen."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "theta = np.radians(np.linspace(-90.0, 90.0, 721))\n",
    "arc = 0.9 * np.column_stack((np.sin(theta), np.cos(theta)))\n",
    "ahead = theta.size // 2\n",
    "patterns, references = {}, {}\n",
    "on_arc = np.abs(np.asarray(space.evaluate(result.pressure.T, arc)))\n",
    "for ratio, omega, computed in zip(ratios, 2 * np.pi * frequencies, on_arc.T):\n",
    "    exact = np.abs(rayleigh(omega, arc))\n",
    "    patterns[ratio], references[ratio] = (\n",
    "        computed / computed[ahead],\n",
    "        exact / exact[ahead],\n",
    "    )\n",
    "    minima = [\n",
    "        i\n",
    "        for i in range(ahead, theta.size - 1)\n",
    "        if computed[i] < min(computed[i - 1], computed[i + 1])\n",
    "        and theta[i] < np.radians(75)\n",
    "    ]\n",
    "    fraunhofer_minima = np.degrees(np.arcsin((np.arange(len(minima)) + 0.5) / ratio))\n",
    "    level = 20 * np.log10(patterns[ratio] / references[ratio])\n",
    "    print(\n",
    "        f\"d = {ratio:.0f} wavelengths ({omega / (2 * np.pi):.0f} Hz): minima at \"\n",
    "        + \", \".join(f\"{np.degrees(theta[i]):.2f}\" for i in minima)\n",
    "        + \" deg; Fraunhofer \"\n",
    "        + \", \".join(f\"{m:.2f}\" for m in fraunhofer_minima)\n",
    "        + f\" deg; level against Rayleigh's integral within 60 deg of the axis where the pattern is above -20 dB: largest deviation \"\n",
    "        f\"{np.max(np.abs(level[(patterns[ratio] > 0.1) & (np.abs(theta) <= np.radians(60))])):.2f} dB, beyond 60 deg \"\n",
    "        f\"{np.max(np.abs(level[np.abs(theta) > np.radians(60)])):.2f} dB\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The instantaneous pressure behind the screen at $d=3\\lambda$, with the bright and dark fringes,\n",
    "and the three interference patterns against Rayleigh's integral (dashed) and Fraunhofer's far\n",
    "field (dots)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "pressure = result.pressure[1][: mesh.node_count].real\n",
    "x, y = np.asarray(mesh.coordinates).T\n",
    "fig = plots.figure(layout=[[\"field\", \"field\"], [\"p0\", \"p1\"]], size=(16, 14))\n",
    "plots.heatmap(\n",
    "    x,\n",
    "    y,\n",
    "    pressure,\n",
    "    triangles=np.asarray(mesh.cells),\n",
    "    colormap=\"diverging\",\n",
    "    limits=(-0.6, 0.6),\n",
    "    label=\"pressure [Pa]\",\n",
    "    title=f\"Pressure at {frequencies[1]:.0f} Hz (d = 3 wavelengths), incoming wave 1 Pa\",\n",
    "    ax=fig[\"field\"],\n",
    ")\n",
    "plots.line(\n",
    "    np.degrees(theta),\n",
    "    {f\"d = {ratio:.0f} wavelengths\": patterns[ratio] for ratio in ratios},\n",
    "    reference={f\"d = {ratio:.0f} wavelengths\": references[ratio] for ratio in ratios},\n",
    "    xlabel=\"angle from the axis [deg]\",\n",
    "    ylabel=\"|p| / |p(0)| at 0.9 m\",\n",
    "    title=\"Interference patterns (dashed: Rayleigh integral)\",\n",
    "    legend=\"lower center\",\n",
    "    ylimits=(0, 1.35),\n",
    "    ax=fig[\"p0\"],\n",
    ")\n",
    "plots.line(\n",
    "    np.degrees(theta),\n",
    "    {\"d = 3 wavelengths\": patterns[3.0]},\n",
    "    reference={\"d = 3 wavelengths\": references[3.0]},\n",
    "    points={\n",
    "        \"Fraunhofer far field\": (np.degrees(theta[::12]), fraunhofer(3.0, theta[::12]))\n",
    "    },\n",
    "    scale=\"logy\",\n",
    "    ylimits=(1e-2, 2),\n",
    "    xlabel=\"angle from the axis [deg]\",\n",
    "    ylabel=\"|p| / |p(0)| at 0.9 m\",\n",
    "    title=\"d = 3 wavelengths, logarithmic\",\n",
    "    legend=\"lower center\",\n",
    "    ax=fig[\"p1\"],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Close one slit in `double_slit_diffraction_geometry.py` (drop one guide) and write the STEP file\n",
    "again: the fringes vanish and the single-slit envelope remains. Widen the slits towards a\n",
    "wavelength to see the envelope's own zeros suppress interference orders."
   ]
  }
 ]
}
