{
 "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": [
    "# Rayleigh-Bénard convection: onset of the convection rolls\n",
    "\n",
    "A fluid layer of depth $d$ lies between two rigid horizontal plates; the lower plate is warmer\n",
    "than the upper one by $\\Delta T$. Warm, light fluid sits under cold, heavy fluid, but viscosity\n",
    "and heat conduction damp every disturbance as long as the Rayleigh number\n",
    "\n",
    "$$Ra=\\frac{g\\beta\\Delta T\\,d^3}{\\nu\\alpha}$$\n",
    "\n",
    "stays below the critical value $Ra_c=1707.76$. Above it the conduction state is unstable and\n",
    "steady two-dimensional rolls of wavelength $2\\pi d/3.117$ appear. The Nusselt number, the heat\n",
    "carried across the layer divided by the conducted heat, grows from 1 linearly in $Ra-Ra_c$ near\n",
    "the onset.\n",
    "\n",
    "In units of $d$, $\\Delta T$ and $\\alpha$ (Prandtl number $Pr=1$) the steady Boussinesq equations\n",
    "are solved on a layer one critical wavelength wide. Its side walls are planes of symmetry of the\n",
    "roll pattern (free slip, no heat flux), so two counter-rotating rolls fit exactly; the initial\n",
    "temperature carries a small disturbance of that shape. The layer comes from the CAD file\n",
    "`rayleigh_benard_convection_onset.step`, written by `rayleigh_benard_convection_onset_geometry.py`\n",
    "with the CAD objects of OneSimulation.\n",
    "\n",
    "| face | flow | heat |\n",
    "|---|---|---|\n",
    "| `heated_bottom` | no slip | $T=1$ |\n",
    "| `cooled_top` | no slip | $T=0$ |\n",
    "| `sides` | free slip (symmetry) | no flux |\n",
    "\n",
    "**Reference.** Linear stability of the layer between rigid plates: $Ra_c=1707.76$ at wave number\n",
    "$a_c=3.117$ (W. H. Reid and D. L. Harris, *Phys. Fluids* 1, 102 (1958); S. Chandrasekhar,\n",
    "*Hydrodynamic and Hydromagnetic Stability*, 1961, Ch. II). Steady rolls of the critical wavelength\n",
    "at $Ra=2500$: $Nu=1.47$ (R. M. Clever and F. H. Busse, *J. Fluid Mech.* 65, 625 (1974))."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import ThermalFluid\n",
    "from onesim.meshing import TriangularMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.coupled_systems import StationaryPartitionedCoupling\n",
    "from onesim.numerics.fem import FiniteElement, GalerkinAdvection, Lagrange, TaylorHood\n",
    "from onesim.numerics.field_transfer import FieldInterpolation\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.numerics.nonlinear import FixedPoint, Newton\n",
    "from onesim.physics.heat_transfer import (\n",
    "    BoussinesqBuoyancy,\n",
    "    ConvectiveHeatTransfer,\n",
    "    FixedTemperature,\n",
    "    HeatFlux,\n",
    ")\n",
    "from onesim.physics.hydrodynamics import (\n",
    "    FreeSlipLaw,\n",
    "    IncompressibleNavierStokes,\n",
    "    NoSlipWall,\n",
    "    WallShear,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.simulation.field_connections import FieldCoupling\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": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "The cross-section at half thickness keeps the face names. Two meshes: triangles of 1/8 and 1/12\n",
    "of the layer depth."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "part = load(\"rayleigh_benard_convection_onset.step\")\n",
    "layer = part.section((0, 0, 1), origin=(0, 0, part.size[2] / 2))\n",
    "faces = layer.boundaries\n",
    "width = layer.size[0]\n",
    "meshes = {\n",
    "    size: TriangularMesher(target_size=size).generate(layer) for size in (1 / 8, 1 / 12)\n",
    "}\n",
    "\n",
    "fig = plots.figure(1, 2, size=(14, 5))\n",
    "plots.geometry(\n",
    "    part,\n",
    "    selection={\n",
    "        \"heated bottom\": part.boundaries.heated_bottom,\n",
    "        \"cooled top\": part.boundaries.cooled_top,\n",
    "        \"symmetry sides\": part.boundaries.sides,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=62, azimuth=-90),\n",
    "    title=\"Fluid layer, one critical wavelength wide\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[1 / 12],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Finer mesh: {meshes[1 / 12].cell_count} triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Sweep over the Rayleigh number\n",
    "\n",
    "Flow (Taylor-Hood) and heat (quadratic elements) are coupled both ways: `BoussinesqBuoyancy` turns\n",
    "the temperature into the body force, the solved velocity carries the heat.\n",
    "`StationaryPartitionedCoupling` iterates the two stationary solvers to their common fixed point.\n",
    "One Rayleigh number lies below the onset, four above it, on the coarser mesh; $Ra=2500$ is also\n",
    "solved on the finer mesh."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "prandtl = 1.0\n",
    "fluid = ThermalFluid(\n",
    "    density=1.0,\n",
    "    dynamic_viscosity=prandtl,\n",
    "    thermal_conductivity=1.0,\n",
    "    specific_heat_capacity=1.0,\n",
    "    thermal_expansion_coefficient=1.0,\n",
    ")\n",
    "flow = IncompressibleNavierStokes(domain=layer.domain(), material=fluid)\n",
    "heat = ConvectiveHeatTransfer(domain=layer.domain(), material=fluid, velocity=None)\n",
    "numerics = {\n",
    "    flow: Numerics(\n",
    "        spatial=FiniteElement(element=TaylorHood()),\n",
    "        initial_guess={flow.velocity: (0.0, 0.0)},\n",
    "        nonlinear_solver=Newton(\n",
    "            linear_solver=SparseDirect(),\n",
    "            absolute_tolerance=1e-10,\n",
    "            relative_tolerance=1e-9,\n",
    "        ),\n",
    "    ),\n",
    "    heat: Numerics(\n",
    "        spatial=FiniteElement(\n",
    "            element=Lagrange(order=2), convection=GalerkinAdvection()\n",
    "        ),\n",
    "        linear_solver=SparseDirect(),\n",
    "    ),\n",
    "}\n",
    "runs = [(rayleigh, 1 / 8) for rayleigh in (1500.0, 1800.0, 2000.0, 2250.0, 2500.0)] + [\n",
    "    (2500.0, 1 / 12)\n",
    "]\n",
    "results = {}\n",
    "for rayleigh, size in runs:\n",
    "    problem = Problem(\n",
    "        name=f\"Rayleigh-Benard layer, Ra = {rayleigh:.0f}\",\n",
    "        geometry=layer,\n",
    "        physics=(flow, heat),\n",
    "        boundary_conditions=(\n",
    "            NoSlipWall(physics=flow, boundary=faces.heated_bottom | faces.cooled_top),\n",
    "            WallShear(physics=flow, boundary=faces.sides, law=FreeSlipLaw()),\n",
    "            FixedTemperature(physics=heat, boundary=faces.heated_bottom, value=1.0),\n",
    "            FixedTemperature(physics=heat, boundary=faces.cooled_top, value=0.0),\n",
    "            HeatFlux(physics=heat, boundary=faces.sides, value=0.0),\n",
    "        ),\n",
    "        constraints=(MeanValue(flow.pressure, 0.0),),\n",
    "        initial_conditions=(\n",
    "            InitialValue(\n",
    "                heat.temperature,\n",
    "                lambda x, y: 1\n",
    "                - y\n",
    "                + 0.05 * np.sin(np.pi * y) * np.cos(2 * np.pi * x / width),\n",
    "            ),\n",
    "        ),\n",
    "        couplings=(\n",
    "            FieldCoupling(\n",
    "                source=heat.temperature,\n",
    "                target=flow.field(\"body_force\"),\n",
    "                transfer=BoussinesqBuoyancy(\n",
    "                    gravity=(0, -rayleigh * prandtl), reference_temperature=0.5\n",
    "                ),\n",
    "            ),\n",
    "            FieldCoupling(\n",
    "                source=flow.velocity,\n",
    "                target=heat.advecting_velocity,\n",
    "                transfer=FieldInterpolation(),\n",
    "            ),\n",
    "        ),\n",
    "    )\n",
    "    results[rayleigh, size] = Simulation(\n",
    "        problem=problem,\n",
    "        mesh={flow: meshes[size], heat: meshes[size]},\n",
    "        numerics=numerics,\n",
    "        coupling_solver=StationaryPartitionedCoupling(\n",
    "            stationary_systems=(flow, heat),\n",
    "            iteration=FixedPoint(\n",
    "                relative_tolerance=1e-6,\n",
    "                absolute_tolerance=1e-9,\n",
    "                maximum_iterations=400,\n",
    "                relaxation=0.8,\n",
    "            ),\n",
    "        ),\n",
    "    ).solve_stationary()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Onset and heat transfer\n",
    "\n",
    "The Nusselt number is the heat entering through the bottom per unit width. Near the onset\n",
    "$Nu-1$ and the square of the roll velocity both grow linearly with $Ra-Ra_c$; a fit through the\n",
    "convecting states, extrapolated to zero, gives two estimates of the critical Rayleigh number."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "probe = np.array(\n",
    "    [[x, y] for x in np.linspace(0, width, 41) for y in np.linspace(0.05, 0.95, 19)]\n",
    ")\n",
    "table = {\n",
    "    key: (\n",
    "        -result.field(heat.temperature).boundary_flux(faces.heated_bottom) / width,\n",
    "        result.field(heat.temperature).boundary_flux(faces.cooled_top) / width,\n",
    "        np.abs(result.field(flow.velocity).evaluate(probe)).max(),\n",
    "        len(result.result_set.solver_report[\"coupling\"][\"scaled_changes\"]),\n",
    "    )\n",
    "    for key, result in results.items()\n",
    "}\n",
    "print(\n",
    "    \"    Ra   mesh h   Nu (bottom)   Nu (top)   largest velocity [alpha/d]   coupling sweeps\"\n",
    ")\n",
    "for (rayleigh, size), (bottom, top, speed, sweeps) in table.items():\n",
    "    print(\n",
    "        f\"{rayleigh:6.0f} {size:8.4f} {bottom:13.5f} {top:10.5f} {speed:28.4f} {sweeps:17d}\"\n",
    "    )\n",
    "convecting = [rayleigh for rayleigh, size in runs[:-1] if rayleigh > 1707.76]\n",
    "nusselt_fit = np.polyfit(\n",
    "    convecting, [table[rayleigh, 1 / 8][0] - 1 for rayleigh in convecting], 2\n",
    ")\n",
    "speed_fit = np.polyfit(\n",
    "    convecting, [table[rayleigh, 1 / 8][2] ** 2 for rayleigh in convecting], 2\n",
    ")\n",
    "onsets = {\n",
    "    name: min(np.roots(fit).real, key=lambda root: abs(root - 1700))\n",
    "    for name, fit in ((\"Nu - 1\", nusselt_fit), (\"velocity²\", speed_fit))\n",
    "}\n",
    "print(\n",
    "    f\"\\nbelow the onset (Ra = 1500): Nu - 1 = {table[1500.0, 1 / 8][0] - 1:.1e}, largest velocity {table[1500.0, 1 / 8][2]:.1e}: \"\n",
    "    f\"the disturbance has decayed\"\n",
    ")\n",
    "for name, onset in onsets.items():\n",
    "    print(\n",
    "        f\"critical Rayleigh number from {name:9s}: {onset:8.1f}, linear stability 1707.76 ({100 * (onset / 1707.76 - 1):+.2f} %)\"\n",
    "    )\n",
    "print(\n",
    "    f\"Nusselt number at Ra = 2500: {table[2500.0, 1 / 8][0]:.4f}, Clever & Busse 1.47 ({100 * (table[2500.0, 1 / 8][0] / 1.47 - 1):+.2f} %); \"\n",
    "    f\"finer mesh {table[2500.0, 1 / 12][0]:.4f} ({100 * (table[2500.0, 1 / 12][0] / table[2500.0, 1 / 8][0] - 1):+.3f} %)\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Temperature and roll streamlines at $Ra=2500$, and the Nusselt number over the Rayleigh number\n",
    "with the extrapolated onset."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "grid_x, grid_y = np.linspace(0.0, width, 81), np.linspace(0.0, 1.0, 41)\n",
    "flow_samples = (\n",
    "    results[2500.0, 1 / 12]\n",
    "    .field(flow.velocity)\n",
    "    .evaluate(np.array([[a, b] for a in grid_x for b in grid_y]))\n",
    "    .reshape(81, 41, 2)\n",
    ")\n",
    "curve = np.linspace(onsets[\"Nu - 1\"], 2600.0, 200)\n",
    "fig = plots.figure(\n",
    "    layout=[[\"temperature\", \"nusselt\"], [\"streamlines\", \"nusselt\"]], size=(16, 8.5)\n",
    ")\n",
    "plots.surface(\n",
    "    results[2500.0, 1 / 12].field(heat.temperature),\n",
    "    limits=(0.0, 1.0),\n",
    "    contours=10,\n",
    "    subdivisions=2,\n",
    "    label=\"T\",\n",
    "    xlabel=\"x / d\",\n",
    "    ylabel=\"y / d\",\n",
    "    title=\"Temperature, Ra = 2500\",\n",
    "    ax=fig[\"temperature\"],\n",
    ")\n",
    "plots.streamlines(\n",
    "    grid_x,\n",
    "    grid_y,\n",
    "    flow_samples[..., 0],\n",
    "    flow_samples[..., 1],\n",
    "    density=1.2,\n",
    "    label=\"speed [alpha/d]\",\n",
    "    xlabel=\"x / d\",\n",
    "    ylabel=\"y / d\",\n",
    "    title=\"Two counter-rotating rolls\",\n",
    "    ax=fig[\"streamlines\"],\n",
    ")\n",
    "plots.line(\n",
    "    np.r_[1200.0, curve],\n",
    "    {\n",
    "        \"fit through the convecting states\": np.r_[\n",
    "            1.0, 1 + np.polyval(nusselt_fit, curve)\n",
    "        ]\n",
    "    },\n",
    "    points={\n",
    "        \"OneSimulation\": (\n",
    "            [rayleigh for rayleigh, size in runs[:-1]],\n",
    "            [table[key][0] for key in runs[:-1]],\n",
    "        ),\n",
    "        \"Clever & Busse (1974)\": ([2500.0], [1.47]),\n",
    "    },\n",
    "    vlines={\"Ra_c = 1707.76\": 1707.76},\n",
    "    ylimits=(0.9, 1.6),\n",
    "    xlabel=\"Rayleigh number\",\n",
    "    ylabel=\"Nusselt number\",\n",
    "    title=\"Onset of convection\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[\"nusselt\"],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Change the width of the layer in `rayleigh_benard_convection_onset_geometry.py` and the onset\n",
    "moves up along the neutral curve $Ra(a)$; raise the Rayleigh number further to follow\n",
    "$Nu(Ra)$ until the rolls become time dependent; or replace the upper plate by a free surface\n",
    "(free slip), for which the critical value drops to 1100.65."
   ]
  }
 ]
}
