{
 "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": [
    "# Hartmann layers in a liquid-metal duct\n",
    "\n",
    "An electrically conducting liquid driven by a pressure gradient $G=-\\partial p/\\partial x$ through a\n",
    "duct is braked by a transverse magnetic field $B$: the motion induces currents, and the Lorentz force\n",
    "of these currents flattens the velocity profile. The velocity drops to zero in thin **Hartmann\n",
    "layers** on the walls normal to the field, whose thickness shrinks as the field grows.\n",
    "\n",
    "Far from inlet and outlet the flow is fully developed and depends only on the cross-section\n",
    "coordinates $(y,z)$; $\\mathbf B=B\\hat{\\mathbf z}$. For a liquid metal the magnetic Reynolds number is\n",
    "tiny, so the field is not disturbed by the flow (**inductionless** approximation). The axial\n",
    "velocity $u$ and the streamfunction $\\psi$ of the induced current\n",
    "($j_y=\\partial_z\\psi$, $j_z=-\\partial_y\\psi$) then satisfy\n",
    "\n",
    "$$\\mu\\nabla^2u+B\\,\\frac{\\partial\\psi}{\\partial z}=-G,\\qquad\n",
    "  \\nabla^2\\psi+\\sigma B\\,\\frac{\\partial u}{\\partial z}=0 .$$\n",
    "\n",
    "The cross-section is cut from the duct in the CAD file `hartmann_layer_duct_section.step`, written by\n",
    "`hartmann_layer_duct_section_geometry.py` with the CAD objects of OneSimulation:\n",
    "\n",
    "| wall | condition |\n",
    "|---|---|\n",
    "| Hartmann walls `z_min`, `z_max` ($z=\\pm b$, normal to $\\mathbf B$) | no slip $u=0$, electrically insulating $\\psi=0$ |\n",
    "| side walls `y_min`, `y_max` ($y=\\pm a$, parallel to $\\mathbf B$) | no slip $u=0$, electrically insulating $\\psi=0$ |\n",
    "\n",
    "The fluid is the eutectic gallium-indium-tin alloy ($\\mu=2.16$ mPa s, $\\sigma=3.3$ MS/m). The duct is\n",
    "seven times wider than high ($a=70$ mm, $b=10$ mm), so its middle behaves like the flow between two\n",
    "infinite plates.\n",
    "\n",
    "**Reference** (J. Hartmann, *Hg-Dynamics I*, Kgl. Danske Vidensk. Selsk. Mat.-fys. Medd. **15**(6),\n",
    "1937; U. Müller and L. Bühler, *Magnetofluiddynamics in Channels and Containers*, Springer 2001,\n",
    "§3.2). With the Hartmann number $\\mathrm{Ha}=Bb\\sqrt{\\sigma/\\mu}$ the velocity between two\n",
    "insulating plates is\n",
    "\n",
    "$$u(z)=\\frac{Gb^2}{\\mu\\,\\mathrm{Ha}}\\,\\frac{\\cosh\\mathrm{Ha}-\\cosh(\\mathrm{Ha}\\,z/b)}{\\sinh\\mathrm{Ha}},\n",
    "  \\qquad \\delta_\\mathrm{Ha}=\\frac{b}{\\mathrm{Ha}},$$\n",
    "\n",
    "a flat core and two wall layers of thickness $\\delta_\\mathrm{Ha}$ in which the velocity rises as\n",
    "$1-e^{-d/\\delta_\\mathrm{Ha}}$ with the wall distance $d$. The power balance requires that the work of the\n",
    "pressure gradient, $GQ$, equals the viscous plus the Joule dissipation."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.meshing import TriangularMesher\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange, PlanarDirichletFiniteElement\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.physics.magnetohydrodynamics import InductionlessDuct\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 duct normal to the flow direction; the sides of the cross-section keep the names of\n",
    "the duct walls. The triangles are refined along the Hartmann walls to a quarter of the thinnest layer\n",
    "considered and grow slowly towards the core; the figure shows the coarsest mesh\n",
    "of the mesh study below, whose wall size is a quarter of the layer at $\\mathrm{Ha}=20$ (sizes in m)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "duct = load(\"hartmann_layer_duct_section.step\")\n",
    "section = duct.section((1, 0, 0), origin=(0.025, 0.07, 0.01))\n",
    "walls = section.boundaries\n",
    "width, height = section.size[:2]\n",
    "a, b = width / 2, height / 2\n",
    "hartmann_numbers = (5, 10, 20, 50)\n",
    "mesh_for = lambda size: TriangularMesher(\n",
    "    target_size=4 * size, grading=0.2, local_sizes={\"z_min\": size, \"z_max\": size}\n",
    ").generate(section)\n",
    "mesh = mesh_for(b / max(hartmann_numbers) / 4)\n",
    "coarse = mesh_for(b / 20 / 2)\n",
    "\n",
    "fig = plots.figure(1, 2, size=(14, 4.5))\n",
    "plots.geometry(\n",
    "    duct,\n",
    "    selection={\n",
    "        \"Hartmann walls\": duct.boundaries.z_min | duct.boundaries.z_max,\n",
    "        \"side walls\": duct.boundaries.y_min | duct.boundaries.y_max,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=25, azimuth=-60),\n",
    "    title=\"Piece of the insulating duct\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    coarse,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Cross-section, coarsest mesh: {len(coarse.cells)} triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "`InductionlessDuct` solves both equations with linear finite elements on the section; the walls carry\n",
    "the homogeneous conditions of no slip and insulation. One solve per Hartmann number, all with the\n",
    "same pressure gradient of 10 Pa/m."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "viscosity, conductivity, pressure_gradient = 2.16e-3, 3.3e6, 10.0\n",
    "finite_element = FiniteElement(element=Lagrange(order=1))\n",
    "spatial = PlanarDirichletFiniteElement(\n",
    "    finite_element=finite_element, boundary=walls.all\n",
    ")\n",
    "field_for = lambda hartmann: hartmann / b * np.sqrt(viscosity / conductivity)\n",
    "models = {\n",
    "    Ha: InductionlessDuct(\n",
    "        viscosity=viscosity,\n",
    "        conductivity=conductivity,\n",
    "        magnetic_field=field_for(Ha),\n",
    "        pressure_gradient=pressure_gradient,\n",
    "    )\n",
    "    for Ha in hartmann_numbers\n",
    "}\n",
    "print(\n",
    "    f\"solution mesh: {len(mesh.cells)} triangles, smallest size {1e3 * b / max(hartmann_numbers) / 4:.3f} mm at the Hartmann walls\"\n",
    ")\n",
    "solutions = {\n",
    "    Ha: model.solve(mesh=mesh, spatial=spatial, linear_solver=SparseDirect().bind())\n",
    "    for Ha, model in models.items()\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with Hartmann's solution\n",
    "\n",
    "The velocity is evaluated on the vertical line through the middle of the duct, across both Hartmann\n",
    "layers. The layer thickness is read off as the wall distance at which the velocity reaches\n",
    "$1-1/e$ of its centre value."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "nodes = solutions[20].velocity_coordinates\n",
    "centre = (nodes.min(axis=0) + nodes.max(axis=0)) / 2\n",
    "z = b * np.concatenate(\n",
    "    (\n",
    "        -np.cos(np.linspace(0, np.pi / 2, 300)),\n",
    "        np.sin(np.linspace(0, np.pi / 2, 300))[1:],\n",
    "    )\n",
    ")\n",
    "line = np.column_stack((np.full_like(z, centre[0]), centre[1] + z))\n",
    "hartmann = (\n",
    "    lambda Ha, z: pressure_gradient\n",
    "    * b**2\n",
    "    / (viscosity * Ha)\n",
    "    * (np.cosh(Ha) - np.cosh(Ha * z / b))\n",
    "    / np.sinh(Ha)\n",
    ")\n",
    "profiles = {\n",
    "    Ha: finite_element.bind_space(mesh).evaluate(solution.velocity, line)\n",
    "    for Ha, solution in solutions.items()\n",
    "}\n",
    "thickness = lambda u: np.interp(\n",
    "    (1 - 1 / np.e) * u[len(z) // 2], u[: len(z) // 2 + 1], z[: len(z) // 2 + 1] + b\n",
    ")\n",
    "print(\n",
    "    \"Ha    B [mT]   centre velocity [mm/s]       profile error   layer thickness [mm]            power balance\"\n",
    ")\n",
    "print(\n",
    "    \"               computed    Hartmann         (of centre)     computed  Hartmann   b/Ha         (P_visc+P_Joule)/GQ - 1\"\n",
    ")\n",
    "for Ha, u in profiles.items():\n",
    "    exact = hartmann(Ha, z)\n",
    "    solution = solutions[Ha]\n",
    "    balance = (solution.viscous_power + solution.joule_power) / (\n",
    "        pressure_gradient * solution.flow_rate\n",
    "    ) - 1\n",
    "    print(\n",
    "        f\"{Ha:3d} {1e3 * field_for(Ha):8.1f} {1e3 * u[len(z) // 2]:10.3f} {1e3 * exact[len(z) // 2]:10.3f} {100 * np.abs(u - exact).max() / exact.max():14.2f} %\"\n",
    "        f\" {1e3 * thickness(u):11.3f} {1e3 * thickness(exact):9.3f} {1e3 * b / Ha:7.3f} {balance:16.1e}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A mesh study at $\\mathrm{Ha}=20$: the target size along the Hartmann walls is halved twice."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "sizes = [b / 20 / 2, b / 20 / 4, b / 20 / 8]\n",
    "study_profiles = [\n",
    "    finite_element.bind_space(m).evaluate(\n",
    "        models[20]\n",
    "        .solve(mesh=m, spatial=spatial, linear_solver=SparseDirect().bind())\n",
    "        .velocity,\n",
    "        line,\n",
    "    )\n",
    "    for m in map(mesh_for, sizes)\n",
    "]\n",
    "study_errors = [\n",
    "    np.abs(u - hartmann(20, z)).max() / hartmann(20, 0) for u in study_profiles\n",
    "]\n",
    "order = np.log(study_errors[0] / study_errors[-1]) / np.log(sizes[0] / sizes[-1])\n",
    "print(\n",
    "    \"Ha = 20 mesh study: \"\n",
    "    + \", \".join(\n",
    "        f\"h = {1e3 * h:.3f} mm: {100 * e:.3f} %\" for h, e in zip(sizes, study_errors)\n",
    "    )\n",
    "    + f\"; observed order {order:.2f}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Top: the velocity over the cross-section at $\\mathrm{Ha}=20$ and the closed loops of the induced\n",
    "current (isolines of $\\psi$): it flows across the core and returns through the thin Hartmann layers.\n",
    "Bottom: the velocity profiles across the field, scaled to their centre value, against Hartmann's\n",
    "solution, and a close-up of the lower wall layer in units of the wall distance over $b$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "y, z_nodes = (nodes - centre).T\n",
    "fig = plots.figure(2, 2, size=(15, 8.5))\n",
    "plots.heatmap(\n",
    "    1e3 * y,\n",
    "    1e3 * z_nodes,\n",
    "    1e3 * solutions[20].velocity,\n",
    "    triangles=mesh.cells,\n",
    "    label=\"u [mm/s]\",\n",
    "    xlabel=\"y [mm]\",\n",
    "    ylabel=\"z [mm]\",\n",
    "    title=\"Axial velocity, Ha = 20\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.heatmap(\n",
    "    1e3 * y,\n",
    "    1e3 * z_nodes,\n",
    "    solutions[20].current_streamfunction,\n",
    "    triangles=mesh.cells,\n",
    "    contours=14,\n",
    "    colormap=\"diverging\",\n",
    "    label=\"ψ [A/m]\",\n",
    "    xlabel=\"y [mm]\",\n",
    "    ylabel=\"z [mm]\",\n",
    "    title=\"Induced current loops, Ha = 20\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    z / b,\n",
    "    {f\"Ha = {Ha}\": u / u[len(z) // 2] for Ha, u in profiles.items()},\n",
    "    reference={f\"Ha = {Ha}\": hartmann(Ha, z) / hartmann(Ha, 0) for Ha in profiles},\n",
    "    xlabel=\"z / b\",\n",
    "    ylabel=\"u / u(0)\",\n",
    "    title=\"Velocity across the field (dashed: Hartmann)\",\n",
    "    legend=\"lower center\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.line(\n",
    "    (z + b) / b,\n",
    "    {f\"Ha = {Ha}\": u / u[len(z) // 2] for Ha, u in profiles.items()},\n",
    "    reference={f\"Ha = {Ha}\": hartmann(Ha, z) / hartmann(Ha, 0) for Ha in profiles},\n",
    "    xlimits=(0, 0.6),\n",
    "    xlabel=\"wall distance d / b\",\n",
    "    ylabel=\"u / u(0)\",\n",
    "    title=\"Hartmann layer at the lower wall\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[3],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Make the duct square in `hartmann_layer_duct_section_geometry.py`: the side layers parallel to the\n",
    "field, of thickness $b/\\sqrt{\\mathrm{Ha}}$, then carry a noticeable part of the flow, and the flow\n",
    "rate departs from the plate formula towards Shercliff's duct solution. Raising the field further thins\n",
    "the Hartmann layers; the wall refinement in `local_sizes` follows $b/\\mathrm{Ha}$."
   ]
  }
 ]
}
