{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# The Sod shock tube with smoothed-particle hydrodynamics\n",
    "\n",
    "A tube filled with an ideal gas ($\\gamma=1.4$) is divided by a diaphragm. Both halves are at rest:\n",
    "\n",
    "$$(\\rho,u,p)_L=(1,\\,0,\\,1),\\qquad (\\rho,u,p)_R=(0.125,\\,0,\\,0.1).$$\n",
    "\n",
    "When the diaphragm is removed, three waves emerge: a rarefaction fan running left into the\n",
    "dense gas, a contact discontinuity and a shock running right into the thin gas.\n",
    "\n",
    "The gas is represented by moving particles with a cubic-spline kernel and Monaghan's artificial\n",
    "viscosity for the shock. Mass, momentum and total energy are conserved by construction.\n",
    "\n",
    "**Reference.** The exact solution of the Riemann problem: the pressure $p_*$ between the waves\n",
    "solves $f_L(p_*)+f_R(p_*)=0$ (shock relation on the right, isentropic relation on the left), and\n",
    "the self-similar wave pattern follows from it (Toro, *Riemann Solvers and Numerical Methods for\n",
    "Fluid Dynamics*)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from onesim.physics.hydrodynamics import HydrodynamicPublicApi\n",
    "from onesim.visualization import plots, theme\n",
    "from scipy.optimize import brentq\n",
    "\n",
    "theme.set()\n",
    "\n",
    "gamma, diaphragm, end_time = 1.4, 0.5, 0.2\n",
    "left, right = (1.0, 1.0), (0.125, 0.1)\n",
    "\n",
    "\n",
    "def exact_solution(x):\n",
    "    \"\"\"Density, velocity and pressure of the exact Riemann solution at the end time.\"\"\"\n",
    "    (rho_l, p_l), (rho_r, p_r) = left, right\n",
    "    a_l, a_r, g = (\n",
    "        np.sqrt(gamma * p_l / rho_l),\n",
    "        np.sqrt(gamma * p_r / rho_r),\n",
    "        (gamma - 1) / (gamma + 1),\n",
    "    )\n",
    "    fan = (\n",
    "        lambda p: 2 * a_l / (gamma - 1) * ((p / p_l) ** ((gamma - 1) / (2 * gamma)) - 1)\n",
    "    )\n",
    "    shock = lambda p: (p - p_r) * np.sqrt(2 / ((gamma + 1) * rho_r) / (p + g * p_r))\n",
    "    p_star = brentq(lambda p: fan(p) + shock(p), 1e-6, 10.0, xtol=1e-14)\n",
    "    u_star = 0.5 * (shock(p_star) - fan(p_star))\n",
    "    rho_star_l = rho_l * (p_star / p_l) ** (1 / gamma)\n",
    "    rho_star_r = rho_r * (p_star / p_r + g) / (g * p_star / p_r + 1)\n",
    "    shock_speed = a_r * np.sqrt(\n",
    "        (gamma + 1) / (2 * gamma) * p_star / p_r + (gamma - 1) / (2 * gamma)\n",
    "    )\n",
    "    xi = (x - diaphragm) / end_time\n",
    "    u_fan = 2 / (gamma + 1) * (a_l + xi)\n",
    "    a_fan = a_l - 0.5 * (gamma - 1) * u_fan\n",
    "    regions = [\n",
    "        xi <= -a_l,\n",
    "        xi < u_star - np.sqrt(gamma * p_star / rho_star_l),\n",
    "        xi < u_star,\n",
    "        xi < shock_speed,\n",
    "    ]\n",
    "    return (\n",
    "        np.select(\n",
    "            regions,\n",
    "            [rho_l, rho_l * (a_fan / a_l) ** (2 / (gamma - 1)), rho_star_l, rho_star_r],\n",
    "            rho_r,\n",
    "        ),\n",
    "        np.select(regions, [0.0, u_fan, u_star, u_star], 0.0),\n",
    "        np.select(\n",
    "            regions,\n",
    "            [p_l, p_l * (a_fan / a_l) ** (2 * gamma / (gamma - 1)), p_star, p_star],\n",
    "            p_r,\n",
    "        ),\n",
    "    )"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Simulation\n",
    "\n",
    "1600 equally spaced particles carry the mass of their cell; the smoothing length is 2.5\n",
    "particle spacings."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "count, lower, upper = 1600, -0.5, 1.5\n",
    "spacing = (upper - lower) / count\n",
    "start = lower + (np.arange(count) + 0.5) * spacing\n",
    "density, pressure = np.where(start < diaphragm, left[0], right[0]), np.where(\n",
    "    start < diaphragm, left[1], right[1]\n",
    ")\n",
    "gas = HydrodynamicPublicApi.create_provider(\n",
    "    \"sph_hydrodynamics\",\n",
    "    positions=start,\n",
    "    masses=density * spacing,\n",
    "    velocities=np.zeros(count),\n",
    "    specific_internal_energy=pressure / ((gamma - 1) * density),\n",
    "    smoothing_length=2.5 * spacing,\n",
    "    gamma=gamma,\n",
    "    viscosity_alpha=1.0,\n",
    "    viscosity_beta=2.0,\n",
    "    periodic_bounds=((lower, upper),),\n",
    "    final_time=end_time,\n",
    "    time_step=1.0e-3,\n",
    "    cfl=0.25,\n",
    ")\n",
    "result = gas.run()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "Particle values between $x=0$ and $x=1$ against the exact solution."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "order = np.argsort(result.positions[:, 0])\n",
    "x = result.positions[order, 0]\n",
    "inside = (x >= 0) & (x <= 1)\n",
    "x = x[inside]\n",
    "particles = {\n",
    "    \"density\": result.density[order][inside],\n",
    "    \"velocity\": result.velocities[order, 0][inside],\n",
    "    \"pressure\": result.pressure[order][inside],\n",
    "}\n",
    "exact = dict(zip(particles, exact_solution(x)))\n",
    "for name in particles:\n",
    "    print(\n",
    "        f\"{name:9s} mean deviation from the exact solution: \"\n",
    "        f\"{100 * np.abs(particles[name] - exact[name]).sum() / np.abs(exact[name]).sum():.2f} %\"\n",
    "    )\n",
    "print(\n",
    "    f\"mass {result.initial_balance.mass:.6f} -> {result.final_balance.mass:.6f},  \"\n",
    "    f\"total energy {result.initial_balance.total_energy:.6f} -> {result.final_balance.total_energy:.6f}\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "fine = np.linspace(0, 1, 1200)\n",
    "fig = plots.figure(1, 3, size=(15, 4.5))\n",
    "for panel, name, reference in zip(fig, particles, exact_solution(fine)):\n",
    "    plots.line(\n",
    "        points={\"SPH particles\": (x, particles[name])},\n",
    "        reference={\"exact Riemann solution\": (fine, reference)},\n",
    "        xlabel=\"position\",\n",
    "        ylabel=name,\n",
    "        title=f\"{name.capitalize()} at t = {end_time}\",\n",
    "        ax=panel,\n",
    "    )\n",
    "plots.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Halve the particle spacing and the waves sharpen; lower the artificial viscosity and\n",
    "oscillations appear behind the shock. A stronger pressure ratio turns the problem into a blast\n",
    "wave."
   ]
  }
 ],
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "display_name": "OneSimulation (venv)",
   "language": "python",
   "name": "onesim"
  },
  "language_info": {
   "name": "python"
  }
 }
}
