{
 "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": [
    "# Schroeder diffuser\n",
    "\n",
    "M. R. Schroeder (*J. Acoust. Soc. Am.* 57, 149, 1975) proposed wells whose depths follow the\n",
    "quadratic-residue sequence $s_n=n^2\\bmod N$: at the design frequency $f_0$ a well of depth\n",
    "$d_n=s_n\\lambda_0/(2N)$ reflects with the phase $e^{-2ikd_n}$, and the Fourier transform of that\n",
    "phase pattern is flat - the reflected energy goes equally into all diffraction lobes. Here $N=7$,\n",
    "$f_0=500$ Hz, the wells are 45 mm wide between 5 mm fins, and the deepest is 196 mm. The model is\n",
    "two-dimensional (a cut across long wells); a plane wave falls perpendicularly on the wall.\n",
    "\n",
    "The field is split into the incident wave reflected by a flat rigid wall, $p_b=2p_0\\cos ky$, and\n",
    "the scattered wave $p_s=p-p_b$ that the wells add. The air is a half disc of radius $R=3$ m.\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| wall, fins and wells | rigid, $\\partial p/\\partial n=0$ |\n",
    "| half circle $r=R$ | $p_s$ outgoing: $v_n=-i\\,\\dfrac{H_1^{(2)}(kR)}{H_0^{(2)}(kR)}\\,\\dfrac{p-p_b}{\\rho_0c}$ |\n",
    "\n",
    "**Reference.** The standard design model of diffusers (T. J. Cox and P. D'Antonio, *Acoustic\n",
    "Absorbers and Diffusers*, 3rd ed., CRC Press 2017, ch. 9) treats the surface as locally\n",
    "reacting with the reflection factor $R(x)=e^{-2ikd(x)}$ and adds up its contributions in the\n",
    "Kirchhoff approximation,\n",
    "\n",
    "$$p_s(\\mathbf x)\\propto\\int_\\mathrm{diffuser}\\big(R(x')-1\\big)\\,\\frac{1+\\cos\\theta'}{2}\\,\n",
    "  H_0^{(2)}\\big(k\\,|\\mathbf x-\\mathbf x'|\\big)\\,\\mathrm dx' .$$\n",
    "\n",
    "It ignores the coupling between neighbouring wells and diffraction at the edges, so it is\n",
    "approximate: good near the design frequency and in the main lobes, worse at low frequency and\n",
    "towards grazing angles. As a summary number both are reduced to the diffusion coefficient\n",
    "$d=\\big[(\\sum_i I_i)^2-\\sum_i I_i^2\\big]/\\big[(n-1)\\sum_i I_i^2\\big]$ of the scattered intensities\n",
    "$I_i=|p_s|^2$ on $n$ equally spaced receivers (ISO 17497-2), 0 for a single direction and 1 for\n",
    "perfectly even scattering."
   ]
  },
  {
   "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",
    "cell, fin, unit = 0.05, 0.005, c0 / 500.0 / 14\n",
    "frequencies = np.array([250.0, 500.0, 1000.0, 2000.0])"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`load` reads the air in front of four periods and of one period of the diffuser; `section` cuts\n",
    "each at half thickness. The triangles are a sixth of the wavelength at 2 kHz (29 mm) in the open\n",
    "air and 8 mm in the wells."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "parts = {\n",
    "    \"4 periods\": load(\"schroeder_diffuser_scattering.step\"),\n",
    "    \"1 period\": load(\"schroeder_diffuser_scattering_single.step\"),\n",
    "}\n",
    "planes = {\n",
    "    name: part.section((0, 0, 1), origin=(0, 0, 0.005)) for name, part in parts.items()\n",
    "}\n",
    "outer = planes[\"1 period\"].size[0] / 2\n",
    "h = c0 / frequencies.max() / 6\n",
    "half_width = {\"4 periods\": 0.7, \"1 period\": 0.175}\n",
    "meshes = {\n",
    "    name: TriangularMesher(\n",
    "        target_size=h,\n",
    "        size_field=lambda p, w=half_width[name]: np.minimum(\n",
    "            h,\n",
    "            0.008\n",
    "            + 0.2\n",
    "            * np.hypot(np.maximum(np.abs(p[:, 0]) - w, 0.0), np.maximum(p[:, 1], 0.0)),\n",
    "        ),\n",
    "    ).generate(plane)\n",
    "    for name, plane in planes.items()\n",
    "}\n",
    "\n",
    "fig = plots.figure(1, 2, size=(16, 6))\n",
    "plots.geometry(\n",
    "    parts[\"4 periods\"],\n",
    "    selection={\n",
    "        \"wells\": parts[\"4 periods\"].boundaries.wells,\n",
    "        \"wall\": parts[\"4 periods\"].boundaries.wall,\n",
    "        \"outer half circle\": parts[\"4 periods\"].boundaries.outer,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=70, azimuth=-90),\n",
    "    title=\"Air in front of the diffuser, 4 periods (STEP)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[\"4 periods\"],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Cross-section, 4 periods: {meshes['4 periods'].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",
    "half circle carries the cylindrical-wave admittance $Y$ with the load\n",
    "$\\int\\big(\\rho_0^{-1}\\partial_np_b+i\\omega Yp_b\\big)\\phi_i\\,\\mathrm dS$ through which the incident\n",
    "wave enters. `AcousticHarmonicPressure` solves the four frequencies."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "def solve_diffuser(name):\n",
    "    \"\"\"Pressure at the four frequencies in front of one diffuser.\"\"\"\n",
    "    plane, mesh = planes[name], meshes[name]\n",
    "    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",
    "    rim = [\n",
    "        PressureTraceSamples(space.cell_dofs[owner], points, weights, basis)\n",
    "        for owner, points, weights, _, basis, _ in map(\n",
    "            space.trace_data, mesh.facets(plane.boundaries.outer)\n",
    "        )\n",
    "    ]\n",
    "    trace = SampledPressureAdmittanceForms(\n",
    "        size=space.dof_count,\n",
    "        samples=lambda: iter(rim),\n",
    "        admittance=lambda omega, sample: 1.0,\n",
    "    )(0.0)\n",
    "    admittance = (\n",
    "        lambda omega: -1j\n",
    "        * hankel2(1, omega.real * outer / c0)\n",
    "        / hankel2(0, omega.real * outer / c0)\n",
    "        / impedance\n",
    "    )\n",
    "    y = space.dof_coordinates[:, 1]\n",
    "    flat = lambda omega: 2 * incident * np.cos(omega.real / c0 * y)\n",
    "    flux = (\n",
    "        lambda omega: -2\n",
    "        * incident\n",
    "        * omega.real\n",
    "        / c0\n",
    "        * np.sin(omega.real / c0 * y)\n",
    "        * y\n",
    "        / outer\n",
    "    )\n",
    "    pressure = (\n",
    "        AcousticHarmonicPressure(\n",
    "            operator=ComplexPressurePencil(\n",
    "                volume,\n",
    "                boundary=PressureAdmittanceBoundary(\n",
    "                    lambda omega: admittance(omega) * trace\n",
    "                ),\n",
    "            ),\n",
    "            angular_frequencies=2 * np.pi * frequencies,\n",
    "            linear_solver=spsolve,\n",
    "            load=lambda omega: trace\n",
    "            @ (flux(omega) / rho0 + 1j * omega * admittance(omega) * flat(omega)),\n",
    "        )\n",
    "        .run()\n",
    "        .pressure\n",
    "    )\n",
    "    return dict(space=space, mesh=mesh, pressure=pressure)\n",
    "\n",
    "\n",
    "runs = {name: solve_diffuser(name) for name in planes}\n",
    "scattered = lambda name, points: np.asarray(\n",
    "    runs[name][\"space\"].evaluate(runs[name][\"pressure\"].T, points)\n",
    ") - 2 * incident * np.cos(2 * np.pi * frequencies / c0 * points[:, 1:2])"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Reference\n",
    "\n",
    "The Kirchhoff integral over the diffuser surface with 24 Gauss points across every well."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "nodes, weights = np.polynomial.legendre.leggauss(24)\n",
    "kirchhoff = {}\n",
    "for name, periods in ((\"4 periods\", 4), (\"1 period\", 1)):\n",
    "    left, width = -periods * 7 * cell / 2, cell - fin\n",
    "    wells = [\n",
    "        (left + i * cell + cell / 2, (i % 7) ** 2 % 7 * unit)\n",
    "        for i in range(7 * periods)\n",
    "    ]\n",
    "    x_source = np.concatenate([centre + width / 2 * nodes for centre, _ in wells])\n",
    "    depth = np.repeat([d for _, d in wells], len(nodes))\n",
    "    kirchhoff[name] = lambda points, f, x_source=x_source, depth=depth: (\n",
    "        (np.exp(-4j * np.pi * f / c0 * depth) - 1)\n",
    "        * np.tile(weights, len(depth) // len(weights))\n",
    "        * width\n",
    "        / 2\n",
    "        * (1 + points[:, 1:2] / np.hypot(points[:, :1] - x_source, points[:, 1:2]))\n",
    "        / 2\n",
    "        * hankel2(\n",
    "            0, 2 * np.pi * f / c0 * np.hypot(points[:, :1] - x_source, points[:, 1:2])\n",
    "        )\n",
    "    ).sum(axis=1)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "Polar responses on a half circle of radius 2.8 m, normalised by their maximum, the level\n",
    "difference to the Kirchhoff model in the main lobes, and the diffusion coefficients."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "theta = np.radians(np.linspace(-90.0, 90.0, 37))\n",
    "receivers = 2.8 * np.column_stack((np.sin(theta), np.cos(theta)))\n",
    "fine_theta = np.radians(np.linspace(-90.0, 90.0, 361))\n",
    "ring = 2.8 * np.column_stack((np.sin(fine_theta), np.cos(fine_theta)))\n",
    "diffusion = lambda values: (np.sum(values) ** 2 - np.sum(values**2)) / (\n",
    "    (len(values) - 1) * np.sum(values**2)\n",
    ")\n",
    "polar, model = {}, {}\n",
    "print(\n",
    "    \" case        f [Hz]   diffusion coeff. FE   Kirchhoff   |level difference| where both above -10 dB\"\n",
    ")\n",
    "for name in planes:\n",
    "    on_ring, at_receivers = (\n",
    "        np.abs(scattered(name, ring)) ** 2,\n",
    "        np.abs(scattered(name, receivers)) ** 2,\n",
    "    )\n",
    "    for i, f in enumerate(frequencies):\n",
    "        reference_ring = np.abs(kirchhoff[name](ring, f)) ** 2\n",
    "        polar[name, f] = 10 * np.log10(on_ring[:, i] / on_ring[:, i].max())\n",
    "        model[name, f] = 10 * np.log10(reference_ring / reference_ring.max())\n",
    "        main = (polar[name, f] > -10) & (model[name, f] > -10)\n",
    "        print(\n",
    "            f\" {name:10s} {f:7.0f}   {diffusion(at_receivers[:, i]):19.3f}   {diffusion(np.abs(kirchhoff[name](receivers, f)) ** 2):9.3f}\"\n",
    "            f\"   median {np.median(np.abs(polar[name, f] - model[name, f])[main]):.1f} dB, largest {np.max(np.abs(polar[name, f] - model[name, f])[main]):.1f} dB\"\n",
    "        )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Top: the pressure in front of four periods and inside the wells at the design frequency. Bottom: the polar\n",
    "responses of one and of four periods at 500 Hz and 1 kHz against the Kirchhoff model; four\n",
    "periods split the response into the lobes of the periodic grating."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "mesh = meshes[\"4 periods\"]\n",
    "x, y = np.asarray(mesh.coordinates).T\n",
    "field = runs[\"4 periods\"][\"pressure\"][1][: len(x)].real\n",
    "fig = plots.figure(layout=[[\"field\", \"field\"], [\"one\", \"four\"]], size=(17, 14))\n",
    "plots.heatmap(\n",
    "    x,\n",
    "    y,\n",
    "    field,\n",
    "    triangles=np.asarray(mesh.cells),\n",
    "    colormap=\"diverging\",\n",
    "    limits=(-2.5, 2.5),\n",
    "    xlimits=(-1.6, 1.6),\n",
    "    ylimits=(-0.25, 1.6),\n",
    "    label=\"pressure / p0\",\n",
    "    title=\"Pressure in front of four periods and in the wells at 500 Hz (instantaneous)\",\n",
    "    ax=fig[\"field\"],\n",
    ")\n",
    "for panel, name in ((\"one\", \"1 period\"), (\"four\", \"4 periods\")):\n",
    "    plots.line(\n",
    "        np.degrees(fine_theta),\n",
    "        {f\"{f:.0f} Hz\": polar[name, f] for f in (500.0, 1000.0)},\n",
    "        reference={f\"{f:.0f} Hz\": model[name, f] for f in (500.0, 1000.0)},\n",
    "        ylimits=(-30, 3),\n",
    "        xlabel=\"angle from the wall normal [deg]\",\n",
    "        ylabel=\"scattered level, normalised [dB]\",\n",
    "        title=f\"{name}: polar response (dashed: Kirchhoff)\",\n",
    "        legend=\"lower center\",\n",
    "        ax=fig[panel],\n",
    "    )\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Change $N$ or the design frequency in `schroeder_diffuser_scattering_geometry.py` and write the\n",
    "STEP files again, or let the wave fall obliquely: replace $p_b$ by the oblique incident plus\n",
    "specularly reflected wave. The same model with an absorbing lining in the wells gives the\n",
    "absorption that deep narrow wells add at low frequency."
   ]
  }
 ]
}
