{
 "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": [
    "# Buoyancy-driven flow in a differentially heated square cavity\n",
    "\n",
    "A square cavity of side $L$ is filled with a fluid of Prandtl number $Pr=\\nu/\\alpha=0.71$\n",
    "(air). The left wall is held at $T_h$, the right wall at $T_c$, top and bottom are insulated.\n",
    "Warm fluid rises along the hot wall, crosses under the top, sinks along the cold wall and returns\n",
    "along the bottom. With the Boussinesq approximation (density variation only in the gravity term)\n",
    "the steady flow obeys\n",
    "\n",
    "$$\\rho(\\mathbf u\\cdot\\nabla)\\mathbf u=-\\nabla p+\\mu\\nabla^2\\mathbf u-\\rho\\beta(T-T_0)\\mathbf g,\n",
    "  \\qquad \\nabla\\cdot\\mathbf u=0,\\qquad \\rho c_p\\,\\mathbf u\\cdot\\nabla T=k\\nabla^2T .$$\n",
    "\n",
    "In units of $L$, $T_h-T_c$ and the thermal diffusivity $\\alpha$ the only parameters are $Pr$ and\n",
    "the Rayleigh number $Ra=g\\beta(T_h-T_c)L^3/(\\nu\\alpha)$; the example solves $Ra=10^3$, where\n",
    "conduction still dominates, $Ra=10^4$, where the circulation bends the isotherms and concentrates\n",
    "the heat transfer at the lower end of the hot wall, and $Ra=10^5$ and $10^6$, where the flow\n",
    "gathers in thin boundary layers along the side walls around a stratified, almost still core.\n",
    "\n",
    "The cavity comes from the CAD file `differentially_heated_square_cavity.step`, written by\n",
    "`differentially_heated_square_cavity_geometry.py` with the CAD objects of OneSimulation; the model\n",
    "lives on its cross-section.\n",
    "\n",
    "| face | flow | heat |\n",
    "|---|---|---|\n",
    "| `hot` | no slip | $T=1$ |\n",
    "| `cold` | no slip | $T=0$ |\n",
    "| `insulated` (top and bottom) | no slip | no flux |\n",
    "\n",
    "**Reference.** G. de Vahl Davis, \"Natural convection of air in a square cavity: a bench mark\n",
    "numerical solution\", *Int. J. Numer. Methods Fluids* 3, 249-264 (1983): the mean Nusselt number\n",
    "of the hot wall, the largest horizontal velocity on the vertical centre line and the largest\n",
    "vertical velocity on the horizontal centre line with their positions, and the largest local\n",
    "Nusselt number on the hot wall."
   ]
  },
  {
   "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 (\n",
    "    CouplingContinuation,\n",
    "    MonolithicStationaryCoupling,\n",
    "    StationaryPartitionedCoupling,\n",
    ")\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 IncompressibleNavierStokes, NoSlipWall\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",
    "`section` cuts the slab at half thickness; the cross-section keeps the face names. Two meshes\n",
    "whose triangles shrink towards the walls, where the thermal and viscous boundary layers sit:\n",
    "from 1/8 to 1/33 of the side and from 1/12 to 1/50, and a third one for the thin layers of the two\n",
    "high Rayleigh numbers, from 1/20 to 1/125 of the side."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "part = load(\"differentially_heated_square_cavity.step\")\n",
    "cavity = part.section((0, 0, 1), origin=(0, 0, part.size[2] / 2))\n",
    "faces = cavity.boundaries\n",
    "meshes = {\n",
    "    name: TriangularMesher(\n",
    "        target_size=core,\n",
    "        size_field=lambda p, core=core, wall=wall: np.minimum(\n",
    "            core,\n",
    "            wall\n",
    "            + 0.5\n",
    "            * np.minimum(\n",
    "                np.minimum(p[:, 0], 1 - p[:, 0]), np.minimum(p[:, 1], 1 - p[:, 1])\n",
    "            ),\n",
    "        ),\n",
    "    ).generate(cavity)\n",
    "    for name, core, wall in ((\"coarser\", 0.12, 0.03), (\"finer\", 0.08, 0.02))\n",
    "}\n",
    "meshes[\"layers\"] = TriangularMesher(\n",
    "    target_size=0.05,\n",
    "    size_field=lambda p: np.minimum(\n",
    "        0.05,\n",
    "        0.008\n",
    "        + 0.3\n",
    "        * np.minimum(\n",
    "            np.minimum(p[:, 0], 1 - p[:, 0]), np.minimum(p[:, 1], 1 - p[:, 1])\n",
    "        ),\n",
    "    ),\n",
    ").generate(cavity)\n",
    "mesh = meshes[\"finer\"]\n",
    "\n",
    "fig = plots.figure(1, 2, size=(13, 6))\n",
    "plots.geometry(\n",
    "    part,\n",
    "    selection={\n",
    "        \"hot wall\": part.boundaries.hot,\n",
    "        \"cold wall\": part.boundaries.cold,\n",
    "        \"insulated\": part.boundaries.insulated,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=30, azimuth=-110),\n",
    "    title=\"Cavity with its heated and cooled walls\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[\"layers\"],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Boundary-layer mesh: {meshes['layers'].cell_count} triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "One flow model (Taylor-Hood elements) and one heat model (quadratic elements) on the same mesh.\n",
    "Two `FieldCoupling`s close the loop: `BoussinesqBuoyancy` turns the temperature into the body\n",
    "force of the flow, and the solved velocity carries the heat. Up to $Ra=10^4$\n",
    "`StationaryPartitionedCoupling` alternates the two stationary solvers with under-relaxation until\n",
    "both fields stop changing. At high Rayleigh numbers the buoyancy feeds back too strongly for that:\n",
    "at $Ra=10^6$ the flow solver alone no longer converges with the temperature of the previous sweep.\n",
    "There `MonolithicStationaryCoupling` solves flow and heat together with one Newton method whose\n",
    "Jacobian holds both coupling blocks, and `CouplingContinuation` reaches the target through\n",
    "smaller Rayleigh numbers ($10^4\\to10^5\\to10^6$, as factors of the buoyancy).\n",
    "In the dimensionless units $\\rho=c_p=k=\\beta=1$, $\\mu=Pr$ and $g=Ra\\,Pr$. $Ra=10^3$ and $10^4$ are\n",
    "solved on the finer mesh, $Ra=10^4$ also on the coarser one, $Ra=10^5$ and $10^6$ on the\n",
    "boundary-layer mesh."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "prandtl = 0.71\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=cavity.domain(), material=fluid)\n",
    "heat = ConvectiveHeatTransfer(domain=cavity.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",
    "results, coarse = {}, {}\n",
    "continuation = {1e5: (0.1, 1.0), 1e6: (0.01, 0.1, 1.0)}\n",
    "for rayleigh, name in (\n",
    "    (1e3, \"finer\"),\n",
    "    (1e4, \"coarser\"),\n",
    "    (1e4, \"finer\"),\n",
    "    (1e5, \"layers\"),\n",
    "    (1e6, \"layers\"),\n",
    "):\n",
    "    problem = Problem(\n",
    "        name=f\"Heated cavity, Ra = {rayleigh:.0e}\",\n",
    "        geometry=cavity,\n",
    "        physics=(flow, heat),\n",
    "        boundary_conditions=(\n",
    "            NoSlipWall(physics=flow, boundary=faces.all),\n",
    "            FixedTemperature(physics=heat, boundary=faces.hot, value=1.0),\n",
    "            FixedTemperature(physics=heat, boundary=faces.cold, value=0.0),\n",
    "            HeatFlux(physics=heat, boundary=faces.insulated, value=0.0),\n",
    "        ),\n",
    "        constraints=(MeanValue(flow.pressure, 0.0),),\n",
    "        initial_conditions=(InitialValue(heat.temperature, lambda x: 1 - x),),\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",
    "    (coarse if name == \"coarser\" else results)[rayleigh] = Simulation(\n",
    "        problem=problem,\n",
    "        mesh={flow: meshes[name], heat: meshes[name]},\n",
    "        numerics=numerics,\n",
    "        coupling_solver=(\n",
    "            MonolithicStationaryCoupling(\n",
    "                stationary_systems=(flow, heat),\n",
    "                continuation=CouplingContinuation(factors=continuation[rayleigh]),\n",
    "                nonlinear_solver=Newton(\n",
    "                    linear_solver=SparseDirect(),\n",
    "                    relative_tolerance=1e-8,\n",
    "                    absolute_tolerance=1e-10,\n",
    "                ),\n",
    "            )\n",
    "            if rayleigh in continuation\n",
    "            else StationaryPartitionedCoupling(\n",
    "                stationary_systems=(flow, heat),\n",
    "                iteration=FixedPoint(\n",
    "                    relative_tolerance=1e-6,\n",
    "                    absolute_tolerance=1e-9,\n",
    "                    maximum_iterations=150,\n",
    "                    relaxation=0.7,\n",
    "                ),\n",
    "            )\n",
    "        ),\n",
    "    ).solve_stationary()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the benchmark\n",
    "\n",
    "The mean Nusselt number is the heat flowing in through the hot wall (it equals the heat leaving\n",
    "through the cold wall). The velocity extrema are read on the centre lines, the local Nusselt\n",
    "number $-\\partial T/\\partial x$ on the hot wall from the heat flux field. At $Ra=10^6$ the 1983\n",
    "values came from extrapolated finite differences; later spectral solutions (P. Le Quéré,\n",
    "*Computers & Fluids* 20, 29-41, 1991) put the mean Nusselt number at 8.825 and the largest local\n",
    "value near 17.5, where the results here lie."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "benchmark = {\n",
    "    1e3: (1.118, 3.649, 0.813, 3.697, 0.178, 1.505, 0.092),\n",
    "    1e4: (2.243, 16.178, 0.823, 19.617, 0.119, 3.528, 0.143),\n",
    "    1e5: (4.519, 34.73, 0.855, 68.59, 0.066, 7.717, 0.081),\n",
    "    1e6: (8.800, 64.63, 0.850, 219.36, 0.0379, 17.925, 0.0378),\n",
    "}\n",
    "line = np.linspace(0.0, 1.0, 2001)\n",
    "measured = {}\n",
    "for rayleigh, result in results.items():\n",
    "    temperature, velocity = result.field(heat.temperature), result.field(flow.velocity)\n",
    "    u = velocity.evaluate(np.column_stack((np.full_like(line, 0.5), line)))[:, 0]\n",
    "    v = velocity.evaluate(np.column_stack((line, np.full_like(line, 0.5))))[:, 1]\n",
    "    local = result.field(heat.heat_flux).evaluate(\n",
    "        np.column_stack((np.full_like(line, 1e-9), line))\n",
    "    )[:, 0]\n",
    "    measured[rayleigh] = (\n",
    "        -temperature.boundary_flux(faces.hot),\n",
    "        u.max(),\n",
    "        line[u.argmax()],\n",
    "        v.max(),\n",
    "        line[v.argmax()],\n",
    "        local.max(),\n",
    "        line[local.argmax()],\n",
    "    )\n",
    "    report = result.result_set.solver_report[\"coupling\"]\n",
    "    print(\n",
    "        f\"Ra = {rayleigh:.0e}: \"\n",
    "        + (\n",
    "            f\"{report['sweeps']} coupling sweeps\"\n",
    "            if \"sweeps\" in report\n",
    "            else \"Newton steps \"\n",
    "            + \" + \".join(str(step[\"iterations\"]) for step in report[\"continuation\"])\n",
    "        )\n",
    "        + f\", heat in {-temperature.boundary_flux(faces.hot):.5f}, heat out {temperature.boundary_flux(faces.cold):.5f}\"\n",
    "    )\n",
    "names = (\n",
    "    \"mean Nusselt number\",\n",
    "    \"largest u on x = 0.5\",\n",
    "    \"  at height y\",\n",
    "    \"largest v on y = 0.5\",\n",
    "    \"  at distance x\",\n",
    "    \"largest local Nusselt number\",\n",
    "    \"  at height y\",\n",
    ")\n",
    "print(\n",
    "    f\"\\n{'quantity':30s}\"\n",
    "    + \"\".join(f\"{'Ra = %.0e' % rayleigh:>26s}\" for rayleigh in results)\n",
    ")\n",
    "print(\n",
    "    f\"{'':30s}\"\n",
    "    + \"   benchmark   OneSim    dev.\" * len(results)\n",
    "    + \"   (positions: difference in L)\"\n",
    ")\n",
    "for row, name in enumerate(names):\n",
    "    print(\n",
    "        f\"{name:30s}\"\n",
    "        + \"\".join(\n",
    "            f\"{benchmark[ra][row]:12.3f}{measured[ra][row]:9.3f}\"\n",
    "            + (\n",
    "                f\"{100 * (measured[ra][row] / benchmark[ra][row] - 1):+6.2f}%\"\n",
    "                if row in (0, 1, 3, 5)\n",
    "                else f\"{measured[ra][row] - benchmark[ra][row]:+7.3f}\"\n",
    "            )\n",
    "            for ra in results\n",
    "        )\n",
    "    )\n",
    "coarse_nusselt = -coarse[1e4].field(heat.temperature).boundary_flux(faces.hot)\n",
    "print(\n",
    "    f\"\\nmesh study, Ra = 1e4: Nusselt number {coarse_nusselt:.4f} on the coarser mesh ({meshes['coarser'].cell_count} triangles), \"\n",
    "    f\"{measured[1e4][0]:.4f} on the finer mesh ({mesh.cell_count} triangles); benchmark 2.243\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Temperature with isotherms and the streamlines for the four Rayleigh numbers: with growing $Ra$\n",
    "the isotherms turn from vertical (conduction) to horizontal in a stratified core, and the\n",
    "circulation moves into thin layers along the side walls, with secondary eddies in the core at\n",
    "$Ra=10^6$. Below, the local Nusselt number on the hot wall and the horizontal velocity on the\n",
    "vertical centre line."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "grid = np.linspace(0.0, 1.0, 61)\n",
    "points = np.array([[a, b] for a in grid for b in grid])\n",
    "fig = plots.figure(2, 4, size=(22, 11))\n",
    "for column, (rayleigh, result) in enumerate(results.items()):\n",
    "    plots.surface(\n",
    "        result.field(heat.temperature),\n",
    "        limits=(0.0, 1.0),\n",
    "        contours=10,\n",
    "        subdivisions=2,\n",
    "        label=\"T\",\n",
    "        xlabel=\"x / L\",\n",
    "        ylabel=\"y / L\",\n",
    "        title=f\"Temperature, Ra = {rayleigh:.0e}\",\n",
    "        ax=fig[column],\n",
    "    )\n",
    "    flow_samples = (\n",
    "        result.field(flow.velocity).evaluate(points).reshape(len(grid), len(grid), 2)\n",
    "    )\n",
    "    plots.streamlines(\n",
    "        grid,\n",
    "        grid,\n",
    "        flow_samples[..., 0],\n",
    "        flow_samples[..., 1],\n",
    "        density=1.3,\n",
    "        label=\"speed [alpha / L]\",\n",
    "        xlabel=\"x / L\",\n",
    "        ylabel=\"y / L\",\n",
    "        title=f\"Streamlines, Ra = {rayleigh:.0e}\",\n",
    "        ax=fig[4 + column],\n",
    "    )\n",
    "plots.show()\n",
    "\n",
    "fig = plots.figure(1, 2, size=(14, 6))\n",
    "plots.line(\n",
    "    y={\n",
    "        f\"Ra = {ra:.0e}\": (\n",
    "            result.field(heat.heat_flux).evaluate(\n",
    "                np.column_stack((np.full_like(line, 1e-9), line))\n",
    "            )[:, 0],\n",
    "            line,\n",
    "        )\n",
    "        for ra, result in results.items()\n",
    "    },\n",
    "    points={\n",
    "        f\"Ra = {ra:.0e}\": ([benchmark[ra][5]], [benchmark[ra][6]]) for ra in results\n",
    "    },\n",
    "    xlabel=\"local Nusselt number on the hot wall\",\n",
    "    ylabel=\"height y / L\",\n",
    "    title=\"Heat transfer along the hot wall (markers: benchmark maxima)\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    y={\n",
    "        f\"Ra = {ra:.0e}\": (\n",
    "            result.field(flow.velocity).evaluate(\n",
    "                np.column_stack((np.full_like(line, 0.5), line))\n",
    "            )[:, 0],\n",
    "            line,\n",
    "        )\n",
    "        for ra, result in results.items()\n",
    "    },\n",
    "    points={\n",
    "        f\"Ra = {ra:.0e}\": ([benchmark[ra][1]], [benchmark[ra][2]]) for ra in results\n",
    "    },\n",
    "    vlines=0.0,\n",
    "    xlabel=\"horizontal velocity u L / alpha\",\n",
    "    ylabel=\"height y / L\",\n",
    "    title=\"Velocity on the vertical centre line (markers: benchmark maxima)\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Continue to $Ra=10^7$ and $10^8$ (benchmark $Nu=16.52$ and $30.23$, Le Quéré 1991) with a wall\n",
    "spacing of about 1/300 of the side and one more continuation factor; change the Prandtl number to\n",
    "that of water; or make the cavity taller in\n",
    "`differentially_heated_square_cavity_geometry.py` and follow the Nusselt number with the aspect\n",
    "ratio. The same coupling in dimensional units for air between two plates is the example\n",
    "`air_cavity_free_convection`."
   ]
  }
 ]
}
