{
 "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": [
    "# Free convection of air between two vertical plates\n",
    "\n",
    "Two vertical plates face each other across an air gap of width $L=20$ mm and height $H=20$ mm;\n",
    "floor and ceiling are insulated. The left plate is warmer than the right one by $\\Delta T$, both\n",
    "symmetric about 20 °C. The air rises at the warm plate, falls at the cool one, and the circulation\n",
    "carries more heat across the gap than conduction alone would. With the Boussinesq approximation\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",
    "with air at 20 °C: $\\rho=1.204$ kg/m³, $\\mu=1.825\\cdot10^{-5}$ Pa s, $k=0.02587$ W/(m K),\n",
    "$c_p=1006$ J/(kg K) ($Pr=0.71$) and $\\beta=1/T_0$. The temperature differences are chosen for\n",
    "Rayleigh numbers $Ra=g\\beta\\Delta T L^3/(\\nu\\alpha)$ of $10^3$, $3\\cdot10^3$ and $10^4$: from\n",
    "about 1 K to 12 K. A fourth case at $Ra=10^5$ needs $\\Delta T\\approx121$ K in this small gap;\n",
    "with $\\beta\\Delta T\\approx0.4$ real air would ask for the variable-density equations, so this case\n",
    "only serves the comparison with the Boussinesq benchmark at strong convection.\n",
    "\n",
    "The gap comes from the CAD file `air_cavity_free_convection.step`, written by\n",
    "`air_cavity_free_convection_geometry.py` with the CAD objects of OneSimulation.\n",
    "\n",
    "| face | flow | heat |\n",
    "|---|---|---|\n",
    "| `hot_plate` | no slip | $T_0+\\Delta T/2$ |\n",
    "| `cold_plate` | no slip | $T_0-\\Delta T/2$ |\n",
    "| `floor`, `ceiling` | no slip | insulated |\n",
    "\n",
    "**Reference.** The square cavity at $Pr=0.71$ is the benchmark of G. de Vahl Davis, *Int. J.\n",
    "Numer. Methods Fluids* 3, 249-264 (1983): mean Nusselt numbers 1.118 at $Ra=10^3$, 2.243 at\n",
    "$Ra=10^4$ and 4.519 at $Ra=10^5$, largest vertical velocity 19.617 $\\alpha/L$ at $Ra=10^4$ and\n",
    "68.59 $\\alpha/L$ at $Ra=10^5$. The engineering correlation\n",
    "for enclosures with $1<H/L<2$ (Catton; F. P. Incropera et al., *Fundamentals of Heat and Mass\n",
    "Transfer*, Eq. 9.51), $\\overline{Nu}=0.18\\,\\big(Pr\\,Ra/(0.2+Pr)\\big)^{0.29}$, holds for\n",
    "$Pr\\,Ra/(0.2+Pr)>10^3$, i.e. above $Ra\\approx1300$."
   ]
  },
  {
   "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",
    "The cross-section at half depth keeps the face names. Two meshes refine towards the plates and\n",
    "the insulated faces, where the boundary layers sit: from 1.6 mm to 0.4 mm and from 2.4 mm to\n",
    "0.6 mm; a third one for the thin layers at $Ra=10^5$ goes from 1.2 mm to 0.24 mm."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "part = load(\"air_cavity_free_convection.step\")\n",
    "gap = part.section((0, 0, 1), origin=(0, 0, part.size[2] / 2))\n",
    "faces = gap.boundaries\n",
    "width, height = gap.size[:2]\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], width - p[:, 0]),\n",
    "                np.minimum(p[:, 1], height - p[:, 1]),\n",
    "            ),\n",
    "        ),\n",
    "    ).generate(gap)\n",
    "    for name, core, wall in (\n",
    "        (\"coarser\", 2.4e-3, 6e-4),\n",
    "        (\"finer\", 1.6e-3, 4e-4),\n",
    "        (\"layers\", 1.2e-3, 2.4e-4),\n",
    "    )\n",
    "}\n",
    "\n",
    "fig = plots.figure(1, 2, size=(13, 6))\n",
    "plots.geometry(\n",
    "    part,\n",
    "    selection={\n",
    "        \"warm plate\": part.boundaries.hot_plate,\n",
    "        \"cool plate\": part.boundaries.cold_plate,\n",
    "        \"insulated\": part.boundaries.floor | part.boundaries.ceiling,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=30, azimuth=-110),\n",
    "    title=\"Air gap between the plates\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[\"finer\"],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Finer mesh: {meshes['finer'].cell_count} triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "The flow (Taylor-Hood elements) and the heat transport (quadratic elements) share the mesh.\n",
    "`BoussinesqBuoyancy` turns the temperature into the body force of the flow, taking $\\rho$ and\n",
    "$\\beta$ from the `ThermalFluid`; the solved velocity carries the heat back.\n",
    "Up to $Ra=10^4$ `StationaryPartitionedCoupling` alternates the two stationary solvers until both\n",
    "fields settle. At $Ra=10^5$ `MonolithicStationaryCoupling` solves flow and heat together with one\n",
    "Newton method (both coupling blocks in its Jacobian), reaching the case through $Ra=10^4$ with\n",
    "`CouplingContinuation`. The three small temperature differences are solved on the finer mesh, the\n",
    "largest of them also on the coarser, $Ra=10^5$ on the boundary-layer mesh."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "ambient, gravity = 293.15, 9.81\n",
    "air = ThermalFluid(\n",
    "    density=1.204,\n",
    "    dynamic_viscosity=1.825e-5,\n",
    "    thermal_conductivity=0.02587,\n",
    "    specific_heat_capacity=1006.0,\n",
    "    thermal_expansion_coefficient=1 / ambient,\n",
    ")\n",
    "nu, alpha = air.dynamic_viscosity / air.density, air.thermal_conductivity / (\n",
    "    air.density * air.specific_heat_capacity\n",
    ")\n",
    "flow = IncompressibleNavierStokes(domain=gap.domain(), material=air)\n",
    "heat = ConvectiveHeatTransfer(domain=gap.domain(), material=air, 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-12,\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 = {}\n",
    "for rayleigh, name in (\n",
    "    (1e3, \"finer\"),\n",
    "    (3e3, \"finer\"),\n",
    "    (1e4, \"finer\"),\n",
    "    (1e4, \"coarser\"),\n",
    "    (1e5, \"layers\"),\n",
    "):\n",
    "    delta = (\n",
    "        rayleigh * nu * alpha / (gravity * air.thermal_expansion_coefficient * width**3)\n",
    "    )\n",
    "    problem = Problem(\n",
    "        name=f\"Air between two plates, dT = {delta:.2f} K\",\n",
    "        geometry=gap,\n",
    "        physics=(flow, heat),\n",
    "        boundary_conditions=(\n",
    "            NoSlipWall(physics=flow, boundary=faces.all),\n",
    "            FixedTemperature(\n",
    "                physics=heat, boundary=faces.hot_plate, value=ambient + delta / 2\n",
    "            ),\n",
    "            FixedTemperature(\n",
    "                physics=heat, boundary=faces.cold_plate, value=ambient - delta / 2\n",
    "            ),\n",
    "            HeatFlux(physics=heat, boundary=faces.floor | faces.ceiling, value=0.0),\n",
    "        ),\n",
    "        constraints=(MeanValue(flow.pressure, 0.0),),\n",
    "        initial_conditions=(InitialValue(heat.temperature, ambient),),\n",
    "        couplings=(\n",
    "            FieldCoupling(\n",
    "                source=heat.temperature,\n",
    "                target=flow.field(\"body_force\"),\n",
    "                transfer=BoussinesqBuoyancy(\n",
    "                    gravity=(0, -gravity), reference_temperature=ambient\n",
    "                ),\n",
    "            ),\n",
    "            FieldCoupling(\n",
    "                source=flow.velocity,\n",
    "                target=heat.advecting_velocity,\n",
    "                transfer=FieldInterpolation(),\n",
    "            ),\n",
    "        ),\n",
    "    )\n",
    "    results[rayleigh, name] = (\n",
    "        delta,\n",
    "        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=(0.1, 1.0)),\n",
    "                    nonlinear_solver=Newton(\n",
    "                        linear_solver=SparseDirect(),\n",
    "                        relative_tolerance=1e-8,\n",
    "                        absolute_tolerance=1e-12,\n",
    "                    ),\n",
    "                )\n",
    "                if rayleigh > 1e4\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(),\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Heat flux between the plates\n",
    "\n",
    "The heat per metre of plate length entering at the warm plate gives the mean heat flux and the\n",
    "Nusselt number $\\overline{Nu}=\\bar q\\,L/(k\\,\\Delta T)$; velocities are also given in units of\n",
    "$\\alpha/L$ for the benchmark."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "catton = lambda ra: 0.18 * (nu / alpha / (0.2 + nu / alpha) * ra) ** 0.29\n",
    "benchmark = {1e3: 1.118, 1e4: 2.243, 1e5: 4.519}\n",
    "line = np.linspace(0.0, 1.0, 2001)\n",
    "nusselt = {}\n",
    "print(f\"Pr = {nu / alpha:.4f}\")\n",
    "print(\n",
    "    \"     Ra   mesh      dT [K]   heat in [W/m]   heat out [W/m]   flux [W/m²]   Nusselt   benchmark   correlation   v_max [mm/s]\"\n",
    ")\n",
    "for (rayleigh, name), (delta, result) in results.items():\n",
    "    temperature, velocity = result.field(heat.temperature), result.field(flow.velocity)\n",
    "    v = velocity.evaluate(\n",
    "        np.column_stack((line * width, np.full_like(line, height / 2)))\n",
    "    )[:, 1]\n",
    "    nusselt[rayleigh, name] = -temperature.boundary_flux(faces.hot_plate) / (\n",
    "        air.thermal_conductivity * delta\n",
    "    )\n",
    "    print(\n",
    "        f\"{rayleigh:7.0f}   {name:8s} {delta:7.3f} {-temperature.boundary_flux(faces.hot_plate):15.5f} \"\n",
    "        f\"{temperature.boundary_flux(faces.cold_plate):16.5f} {-temperature.boundary_flux(faces.hot_plate) / height:13.2f} \"\n",
    "        f\"{nusselt[rayleigh, name]:9.4f} {benchmark[rayleigh] if rayleigh in benchmark else '-':>11} {catton(rayleigh):13.3f} {1e3 * v.max():14.3f}\"\n",
    "    )\n",
    "finest = {rayleigh: name for rayleigh, name in results if name != \"coarser\"}\n",
    "for rayleigh in benchmark:\n",
    "    print(\n",
    "        f\"Ra = {rayleigh:.0e}: Nusselt number {100 * (nusselt[rayleigh, finest[rayleigh]] / benchmark[rayleigh] - 1):+.2f} % from the benchmark\"\n",
    "    )\n",
    "for rayleigh in (3e3, 1e4, 1e5):\n",
    "    print(\n",
    "        f\"Ra = {rayleigh:.0e}: Nusselt number {100 * (nusselt[rayleigh, finest[rayleigh]] / catton(rayleigh) - 1):+.1f} % from the correlation\"\n",
    "    )\n",
    "for rayleigh, reference, position in ((1e4, 19.617, 0.119), (1e5, 68.59, 0.066)):\n",
    "    v = (\n",
    "        results[rayleigh, finest[rayleigh]][1]\n",
    "        .field(flow.velocity)\n",
    "        .evaluate(np.column_stack((line * width, np.full_like(line, height / 2))))[:, 1]\n",
    "    )\n",
    "    print(\n",
    "        f\"Ra = {rayleigh:.0e}: largest vertical velocity {v.max() * width / alpha:.3f} alpha/L at x = {line[v.argmax()]:.3f} L, \"\n",
    "        f\"benchmark {reference} at {position} L ({100 * (v.max() * width / alpha / reference - 1):+.2f} %)\"\n",
    "    )\n",
    "print(\n",
    "    f\"mesh study, Ra = 1e4: Nusselt number {nusselt[1e4, 'coarser']:.4f} ({meshes['coarser'].cell_count} triangles) and \"\n",
    "    f\"{nusselt[1e4, 'finer']:.4f} ({meshes['finer'].cell_count} triangles)\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Temperature with isotherms and the streamlines coloured by speed at $\\Delta T$ for $Ra=10^4$,\n",
    "the Nusselt number over the Rayleigh number against the references, and the vertical velocity\n",
    "across the gap at mid-height for the four temperature differences."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "delta, result = results[1e4, \"finer\"]\n",
    "grid_x, grid_y = np.linspace(0.0, width, 61), np.linspace(0.0, height, 61)\n",
    "flow_samples = 1e3 * result.field(flow.velocity).evaluate(\n",
    "    np.array([[a, b] for a in grid_x for b in grid_y])\n",
    ").reshape(61, 61, 2)\n",
    "sweep = np.geomspace(1.3e3, 1.2e5, 100)\n",
    "fig = plots.figure(2, 2, size=(17, 12.5))\n",
    "plots.surface(\n",
    "    result.field(heat.temperature),\n",
    "    component=lambda T, position: T - 273.15,\n",
    "    limits=(np.ceil(20 - delta / 2), np.floor(20 + delta / 2)),\n",
    "    contours=12,\n",
    "    subdivisions=2,\n",
    "    label=\"T [°C]\",\n",
    "    title=f\"Temperature, Ra = 1e4 (dT = {delta:.1f} K)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.streamlines(\n",
    "    grid_x,\n",
    "    grid_y,\n",
    "    flow_samples[..., 0],\n",
    "    flow_samples[..., 1],\n",
    "    density=1.4,\n",
    "    label=\"speed [mm/s]\",\n",
    "    title=\"Streamlines of the circulation\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    sweep,\n",
    "    {\"enclosure correlation (Catton)\": catton(sweep)},\n",
    "    points={\n",
    "        \"OneSimulation\": (\n",
    "            list(finest),\n",
    "            [nusselt[ra, name] for ra, name in finest.items()],\n",
    "        ),\n",
    "        \"de Vahl Davis (1983)\": (list(benchmark), list(benchmark.values())),\n",
    "    },\n",
    "    hlines={\"conduction only\": 1.0},\n",
    "    scale=\"logx\",\n",
    "    ylimits=(0.8, 5.0),\n",
    "    xlabel=\"Rayleigh number\",\n",
    "    ylabel=\"mean Nusselt number\",\n",
    "    title=\"Heat transfer across the gap\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.line(\n",
    "    1e3 * width * line,\n",
    "    {\n",
    "        f\"dT = {d:.1f} K\": 1e3\n",
    "        * r.field(flow.velocity).evaluate(\n",
    "            np.column_stack((line * width, np.full_like(line, height / 2)))\n",
    "        )[:, 1]\n",
    "        for (ra, name), (d, r) in results.items()\n",
    "        if name != \"coarser\"\n",
    "    },\n",
    "    hlines=0.0,\n",
    "    xlabel=\"distance from the warm plate [mm]\",\n",
    "    ylabel=\"vertical velocity [mm/s]\",\n",
    "    title=\"Vertical velocity at mid-height\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[3],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Make the gap narrower and taller in `air_cavity_free_convection_geometry.py` (a double-glazing\n",
    "gap) and compare with the correlations for tall enclosures; tilt gravity to model an inclined\n",
    "gap; or replace air by water. The same coupling in dimensionless form with the full benchmark\n",
    "table is the example `differentially_heated_square_cavity`."
   ]
  }
 ]
}
