{
 "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": [
    "# Supersonic flow over a bump in a channel\n",
    "\n",
    "A supersonic stream that meets an obstacle on a wall cannot be warned in advance: the flow turns\n",
    "abruptly through an oblique shock attached to the leading edge, expands over the crest and is\n",
    "turned back by a second shock at the trailing edge. In a channel the shocks are reflected by the\n",
    "opposite walls, and a bump that covers only part of the width adds shocks and expansions that\n",
    "spread sideways, so that a three-dimensional pattern of crossing waves fills the channel.\n",
    "\n",
    "The channel comes from the CAD file `supersonic_bump_channel_3d.step`, written by\n",
    "`supersonic_bump_channel_3d_geometry.py`: 1 m long, 0.4 m high and 0.3 m wide, of which the half\n",
    "next to the mid-plane is modelled. The bump covers the middle half of the width; it rises at\n",
    "$\\theta=10°$, stays level and falls at 10°. Air at 1 bar and 288 K enters at $M=2$.\n",
    "\n",
    "$$\\frac{\\partial}{\\partial t}\\begin{pmatrix}\\rho\\\\\\rho\\mathbf u\\\\E\\end{pmatrix}+\\nabla\\cdot\n",
    "  \\begin{pmatrix}\\rho\\mathbf u\\\\\\rho\\mathbf u\\otimes\\mathbf u+p\\mathbf I\\\\(E+p)\\mathbf u\\end{pmatrix}=0$$\n",
    "\n",
    "| face | condition |\n",
    "|---|---|\n",
    "| `x_min` | supersonic inflow: $\\rho$, $\\mathbf u$, $p$ of the free stream |\n",
    "| `x_max` | supersonic outflow |\n",
    "| `z_min` (mid-plane) | symmetry |\n",
    "| floor, ceiling, side wall, bump | slip wall |\n",
    "\n",
    "**Reference.** Near the leading edge, on the mid-plane of the bump, the shock is the oblique shock\n",
    "of a wedge: the theta-beta-Mach relation gives the shock angle $\\beta=39.31°$ and the pressure\n",
    "ratio $p_2/p_1=1.707$ for $M=2$ and $\\theta=10°$ (J. D. Anderson, *Modern Compressible Flow*, 3rd\n",
    "ed., McGraw-Hill 2003, ch. 4). The mass that enters must leave."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.d2 import Plane\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.meshing import LocalRefinement, TetrahedralMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fluxes import HLLC\n",
    "from onesim.numerics.fvm import (\n",
    "    MUSCL,\n",
    "    BarthJespersenLimiter,\n",
    "    FiniteVolume,\n",
    "    LocalTimeStepping,\n",
    ")\n",
    "from onesim.numerics.time import ForwardEuler, TimeStepLimits\n",
    "from onesim.physics.hydrodynamics import (\n",
    "    CompressibleEuler,\n",
    "    IdealGasEquationOfState,\n",
    "    SlipWall,\n",
    "    SupersonicInflow,\n",
    "    SupersonicOutflow,\n",
    "    Symmetry,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.simulation.initial_conditions import InitialValue\n",
    "from onesim.visualization import plots, theme\n",
    "from scipy.optimize import brentq\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "Tetrahedra of 35, 26 and 20 mm for the mesh study, three times finer on the bump."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "channel = load(\"supersonic_bump_channel_3d.step\")\n",
    "faces = channel.boundaries\n",
    "bump = (\n",
    "    faces.all\n",
    "    - faces.x_min\n",
    "    - faces.x_max\n",
    "    - faces.y_min\n",
    "    - faces.y_max\n",
    "    - faces.z_min\n",
    "    - faces.z_max\n",
    ")\n",
    "meshes = {\n",
    "    size: TetrahedralMesher(\n",
    "        target_size=size,\n",
    "        refinements=(LocalRefinement(region=bump, target_size=size / 3),),\n",
    "    ).generate(channel)\n",
    "    for size in (0.035, 0.026, 0.020)\n",
    "}\n",
    "\n",
    "view = plots.Camera(elevation=30, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(15, 6))\n",
    "plots.geometry(\n",
    "    channel,\n",
    "    selection={\"bump\": bump, \"inlet\": faces.x_min},\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Half channel with the bump\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[0.020],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"{meshes[0.020].cell_count} tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "Air as an ideal gas, HLLC flux with MUSCL reconstruction and the Barth-Jespersen limiter; local\n",
    "pseudo-time stepping (CFL 0.9) drives each mesh to steady state in 800 iterations."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "gamma, mach, pressure_in, density_in = 1.4, 2.0, 1.0e5, 1.21\n",
    "speed = mach * np.sqrt(gamma * pressure_in / density_in)\n",
    "model = CompressibleEuler(\n",
    "    domain=channel.volume, equation_of_state=IdealGasEquationOfState(gamma=gamma)\n",
    ")\n",
    "problem = Problem(\n",
    "    name=\"Supersonic bump channel\",\n",
    "    geometry=channel,\n",
    "    physics=(model,),\n",
    "    boundary_conditions=(\n",
    "        SupersonicInflow(\n",
    "            boundary=faces.x_min,\n",
    "            physics=model,\n",
    "            density=density_in,\n",
    "            velocity=(speed, 0.0, 0.0),\n",
    "            pressure=pressure_in,\n",
    "        ),\n",
    "        SupersonicOutflow(boundary=faces.x_max, physics=model),\n",
    "        Symmetry(boundary=faces.z_min, physics=model),\n",
    "        SlipWall(\n",
    "            boundary=faces.all - faces.x_min - faces.x_max - faces.z_min, physics=model\n",
    "        ),\n",
    "    ),\n",
    "    initial_conditions=(\n",
    "        InitialValue(model.density, density_in),\n",
    "        InitialValue(model.momentum, (density_in * speed, 0.0, 0.0)),\n",
    "        InitialValue(\n",
    "            model.total_energy, pressure_in / (gamma - 1) + 0.5 * density_in * speed**2\n",
    "        ),\n",
    "    ),\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteVolume(\n",
    "        convection=HLLC(),\n",
    "        reconstruction=MUSCL(),\n",
    "        limiter=BarthJespersenLimiter(),\n",
    "        stability=LocalTimeStepping(cfl=0.9),\n",
    "    ),\n",
    "    time_integrator=ForwardEuler(),\n",
    "    step_limits=TimeStepLimits(stability_safety_factor=1.0),\n",
    ")\n",
    "results = {\n",
    "    size: Simulation(problem=problem, mesh=mesh, numerics=numerics).run(\n",
    "        start_time=0, end_time=800, time_step=1.0\n",
    "    )\n",
    "    for size, mesh in meshes.items()\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The shock front on the mid-plane is where the pressure crosses the middle between free stream and\n",
    "post-shock value on horizontal lines at heights 12 to 30 mm; its angle is measured from the bump\n",
    "nose. The mass flow is integrated over cross-sections behind the inlet and in front of the outlet."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "turn = np.radians(10)\n",
    "deflection = (\n",
    "    lambda beta: 2\n",
    "    / np.tan(beta)\n",
    "    * (mach**2 * np.sin(beta) ** 2 - 1)\n",
    "    / (mach**2 * (gamma + np.cos(2 * beta)) + 2)\n",
    ")\n",
    "beta = brentq(lambda b: deflection(b) - np.tan(turn), np.arcsin(1 / mach), 1.1)\n",
    "ratio = 1 + 2 * gamma / (gamma + 1) * ((mach * np.sin(beta)) ** 2 - 1)\n",
    "grid_y, grid_z = np.meshgrid(\n",
    "    np.linspace(0.005, 0.395, 40), np.linspace(0.003, 0.147, 15)\n",
    ")\n",
    "plane = lambda x: np.column_stack(\n",
    "    (np.full(grid_y.size, x), grid_y.ravel(), grid_z.ravel())\n",
    ")\n",
    "mass_flow = lambda result, x: np.trapezoid(\n",
    "    np.trapezoid(\n",
    "        result.field(model.momentum).evaluate(plane(x))[:, 0].reshape(grid_y.shape),\n",
    "        grid_y[0],\n",
    "        axis=1,\n",
    "    ),\n",
    "    grid_z[:, 0],\n",
    ")\n",
    "summary = {}\n",
    "for size, result in results.items():\n",
    "    pressure = result.field(model.pressure)\n",
    "    angles = []\n",
    "    for height in (0.012, 0.018, 0.024, 0.030):\n",
    "        xs = np.linspace(0.38, 0.4 + 0.95 * height / np.tan(turn), 801)\n",
    "        values = np.ravel(\n",
    "            pressure.evaluate(\n",
    "                np.column_stack((xs, np.full_like(xs, height), np.full_like(xs, 0.005)))\n",
    "            )\n",
    "        )\n",
    "        level = pressure_in * (1 + ratio) / 2\n",
    "        crossing = int(np.argmax(values > level))\n",
    "        front = np.interp(\n",
    "            level, values[crossing - 1 : crossing + 1], xs[crossing - 1 : crossing + 1]\n",
    "        )\n",
    "        angles.append(np.arctan2(height, front - 0.4))\n",
    "    ramp = np.linspace(0.42, 0.46, 5)\n",
    "    behind = np.ravel(\n",
    "        pressure.evaluate(\n",
    "            np.column_stack(\n",
    "                (ramp, (ramp - 0.4) * np.tan(turn) + 0.008, np.full(5, 0.005))\n",
    "            )\n",
    "        )\n",
    "    )\n",
    "    summary[size] = (\n",
    "        np.degrees(np.mean(angles)),\n",
    "        np.mean(behind) / pressure_in,\n",
    "        mass_flow(result, 0.98) / mass_flow(result, 0.02) - 1,\n",
    "    )\n",
    "\n",
    "print(f\"oblique-shock theory: β = {np.degrees(beta):.2f}°, p2/p1 = {ratio:.3f}\")\n",
    "print(\n",
    "    \" mesh [mm]  tetrahedra   shock angle [°]   deviation   p2/p1 on the ramp   deviation   mass outflow / inflow - 1\"\n",
    ")\n",
    "for size, (angle, pressure_ratio, mass) in summary.items():\n",
    "    print(\n",
    "        f\"{1e3 * size:8.0f} {meshes[size].cell_count:11d} {angle:14.2f} {100 * (angle / np.degrees(beta) - 1):+11.1f} % {pressure_ratio:15.3f}\"\n",
    "        f\" {100 * (pressure_ratio / ratio - 1):+11.1f} % {mass:22.1e}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The pressure on the mid-plane - the nose shock, the expansion over the crest, the trailing shock\n",
    "and their reflections - and along a line 30 mm above the floor on the three meshes."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fine = results[0.020]\n",
    "fig = plots.figure(1, 2, size=(16, 6))\n",
    "plots.section(\n",
    "    fine.field(model.pressure),\n",
    "    plane=Plane(origin=(0, 0, 0.005), normal=(0, 0, 1)),\n",
    "    component=lambda p, position: p / pressure_in,\n",
    "    limits=(0.4, 1.8),\n",
    "    contours=12,\n",
    "    subdivisions=1,\n",
    "    aspect=1.0,\n",
    "    label=\"p / p∞\",\n",
    "    title=\"Pressure on the mid-plane of the bump\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "line = np.linspace(0.0, 1.0, 801)\n",
    "plots.line(\n",
    "    line,\n",
    "    {\n",
    "        f\"{1e3 * size:.0f} mm\": np.ravel(\n",
    "            result.field(model.pressure).evaluate(\n",
    "                np.column_stack(\n",
    "                    (line, np.full_like(line, 0.03), np.full_like(line, 0.005))\n",
    "                )\n",
    "            )\n",
    "        )\n",
    "        / pressure_in\n",
    "        for size, result in results.items()\n",
    "    },\n",
    "    hlines={\"oblique shock, p2/p1\": ratio},\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"p / p∞\",\n",
    "    title=\"Pressure on the mid-plane, 30 mm above the floor\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Make the bump span the full width in `supersonic_bump_channel_3d_geometry.py` and write the STEP\n",
    "file again: the side waves disappear and the flow becomes the plane flow over a wedge. Lowering\n",
    "the Mach number towards 1.3 detaches the nose shock at this angle, the case of a blunt obstacle."
   ]
  }
 ]
}
