{
 "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": [
    "# Acoustic cloak around a rigid cylinder\n",
    "\n",
    "A rigid cylinder of radius $a=0.1$ m scatters a plane sound wave strongly when it is several\n",
    "wavelengths around ($ka=2\\pi$ here). Transformation acoustics (S. A. Cummer and D. Schurig,\n",
    "*New J. Phys.* 9, 45, 2007; H. Chen and C. T. Chan, *Appl. Phys. Lett.* 91, 183518, 2007) builds a\n",
    "shell $R_1<r<R_2$ that guides the wave around the obstacle: the radial map\n",
    "$r=R_1+r'\\,(R_2-R_1)/R_2$ squeezes the disc $r'<R_2$ of empty air into the shell, and the\n",
    "Helmholtz equation $\\nabla\\cdot(\\boldsymbol\\rho^{-1}\\nabla p)+\\omega^2\\kappa^{-1}p=0$ in the shell\n",
    "then needs an anisotropic density and a graded bulk modulus,\n",
    "\n",
    "$$\\frac{\\rho_r}{\\rho_0}=\\frac{r}{r-R_1},\\qquad\\frac{\\rho_\\theta}{\\rho_0}=\\frac{r-R_1}{r},\\qquad\n",
    "  \\frac{\\kappa_0}{\\kappa}=\\Big(\\frac{R_2}{R_2-R_1}\\Big)^2\\frac{r-R_1}{r}.$$\n",
    "\n",
    "The ideal cloak ($R_1=a$) has a singular density at the obstacle. As in real designs the map\n",
    "starts slightly inside the obstacle, at $R_1=0.098$ m, which keeps the material finite. The\n",
    "obstacle then looks like a rigid cylinder of the virtual radius\n",
    "$a'=R_2(a-R_1)/(R_2-R_1)=3.9$ mm.\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| obstacle, $r=a$ | rigid, $\\partial p/\\partial n=0$ |\n",
    "| outer circle, $R=0.6$ m | the scattered wave $p-p_i$ is outgoing: $v_n=-i\\,\\dfrac{H_1^{(2)}(kR)}{H_0^{(2)}(kR)}\\,\\dfrac{p-p_i}{\\rho_0c}$ |\n",
    "\n",
    "The outer condition is exact for the circularly symmetric part of the scattered wave and leaves\n",
    "a small reflection of its directional part, of order $1/(kR)^2\\approx10^{-3}$.\n",
    "\n",
    "**Reference.** A rigid cylinder of radius $a$ in the plane wave $p_i=p_0e^{-ikx}$ scatters\n",
    "(P. M. Morse and K. U. Ingard, *Theoretical Acoustics*, §8.1)\n",
    "\n",
    "$$p_s=-p_0\\sum_{n=0}^\\infty\\varepsilon_n(-i)^n\\,\\frac{J_n'(ka)}{H_n^{(2)\\prime}(ka)}\\,H_n^{(2)}(kr)\\cos n\\theta,\n",
    "  \\qquad\\varepsilon_0=1,\\ \\varepsilon_{n>0}=2 .$$\n",
    "\n",
    "Outside the cloak its scattered wave must be that of the virtual cylinder of radius $a'$."
   ]
  },
  {
   "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 h2vp, hankel2, jvp\n",
    "\n",
    "theme.set()\n",
    "\n",
    "c0, rho0, amplitude = 343.0, 1.204, 1.0\n",
    "impedance = rho0 * c0\n",
    "obstacle, inner, cloak = 0.1, 0.098, 0.2\n",
    "omega = 2 * np.pi * c0 / 0.1\n",
    "k = omega / c0\n",
    "virtual = cloak * (obstacle - inner) / (cloak - inner)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`load` reads the air around the obstacle and the cloak shell; `section` cuts the air at half\n",
    "thickness. The triangles are 12.5 mm (an eighth of the wavelength) in the open air, 6 mm at the\n",
    "outer rim of the cloak and 2.5 mm at the obstacle, where the cloak compresses the wave most."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "air, shell = load(\"acoustic_cloak.step\"), load(\"acoustic_cloak_shell.step\")\n",
    "plane = air.section((0, 0, 1), origin=(0, 0, 0.005))\n",
    "outer = plane.size[0] / 2\n",
    "size = lambda r: np.where(\n",
    "    r < obstacle,\n",
    "    0.0125,\n",
    "    np.where(\n",
    "        r < cloak,\n",
    "        0.0025 + 0.035 * (r - obstacle),\n",
    "        np.minimum(0.0125, 0.006 + 0.1 * (r - cloak)),\n",
    "    ),\n",
    ")\n",
    "mesh = TriangularMesher(\n",
    "    target_size=0.0125, size_field=lambda p: size(np.hypot(p[:, 0], p[:, 1]))\n",
    ").generate(plane)\n",
    "\n",
    "view = plots.Camera(elevation=60, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(15, 7))\n",
    "plots.geometry(\n",
    "    [air.named(\"air\"), shell.named(\"cloak\")],\n",
    "    camera=view,\n",
    "    title=\"Air and cloak (STEP)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"{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` takes the inverse density as a\n",
    "$2\\times2$ tensor at every quadrature point - $\\rho_r^{-1}\\hat{\\mathbf r}\\hat{\\mathbf r}^\\top+\n",
    "\\rho_\\theta^{-1}\\hat{\\boldsymbol\\theta}\\hat{\\boldsymbol\\theta}^\\top$ inside the cloak, $\\rho_0^{-1}$\n",
    "outside - and the compressibility likewise. The incident wave enters through the outer circle:\n",
    "its trace carries the admittance $Y$ and the load\n",
    "$\\int\\big(\\rho_0^{-1}\\partial_np_i+i\\omega Yp_i\\big)\\phi_i\\,\\mathrm dS$. The bare cylinder is the same\n",
    "model with air in the shell."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "space = FiniteElement(element=Lagrange(order=2)).bind_space(mesh)\n",
    "radial = lambda points: points / np.linalg.norm(points, axis=1)[:, None]\n",
    "stretch = lambda points, on: np.where(\n",
    "    on & (np.linalg.norm(points, axis=1) < cloak),\n",
    "    (np.linalg.norm(points, axis=1) - inner) / np.linalg.norm(points, axis=1),\n",
    "    1.0,\n",
    ")\n",
    "inverse_density = (\n",
    "    lambda points, on: (\n",
    "        stretch(points, on)[:, None, None]\n",
    "        * np.einsum(\"qi,qj->qij\", radial(points), radial(points))\n",
    "        + 1\n",
    "        / stretch(points, on)[:, None, None]\n",
    "        * (np.eye(2) - np.einsum(\"qi,qj->qij\", radial(points), radial(points)))\n",
    "    )\n",
    "    / rho0\n",
    ")\n",
    "compressibility = lambda points, on: np.where(\n",
    "    on & (np.linalg.norm(points, axis=1) < cloak),\n",
    "    (cloak / (cloak - inner)) ** 2 * stretch(points, on),\n",
    "    1.0,\n",
    ") / (rho0 * c0**2)\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_wall)\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 = -1j * hankel2(1, k * outer) / hankel2(0, k * outer) / impedance\n",
    "nodes = space.dof_coordinates\n",
    "incident = amplitude * np.exp(-1j * k * nodes[:, 0])\n",
    "load_vector = trace @ (\n",
    "    (-1j * k * nodes[:, 0] / outer * incident) / rho0\n",
    "    + 1j * omega * admittance * incident\n",
    ")\n",
    "solutions = {}\n",
    "for name, on in ((\"bare cylinder\", False), (\"cloaked cylinder\", True)):\n",
    "    volume = ConstantPressureForms(\n",
    "        *SampledPressureVolumeForms(\n",
    "            size=space.dof_count,\n",
    "            samples=lambda: pressure_space_volume_samples(space),\n",
    "            inverse_density=lambda omega, sample: inverse_density(sample.points, on),\n",
    "            compressibility=lambda omega, sample: compressibility(sample.points, on),\n",
    "        )(0.0)\n",
    "    )\n",
    "    solutions[name] = (\n",
    "        AcousticHarmonicPressure(\n",
    "            operator=ComplexPressurePencil(\n",
    "                volume,\n",
    "                boundary=PressureAdmittanceBoundary(lambda omega: admittance * trace),\n",
    "            ),\n",
    "            load=lambda omega: load_vector,\n",
    "            angular_frequencies=[omega],\n",
    "            linear_solver=spsolve,\n",
    "        )\n",
    "        .run()\n",
    "        .pressure[0]\n",
    "    )\n",
    "print(\n",
    "    f\"{space.dof_count} pressure unknowns, {mesh.cell_count} triangles; virtual cylinder radius {1e3 * virtual:.2f} mm\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The scattered wave $p-p_i$ on a circle of radius 0.35 m around the obstacle, against the series\n",
    "for the bare cylinder and for the virtual cylinder."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "orders = np.arange(80)\n",
    "series = (\n",
    "    lambda radius, r, theta: -amplitude\n",
    "    * (\n",
    "        np.where(orders == 0, 1, 2)\n",
    "        * (-1j) ** orders\n",
    "        * jvp(orders, k * radius)\n",
    "        / h2vp(orders, k * radius)\n",
    "    )\n",
    "    @ (hankel2(orders[:, None], k * r) * np.cos(orders[:, None] * theta))\n",
    ")\n",
    "theta = np.linspace(0.0, 2 * np.pi, 721)\n",
    "ring = 0.35 * np.column_stack((np.cos(theta), np.sin(theta)))\n",
    "scattered = {\n",
    "    name: np.asarray(space.evaluate(p, ring)) - amplitude * np.exp(-1j * k * ring[:, 0])\n",
    "    for name, p in solutions.items()\n",
    "}\n",
    "exact = {\n",
    "    \"bare cylinder\": series(obstacle, 0.35, theta),\n",
    "    \"cloaked cylinder\": series(virtual, 0.35, theta),\n",
    "}\n",
    "for name in solutions:\n",
    "    print(\n",
    "        f\"{name}: max |p_s| at 0.35 m {np.abs(scattered[name]).max():.4f} p0 (series {np.abs(exact[name]).max():.4f} p0), \"\n",
    "        f\"largest deviation {np.abs(scattered[name] - exact[name]).max():.4f} p0, \"\n",
    "        f\"RMS of |p_s| {np.sqrt(np.mean(np.abs(scattered[name]) ** 2)):.4f} p0 (series {np.sqrt(np.mean(np.abs(exact[name]) ** 2)):.4f} p0)\"\n",
    "    )\n",
    "print(\n",
    "    f\"the cloak lowers the scattered power by {10 * np.log10(np.mean(np.abs(scattered['bare cylinder']) ** 2) / np.mean(np.abs(scattered['cloaked cylinder']) ** 2)):.1f} dB \"\n",
    "    f\"(series: {10 * np.log10(np.mean(np.abs(exact['bare cylinder']) ** 2) / np.mean(np.abs(exact['cloaked cylinder']) ** 2)):.1f} dB)\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The instantaneous pressure with the bare and with the cloaked cylinder: behind the bare one a\n",
    "shadow and interference fringes, around the cloaked one plane wave fronts that close again behind\n",
    "it. Right: the scattered amplitude around the obstacle against the series."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "x, y = np.asarray(mesh.coordinates).T\n",
    "fig = plots.figure(1, 3, size=(22, 7))\n",
    "for panel, name in zip((fig[0], fig[1]), solutions):\n",
    "    plots.heatmap(\n",
    "        x,\n",
    "        y,\n",
    "        solutions[name][: len(x)].real,\n",
    "        triangles=np.asarray(mesh.cells),\n",
    "        colormap=\"diverging\",\n",
    "        limits=(-2, 2),\n",
    "        label=\"pressure / p0\",\n",
    "        title=f\"{name}, ka = {k * obstacle:.2f}\",\n",
    "        ax=panel,\n",
    "    )\n",
    "plots.line(\n",
    "    np.degrees(theta),\n",
    "    {name: np.abs(value) for name, value in scattered.items()},\n",
    "    reference={name: np.abs(exact[name]) for name in solutions},\n",
    "    scale=\"logy\",\n",
    "    ylimits=(1e-4, 3),\n",
    "    xlabel=\"angle from the direction of travel [deg]\",\n",
    "    ylabel=\"|p - p_i| / p0 at r = 0.35 m\",\n",
    "    title=\"Scattered wave (dashed: series, real and virtual cylinder)\",\n",
    "    legend=\"lower center\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Move the start of the map $R_1$ closer to the obstacle: the virtual cylinder shrinks and the\n",
    "scattering falls further, but the density contrast grows and the mesh at the obstacle must follow.\n",
    "A cloak made of a few layers of isotropic fluids (a layered approximation of the tensor) can be\n",
    "built as separate STEP shells in `acoustic_cloak_geometry.py`."
   ]
  }
 ]
}
