{
 "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 in a porous cavity\n",
    "\n",
    "In a porous medium saturated with a fluid, a temperature difference makes the fluid move: warm\n",
    "fluid rises along the hot wall, cold fluid sinks along the cold wall, and a single convection\n",
    "cell carries heat across the cavity. With the Darcy law and the Boussinesq approximation the\n",
    "nondimensional equations read\n",
    "\n",
    "$$\\nabla\\cdot\\mathbf q=0,\\qquad \\mathbf q=-\\nabla p+\\mathrm{Ra}\\,T\\,\\mathbf e_y,\\qquad\n",
    "  \\mathbf q\\cdot\\nabla T=\\nabla^2T ,$$\n",
    "\n",
    "with the Darcy velocity $\\mathbf q$, the pressure $p$, the temperature $T\\in[0,1]$ and the\n",
    "**Darcy-Rayleigh number** $\\mathrm{Ra}=k\\rho_0g\\beta\\Delta T H/(\\mu\\alpha_m)$. The heat carried\n",
    "across the cavity is the Nusselt number $\\mathrm{Nu}$, the wall heat flux relative to pure\n",
    "conduction.\n",
    "\n",
    "**Setup.** The unit square, nondimensional; the cavity comes from the CAD file\n",
    "`porous_cavity_free_convection.step`, written by `porous_cavity_free_convection_geometry.py` with\n",
    "the CAD objects of OneSimulation.\n",
    "\n",
    "| side | flow | heat |\n",
    "|---|---|---|\n",
    "| `x_min` (hot wall) | no flow | $T=1$ |\n",
    "| `x_max` (cold wall) | no flow | $T=0$ |\n",
    "| `y_min`, `y_max` | no flow | insulated |\n",
    "\n",
    "**Reference.** The side-heated porous square is a classical benchmark; published Nusselt\n",
    "numbers lie between 1.07 and 1.08 at Ra = 10, between 3.10 and 3.16 at Ra = 100 and between\n",
    "12.96 and 13.64 at Ra = 1000 (P. Walker, G.M. Homsy, J. Fluid Mech. 87, 1978, 449-474;\n",
    "A. Bejan, Lett. Heat Mass Transfer 6, 1979, 93-102; D.M. Manole, J.L. Lage, ASME HTD 216, 1992;\n",
    "A.C. Baytas, I. Pop, Int. J. Heat Mass Transfer 42, 1999, 1047-1057)."
   ]
  },
  {
   "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\n",
    "from onesim.numerics.field_transfer import FieldInterpolation\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.numerics.nonlinear import FixedPoint\n",
    "from onesim.physics.heat_transfer import (\n",
    "    BoussinesqBuoyancy,\n",
    "    ConvectiveHeatTransfer,\n",
    "    FixedTemperature,\n",
    "    HeatFlux,\n",
    ")\n",
    "from onesim.physics.hydrodynamics import DarcyFlow, DarcyFluxBoundary\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 block at half thickness; the cut faces keep their names. The triangles are\n",
    "0.012 at the four walls, where the thermal boundary layers form, and grow to 0.05 inside."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "block = load(\"porous_cavity_free_convection.step\")\n",
    "cavity = block.section((0, 0, 1), origin=(0, 0, block.size[2] / 2))\n",
    "side = cavity.boundaries\n",
    "wall_distance = lambda p: np.minimum(\n",
    "    np.minimum(p[:, 0], 1 - p[:, 0]), np.minimum(p[:, 1], 1 - p[:, 1])\n",
    ")\n",
    "mesh = TriangularMesher(\n",
    "    target_size=0.05,\n",
    "    size_field=lambda p: np.minimum(0.012 + 0.25 * wall_distance(p), 0.05),\n",
    ").generate(cavity)\n",
    "\n",
    "fig = plots.figure(1, 2, size=(12, 6))\n",
    "plots.geometry(\n",
    "    cavity,\n",
    "    selection={\n",
    "        \"hot wall\": side.x_min,\n",
    "        \"cold wall\": side.x_max,\n",
    "        \"insulated\": side.y_min | side.y_max,\n",
    "    },\n",
    "    labels=False,\n",
    "    title=\"Porous cavity\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh, groups=(\"all\",), legend=False, title=f\"{mesh.cell_count} triangles\", ax=fig[1]\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "Darcy flow and convective heat transport on the same mesh with quadratic elements. The\n",
    "temperature drives the flow through `BoussinesqBuoyancy` with the gravity scaled to Ra, the\n",
    "Darcy velocity is handed to the heat equation; a relaxed fixed-point iteration couples the two\n",
    "stationary problems. The pressure level is fixed by a zero mean."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "unit = ThermalFluid(\n",
    "    density=1.0,\n",
    "    dynamic_viscosity=1.0,\n",
    "    thermal_conductivity=1.0,\n",
    "    specific_heat_capacity=1.0,\n",
    "    thermal_expansion_coefficient=1.0,\n",
    ")\n",
    "\n",
    "\n",
    "def cavity_flow(rayleigh):\n",
    "    \"\"\"Coupled Darcy flow and heat transport at the Darcy-Rayleigh number.\"\"\"\n",
    "    darcy = DarcyFlow(domain=cavity.domain(), permeability=1.0, material=unit)\n",
    "    heat = ConvectiveHeatTransfer(domain=cavity.domain(), material=unit, velocity=None)\n",
    "    problem = Problem(\n",
    "        name=f\"porous cavity, Ra = {rayleigh}\",\n",
    "        geometry=cavity,\n",
    "        physics=(darcy, heat),\n",
    "        boundary_conditions=(\n",
    "            DarcyFluxBoundary(physics=darcy, boundary=side.all, flux=0.0),\n",
    "            FixedTemperature(physics=heat, boundary=side.x_min, value=1.0),\n",
    "            FixedTemperature(physics=heat, boundary=side.x_max, value=0.0),\n",
    "            HeatFlux(physics=heat, boundary=side.y_min | side.y_max, value=0.0),\n",
    "        ),\n",
    "        constraints=(MeanValue(darcy.pressure, 0.0),),\n",
    "        initial_conditions=(InitialValue(heat.temperature, lambda x, y: 1 - x),),\n",
    "        couplings=(\n",
    "            FieldCoupling(\n",
    "                source=heat.temperature,\n",
    "                target=darcy.field(\"body_force\"),\n",
    "                transfer=BoussinesqBuoyancy(\n",
    "                    gravity=(0, -rayleigh), reference_temperature=0.5\n",
    "                ),\n",
    "            ),\n",
    "            FieldCoupling(\n",
    "                source=darcy.darcy_velocity,\n",
    "                target=heat.advecting_velocity,\n",
    "                transfer=FieldInterpolation(),\n",
    "            ),\n",
    "        ),\n",
    "    )\n",
    "    result = Simulation(\n",
    "        problem=problem,\n",
    "        mesh={darcy: mesh, heat: mesh},\n",
    "        numerics={\n",
    "            darcy: Numerics(\n",
    "                spatial=FiniteElement(element=Lagrange(order=2)),\n",
    "                linear_solver=SparseDirect(),\n",
    "            ),\n",
    "            heat: Numerics(\n",
    "                spatial=FiniteElement(\n",
    "                    element=Lagrange(order=2), convection=GalerkinAdvection()\n",
    "                ),\n",
    "                linear_solver=SparseDirect(),\n",
    "            ),\n",
    "        },\n",
    "        coupling_solver=StationaryPartitionedCoupling(\n",
    "            stationary_systems=(darcy, heat),\n",
    "            iteration=FixedPoint(\n",
    "                relative_tolerance=1e-6,\n",
    "                absolute_tolerance=1e-12,\n",
    "                maximum_iterations=300,\n",
    "                relaxation=0.6 if rayleigh > 500 else 0.8,\n",
    "            ),\n",
    "        ),\n",
    "    ).solve_stationary()\n",
    "    return result.field(heat.temperature), result.field(darcy.darcy_velocity)\n",
    "\n",
    "\n",
    "rayleighs = (10, 100, 1000)\n",
    "fields = {ra: cavity_flow(ra) for ra in rayleighs}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the reference\n",
    "\n",
    "The Nusselt number from the heat flux through the hot and the cold wall against the published\n",
    "range."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "published = {10: (1.07, 1.08), 100: (3.10, 3.16), 1000: (12.96, 13.64)}\n",
    "print(\n",
    "    f\"{'Ra':>6s} {'Nu, hot wall':>13s} {'Nu, cold wall':>14s} {'published':>15s} {'largest Darcy speed':>20s}\"\n",
    ")\n",
    "probe = np.array(\n",
    "    [[x, y] for x in np.linspace(0.01, 0.99, 50) for y in np.linspace(0.01, 0.99, 50)]\n",
    ")\n",
    "for ra, (temperature, velocity) in fields.items():\n",
    "    print(\n",
    "        f\"{ra:6d} {-temperature.boundary_flux(side.x_min):13.3f} {temperature.boundary_flux(side.x_max):14.3f}\"\n",
    "        f\" {published[ra][0]:7.2f} - {published[ra][1]:<5.2f} {np.linalg.norm(velocity.evaluate(probe), axis=1).max():20.2f}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Temperature with isotherms for the three Rayleigh numbers, and the Nusselt number against the\n",
    "published range."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 4, size=(20, 5))\n",
    "for k, (ra, (temperature, velocity)) in enumerate(fields.items()):\n",
    "    plots.surface(\n",
    "        temperature,\n",
    "        limits=(0, 1),\n",
    "        contours=10,\n",
    "        subdivisions=2,\n",
    "        label=\"temperature T\",\n",
    "        title=f\"Ra = {ra}\",\n",
    "        ax=fig[k],\n",
    "    )\n",
    "plots.line(\n",
    "    points={\n",
    "        \"simulation\": (\n",
    "            np.array(rayleighs),\n",
    "            [-fields[ra][0].boundary_flux(side.x_min) for ra in rayleighs],\n",
    "        )\n",
    "    },\n",
    "    reference={\n",
    "        \"published, lower\": (\n",
    "            np.array(rayleighs),\n",
    "            [published[ra][0] for ra in rayleighs],\n",
    "        ),\n",
    "        \"published, upper\": (\n",
    "            np.array(rayleighs),\n",
    "            [published[ra][1] for ra in rayleighs],\n",
    "        ),\n",
    "    },\n",
    "    scale=\"loglog\",\n",
    "    xlabel=\"Darcy-Rayleigh number Ra\",\n",
    "    ylabel=\"Nusselt number Nu\",\n",
    "    title=\"Heat transfer across the cavity\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[3],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Heat the cavity from below instead: below Ra = 4π² the fluid stays at rest (the onset of\n",
    "Horton, Rogers and Lapwood), above it convection rolls form. Make the cavity taller in\n",
    "`porous_cavity_free_convection_geometry.py` and write the STEP file again: the Nusselt number\n",
    "falls with the aspect ratio."
   ]
  }
 ]
}
