{
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "name": "python3",
   "language": "python",
   "display_name": "Python 3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# The rising bubble benchmark\n",
    "\n",
    "A circular bubble of radius $r_0=0.25$ m starts at rest at $(0.5, 0.5)$ m in a liquid column of\n",
    "$1\\times2$ m. Buoyancy lifts it; on its way up it flattens into an ellipse and develops a dimpled\n",
    "rear while surface tension keeps it in one piece. Liquid (index 1) and gas (index 2) are two\n",
    "immiscible incompressible fluids,\n",
    "\n",
    "$$\\rho(\\phi)\\Big(\\frac{\\partial\\mathbf u}{\\partial t}+\\mathbf u\\cdot\\nabla\\mathbf u\\Big)=-\\nabla p+\\nabla\\cdot\\big(\\mu(\\phi)(\\nabla\\mathbf u+\\nabla\\mathbf u^T)\\big)+\\sigma\\kappa\\,\\mathbf n\\,\\delta_\\Gamma+\\rho(\\phi)\\,\\mathbf g,\\qquad\\nabla\\cdot\\mathbf u=0,$$\n",
    "\n",
    "with density and viscosity jumping across the interface $\\Gamma$, which a level set $\\phi$ carries\n",
    "with the flow. Test case 1: $\\rho_1=1000$, $\\rho_2=100$ kg/m³, $\\mu_1=10$, $\\mu_2=1$ Pa s,\n",
    "$\\sigma=24.5$ N/m, $g=0.98$ m/s² ($Re=35$, $Eo=10$).\n",
    "\n",
    "| face | condition |\n",
    "|---|---|\n",
    "| `floor`, `lid` | no slip |\n",
    "| `sides` | free slip |\n",
    "\n",
    "**Reference.** S. Hysing, S. Turek, D. Kuzmin, N. Parolini, E. Burman, S. Ganesan, L. Tobiska,\n",
    "\"Quantitative benchmark computations of two-dimensional bubble dynamics\", *Int. J. Numer. Meth.\n",
    "Fluids* 60, 1259-1288 (2009), test case 1, finest-grid values of the code TP2D: maximum rise\n",
    "velocity 0.2417 m/s at $t=0.9213$ s, minimum circularity 0.9013 at $t=1.9041$ s, centre of mass\n",
    "$y_c=1.0813$ m at $t=3$ s. The benchmark defines centre of mass and rise velocity as averages over\n",
    "the bubble and the circularity as the perimeter of the circle of equal area over the perimeter of\n",
    "the bubble."
   ],
   "id": "markdown-01"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import NewtonianFluid\n",
    "from onesim.meshing import TriangularMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, TaylorHood\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.numerics.time import BDF\n",
    "from onesim.physics.hydrodynamics import FreeSlipLaw, LevelSet, NoSlipWall, TwoPhaseFlow, WallShear\n",
    "from onesim.results import ResultRetentionPolicy, phase_statistics\n",
    "from onesim.simulation import ExecutionOptions, Problem, Simulation\n",
    "from onesim.simulation.field_constraints import MeanValue\n",
    "from onesim.simulation.initial_conditions import InitialValue\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "code-02"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and meshes\n",
    "\n",
    "The cross-section at half depth keeps the face names. Three uniform meshes of quadratic triangles\n",
    "with 1/28, 1/40 and 1/64 m target size form the mesh study."
   ],
   "id": "markdown-03"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "part = load(\"rising_bubble_benchmark.step\")\n",
    "column = part.section((0, 0, 1), origin=(0, 0, part.size[2] / 2))\n",
    "faces = column.boundaries\n",
    "sizes = (1 / 28, 1 / 40, 1 / 64)\n",
    "meshes = {size: TriangularMesher(target_size=size).generate(column) for size in sizes}\n",
    "\n",
    "for h, mesh in meshes.items():\n",
    "    print(f\"h = 1/{round(1/h)}: {len(mesh.coordinates):,} nodes, {mesh.cell_count:,} triangles\")\n",
    "\n",
    "fig = plots.figure(1, 2, size=(11, 7))\n",
    "plots.geometry(part, selection={\"no slip\": part.boundaries.floor | part.boundaries.lid, \"free slip\": part.boundaries.sides},\n",
    "               labels=False, camera=plots.Camera(elevation=20, azimuth=-60), title=\"Liquid column\", ax=fig[0])\n",
    "plots.mesh(meshes[sizes[-1]], groups=(\"all\",), legend=False, title=f\"Finest mesh: {meshes[sizes[-1]].cell_count} triangles\", ax=fig[1])\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "code-04"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "`TwoPhaseFlow` takes both fluids, the surface tension, gravity and the interface method. The\n",
    "level set starts as the signed distance to the circle, positive in the liquid. Each BDF2 step\n",
    "first moves the interface with the extrapolated velocity, then solves the momentum and continuity\n",
    "equations with the new density and viscosity and a semi-implicit surface tension. The pressure\n",
    "mean is fixed because all walls are closed."
   ],
   "id": "markdown-05"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "liquid, gas = NewtonianFluid(density=1000.0, dynamic_viscosity=10.0), NewtonianFluid(density=100.0, dynamic_viscosity=1.0)\n",
    "flow = TwoPhaseFlow(domain=column.surface, fluids=(liquid, gas), interface=LevelSet(), surface_tension=24.5,\n",
    "                    gravity=(0.0, -0.98))\n",
    "problem = Problem(name=\"Rising bubble\", geometry=column, physics=(flow,), boundary_conditions=(\n",
    "    NoSlipWall(physics=flow, boundary=faces.floor | faces.lid),\n",
    "    WallShear(physics=flow, boundary=faces.sides, law=FreeSlipLaw())),\n",
    "    initial_conditions=(InitialValue(flow.phase, lambda x, y: np.hypot(x - 0.5, y - 0.5) - 0.25),),\n",
    "    constraints=(MeanValue(flow.pressure, 0.0),))\n",
    "numerics = Numerics(spatial=FiniteElement(element=TaylorHood()), time_integrator=BDF(order=2), linear_solver=SparseDirect())\n",
    "keep = ExecutionOptions(result_retention=ResultRetentionPolicy(mode=\"stride\", stride=2))\n",
    "results = {size: Simulation(problem=problem, mesh=meshes[size], numerics=numerics).run(\n",
    "    start_time=0.0, end_time=3.0, time_step=min(0.01, 0.32 * size), execution_options=keep) for size in sizes}"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "code-06"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "`phase_statistics` returns the bubble volume, centroid, mean velocity, perimeter and circularity\n",
    "at every saved time; the level set keeps the bubble volume to round-off."
   ],
   "id": "markdown-07"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "statistics = {size: phase_statistics(results[size], flow) for size in sizes}\n",
    "reference = {\"maximum rise velocity [m/s]\": 0.2417, \"time of maximum [s]\": 0.9213, \"minimum circularity\": 0.9013,\n",
    "             \"time of minimum [s]\": 1.9041, \"centre of mass at t = 3 s [m]\": 1.0813}\n",
    "measured = {size: {\"maximum rise velocity [m/s]\": s.velocity[:, 1].max(), \"time of maximum [s]\": s.times[np.argmax(s.velocity[:, 1])],\n",
    "                   \"minimum circularity\": s.circularity.min(), \"time of minimum [s]\": s.times[np.argmin(s.circularity)],\n",
    "                   \"centre of mass at t = 3 s [m]\": s.centroid[-1, 1]} for size, s in statistics.items()}\n",
    "print(f\"{'quantity':32s}{'Hysing et al.':>14s}\" + \"\".join(f\"{f'h = 1/{round(1 / h)}':>12s}\" for h in sizes) + f\"{'deviation':>11s}\")\n",
    "for name, value in reference.items():\n",
    "    print(f\"{name:32s}{value:14.4f}\" + \"\".join(f\"{measured[h][name]:12.4f}\" for h in sizes)\n",
    "          + f\"{100 * (measured[sizes[-1]][name] / value - 1):+10.2f}%\")\n",
    "print(f\"bubble volume change on the finest mesh: {statistics[sizes[-1]].volume_change[-1]:.1e}\")"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "code-08"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Bubble at $t=3$ s on the finest mesh (gas fraction) and the three benchmark curves on all meshes;\n",
    "the markers are the extrema of the reference."
   ],
   "id": "markdown-09"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fine = statistics[sizes[-1]]\n",
    "fig = plots.figure(layout=[[\"shape\", \"centre\", \"rise\"], [\"shape\", \"circularity\", \"circularity\"]], size=(16, 10))\n",
    "plots.surface(results[sizes[-1]].field(flow.volume_fraction), time=3.0, limits=(0.0, 1.0), subdivisions=2, label=\"gas fraction\",\n",
    "              xlabel=\"x [m]\", ylabel=\"y [m]\", title=\"Bubble at t = 3 s\", ax=fig[\"shape\"])\n",
    "plots.line(y={f\"h = 1/{round(1 / h)}\": (statistics[h].times, statistics[h].centroid[:, 1]) for h in sizes},\n",
    "           points={\"Hysing et al., t = 3 s\": ([3.0], [1.0813])}, xlabel=\"time [s]\", ylabel=\"centre of mass [m]\",\n",
    "           title=\"Centre of mass\", legend=\"upper left\", ax=fig[\"centre\"])\n",
    "plots.line(y={f\"h = 1/{round(1 / h)}\": (statistics[h].times, statistics[h].velocity[:, 1]) for h in sizes},\n",
    "           points={\"Hysing et al., maximum\": ([0.9213], [0.2417])}, xlabel=\"time [s]\", ylabel=\"rise velocity [m/s]\",\n",
    "           title=\"Rise velocity\", legend=\"lower right\", ax=fig[\"rise\"])\n",
    "plots.line(y={f\"h = 1/{round(1 / h)}\": (statistics[h].times, statistics[h].circularity) for h in sizes},\n",
    "           points={\"Hysing et al., minimum\": ([1.9041], [0.9013])}, xlabel=\"time [s]\", ylabel=\"circularity\",\n",
    "           title=\"Circularity\", legend=\"upper right\", ax=fig[\"circularity\"])\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "code-10"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Test case 2 of the benchmark ($\\rho_2=1$ kg/m³, $\\mu_2=0.1$ Pa s, $\\sigma=1.96$ N/m) tears thin\n",
    "filaments off the bubble: change the gas and the surface tension. `interface=ConservativeLevelSet()`\n",
    "or `interface=PhaseField(interface_width=..., mobility=...)` switches the interface method without\n",
    "touching the rest of the model, and `kinematics=AxisymmetricFlow()` on an r-z section computes a\n",
    "rising drop in a tube."
   ],
   "id": "markdown-11"
  }
 ]
}
