{
 "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 expansion fan at a convex corner\n",
    "\n",
    "When a supersonic stream meets a wall that turns away from it, the flow cannot follow the corner\n",
    "at once. It turns gradually through a centred fan of Mach waves that spread out from the corner:\n",
    "the Mach number rises and the pressure falls isentropically across the fan. The flow is described\n",
    "by the Prandtl-Meyer function\n",
    "\n",
    "$$\\nu(M)=\\sqrt{\\frac{\\gamma+1}{\\gamma-1}}\\arctan\\sqrt{\\frac{\\gamma-1}{\\gamma+1}(M^2-1)}-\\arctan\\sqrt{M^2-1},$$\n",
    "\n",
    "with $\\nu(M_2)=\\nu(M_1)+\\theta$ for a turn by the angle $\\theta$. The fan starts on the Mach line\n",
    "$\\mu_1=\\arcsin(1/M_1)$ of the oncoming flow and ends on the line $\\mu_2-\\theta$; inside it, the\n",
    "Mach number on each ray from the corner follows from $\\mu(M)=\\phi+\\nu(M)-\\nu(M_1)$.\n",
    "\n",
    "The gas region comes from the CAD file `prandtl_meyer_expansion_fan.step`, written by\n",
    "`prandtl_meyer_expansion_fan_geometry.py`: a wall that turns by $\\theta=10°$ at $x=0.5$ m. The model is\n",
    "its cross-section. The gas ($\\gamma=1.4$) arrives at $M_1=2$; density, pressure and velocity are\n",
    "given relative to the free stream, which has the density 1.4, the pressure 1 and the sound speed 1.\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,\\qquad\n",
    "  p=(\\gamma-1)\\Big(E-\\tfrac12\\rho|\\mathbf u|^2\\Big)$$\n",
    "\n",
    "| side | condition |\n",
    "|---|---|\n",
    "| `inlet` | supersonic inflow: $\\rho$, $\\mathbf u$, $p$ of the free stream |\n",
    "| `outlet` | supersonic outflow (all characteristics leave) |\n",
    "| `wall`, `ramp`, `upper` | slip wall |\n",
    "\n",
    "**Reference.** The exact Prandtl-Meyer solution (J. D. Anderson, *Modern Compressible Flow*, 3rd\n",
    "ed., McGraw-Hill 2003, ch. 4): for $M_1=2$ and $\\theta=10°$, $M_2=2.385$ and\n",
    "$p_2/p_1=0.5480$."
   ]
  },
  {
   "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 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",
    ")\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",
    "`section` cuts the slab at half thickness. Triangles of 5, 4 and 3 cm for the mesh study."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "part = load(\"prandtl_meyer_expansion_fan.step\")\n",
    "region = part.section((0, 0, 1), origin=(0, 0, part.size[2] / 2))\n",
    "faces = region.boundaries\n",
    "meshes = {\n",
    "    size: TriangularMesher(target_size=size).generate(region)\n",
    "    for size in (0.05, 0.04, 0.03)\n",
    "}\n",
    "\n",
    "fig = plots.figure(1, 2, size=(15, 6))\n",
    "plots.geometry(\n",
    "    part,\n",
    "    selection={\"inlet\": part.boundaries.inlet, \"turned wall\": part.boundaries.ramp},\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=60, azimuth=-70),\n",
    "    title=\"Gas region above the convex corner\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[0.03],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"{meshes[0.03].cell_count} triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "An ideal gas; the free stream also fills the region at the start. Local pseudo-time\n",
    "stepping (each cell at its own stable step, CFL 0.9) drives the solution to steady state in 1500\n",
    "iterations."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "gamma, mach, pressure_in, density_in = 1.4, 2.0, 1.0, 1.4\n",
    "speed = mach * np.sqrt(gamma * pressure_in / density_in)\n",
    "energy = pressure_in / (gamma - 1) + 0.5 * density_in * speed**2\n",
    "model = CompressibleEuler(\n",
    "    domain=region.domain(), equation_of_state=IdealGasEquationOfState(gamma=gamma)\n",
    ")\n",
    "problem = Problem(\n",
    "    name=\"Prandtl-Meyer expansion\",\n",
    "    geometry=region,\n",
    "    physics=(model,),\n",
    "    boundary_conditions=(\n",
    "        SupersonicInflow(\n",
    "            boundary=faces.inlet,\n",
    "            physics=model,\n",
    "            density=density_in,\n",
    "            velocity=(speed, 0.0),\n",
    "            pressure=pressure_in,\n",
    "        ),\n",
    "        SupersonicOutflow(boundary=faces.outlet, physics=model),\n",
    "        SlipWall(boundary=faces.wall | faces.ramp | faces.upper, physics=model),\n",
    "    ),\n",
    "    initial_conditions=(\n",
    "        InitialValue(model.density, density_in),\n",
    "        InitialValue(model.momentum, (density_in * speed, 0.0)),\n",
    "        InitialValue(model.total_energy, energy),\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=1500, 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 exact solution on rays from the corner, and the state behind the fan sampled along the turned\n",
    "wall."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "turn = np.radians(10)\n",
    "nu = lambda m: np.sqrt((gamma + 1) / (gamma - 1)) * np.arctan(\n",
    "    np.sqrt((gamma - 1) / (gamma + 1) * (m**2 - 1))\n",
    ") - np.arctan(np.sqrt(m**2 - 1))\n",
    "behind = brentq(lambda m: nu(m) - nu(mach) - turn, mach, 5.0)\n",
    "isentropic = lambda m: (\n",
    "    (1 + 0.5 * (gamma - 1) * mach**2) / (1 + 0.5 * (gamma - 1) * m**2)\n",
    ") ** (gamma / (gamma - 1))\n",
    "head, tail = np.arcsin(1 / mach), np.arcsin(1 / behind) - turn\n",
    "rays = np.linspace(tail - 0.08, head + 0.08, 121)\n",
    "exact_mach = np.array(\n",
    "    [\n",
    "        (\n",
    "            mach\n",
    "            if phi >= head\n",
    "            else (\n",
    "                behind\n",
    "                if phi <= tail\n",
    "                else brentq(\n",
    "                    lambda m: np.arcsin(1 / m) - (nu(m) - nu(mach)) - phi, mach, behind\n",
    "                )\n",
    "            )\n",
    "        )\n",
    "        for phi in rays\n",
    "    ]\n",
    ")\n",
    "arc = np.column_stack((0.5 + 0.7 * np.cos(rays), 0.7 * np.sin(rays)))\n",
    "along = (\n",
    "    np.array([0.5, 0.0])\n",
    "    + np.outer(np.linspace(0.45, 0.85, 20), (np.cos(turn), -np.sin(turn)))\n",
    "    + 0.04 * np.array([np.sin(turn), np.cos(turn)])\n",
    ")\n",
    "fields = {\n",
    "    size: (result.field(model.mach_number), result.field(model.pressure))\n",
    "    for size, result in results.items()\n",
    "}\n",
    "\n",
    "print(\n",
    "    f\"exact: M2 = {behind:.4f}, p2/p1 = {isentropic(behind):.4f}, fan from {np.degrees(head):.2f}° to {np.degrees(tail):.2f}°\"\n",
    ")\n",
    "print(\n",
    "    \" mesh [cm]  triangles   M behind the fan   deviation   p2/p1    deviation   mean |M - exact| on the arc r = 0.7 m\"\n",
    ")\n",
    "for size, (mach_field, pressure_field) in fields.items():\n",
    "    m2, p2 = (\n",
    "        np.mean(mach_field.evaluate(along)),\n",
    "        np.mean(pressure_field.evaluate(along)) / pressure_in,\n",
    "    )\n",
    "    error = np.mean(np.abs(np.ravel(mach_field.evaluate(arc)) - exact_mach))\n",
    "    print(\n",
    "        f\"{100 * size:8.0f} {meshes[size].cell_count:10d} {m2:14.4f} {100 * (m2 / behind - 1):+11.2f} % {p2:8.4f} {100 * (p2 / isentropic(behind) - 1):+8.2f} %\"\n",
    "        f\" {error:20.4f}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The Mach number in the gas region and on the arc of radius 0.7 m around the corner, against the\n",
    "exact centred fan."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 2, size=(16, 6))\n",
    "plots.surface(\n",
    "    fields[0.03][0],\n",
    "    limits=(1.95, 2.45),\n",
    "    contours=10,\n",
    "    subdivisions=1,\n",
    "    label=\"Mach number\",\n",
    "    title=\"Mach number: the centred fan spreads from the corner\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    np.degrees(rays),\n",
    "    {\n",
    "        f\"simulation, {100 * size:.0f} cm\": np.ravel(fields[size][0].evaluate(arc))\n",
    "        for size in meshes\n",
    "    },\n",
    "    reference={\"exact Prandtl-Meyer fan\": exact_mach},\n",
    "    xlabel=\"ray angle from the incoming flow direction [°]\",\n",
    "    ylabel=\"Mach number\",\n",
    "    title=\"Mach number on the arc r = 0.7 m around the corner\",\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",
    "Turn the wall the other way in `prandtl_meyer_expansion_fan_geometry.py` (a compression corner) and\n",
    "write the STEP file again: the flow then turns through an oblique shock, which the\n",
    "theta-beta-Mach relation predicts. Raising the turn angle until the pressure behind the fan\n",
    "vanishes gives the largest possible turn, about 104° at Mach 2."
   ]
  }
 ]
}
