{
 "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 PCR in a triangular loop\n",
    "\n",
    "The polymerase chain reaction doubles a DNA segment in every thermal cycle: denaturation at\n",
    "95 °C, annealing of the primers at 55 °C and extension at 72 °C. In a convective PCR chip the\n",
    "sample circulates through a closed loop whose legs are held at these temperatures, so every\n",
    "lap is one cycle. Here the loop is an upright equilateral triangle with 20 mm legs (along the\n",
    "centre line of the channel) and a square channel of 1 x 1 mm: the left leg is the denaturation\n",
    "zone, the right leg the annealing zone and the bottom leg the extension zone. Water heated in\n",
    "the left leg rises, cools in the right leg, sinks, and is brought to 72 °C in the bottom leg on\n",
    "its way back: denaturation, annealing, extension, in the right order.\n",
    "\n",
    "The wall temperature is one function of the position: the extension temperature on the walls of\n",
    "the bottom leg, the denaturation temperature on the left and the annealing temperature on the\n",
    "right leg, joined by linear transitions 0.5 mm wide at the corners. The steady flow obeys the Navier-Stokes equations with the Boussinesq buoyancy force and the heat\n",
    "transport equation,\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",
    "for water at about 75 °C ($\\rho=975$ kg/m³, $\\mu=3.8\\cdot10^{-4}$ Pa s, $k=0.665$ W/(m K),\n",
    "$c_p=4190$ J/(kg K), $\\beta=6\\cdot10^{-4}$ 1/K) and gravity along $-y$.\n",
    "\n",
    "The loop comes from the CAD file `buoyancy_driven_pcr_loop.step`, written by\n",
    "`buoyancy_driven_pcr_loop_geometry.py` with the CAD objects of OneSimulation. It holds the front\n",
    "half of the channel depth; the mid-depth plane is a plane of symmetry.\n",
    "\n",
    "| face | flow | heat |\n",
    "|---|---|---|\n",
    "| `denaturation` (left leg) | no slip | $T=95$ °C |\n",
    "| `annealing` (right leg) | no slip | $T=55$ °C |\n",
    "| `extension` (bottom leg) | no slip | $T=72$ °C |\n",
    "| `front` (cover) | no slip | insulated |\n",
    "| `mid_plane` | free slip (symmetry) | no flux |\n",
    "\n",
    "**Reference.** A one-dimensional momentum balance of the loop: the buoyancy of the warm left leg\n",
    "against the cool right leg, $\\rho\\beta g\\,(T_D-T_A)\\,h$ with the height $h$ of the loop, drives\n",
    "the flow against the laminar friction of the fully developed square-duct flow,\n",
    "$\\Delta p=(f\\,Re)\\,\\mu\\bar u L/(2D_h^2)$ with $f\\,Re=56.91$ (R. K. Shah and A. L. London,\n",
    "*Laminar Flow Forced Convection in Ducts*, 1978) over the loop length $L$:\n",
    "\n",
    "$$\\bar u=\\frac{2\\rho\\beta g\\,(T_D-T_A)\\,h\\,D_h^2}{(f\\,Re)\\,\\mu L}.$$\n",
    "\n",
    "It assumes that the water takes the wall temperature at once on entering each leg, so it gives an\n",
    "upper bound. Driven instead by the temperatures computed along the centre line of the channel,\n",
    "where the fast water lags the walls most, the same balance gives a lower bound; the buoyancy acts\n",
    "on the area-mean temperature in between. In the steady state the\n",
    "heat entering through the warm legs leaves through the annealing leg."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.d2 import Plane\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import ThermalFluid\n",
    "from onesim.meshing import SweepMesher\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.results.integration import integrate_plane\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",
    "`SweepMesher` lays quadrilaterals on the front face and sweeps them to the mid-depth plane. Two\n",
    "meshes of quadratic hexahedra, 0.5 mm and 0.4 mm on the front face, one layer through the half\n",
    "depth."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "loop = load(\"buoyancy_driven_pcr_loop.step\")\n",
    "faces = loop.boundaries\n",
    "walls = faces.denaturation | faces.annealing | faces.extension | faces.front\n",
    "meshes = [\n",
    "    SweepMesher(source=faces.front, target_size=size, layers=layers).generate(loop)\n",
    "    for size, layers in ((5e-4, 1), (4e-4, 1))\n",
    "]\n",
    "\n",
    "view = plots.Camera(elevation=65, azimuth=-90)\n",
    "fig = plots.figure(1, 2, size=(15, 6.5))\n",
    "plots.geometry(\n",
    "    loop,\n",
    "    selection={\n",
    "        \"denaturation 95 °C\": faces.denaturation,\n",
    "        \"annealing 55 °C\": faces.annealing,\n",
    "        \"extension 72 °C\": faces.extension,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Front half of the triangular loop\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[-1],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"Finer mesh: {meshes[-1].cell_count} hexahedra\",\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 each mesh.\n",
    "`BoussinesqBuoyancy` turns the temperature into the body force, with $\\rho$ and $\\beta$ from the\n",
    "`ThermalFluid`; the solved velocity carries the heat. `StationaryPartitionedCoupling` alternates\n",
    "the two stationary solvers until both fields settle. The loop is closed, so the pressure level is\n",
    "fixed by its mean."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "celsius, reference, gravity = 273.15, 348.15, 9.81\n",
    "zones = {\"denaturation\": 95.0, \"annealing\": 55.0, \"extension\": 72.0}\n",
    "side, channel = 20e-3, 1e-3\n",
    "centre = side / (2 * np.sqrt(3))\n",
    "water = ThermalFluid(\n",
    "    density=975.0,\n",
    "    dynamic_viscosity=3.8e-4,\n",
    "    thermal_conductivity=0.665,\n",
    "    specific_heat_capacity=4190.0,\n",
    "    thermal_expansion_coefficient=6e-4,\n",
    ")\n",
    "flow = IncompressibleNavierStokes(domain=loop.volume, material=water)\n",
    "heat = ConvectiveHeatTransfer(domain=loop.volume, material=water, velocity=None)\n",
    "problem = Problem(\n",
    "    name=\"Convective PCR loop\",\n",
    "    geometry=loop,\n",
    "    physics=(flow, heat),\n",
    "    boundary_conditions=(\n",
    "        NoSlipWall(physics=flow, boundary=walls),\n",
    "        WallShear(physics=flow, boundary=faces.mid_plane, law=FreeSlipLaw()),\n",
    "        FixedTemperature(\n",
    "            physics=heat,\n",
    "            boundary=faces.denaturation | faces.annealing | faces.extension,\n",
    "            value=lambda x, y, z: celsius\n",
    "            + zones[\"extension\"]\n",
    "            + np.clip((y + centre - channel / 2) / 5e-4, 0, 1)\n",
    "            * (75.0 - 20.0 * np.clip(x / 5e-4, -1, 1) - zones[\"extension\"]),\n",
    "        ),\n",
    "        HeatFlux(physics=heat, boundary=faces.front | faces.mid_plane, value=0.0),\n",
    "    ),\n",
    "    constraints=(MeanValue(flow.pressure, 0.0),),\n",
    "    initial_conditions=(InitialValue(heat.temperature, reference),),\n",
    "    couplings=(\n",
    "        FieldCoupling(\n",
    "            source=heat.temperature,\n",
    "            target=flow.field(\"body_force\"),\n",
    "            transfer=BoussinesqBuoyancy(\n",
    "                gravity=(0, -gravity, 0), reference_temperature=reference\n",
    "            ),\n",
    "        ),\n",
    "        FieldCoupling(\n",
    "            source=flow.velocity,\n",
    "            target=heat.advecting_velocity,\n",
    "            transfer=FieldInterpolation(),\n",
    "        ),\n",
    "    ),\n",
    ")\n",
    "numerics = {\n",
    "    flow: Numerics(\n",
    "        spatial=FiniteElement(element=TaylorHood()),\n",
    "        initial_guess={flow.velocity: (0.0, 0.0, 0.0)},\n",
    "        nonlinear_solver=Newton(\n",
    "            linear_solver=SparseDirect(),\n",
    "            absolute_tolerance=1e-14,\n",
    "            relative_tolerance=1e-7,\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",
    "    Simulation(\n",
    "        problem=problem,\n",
    "        mesh={flow: mesh, heat: mesh},\n",
    "        numerics=numerics,\n",
    "        coupling_solver=StationaryPartitionedCoupling(\n",
    "            stationary_systems=(flow, heat),\n",
    "            iteration=FixedPoint(\n",
    "                relative_tolerance=1e-5,\n",
    "                absolute_tolerance=1e-9,\n",
    "                maximum_iterations=100,\n",
    "                relaxation=0.8,\n",
    "            ),\n",
    "        ),\n",
    "    ).solve_stationary()\n",
    "    for mesh in meshes\n",
    "]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Circulation and heat balance\n",
    "\n",
    "The flow rate is the velocity integrated over the cut through the bottom leg (`integrate_plane`\n",
    "with `within` keeping that leg); doubled for the full depth and divided by the channel area it is\n",
    "the mean speed. `reaction` gives the heat each zone exchanges with the water, consistent with the\n",
    "discretised balance, so the three must add up to zero. The temperature along the centre line of\n",
    "the channel shows how far the water follows the wall temperatures. One lap of the loop is one\n",
    "PCR cycle."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "height, length = 3 * side / (2 * np.sqrt(3)), 3 * side\n",
    "loop_balance = (\n",
    "    lambda driving: 2\n",
    "    * water.density\n",
    "    * water.thermal_expansion_coefficient\n",
    "    * gravity\n",
    "    * driving\n",
    "    * channel**2\n",
    "    / (56.91 * water.dynamic_viscosity * length)\n",
    ")\n",
    "corners = np.array(\n",
    "    [\n",
    "        [-np.sqrt(3) * centre, -centre],\n",
    "        [0.0, 2 * centre],\n",
    "        [np.sqrt(3) * centre, -centre],\n",
    "        [-np.sqrt(3) * centre, -centre],\n",
    "    ]\n",
    ")\n",
    "lap = np.linspace(0.0, 3.0, 601)\n",
    "path = np.column_stack(\n",
    "    (\n",
    "        np.interp(lap, [0, 1, 2, 3], corners[:, 0]),\n",
    "        np.interp(lap, [0, 1, 2, 3], corners[:, 1]),\n",
    "    )\n",
    ")\n",
    "bottom_cut = Plane(origin=(0.0, 0.0, 0.0), normal=(1.0, 0.0, 0.0))\n",
    "speeds = []\n",
    "for name, mesh, result in zip((\"coarser\", \"finer\"), meshes, results):\n",
    "    velocity, temperature = result.field(flow.velocity), result.field(heat.temperature)\n",
    "    rate = (\n",
    "        2\n",
    "        * integrate_plane(\n",
    "            velocity,\n",
    "            bottom_cut,\n",
    "            normal_component=True,\n",
    "            within=lambda points: points[:, 1] < 0,\n",
    "        ).value\n",
    "    )\n",
    "    speeds.append(abs(rate) / channel**2)\n",
    "    taken = {zone: 2 * temperature.reaction(faces[zone]) for zone in zones}\n",
    "    print(\n",
    "        f\"{name} mesh ({mesh.cell_count} hexahedra, {len(result.result_set.solver_report['coupling']['scaled_changes'])} coupling sweeps): \"\n",
    "        f\"flow rate {abs(rate) * 1e9 * 60:.2f} µl/min, mean speed {1e3 * speeds[-1]:.3f} mm/s, Re = \"\n",
    "        f\"{water.density * speeds[-1] * channel / water.dynamic_viscosity:.1f}\"\n",
    "    )\n",
    "    print(\n",
    "        \"  heat exchanged with the walls: \"\n",
    "        + \", \".join(f\"{zone} {1e3 * value:+.2f} mW\" for zone, value in taken.items())\n",
    "        + f\"; sum {1e3 * sum(taken.values()):+.3f} mW ({100 * sum(taken.values()) / max(abs(v) for v in taken.values()):+.3f} %)\"\n",
    "    )\n",
    "centre_line = (\n",
    "    results[-1]\n",
    "    .field(heat.temperature)\n",
    "    .evaluate(np.column_stack((path, np.full(len(lap), channel / 2 - 1e-9))))\n",
    "    .ravel()\n",
    ")\n",
    "driving = abs(np.trapezoid(centre_line, path[:, 1]))\n",
    "print(\n",
    "    f\"\\ncirculation in the plane: {'clockwise, up the denaturation leg' if rate < 0 else 'counter-clockwise, up the annealing leg'}\"\n",
    ")\n",
    "print(\n",
    "    f\"one-dimensional loop balance with the wall temperatures: {1e3 * loop_balance(40.0 * height):.3f} mm/s; 3D model \"\n",
    "    f\"{1e3 * speeds[-1]:.3f} mm/s ({100 * (speeds[-1] / loop_balance(40.0 * height) - 1):+.1f} %)\"\n",
    ")\n",
    "print(\n",
    "    f\"the water does not reach the wall temperatures: the centre-line temperatures drive with {driving / height:.2f} K instead of 40 K, \"\n",
    "    f\"and the same balance then gives {1e3 * loop_balance(driving):.3f} mm/s ({100 * (speeds[-1] / loop_balance(driving) - 1):+.1f} %)\"\n",
    ")\n",
    "print(\n",
    "    \"the buoyancy acts on the area-mean temperature, which lies between the centre-line and the wall temperatures, \"\n",
    "    \"so the two one-dimensional estimates bracket the 3D result\"\n",
    ")\n",
    "print(\n",
    "    f\"mesh study: mean speed changes by {100 * (speeds[-1] / speeds[0] - 1):+.2f} % from the coarser to the finer mesh\"\n",
    ")\n",
    "print(\n",
    "    f\"cycle time (one lap): {length / speeds[-1]:.1f} s, i.e. {side / speeds[-1]:.1f} s in each temperature zone; \"\n",
    "    f\"30 cycles in {30 * length / speeds[-1] / 60:.1f} min\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Temperature and speed on the mid-depth plane, and the temperature along the centre line of the\n",
    "channel over one lap, starting at the lower left corner and running up the denaturation leg."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(layout=[[\"temperature\", \"speed\"], [\"lap\", \"lap\"]], size=(15, 12))\n",
    "plots.surface(\n",
    "    results[-1].field(heat.temperature),\n",
    "    boundary=faces.mid_plane,\n",
    "    component=lambda T, position: T - celsius,\n",
    "    limits=(55.0, 95.0),\n",
    "    contours=8,\n",
    "    subdivisions=2,\n",
    "    aspect=1.0,\n",
    "    label=\"T [°C]\",\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"y [m]\",\n",
    "    title=\"Temperature on the mid-depth plane\",\n",
    "    ax=fig[\"temperature\"],\n",
    ")\n",
    "plots.surface(\n",
    "    results[-1].field(flow.velocity),\n",
    "    boundary=faces.mid_plane,\n",
    "    component=lambda u, position: 1e3 * np.linalg.norm(u, axis=1),\n",
    "    contours=4,\n",
    "    subdivisions=3,\n",
    "    aspect=1.0,\n",
    "    label=\"speed [mm/s]\",\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"y [m]\",\n",
    "    title=\"Speed on the mid-depth plane\",\n",
    "    ax=fig[\"speed\"],\n",
    ")\n",
    "plots.line(\n",
    "    side * lap * 1e3,\n",
    "    {\"centre line, mid-depth\": centre_line - celsius},\n",
    "    reference={\n",
    "        \"wall temperature\": (\n",
    "            side * lap * 1e3,\n",
    "            np.select([lap < 1, lap < 2], [95.0, 55.0], 72.0),\n",
    "        )\n",
    "    },\n",
    "    vlines=[1e3 * side, 2e3 * side],\n",
    "    ylimits=(50.0, 100.0),\n",
    "    xlabel=\"distance along the loop [mm]\",\n",
    "    ylabel=\"temperature [°C]\",\n",
    "    title=\"One lap = one PCR cycle: denaturation, annealing, extension\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[\"lap\"],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Make the channel narrower or the loop taller in `buoyancy_driven_pcr_loop_geometry.py` and follow\n",
    "the cycle time; give the zones the temperatures of a two-step protocol; or let a dilute species\n",
    "(the amplified DNA) ride on the solved flow with a source in the extension leg to estimate the\n",
    "yield per lap."
   ]
  }
 ]
}
