{
 "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": [
    "# Sod's shock tube: one model, every method\n",
    "\n",
    "A tube of ideal gas ($\\gamma=1.4$) is divided by a diaphragm at $x=0.5$. 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, a rarefaction fan runs left, a contact discontinuity and a shock\n",
    "run right. The one-dimensional Euler equations\n",
    "\n",
    "$$\\partial_t\\begin{pmatrix}\\rho\\\\ \\rho u\\\\ E\\end{pmatrix}\n",
    "+\\partial_x\\begin{pmatrix}\\rho u\\\\ \\rho u^2+p\\\\ u(E+p)\\end{pmatrix}=0,\n",
    "\\qquad p=(\\gamma-1)\\Big(E-\\tfrac12\\rho u^2\\Big)$$\n",
    "\n",
    "are declared once. Everything numerical is an argument of `Numerics`: the discretization family\n",
    "(finite volumes, finite differences, discontinuous and continuous finite elements, and smoothed\n",
    "particle hydrodynamics), the reconstruction and its limiter, the Riemann solver, the time integrator and, for implicit steps,\n",
    "the nonlinear and the linear solver.\n",
    "\n",
    "**Reference.** The exact solution of the Riemann problem (Toro, *Riemann Solvers and Numerical\n",
    "Methods for Fluid Dynamics*, ch. 4) comes from OneSimulation's exact Euler sampler: the star\n",
    "pressure matches an ideal-gas Hugoniot curve on the shock side and an isentrope on the\n",
    "rarefaction side, and the self-similar solution is sampled at $\\xi=(x-0.5)/t$.\n",
    "\n",
    "**Grading.** At $t=0.2$ every run is evaluated at the 400 cell centres $x_i$:\n",
    "$L_1(q)=\\sum_i |q_h(x_i)-q(x_i)|\\,\\Delta x$ for density, velocity and pressure; the shock position\n",
    "is where the density crosses the middle of its jump; the wall time covers validation, binding and\n",
    "time stepping."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import time\n",
    "\n",
    "import numpy as np\n",
    "from onesim.cad.d1 import Line\n",
    "from onesim.meshing import StructuredLineMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.discretization import NodalInterpolation\n",
    "from onesim.numerics.fdm import (\n",
    "    BoundaryFluxDifference,\n",
    "    CentralDifference,\n",
    "    DissipativeFluxDifference,\n",
    "    FiniteDifference,\n",
    "    JSTDissipation,\n",
    "    GlobalLaxFriedrichsSplit,\n",
    "    PolynomialDifference,\n",
    "    SummationByPartsDifference,\n",
    "    WENO5Flux,\n",
    "    WENOFluxDifference,\n",
    ")\n",
    "from onesim.numerics.fem import (\n",
    "    CIP,\n",
    "    GLS,\n",
    "    SUPG,\n",
    "    DGJumpPenalty,\n",
    "    InterpolatedFluxDivergence,\n",
    "    VolumeCIP,\n",
    "    DGPolynomialLimiter,\n",
    "    DiscontinuousLagrange,\n",
    "    FiniteElement,\n",
    "    InvariantDomainGraphViscosity,\n",
    "    Lagrange,\n",
    "    RowSumLumping,\n",
    ")\n",
    "from onesim.numerics.fluxes import HLL, HLLC, HLLE, Rusanov\n",
    "from onesim.numerics.fvm import (\n",
    "    MUSCL,\n",
    "    QUICK,\n",
    "    BarthJespersenLimiter,\n",
    "    CentralWeightedENO,\n",
    "    JiangShuWeights,\n",
    "    SmoothnessDifference,\n",
    "    WenoZWeights,\n",
    "    ConvexInvariantDomain,\n",
    "    Eno2Reconstructor,\n",
    "    Eno3Reconstructor,\n",
    "    FiniteVolume,\n",
    "    MinmodLimiter,\n",
    "    MonotonizedCentralLimiter,\n",
    "    SuperbeeLimiter,\n",
    "    TvbLimiter,\n",
    "    VanLeerLimiter,\n",
    "    VenkatakrishnanLimiter,\n",
    "    Weno3Reconstructor,\n",
    "    Weno5Reconstructor,\n",
    ")\n",
    "from onesim.numerics.linear import (\n",
    "    GMRES,\n",
    "    ILU,\n",
    "    AutomaticLinearSolver,\n",
    "    FlexibleGMRES,\n",
    "    RightGMRES,\n",
    "    SparseDirect,\n",
    ")\n",
    "from onesim.numerics.nonlinear import (\n",
    "    JFNK,\n",
    "    DampedNewton,\n",
    "    FixedPoint,\n",
    "    Newton,\n",
    "    QuasiNewton,\n",
    "    TrustRegionNewton,\n",
    ")\n",
    "from onesim.numerics.time import (\n",
    "    BDF,\n",
    "    AdaptiveBDF,\n",
    "    AdaptiveRungeKutta45,\n",
    "    BackwardEuler,\n",
    "    ClassicalRungeKutta4,\n",
    "    ForwardEuler,\n",
    "    TimeMethod,\n",
    "    TimeStepLimits,\n",
    ")\n",
    "from onesim.physics.hydrodynamics import (\n",
    "    HydrodynamicPublicApi,\n",
    "    CompressibleEuler,\n",
    "    EulerInvariantDomain,\n",
    "    EulerPressureWave,\n",
    "    IdealGasEquationOfState,\n",
    "    NormalEulerPrimitive,\n",
    "    TammannHugoniot,\n",
    "    TammannRarefaction,\n",
    "    TransmissiveBoundary,\n",
    "    exact_euler_pressure_trace,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.simulation.initial_conditions import InitialValue\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The physics, declared once\n",
    "\n",
    "Nothing in this cell names a numerical method."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "gamma, end_time, cells, coarse_cells = 1.4, 0.2, 400, 200\n",
    "tube = Line(start=(0.0, 0.0, 0.0), end=(1.0, 0.0, 0.0))\n",
    "gas = CompressibleEuler(\n",
    "    domain=tube.line, equation_of_state=IdealGasEquationOfState(gamma=gamma)\n",
    ")\n",
    "sod = Problem(\n",
    "    name=\"Sod shock tube\",\n",
    "    geometry=tube,\n",
    "    physics=(gas,),\n",
    "    boundary_conditions=(\n",
    "        TransmissiveBoundary(boundary=tube.boundaries.all, physics=gas),\n",
    "    ),\n",
    "    initial_conditions=(\n",
    "        InitialValue(gas.density, lambda x: np.where(x < 0.5, 1.0, 0.125)),\n",
    "        InitialValue(gas.momentum, 0.0),\n",
    "        InitialValue(gas.total_energy, lambda x: np.where(x < 0.5, 2.5, 0.25)),\n",
    "    ),\n",
    ")\n",
    "meshes = {n: StructuredLineMesher(cells=n).generate(tube) for n in (cells, coarse_cells)}\n",
    "centres = {n: mesh.cell_centers[:, 0] for n, mesh in meshes.items()}\n",
    "print(\n",
    "    f\"{meshes[cells].cell_count} cells of width {1 / cells:.5f} \"\n",
    "    f\"(coarse check: {meshes[coarse_cells].cell_count} cells)\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The exact solution\n",
    "\n",
    "The two initial states with their ideal-gas shock and rarefaction curves; the exact sampler returns\n",
    "the state on every ray $\\xi$ and the speeds of the outermost waves."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "waves = [\n",
    "    EulerPressureWave(\n",
    "        NormalEulerPrimitive(*state), TammannHugoniot(gamma), TammannRarefaction(gamma)\n",
    "    )\n",
    "    for state in ((1.0, 0.0, 1.0), (0.125, 0.0, 0.1))\n",
    "]\n",
    "fine = np.linspace(0.0, 1.0, 2001)\n",
    "exact = {\n",
    "    key: np.array(\n",
    "        [\n",
    "            [\n",
    "                getattr(\n",
    "                    exact_euler_pressure_trace(\n",
    "                        *waves, similarity=(x - 0.5) / end_time\n",
    "                    ).state,\n",
    "                    name,\n",
    "                )\n",
    "                for x in points\n",
    "            ]\n",
    "            for name in (\"density\", \"velocity\", \"pressure\")\n",
    "        ]\n",
    "    )\n",
    "    for key, points in {**centres, \"fine\": fine}.items()\n",
    "}\n",
    "fan_head, shock_speed = exact_euler_pressure_trace(*waves).signal_bounds\n",
    "exact_shock = 0.5 + shock_speed * end_time\n",
    "shock_level = 0.5 * (\n",
    "    exact_euler_pressure_trace(*waves, similarity=shock_speed - 1e-9).state.density\n",
    "    + 0.125\n",
    ")\n",
    "print(\n",
    "    f\"star pressure {exact['fine'][2][1000]:.5f}, contact velocity {exact['fine'][1][1000]:.5f}, \"\n",
    "    f\"shock speed {shock_speed:.5f}, shock at x = {exact_shock:.5f} for t = {end_time}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The method catalogue\n",
    "\n",
    "Four Riemann solvers; seven slope limiters plus the unlimited slope; higher-order reconstructions\n",
    "including WENO3, WENO5, their WENO-Z variants and central WENO (CWENO3, CWENO3-Z); finite elements\n",
    "(FEM) with discontinuous elements of degree 0 to 4, with and without limiting or a jump penalty,\n",
    "and continuous elements of degree 1 to 3 with graph viscosity, continuous interior penalty, volume\n",
    "interior penalty, SUPG, GLS or no stabilization; and finite-difference stencils including\n",
    "summation-by-parts operators of order 2 and 4. Each is an object; the matrix is built from them\n",
    "with plain dictionaries.\n",
    "\n",
    "Limited discontinuous Galerkin runs with all four Riemann solvers for degrees 1 to 4; the limiter\n",
    "is minmod on the slopes plus the Euler invariant domain (positive density and pressure at every\n",
    "node)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "riemann = {\"Rusanov\": Rusanov(), \"HLL\": HLL(), \"HLLE\": HLLE(), \"HLLC\": HLLC()}\n",
    "limiters = {\n",
    "    \"minmod\": MinmodLimiter(),\n",
    "    \"MC\": MonotonizedCentralLimiter(),\n",
    "    \"van Leer\": VanLeerLimiter(),\n",
    "    \"superbee\": SuperbeeLimiter(),\n",
    "    \"Barth-Jespersen\": BarthJespersenLimiter(),\n",
    "    \"Venkatakrishnan\": VenkatakrishnanLimiter(),\n",
    "    \"TVB (M = 50)\": TvbLimiter(\n",
    "        base_limiter=MinmodLimiter(), tvb_constant=50.0, mesh_width=1 / cells\n",
    "    ),\n",
    "}\n",
    "reconstructions = {\n",
    "    \"ENO2\": Eno2Reconstructor(),\n",
    "    \"ENO3\": Eno3Reconstructor(),\n",
    "    \"WENO3\": Weno3Reconstructor(),\n",
    "    \"WENO5\": Weno5Reconstructor(),\n",
    "    \"WENO3-Z\": Weno3Reconstructor(\n",
    "        weights=WenoZWeights(global_indicator=SmoothnessDifference())\n",
    "    ),\n",
    "    \"WENO5-Z\": Weno5Reconstructor(\n",
    "        weights=WenoZWeights(global_indicator=SmoothnessDifference())\n",
    "    ),\n",
    "    \"CWENO3\": CentralWeightedENO(weights=JiangShuWeights()),\n",
    "    \"CWENO3-Z\": CentralWeightedENO(\n",
    "        weights=WenoZWeights(global_indicator=SmoothnessDifference(first=1, last=2))\n",
    "    ),\n",
    "    \"QUICK\": QUICK(),\n",
    "}\n",
    "dg_limiter = DGPolynomialLimiter(\n",
    "    slope_limiter=MinmodLimiter(), invariant_domain=EulerInvariantDomain()\n",
    ")\n",
    "graph_viscosity = InvariantDomainGraphViscosity(\n",
    "    mass=RowSumLumping(), invariant_domain=EulerInvariantDomain()\n",
    ")\n",
    "spatial = {}\n",
    "for flux_name, flux in riemann.items():\n",
    "    spatial[(\"FVM first order\", flux_name)] = FiniteVolume(convection=flux)\n",
    "    spatial[(\"FVM MUSCL, unlimited\", flux_name)] = FiniteVolume(\n",
    "        convection=flux, reconstruction=MUSCL()\n",
    "    )\n",
    "    for limiter_name, limiter in limiters.items():\n",
    "        spatial[(f\"FVM MUSCL + {limiter_name}\", flux_name)] = FiniteVolume(\n",
    "            convection=flux, reconstruction=MUSCL(), limiter=limiter\n",
    "        )\n",
    "    spatial[(\"FVM MUSCL + minmod + positivity\", flux_name)] = FiniteVolume(\n",
    "        convection=flux,\n",
    "        reconstruction=MUSCL(),\n",
    "        limiter=MinmodLimiter(),\n",
    "        positivity=ConvexInvariantDomain(),\n",
    "    )\n",
    "    for reconstruction_name, reconstruction in reconstructions.items():\n",
    "        spatial[(f\"FVM {reconstruction_name}\", flux_name)] = FiniteVolume(\n",
    "            convection=flux, reconstruction=reconstruction\n",
    "        )\n",
    "    spatial[(\"FEM DG P0\", flux_name)] = FiniteElement(\n",
    "        element=DiscontinuousLagrange(0), convection=flux\n",
    "    )\n",
    "    for degree in (1, 2, 3, 4):\n",
    "        spatial[(f\"FEM DG P{degree}, unlimited\", flux_name)] = FiniteElement(\n",
    "            element=DiscontinuousLagrange(degree), convection=flux\n",
    "        )\n",
    "        spatial[(f\"FEM DG P{degree} + minmod + invariant domain\", flux_name)] = FiniteElement(\n",
    "            element=DiscontinuousLagrange(degree), convection=flux, limiter=dg_limiter\n",
    "        )\n",
    "    for degree in (1, 2, 3):\n",
    "        spatial[(f\"FEM CG P{degree} + graph viscosity\", flux_name)] = FiniteElement(\n",
    "            element=Lagrange(degree), convection=flux, stabilization=graph_viscosity\n",
    "        )\n",
    "        spatial[(f\"FEM CG P{degree} Galerkin\", flux_name)] = FiniteElement(\n",
    "            element=Lagrange(degree), convection=flux\n",
    "        )\n",
    "    for degree, penalty in ((1, 0.1), (2, 0.01)):\n",
    "        spatial[(f\"FEM CG P{degree} + continuous interior penalty\", flux_name)] = (\n",
    "            FiniteElement(\n",
    "                element=Lagrange(degree),\n",
    "                convection=flux,\n",
    "                stabilization=CIP(penalty=penalty),\n",
    "                initialization=NodalInterpolation(),\n",
    "            )\n",
    "        )\n",
    "    spatial[(\"FEM CG P1 + volume interior penalty\", flux_name)] = FiniteElement(\n",
    "        element=Lagrange(1),\n",
    "        convection=flux,\n",
    "        stabilization=VolumeCIP(diffusivity=2e-3),\n",
    "        initialization=NodalInterpolation(),\n",
    "    )\n",
    "    for name, kind in ((\"SUPG\", SUPG), (\"GLS\", GLS)):\n",
    "        spatial[(f\"FEM CG P1 + {name}\", flux_name)] = FiniteElement(\n",
    "            element=Lagrange(1),\n",
    "            convection=flux,\n",
    "            stabilization=kind(tau=0.5 / cells, strong_residual=InterpolatedFluxDivergence()),\n",
    "            initialization=NodalInterpolation(),\n",
    "        )\n",
    "    spatial[(\"FEM DG P1 + jump penalty\", flux_name)] = FiniteElement(\n",
    "        element=DiscontinuousLagrange(1),\n",
    "        convection=flux,\n",
    "        stabilization=DGJumpPenalty(coefficient=1.0),\n",
    "    )\n",
    "    spatial[(\"FDM central, 2nd order\", flux_name)] = FiniteDifference(\n",
    "        gradient=BoundaryFluxDifference(derivative=CentralDifference(), boundary_flux=flux)\n",
    "    )\n",
    "    spatial[(\"FDM polynomial, 4th order\", flux_name)] = FiniteDifference(\n",
    "        gradient=BoundaryFluxDifference(\n",
    "            derivative=PolynomialDifference(accuracy_order=4), boundary_flux=flux\n",
    "        )\n",
    "    )\n",
    "    for order in (2, 4):\n",
    "        spatial[(f\"FDM summation by parts, order {order}\", flux_name)] = FiniteDifference(\n",
    "            gradient=BoundaryFluxDifference(\n",
    "                derivative=SummationByPartsDifference(accuracy_order=order),\n",
    "                boundary_flux=flux,\n",
    "            )\n",
    "        )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Schemes that must fail at a shock, and their stabilized counterparts\n",
    "\n",
    "Some declared schemes are linear and of higher than first order: MUSCL and QUICK without a\n",
    "limiter, discontinuous Galerkin without limiting or with only a jump penalty, continuous Galerkin\n",
    "without stabilization or with a linear SUPG/GLS term, and central or summation-by-parts finite\n",
    "differences. By Godunov's theorem every such scheme oscillates at a discontinuity;\n",
    "on Sod's problem the oscillation drives density or pressure negative. The library reports that\n",
    "honestly instead of clipping the state. For each of these schemes the matrix also runs the\n",
    "stabilized counterpart, which adds exactly one ingredient; its result is shown behind a grey\n",
    "hatching in the same cell."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "invariant_dg = DGPolynomialLimiter(invariant_domain=EulerInvariantDomain())\n",
    "stabilized_space = {\n",
    "    \"FVM MUSCL, unlimited\": (\n",
    "        \"MUSCL unlimited + invariant-domain positivity limiter at the faces\",\n",
    "        lambda flux: FiniteVolume(\n",
    "            convection=flux, reconstruction=MUSCL(), positivity=ConvexInvariantDomain()\n",
    "        ),\n",
    "    ),\n",
    "    \"FVM QUICK\": (\n",
    "        \"QUICK + invariant-domain positivity limiter at the faces\",\n",
    "        lambda flux: FiniteVolume(\n",
    "            convection=flux, reconstruction=QUICK(), positivity=ConvexInvariantDomain()\n",
    "        ),\n",
    "    ),\n",
    "    **{\n",
    "        f\"FEM DG P{degree}, unlimited\": (\n",
    "            f\"FEM DG P{degree} + Euler invariant-domain scaling (no slope limiter)\",\n",
    "            lambda flux, degree=degree: FiniteElement(\n",
    "                element=DiscontinuousLagrange(degree), convection=flux, limiter=invariant_dg\n",
    "            ),\n",
    "        )\n",
    "        for degree in (1, 2, 3, 4)\n",
    "    },\n",
    "    \"FDM central, 2nd order\": (\n",
    "        \"central differences + Jameson-Schmidt-Turkel artificial dissipation\",\n",
    "        lambda flux: FiniteDifference(\n",
    "            gradient=DissipativeFluxDifference(\n",
    "                flux_difference=BoundaryFluxDifference(\n",
    "                    derivative=CentralDifference(), boundary_flux=flux\n",
    "                ),\n",
    "                dissipation=JSTDissipation(),\n",
    "            )\n",
    "        ),\n",
    "    ),\n",
    "    \"FDM polynomial, 4th order\": (\n",
    "        \"4th-order differences + Jameson-Schmidt-Turkel artificial dissipation\",\n",
    "        lambda flux: FiniteDifference(\n",
    "            gradient=DissipativeFluxDifference(\n",
    "                flux_difference=BoundaryFluxDifference(\n",
    "                    derivative=PolynomialDifference(accuracy_order=4), boundary_flux=flux\n",
    "                ),\n",
    "                dissipation=JSTDissipation(),\n",
    "            )\n",
    "        ),\n",
    "    ),\n",
    "    **{\n",
    "        f\"FEM CG P1 + {name}\": (\n",
    "            f\"CG P1 + invariant-domain graph viscosity instead of {name}\",\n",
    "            lambda flux: FiniteElement(\n",
    "                element=Lagrange(1), convection=flux, stabilization=graph_viscosity\n",
    "            ),\n",
    "        )\n",
    "        for name in (\"SUPG\", \"GLS\")\n",
    "    },\n",
    "    \"FEM DG P1 + jump penalty\": (\n",
    "        \"DG P1 + Euler invariant-domain scaling instead of the jump penalty\",\n",
    "        lambda flux: FiniteElement(\n",
    "            element=DiscontinuousLagrange(1), convection=flux, limiter=invariant_dg\n",
    "        ),\n",
    "    ),\n",
    "    **{\n",
    "        f\"FDM summation by parts, order {order}\": (\n",
    "            f\"SBP order {order} with SAT boundary flux + Jameson-Schmidt-Turkel artificial dissipation\",\n",
    "            lambda flux, order=order: FiniteDifference(\n",
    "                gradient=DissipativeFluxDifference(\n",
    "                    flux_difference=BoundaryFluxDifference(\n",
    "                        derivative=SummationByPartsDifference(accuracy_order=order),\n",
    "                        boundary_flux=flux,\n",
    "                    ),\n",
    "                    dissipation=JSTDissipation(),\n",
    "                )\n",
    "            ),\n",
    "        )\n",
    "        for order in (2, 4)\n",
    "    },\n",
    "    **{\n",
    "        f\"FEM CG P{degree} Galerkin\": (\n",
    "            f\"FEM CG P{degree} + invariant-domain graph viscosity\"\n",
    "            + (\" (positive Bernstein basis)\" if degree > 1 else \"\"),\n",
    "            lambda flux, degree=degree: FiniteElement(\n",
    "                element=Lagrange(degree), convection=flux, stabilization=graph_viscosity\n",
    "            ),\n",
    "        )\n",
    "        for degree in (1, 2, 3)\n",
    "    },\n",
    "}\n",
    "\n",
    "spatial[(\"FDM WENO5 flux splitting\", \"Lax-Friedrichs splitting\")] = FiniteDifference(\n",
    "    gradient=WENOFluxDifference(\n",
    "        flux_splitting=GlobalLaxFriedrichsSplit(), reconstruction=WENO5Flux()\n",
    "    )\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Time integrators: explicit one-step methods (forward Euler, Heun, explicit midpoint, SSP-RK2,\n",
    "SSP-RK3, RK4 and others) and multistep methods, implicit Runge-Kutta, Adams-Moulton\n",
    "and BDF methods, Rosenbrock methods and the adaptive integrators. Implicit stages take a Newton\n",
    "solver with a coloured finite-difference Jacobian and a sparse direct solve; the linearly implicit\n",
    "Rosenbrock stages take the sparse direct solve alone. The nonlinear and linear solvers are then\n",
    "varied on their own."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "integrators = {\n",
    "    \"forward Euler\": ForwardEuler(),\n",
    "    \"SSP-RK2\": TimeMethod(\"ssprk2\"),\n",
    "    \"SSP-RK3\": TimeMethod(\"ssprk3\"),\n",
    "    \"Heun\": TimeMethod(\"heun\"),\n",
    "    \"explicit midpoint\": TimeMethod(\"explicit_midpoint\"),\n",
    "    \"classical RK4\": ClassicalRungeKutta4(),\n",
    "    \"Adams-Bashforth 2\": TimeMethod(\"adams_bashforth2\"),\n",
    "    \"ABM2 predictor-corrector\": TimeMethod(\"predictor_corrector_abam2\"),\n",
    "    \"Heun-Euler (embedded)\": TimeMethod(\"embedded_heun_euler\"),\n",
    "    \"leapfrog\": TimeMethod(\"leapfrog\"),\n",
    "    \"adaptive RK45\": AdaptiveRungeKutta45(),\n",
    "    \"backward Euler\": BackwardEuler(),\n",
    "    \"Crank-Nicolson\": TimeMethod(\"crank_nicolson\"),\n",
    "    \"theta = 0.75\": TimeMethod(\"theta_075\"),\n",
    "    \"implicit midpoint\": TimeMethod(\"implicit_rk_midpoint\"),\n",
    "    \"SDIRK2\": TimeMethod(\"dirk_sdirk2\"),\n",
    "    \"Adams-Moulton 2\": TimeMethod(\"adams_moulton_2\"),\n",
    "    \"Adams-Moulton 3\": TimeMethod(\"adams_moulton_3\"),\n",
    "    \"Adams-Moulton 4\": TimeMethod(\"adams_moulton_4\"),\n",
    "    \"BDF2 (variable step)\": BDF(order=2),\n",
    "    \"BDF3 (variable step)\": BDF(order=3),\n",
    "    **{f\"BDF{k} (Gear)\": TimeMethod(f\"bdf{k}_gear\") for k in (2, 3, 4, 5, 6)},\n",
    "    \"Rosenbrock-Euler\": TimeMethod(\"rosenbrock_euler\"),\n",
    "    \"Rosenbrock-Wanner Euler\": TimeMethod(\"rosenbrock_wanner_euler\"),\n",
    "    \"adaptive BDF\": AdaptiveBDF(relative_tolerance=1e-3, absolute_tolerance=1e-6),\n",
    "}\n",
    "newton = Newton(linear_solver=SparseDirect(), jacobian=\"colored_finite_difference\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "BDF4 to BDF6 and Adams-Moulton 4 are not A-stable, and a fixed-point (Picard) iteration contracts\n",
    "only while the time step stays below the inverse spectral radius of the stage operator. At\n",
    "Δt = 2·10⁻³ they must fail; their stabilized counterpart is the same method at a step it is stable\n",
    "for, shown behind the hatching.\n",
    "Leapfrog has no damping: on the dissipative upwind operator it is unstable at every step. Its\n",
    "stabilized counterpart adds the Robert-Asselin-Williams time filter and runs at a reduced\n",
    "stability safety factor."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "stabilized_time = {\n",
    "    \"leapfrog\": (\n",
    "        \"leapfrog + Robert-Asselin-Williams filter (ν = 0.2, α = 0.53; first order), safety factor 0.15\",\n",
    "        TimeMethod(\"leapfrog_raw\"),\n",
    "        0.15,\n",
    "    ),\n",
    "}\n",
    "stable_step = {\n",
    "    \"BDF4 (Gear)\": 5e-4,\n",
    "    \"BDF5 (Gear)\": 5e-4,\n",
    "    \"BDF6 (Gear)\": 5e-4,\n",
    "    \"Adams-Moulton 4\": 5e-4,\n",
    "    \"fixed point\": 2.5e-4,\n",
    "    \"fixed point + Aitken\": 2.5e-4,\n",
    "}\n",
    "linear_solvers = {\n",
    "    \"sparse LU\": SparseDirect(),\n",
    "    \"GMRES\": GMRES(),\n",
    "    \"GMRES + ILU\": GMRES(preconditioner=ILU()),\n",
    "    \"right GMRES\": RightGMRES(),\n",
    "    \"flexible GMRES\": FlexibleGMRES(),\n",
    "    \"automatic\": AutomaticLinearSolver(),\n",
    "}\n",
    "nonlinear_solvers = {\n",
    "    **{\n",
    "        (name, linear_name): kind(\n",
    "            linear_solver=linear, jacobian=\"colored_finite_difference\"\n",
    "        )\n",
    "        for name, kind in (\n",
    "            (\"Newton\", Newton),\n",
    "            (\"damped Newton\", DampedNewton),\n",
    "            (\"trust-region Newton\", TrustRegionNewton),\n",
    "            (\"quasi-Newton\", QuasiNewton),\n",
    "        )\n",
    "        for linear_name, linear in linear_solvers.items()\n",
    "    },\n",
    "    **{\n",
    "        (\"JFNK\", linear_name): JFNK(linear_solver=linear)\n",
    "        for linear_name, linear in linear_solvers.items()\n",
    "    },\n",
    "    (\"fixed point\", \"none\"): FixedPoint(),\n",
    "    (\"fixed point + Aitken\", \"none\"): FixedPoint(acceleration=\"aitken\"),\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The test matrix\n",
    "\n",
    "Three cuts through the space of combinations:\n",
    "\n",
    "1. **Space × Riemann solver** — every spatial scheme with every Riemann solver, advanced with\n",
    "   SSP-RK2 at the stable step (safety factor 0.5).\n",
    "2. **Time integrator × space** — every integrator with HLLC fluxes. Explicit integrators run on\n",
    "   first-order, MUSCL-minmod and WENO5 volumes at their stable step; implicit integrators run on the\n",
    "   first-order and the MUSCL-minmod volumes with $\\Delta t=2\\cdot10^{-3}$, a CFL number of about\n",
    "   1.4 that no explicit method could take.\n",
    "3. **Nonlinear × linear solver** — backward Euler on MUSCL-minmod-HLLC with\n",
    "   $\\Delta t=2\\cdot10^{-3}$.\n",
    "\n",
    "A fourth cut, **SPH × time integrator**, follows below: the same problem as a particle method.\n",
    "A few representative combinations are repeated on 200 cells for the mesh check."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "time_spatial = {\n",
    "    name: spatial[(name, \"HLLC\")]\n",
    "    for name in (\"FVM first order\", \"FVM MUSCL + minmod\", \"FVM WENO5\")\n",
    "}\n",
    "runs = [\n",
    "    dict(\n",
    "        matrix=\"space x Riemann solver\",\n",
    "        row=row,\n",
    "        column=column,\n",
    "        cells=cells,\n",
    "        spatial=scheme,\n",
    "        time=TimeMethod(\"ssprk2\"),\n",
    "        nonlinear=None,\n",
    "        step=end_time,\n",
    "    )\n",
    "    for (row, column), scheme in spatial.items()\n",
    "]\n",
    "runs += [\n",
    "    dict(\n",
    "        matrix=\"time integrator x space\",\n",
    "        row=name,\n",
    "        column=space,\n",
    "        cells=cells,\n",
    "        spatial=scheme,\n",
    "        time=integrator,\n",
    "        nonlinear=(\n",
    "            newton\n",
    "            if getattr(integrator, \"implicit\", False)\n",
    "            and \"rosenbrock\" not in getattr(integrator, \"method_id\", \"\")\n",
    "            else None\n",
    "        ),\n",
    "        linear=(\n",
    "            SparseDirect()\n",
    "            if \"rosenbrock\" in getattr(integrator, \"method_id\", \"\")\n",
    "            else None\n",
    "        ),\n",
    "        step=2e-3 if getattr(integrator, \"implicit\", False) else end_time,\n",
    "    )\n",
    "    for name, integrator in integrators.items()\n",
    "    for space, scheme in time_spatial.items()\n",
    "    if space != \"FVM WENO5\" or not getattr(integrator, \"implicit\", False)\n",
    "]\n",
    "runs += [\n",
    "    dict(\n",
    "        matrix=\"nonlinear x linear solver\",\n",
    "        row=row,\n",
    "        column=column,\n",
    "        cells=cells,\n",
    "        spatial=time_spatial[\"FVM MUSCL + minmod\"],\n",
    "        time=BackwardEuler(),\n",
    "        nonlinear=solver,\n",
    "        step=2e-3,\n",
    "    )\n",
    "    for (row, column), solver in nonlinear_solvers.items()\n",
    "]\n",
    "runs += [\n",
    "    dict(\n",
    "        matrix=\"space x Riemann solver\",\n",
    "        variant=\"stabilized\",\n",
    "        row=row,\n",
    "        column=flux_name,\n",
    "        cells=cells,\n",
    "        spatial=make(flux),\n",
    "        time=TimeMethod(\"ssprk2\"),\n",
    "        nonlinear=None,\n",
    "        step=end_time,\n",
    "        note_stabilized=description,\n",
    "    )\n",
    "    for row, (description, make) in stabilized_space.items()\n",
    "    for flux_name, flux in riemann.items()\n",
    "]\n",
    "runs += [\n",
    "    {\n",
    "        **run,\n",
    "        \"variant\": \"stabilized\",\n",
    "        \"time\": stabilized_time[run[\"row\"]][1],\n",
    "        \"safety\": stabilized_time[run[\"row\"]][2],\n",
    "        \"note_stabilized\": stabilized_time[run[\"row\"]][0],\n",
    "    }\n",
    "    for run in list(runs)\n",
    "    if run[\"matrix\"] == \"time integrator x space\"\n",
    "    and run[\"row\"] in stabilized_time\n",
    "    and run.get(\"variant\") is None\n",
    "]\n",
    "runs += [\n",
    "    {\n",
    "        **run,\n",
    "        \"variant\": \"stabilized\",\n",
    "        \"step\": stable_step[run[\"row\"]],\n",
    "        \"note_stabilized\": f\"{run['row']} at Δt = {stable_step[run['row']]:.1e}\",\n",
    "    }\n",
    "    for run in list(runs)\n",
    "    if run[\"matrix\"] in (\"time integrator x space\", \"nonlinear x linear solver\")\n",
    "    and run[\"row\"] in stable_step\n",
    "    and run.get(\"variant\") is None\n",
    "]\n",
    "representative = [\n",
    "    (\"FVM first order\", \"Rusanov\"),\n",
    "    (\"FVM first order\", \"HLLC\"),\n",
    "    (\"FVM MUSCL + minmod\", \"HLLC\"),\n",
    "    (\"FVM MUSCL + superbee\", \"HLLC\"),\n",
    "    (\"FVM WENO5\", \"HLLC\"),\n",
    "    (\"FDM WENO5 flux splitting\", \"Lax-Friedrichs splitting\"),\n",
    "    (\"FEM DG P2 + minmod + invariant domain\", \"HLLC\"),\n",
    "    (\"FEM CG P1 + graph viscosity\", \"HLLC\"),\n",
    "]\n",
    "runs += [\n",
    "    {**run, \"matrix\": \"mesh check\", \"cells\": coarse_cells}\n",
    "    for run in runs\n",
    "    if run[\"matrix\"] == \"space x Riemann solver\"\n",
    "    and (run[\"row\"], run[\"column\"]) in representative\n",
    "]\n",
    "print(\n",
    "    f\"{len(runs)} runs: \"\n",
    "    + \", \".join(\n",
    "        f\"{sum(r['matrix'] == m for r in runs)} {m}\"\n",
    "        for m in dict.fromkeys(r[\"matrix\"] for r in runs)\n",
    "    )\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Run everything\n",
    "\n",
    "One loop, the same problem object every time. A combination the library refuses is recorded with\n",
    "its validation message; a run that stops because the solution left the physical state space\n",
    "(negative density or pressure) is recorded as failed."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "for run in runs:\n",
    "    simulation = Simulation(\n",
    "        problem=sod,\n",
    "        mesh=meshes[run[\"cells\"]],\n",
    "        numerics=Numerics(\n",
    "            spatial=run[\"spatial\"],\n",
    "            linear_solver=(\n",
    "                SparseDirect()\n",
    "                if isinstance(run[\"spatial\"], FiniteElement)\n",
    "                else run.get(\"linear\")\n",
    "            ),\n",
    "            time_integrator=run[\"time\"],\n",
    "            nonlinear_solver=run[\"nonlinear\"],\n",
    "            step_limits=TimeStepLimits(stability_safety_factor=run.get(\"safety\", 0.5)),\n",
    "        ),\n",
    "    )\n",
    "    started = time.perf_counter()\n",
    "    check = simulation.validate()\n",
    "    run.update(status=\"rejected\", note=\"\", errors=(np.nan,) * 3, shock=np.nan, steps=0)\n",
    "    if not check.valid:\n",
    "        run[\"note\"] = check.diagnostics[0].split(\": \", 1)[-1].splitlines()[0]\n",
    "    else:\n",
    "        try:\n",
    "            result = simulation.run(\n",
    "                start_time=0.0, end_time=end_time, time_step=run[\"step\"]\n",
    "            )\n",
    "            points = np.column_stack(\n",
    "                (centres[run[\"cells\"]], np.zeros((run[\"cells\"], 2)))\n",
    "            )\n",
    "            run[\"profiles\"] = np.array(\n",
    "                [\n",
    "                    result.field(field).evaluate(points).reshape(-1)\n",
    "                    for field in (gas.density, gas.velocity, gas.pressure)\n",
    "                ]\n",
    "            )\n",
    "            run[\"errors\"] = tuple(\n",
    "                np.abs(run[\"profiles\"] - exact[run[\"cells\"]]).sum(axis=1) / run[\"cells\"]\n",
    "            )\n",
    "            crossing = np.flatnonzero(run[\"profiles\"][0] > shock_level)[-1]\n",
    "            run[\"shock\"] = np.interp(\n",
    "                shock_level,\n",
    "                run[\"profiles\"][0][[crossing + 1, crossing]],\n",
    "                centres[run[\"cells\"]][[crossing + 1, crossing]],\n",
    "            )\n",
    "            run[\"steps\"] = len(result.times) - 1\n",
    "            run[\"status\"] = \"ran\" if np.isfinite(run[\"profiles\"]).all() else \"failed\"\n",
    "        except Exception as error:\n",
    "            message = str(error).splitlines()[0]\n",
    "            run[\"status\"] = (\n",
    "                \"failed\"\n",
    "                if \"non-positive\" in message\n",
    "                or \"finite\" in message\n",
    "                or \"did not converge\" in message\n",
    "                else \"rejected\"\n",
    "            )\n",
    "            run[\"note\"] = message.split(\": \", 1)[-1] if \": \" in message else message\n",
    "    run[\"seconds\"] = time.perf_counter() - started\n",
    "    print(\n",
    "        f\"{run['matrix'][:12]:12s} {run['row'][:34]:34s} {run['column'][:24]:24s} \"\n",
    "        f\"{run['status']:8s} {run['seconds']:7.1f} s  \"\n",
    "        + (\n",
    "            f\"L1 rho {run['errors'][0]:.2e}  shock {run['shock'] - exact_shock:+.1e}\"\n",
    "            if run[\"status\"] == \"ran\"\n",
    "            else run[\"note\"][:90]\n",
    "        )\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Space × Riemann solver\n",
    "\n",
    "The density error of every spatial scheme with every Riemann solver. Empty cells name why a\n",
    "combination did not produce a solution.\n",
    "\n",
    "Every cell shows the declared combination. Where it failed at the shock and a stabilized\n",
    "counterpart exists, the cell is hatched grey and its colour and number are those of the\n",
    "stabilized run; the legend below each matrix says what was added."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "main = {\n",
    "    (r[\"matrix\"], r[\"row\"], r[\"column\"]): r\n",
    "    for r in runs\n",
    "    if r.get(\"variant\") is None and r[\"matrix\"] != \"mesh check\"\n",
    "}\n",
    "substitute = {\n",
    "    (r[\"matrix\"], r[\"row\"], r[\"column\"]): r for r in runs if r.get(\"variant\") == \"stabilized\"\n",
    "}\n",
    "hatch = {\n",
    "    key\n",
    "    for key, r in main.items()\n",
    "    if r[\"status\"] != \"ran\" and substitute.get(key, {}).get(\"status\") == \"ran\"\n",
    "}\n",
    "cell = {key: substitute[key] if key in hatch else r for key, r in main.items()}\n",
    "legend_head = (\n",
    "    \"Hatched: the declared scheme fails at the shock (negative density or pressure, Godunov's \"\n",
    "    \"theorem); colour and value show its stabilized counterpart:\"\n",
    ")\n",
    "\n",
    "matrix = [r for r in runs if r[\"matrix\"] == \"space x Riemann solver\" and r.get(\"variant\") is None]\n",
    "rows, columns = list(dict.fromkeys(r[\"row\"] for r in matrix)), [\n",
    "    *riemann,\n",
    "    \"Lax-Friedrichs splitting\",\n",
    "]\n",
    "grid = {(r[\"row\"], r[\"column\"]): r for r in matrix}\n",
    "space_key = \"space x Riemann solver\"\n",
    "fig = plots.figure(1, 1, size=(13, 19))\n",
    "plots.matrix(\n",
    "    [\n",
    "        [\n",
    "            cell[(space_key, row, c)][\"errors\"][0] if (space_key, row, c) in cell else np.nan\n",
    "            for c in columns\n",
    "        ]\n",
    "        for row in rows\n",
    "    ],\n",
    "    rows,\n",
    "    columns,\n",
    "    scale=\"log\",\n",
    "    label=\"L1 density error at t = 0.2\",\n",
    "    text=[\n",
    "        [\n",
    "            (\n",
    "                f\"{cell[(space_key, row, c)]['errors'][0]:.2e}\"\n",
    "                if cell[(space_key, row, c)][\"status\"] == \"ran\"\n",
    "                else cell[(space_key, row, c)][\"status\"]\n",
    "            )\n",
    "            if (space_key, row, c) in cell\n",
    "            else \"–\"\n",
    "            for c in columns\n",
    "        ]\n",
    "        for row in rows\n",
    "    ],\n",
    "    hatched=[[(space_key, row, c) in hatch for c in columns] for row in rows],\n",
    "    notes=[legend_head]\n",
    "    + [\n",
    "        f\"  {row}: {description}.\"\n",
    "        for row, (description, _) in stabilized_space.items()\n",
    "        if any((space_key, row, c) in hatch for c in columns)\n",
    "    ],\n",
    "    title=f\"Space x Riemann solver, {cells} cells, SSP-RK2\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "All four measures for the combinations that ran, sorted by the density error."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "print(\n",
    "    f\"{'scheme':36s} {'Riemann solver':24s} {'L1 rho':>9s} {'L1 u':>9s} {'L1 p':>9s} \"\n",
    "    f\"{'shock err':>10s} {'steps':>6s} {'time':>8s}\"\n",
    ")\n",
    "for r in sorted(\n",
    "    (r for r in matrix if r[\"status\"] == \"ran\"), key=lambda r: r[\"errors\"][0]\n",
    "):\n",
    "    print(\n",
    "        f\"{r['row']:36s} {r['column']:24s} {r['errors'][0]:9.2e} {r['errors'][1]:9.2e} \"\n",
    "        f\"{r['errors'][2]:9.2e} {r['shock'] - exact_shock:+10.1e} {r['steps']:6d} {r['seconds']:7.1f}s\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Profiles of representative combinations\n",
    "\n",
    "Density, velocity and pressure at $t=0.2$ against the exact solution, and a close-up of the\n",
    "contact and the shock."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "shown = [\n",
    "    r\n",
    "    for r in matrix\n",
    "    if (r[\"row\"], r[\"column\"]) in representative and r[\"status\"] == \"ran\"\n",
    "]\n",
    "fig = plots.figure(2, 2, size=(15, 9))\n",
    "for panel, index, name, window in (\n",
    "    (fig[0], 0, \"density\", None),\n",
    "    (fig[1], 1, \"velocity\", None),\n",
    "    (fig[2], 2, \"pressure\", None),\n",
    "    (fig[3], 0, \"density, contact and shock\", (0.6, 0.95)),\n",
    "):\n",
    "    window_y = None if window is None else (0.1, 0.45)\n",
    "    plots.line(\n",
    "        y={\n",
    "            f\"{r['row']}, {r['column']}\": (centres[cells], r[\"profiles\"][index])\n",
    "            for r in shown\n",
    "        },\n",
    "        reference={\"exact Riemann solution\": (fine, exact[\"fine\"][index])},\n",
    "        xlabel=\"position x\",\n",
    "        ylabel=name.split(\",\")[0],\n",
    "        title=f\"{name.capitalize()} at t = {end_time}\",\n",
    "        xlimits=window,\n",
    "        ylimits=window_y,\n",
    "        legend=\"upper right\" if index == 0 and window is None else False,\n",
    "        ax=panel,\n",
    "    )\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Time integrator × space\n",
    "\n",
    "Explicit integrators at their stable step, implicit integrators at $\\Delta t=2\\cdot10^{-3}$. A dash\n",
    "marks a combination outside this cut (implicit WENO5)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "timing = [r for r in runs if r[\"matrix\"] == \"time integrator x space\" and r.get(\"variant\") is None]\n",
    "time_key = \"time integrator x space\"\n",
    "time_rows, time_columns = list(dict.fromkeys(r[\"row\"] for r in timing)), list(time_spatial)\n",
    "time_grid = {(r[\"row\"], r[\"column\"]): r for r in timing}\n",
    "fig = plots.figure(1, 2, size=(17, 11))\n",
    "time_hatched = [[(time_key, row, c) in hatch for c in time_columns] for row in time_rows]\n",
    "time_notes = (\n",
    "    [\n",
    "        \"Hatched: the declared integrator is unstable at this step (not A-stable, or undamped on \"\n",
    "        \"a dissipative operator); colour and value show its stabilized counterpart:\"\n",
    "    ]\n",
    "    + [\n",
    "        f\"  {row}: same method at Δt = {stable_step[row]:.1e} instead of 2·10⁻³.\"\n",
    "        for row in stable_step\n",
    "        if any((time_key, row, c) in hatch for c in time_columns)\n",
    "    ]\n",
    "    + [\n",
    "        f\"  {row}: {description}.\"\n",
    "        for row, (description, _, _) in stabilized_time.items()\n",
    "        if any((time_key, row, c) in hatch for c in time_columns)\n",
    "    ]\n",
    ")\n",
    "plots.matrix(\n",
    "    [\n",
    "        [\n",
    "            cell[(time_key, row, c)][\"errors\"][0] if (time_key, row, c) in cell else np.nan\n",
    "            for c in time_columns\n",
    "        ]\n",
    "        for row in time_rows\n",
    "    ],\n",
    "    time_rows,\n",
    "    time_columns,\n",
    "    scale=\"log\",\n",
    "    label=\"L1 density error\",\n",
    "    text=[\n",
    "        [\n",
    "            (\n",
    "                f\"{cell[(time_key, row, c)]['errors'][0]:.2e}\"\n",
    "                if cell[(time_key, row, c)][\"status\"] == \"ran\"\n",
    "                else cell[(time_key, row, c)][\"status\"]\n",
    "            )\n",
    "            if (time_key, row, c) in cell\n",
    "            else \"–\"\n",
    "            for c in time_columns\n",
    "        ]\n",
    "        for row in time_rows\n",
    "    ],\n",
    "    hatched=time_hatched,\n",
    "    notes=time_notes,\n",
    "    title=\"L1 density error\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.matrix(\n",
    "    [\n",
    "        [\n",
    "            (\n",
    "                cell[(time_key, row, c)][\"seconds\"]\n",
    "                if (time_key, row, c) in cell and cell[(time_key, row, c)][\"status\"] == \"ran\"\n",
    "                else np.nan\n",
    "            )\n",
    "            for c in time_columns\n",
    "        ]\n",
    "        for row in time_rows\n",
    "    ],\n",
    "    time_rows,\n",
    "    time_columns,\n",
    "    scale=\"log\",\n",
    "    label=\"wall time [s]\",\n",
    "    text=[\n",
    "        [\n",
    "            (\n",
    "                f\"{cell[(time_key, row, c)]['seconds']:.0f} s, {cell[(time_key, row, c)]['steps']} steps\"\n",
    "                if cell[(time_key, row, c)][\"status\"] == \"ran\"\n",
    "                else cell[(time_key, row, c)][\"status\"]\n",
    "            )\n",
    "            if (time_key, row, c) in cell\n",
    "            else \"–\"\n",
    "            for c in time_columns\n",
    "        ]\n",
    "        for row in time_rows\n",
    "    ],\n",
    "    hatched=time_hatched,\n",
    "    title=\"Wall time and accepted steps\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Nonlinear × linear solver\n",
    "\n",
    "Backward Euler on MUSCL-minmod-HLLC. The discrete solution should not depend on the solver as long\n",
    "as each one converges; the wall time does."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "solving = [\n",
    "    r for r in runs if r[\"matrix\"] == \"nonlinear x linear solver\" and r.get(\"variant\") is None\n",
    "]\n",
    "solver_key = \"nonlinear x linear solver\"\n",
    "solver_rows = list(dict.fromkeys(r[\"row\"] for r in solving))\n",
    "solver_columns = [*linear_solvers, \"none\"]\n",
    "solver_grid = {(r[\"row\"], r[\"column\"]): r for r in solving}\n",
    "fig = plots.figure(1, 1, size=(13, 6))\n",
    "plots.matrix(\n",
    "    [\n",
    "        [\n",
    "            (\n",
    "                cell[(solver_key, row, c)][\"seconds\"]\n",
    "                if (solver_key, row, c) in cell and cell[(solver_key, row, c)][\"status\"] == \"ran\"\n",
    "                else np.nan\n",
    "            )\n",
    "            for c in solver_columns\n",
    "        ]\n",
    "        for row in solver_rows\n",
    "    ],\n",
    "    solver_rows,\n",
    "    solver_columns,\n",
    "    scale=\"log\",\n",
    "    label=\"wall time [s]\",\n",
    "    text=[\n",
    "        [\n",
    "            (\n",
    "                (\n",
    "                    f\"{cell[(solver_key, row, c)]['seconds']:.0f} s\\n\"\n",
    "                    f\"{cell[(solver_key, row, c)]['errors'][0]:.3e}\"\n",
    "                )\n",
    "                if cell[(solver_key, row, c)][\"status\"] == \"ran\"\n",
    "                else cell[(solver_key, row, c)][\"status\"]\n",
    "            )\n",
    "            if (solver_key, row, c) in cell\n",
    "            else \"\"\n",
    "            for c in solver_columns\n",
    "        ]\n",
    "        for row in solver_rows\n",
    "    ],\n",
    "    hatched=[[(solver_key, row, c) in hatch for c in solver_columns] for row in solver_rows],\n",
    "    notes=[\n",
    "        \"Hatched: the fixed-point (Picard) iteration cannot contract at Δt = 2·10⁻³; colour and \"\n",
    "        \"value show the same iteration at the step it converges for:\"\n",
    "    ]\n",
    "    + [\n",
    "        f\"  {row}: Δt = {stable_step[row]:.1e}.\"\n",
    "        for row in stable_step\n",
    "        if any((solver_key, row, c) in hatch for c in solver_columns)\n",
    "    ],\n",
    "    title=\"Backward Euler: wall time and L1 density error per solver pair\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Particles: smoothed-particle hydrodynamics × time integrator × artificial viscosity\n",
    "\n",
    "The same gas as moving particles instead of cells: 800 equally spaced particles in the periodic\n",
    "box $[-0.5, 1.5)$, i.e. 400 particles in the graded window $[0, 1]$, the same resolution as the\n",
    "400 cells. Each particle carries the mass of its cell; the smoothing length is 2.5 spacings and\n",
    "the shock is captured by Monaghan's artificial viscosity with the coefficients $\\alpha, \\beta$.\n",
    "Every time integrator of the grid matrix is passed to the particle solver unchanged. The error\n",
    "is the mean absolute density deviation from the exact solution at the particles in $[0, 1]$.\n",
    "\n",
    "Leapfrog has no damping; with any artificial viscosity it is unstable at every step (the\n",
    "library refuses it). Its stabilized counterpart is again the Robert-Asselin-Williams filtered\n",
    "leapfrog."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "particles, box = 800, (-0.5, 1.5)\n",
    "spacing = (box[1] - box[0]) / particles\n",
    "start = box[0] + (np.arange(particles) + 0.5) * spacing\n",
    "start_density = np.where(start < 0.5, 1.0, 0.125)\n",
    "start_pressure = np.where(start < 0.5, 1.0, 0.1)\n",
    "viscosities = {\n",
    "    \"Monaghan α = 1, β = 2\": (1.0, 2.0),\n",
    "    \"Monaghan α = 0.5, β = 1\": (0.5, 1.0),\n",
    "    \"no artificial viscosity\": (0.0, 0.0),\n",
    "}\n",
    "sph_runs = [\n",
    "    dict(matrix=\"SPH\", row=name, column=column, time=integrator, viscosity=coefficients)\n",
    "    for name, integrator in integrators.items()\n",
    "    for column, coefficients in viscosities.items()\n",
    "]\n",
    "sph_runs += [\n",
    "    {\n",
    "        **run,\n",
    "        \"variant\": \"stabilized\",\n",
    "        \"time\": TimeMethod(\"leapfrog_raw\"),\n",
    "        \"note_stabilized\": \"leapfrog + Robert-Asselin-Williams filter (ν = 0.2, α = 0.53)\",\n",
    "    }\n",
    "    for run in list(sph_runs)\n",
    "    if run[\"row\"] == \"leapfrog\" and run[\"viscosity\"] != (0.0, 0.0)\n",
    "]\n",
    "for run in sph_runs:\n",
    "    started = time.perf_counter()\n",
    "    run.update(status=\"rejected\", note=\"\", errors=(np.nan,) * 3, steps=0)\n",
    "    try:\n",
    "        result = HydrodynamicPublicApi.create_provider(\n",
    "            \"sph_hydrodynamics\",\n",
    "            positions=start,\n",
    "            masses=start_density * spacing,\n",
    "            velocities=np.zeros(particles),\n",
    "            specific_internal_energy=start_pressure / ((gamma - 1) * start_density),\n",
    "            smoothing_length=2.5 * spacing,\n",
    "            gamma=gamma,\n",
    "            viscosity_alpha=run[\"viscosity\"][0],\n",
    "            viscosity_beta=run[\"viscosity\"][1],\n",
    "            periodic_bounds=(box,),\n",
    "            final_time=end_time,\n",
    "            time_step=1.0e-3,\n",
    "            cfl=0.25,\n",
    "            time_integrator=run[\"time\"],\n",
    "        ).run()\n",
    "        window = (result.positions[:, 0] >= 0.0) & (result.positions[:, 0] <= 1.0)\n",
    "        reference = np.array(\n",
    "            [\n",
    "                [\n",
    "                    getattr(\n",
    "                        exact_euler_pressure_trace(\n",
    "                            *waves, similarity=(x - 0.5) / end_time\n",
    "                        ).state,\n",
    "                        name,\n",
    "                    )\n",
    "                    for x in result.positions[window, 0]\n",
    "                ]\n",
    "                for name in (\"density\", \"velocity\", \"pressure\")\n",
    "            ]\n",
    "        )\n",
    "        values = np.array(\n",
    "            (\n",
    "                result.density[window],\n",
    "                result.velocities[window, 0],\n",
    "                result.pressure[window],\n",
    "            )\n",
    "        )\n",
    "        run[\"errors\"] = tuple(np.abs(values - reference).mean(axis=1))\n",
    "        run[\"status\"] = \"ran\" if np.isfinite(values).all() else \"failed\"\n",
    "    except Exception as error:\n",
    "        message = str(error).splitlines()[0]\n",
    "        run[\"status\"] = \"failed\" if \"no stable region\" in message else \"rejected\"\n",
    "        run[\"note\"] = message.split(\": \", 1)[-1] if \": \" in message else message\n",
    "    run[\"seconds\"] = time.perf_counter() - started\n",
    "    print(\n",
    "        f\"SPH {run['row'][:28]:28s} {run['column'][:26]:26s} {run.get('variant') or '':10s} \"\n",
    "        f\"{run['status']:8s} {run['seconds']:6.1f} s  \"\n",
    "        + (f\"L1 rho {run['errors'][0]:.2e}\" if run[\"status\"] == \"ran\" else run[\"note\"][:90])\n",
    "    )\n",
    "\n",
    "sph_main = {(r[\"row\"], r[\"column\"]): r for r in sph_runs if r.get(\"variant\") is None}\n",
    "sph_substitute = {\n",
    "    (r[\"row\"], r[\"column\"]): r for r in sph_runs if r.get(\"variant\") == \"stabilized\"\n",
    "}\n",
    "sph_hatch = {\n",
    "    key\n",
    "    for key, r in sph_main.items()\n",
    "    if r[\"status\"] != \"ran\" and sph_substitute.get(key, {}).get(\"status\") == \"ran\"\n",
    "}\n",
    "sph_cell = {key: sph_substitute[key] if key in sph_hatch else r for key, r in sph_main.items()}\n",
    "sph_rows, sph_columns = list(integrators), list(viscosities)\n",
    "fig = plots.figure(1, 2, size=(17, 12))\n",
    "for panel, measure, label, title in (\n",
    "    (fig[0], \"errors\", \"L1 density error\", \"SPH: L1 density error, 400 particles in [0, 1]\"),\n",
    "    (fig[1], \"seconds\", \"wall time [s]\", \"SPH: wall time\"),\n",
    "):\n",
    "    plots.matrix(\n",
    "        [\n",
    "            [\n",
    "                (\n",
    "                    (sph_cell[(row, c)][\"errors\"][0] if measure == \"errors\" else sph_cell[(row, c)][\"seconds\"])\n",
    "                    if sph_cell[(row, c)][\"status\"] == \"ran\"\n",
    "                    else np.nan\n",
    "                )\n",
    "                for c in sph_columns\n",
    "            ]\n",
    "            for row in sph_rows\n",
    "        ],\n",
    "        sph_rows,\n",
    "        sph_columns,\n",
    "        scale=\"log\",\n",
    "        label=label,\n",
    "        text=[\n",
    "            [\n",
    "                (\n",
    "                    (\n",
    "                        f\"{sph_cell[(row, c)]['errors'][0]:.2e}\"\n",
    "                        if measure == \"errors\"\n",
    "                        else f\"{sph_cell[(row, c)]['seconds']:.1f} s\"\n",
    "                    )\n",
    "                    if sph_cell[(row, c)][\"status\"] == \"ran\"\n",
    "                    else sph_cell[(row, c)][\"status\"]\n",
    "                )\n",
    "                for c in sph_columns\n",
    "            ]\n",
    "            for row in sph_rows\n",
    "        ],\n",
    "        hatched=[[(row, c) in sph_hatch for c in sph_columns] for row in sph_rows],\n",
    "        notes=(\n",
    "            [\n",
    "                \"Hatched: leapfrog is unstable under any artificial viscosity; colour and value show \"\n",
    "                \"leapfrog + Robert-Asselin-Williams filter (ν = 0.2, α = 0.53).\"\n",
    "            ]\n",
    "            if sph_hatch and measure == \"errors\"\n",
    "            else None\n",
    "        ),\n",
    "        title=title,\n",
    "        ax=panel,\n",
    "    )\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Mesh check: 400 against 200 cells\n",
    "\n",
    "The representative combinations on half as many cells. For a discontinuous solution the $L_1$\n",
    "error falls roughly like $\\Delta x^{1/2}$ to $\\Delta x^{1}$; the shock position converges to its\n",
    "exact value."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "coarse = {(r[\"row\"], r[\"column\"]): r for r in runs if r[\"matrix\"] == \"mesh check\"}\n",
    "print(\n",
    "    f\"{'scheme':36s} {'Riemann solver':24s} {'L1 rho 200':>11s} {'L1 rho 400':>11s} \"\n",
    "    f\"{'ratio':>6s} {'shock err 200':>14s} {'shock err 400':>14s}\"\n",
    ")\n",
    "for key, r in coarse.items():\n",
    "    fine_run = grid[key]\n",
    "    if r[\"status\"] == \"ran\" and fine_run[\"status\"] == \"ran\":\n",
    "        print(\n",
    "            f\"{key[0]:36s} {key[1]:24s} {r['errors'][0]:11.3e} {fine_run['errors'][0]:11.3e} \"\n",
    "            f\"{r['errors'][0] / fine_run['errors'][0]:6.2f} {r['shock'] - exact_shock:+14.2e} \"\n",
    "            f\"{fine_run['shock'] - exact_shock:+14.2e}\"\n",
    "        )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## What the library refused, and what failed\n",
    "\n",
    "A refused combination is caught by validation or binding before any time step; a failed one\n",
    "started and produced a non-physical state."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "for status in (\"rejected\", \"failed\"):\n",
    "    selected = [r for r in runs + sph_runs if r[\"status\"] == status]\n",
    "    print(f\"\\n{len(selected)} {status}:\")\n",
    "    for r in selected:\n",
    "        print(f\"  {r['matrix'][:12]:12s} {r['row'][:34]:34s} {r['column'][:24]:24s} {r['note'][:100]}\")\n",
    "print(\n",
    "    \"\\nsummary: \"\n",
    "    + \", \".join(\n",
    "        f\"{sum(r['status'] == s for r in runs + sph_runs)} {s}\"\n",
    "        for s in (\"ran\", \"rejected\", \"failed\")\n",
    "    )\n",
    "    + f\" of {len(runs) + len(sph_runs)} runs, \"\n",
    "    + f\"{sum(r['seconds'] for r in runs + sph_runs) / 60:.0f} min in total\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Methods that do not apply to Sod's problem\n",
    "\n",
    "A few methods in the library are not in the matrix because the Euler system lacks what they are\n",
    "built for: conjugate gradients and algebraic multigrid need a symmetric positive definite operator;\n",
    "Runge-Kutta-Chebyshev and -Legendre super-steps are for parabolic operators; staggered Verlet needs\n",
    "a second-order system; IMEX splits need a stiff and a non-stiff part; local time stepping is for\n",
    "steady states; hydrostatic reconstruction is for shallow water and Scharfetter-Gummel fluxes are\n",
    "for drift-diffusion. Scalar convection fluxes (linear or monotone upwind, central) are refused for\n",
    "the Euler system with a message that names a Riemann solver instead.\n",
    "\n",
    "## Going further\n",
    "\n",
    "Swap the Riemann problem for Lax's or the 123 problem by changing the two initial states; the\n",
    "matrix code stays as it is. Add a column by adding one object to a dictionary: a new limiter, a\n",
    "different flux, another integrator."
   ]
  }
 ]
}
