{
 "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": [
    "# Steady advection-diffusion in a channel\n",
    "\n",
    "A fluid moves through a slender channel of length $L$ with a uniform axial\n",
    "velocity $u$. The two ends are held at fixed temperatures $T_0$ (inlet) and\n",
    "$T_1$ (outlet); the lateral walls are insulated, so the temperature only varies\n",
    "along the flow direction $x$. In steady state the balance\n",
    "\n",
    "$$\\rho c_p\\,u\\,\\frac{dT}{dx}=k\\,\\frac{d^2T}{dx^2}$$\n",
    "\n",
    "describes a competition between advection (carrying heat downstream) and\n",
    "conduction (smoothing it out).\n",
    "\n",
    "The channel comes from the CAD file `advection_diffusion_1d.step`; inlet and outlet are named\n",
    "`x_min` and `x_max`, the four lateral walls form the group `walls`. The script\n",
    "`advection_diffusion_1d_geometry.py` builds it with the CAD objects of OneSimulation.\n",
    "OneSimulation solves the three-dimensional convective heat equation with quadratic finite\n",
    "elements.\n",
    "\n",
    "**Reference.** With the Peclet number $\\mathrm{Pe}=u\\,L\\,\\rho\\,c_p/k$ the exact solution of the\n",
    "boundary value problem is\n",
    "\n",
    "$$T(x)=T_0+(T_1-T_0)\\,\\frac{e^{\\mathrm{Pe}\\,x/L}-1}{e^{\\mathrm{Pe}}-1}.$$"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import IsotropicSolid\n",
    "from onesim.meshing import StructuredHexahedralMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, GalerkinAdvection, Lagrange\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.physics.heat_transfer import (\n",
    "    ConvectiveHeatTransfer,\n",
    "    FixedTemperature,\n",
    "    HeatFlux,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "channel = load(\"advection_diffusion_1d.step\")\n",
    "faces = channel.boundaries\n",
    "length, cross, _ = channel.size\n",
    "mesh = StructuredHexahedralMesher(cells=(80, 2, 2)).generate(channel)\n",
    "\n",
    "fig = plots.figure(1, 2, size=(14, 4.5))\n",
    "plots.geometry(\n",
    "    channel,\n",
    "    selection={\"inlet\": faces.x_min, \"outlet\": faces.x_max},\n",
    "    labels=False,\n",
    "    title=\"Channel with its inlet and outlet\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh, groups=(\"all\",), legend=False, title=f\"{mesh.cell_count} hexahedra\", ax=fig[1]\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "Air near room temperature. The velocity is chosen for a Peclet number of 5, where advection and\n",
    "conduction are comparable."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "inlet, outlet, peclet = 300.0, 360.0, 5.0\n",
    "air = IsotropicSolid(\n",
    "    density=1.2,\n",
    "    specific_heat_capacity=1005.0,\n",
    "    thermal_conductivity=0.025,\n",
    "    youngs_modulus=100e9,\n",
    "    poisson_ratio=0.3,\n",
    "    thermal_expansion_coefficient=1e-5,\n",
    ")\n",
    "velocity = (\n",
    "    peclet\n",
    "    * air.thermal_conductivity\n",
    "    / (length * air.density * air.specific_heat_capacity)\n",
    ")\n",
    "model = ConvectiveHeatTransfer(\n",
    "    domain=channel.volume, material=air, velocity=(velocity, 0.0, 0.0)\n",
    ")\n",
    "problem = Problem(\n",
    "    name=\"Steady advection-diffusion in a channel\",\n",
    "    geometry=channel,\n",
    "    physics=(model,),\n",
    "    boundary_conditions=(\n",
    "        FixedTemperature(boundary=faces.x_min, physics=model, value=inlet),\n",
    "        FixedTemperature(boundary=faces.x_max, physics=model, value=outlet),\n",
    "        HeatFlux(boundary=faces.walls, physics=model, value=0.0),\n",
    "    ),\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2), convection=GalerkinAdvection()),\n",
    "    linear_solver=SparseDirect(),\n",
    ")\n",
    "temperature = (\n",
    "    Simulation(problem=problem, mesh=mesh, numerics=numerics)\n",
    "    .solve_stationary()\n",
    "    .field(model.temperature)\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the closed-form profile"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "x = np.linspace(0.0, length, 41)\n",
    "simulated = temperature.evaluate(\n",
    "    np.column_stack((x, np.full_like(x, cross / 2), np.full_like(x, cross / 2)))\n",
    ").reshape(-1)\n",
    "exact = inlet + (outlet - inlet) * (np.exp(peclet * x / length) - 1) / (\n",
    "    np.exp(peclet) - 1\n",
    ")\n",
    "\n",
    "print(f\"velocity {1e3 * velocity:.4f} mm/s, Peclet number {peclet:.0f}\")\n",
    "print(\n",
    "    f\"largest deviation from the Peclet profile: {np.abs(simulated - exact).max():.2e} K \"\n",
    "    f\"({100 * np.abs(simulated - exact).max() / (outlet - inlet):.4f} % of T1 - T0)\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "plots.line(\n",
    "    1e3 * x,\n",
    "    points={\"simulation\": simulated},\n",
    "    reference={\"closed-form Péclet profile\": exact},\n",
    "    xlabel=\"position x [mm]\",\n",
    "    ylabel=\"temperature [K]\",\n",
    "    title=f\"Advection-diffusion in a channel (Pe = {peclet:.0f})\",\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Raise the Peclet number and watch the profile bend ever more sharply towards the outlet; near the\n",
    "downstream end a thin thermal boundary layer forms whose width scales like $L/\\mathrm{Pe}$.\n",
    "Resolving that layer needs more cells along $x$, so refine the mesh as you increase the velocity."
   ]
  }
 ]
}
