{
 "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": [
    "# Homogenized permeability of a simple cubic sphere packing\n",
    "\n",
    "A macroscopic model of a packed bed, a sintered filter or a granular soil treats the pores as a\n",
    "continuum with two properties: the porosity $\\varepsilon$ and the permeability $K$ of Darcy's law\n",
    "$\\langle\\mathbf u\\rangle=-(K/\\mu)\\nabla\\langle p\\rangle$. Both follow from one periodic cell of\n",
    "the microstructure. Here the cell of side $L$ holds one sphere of radius $a$, the solid fraction\n",
    "is $c=1-\\varepsilon=4\\pi a^3/(3L^3)$. A uniform pressure gradient $G$ along $x$, applied as a body\n",
    "force, drives the creeping flow; then $K=\\mu\\langle u\\rangle/G$ with the superficial velocity\n",
    "$\\langle u\\rangle$, the flow rate per cell cross-section.\n",
    "\n",
    "Two mirror planes through the sphere centres and two between the spheres cut the cell into\n",
    "quarters, so one quarter is enough. It comes from the CAD files\n",
    "`periodic_sphere_array_permeability.step` ($c=0.216$) and\n",
    "`periodic_sphere_array_permeability_64.step` to `..._450.step`, written by\n",
    "`periodic_sphere_array_permeability_geometry.py`.\n",
    "\n",
    "$$-\\nabla p+\\mu\\nabla^2\\mathbf u+G\\,\\mathbf e_x=0,\\qquad\\nabla\\cdot\\mathbf u=0$$\n",
    "\n",
    "| face | condition |\n",
    "|---|---|\n",
    "| `x_min` / `x_max` | periodic pair |\n",
    "| `y_min`, `y_max`, `z_min`, `z_max` (mirror planes) | impermeable, shear free |\n",
    "| `sphere.surface` | no slip |\n",
    "\n",
    "**Reference.** The drag on each sphere, $F=GL^3$, is usually given relative to Stokes' drag on a\n",
    "single sphere in the superficial velocity, $K^*=F/(6\\pi\\mu a\\langle u\\rangle)$, so that\n",
    "$K=L^3/(6\\pi a K^*)$. A. A. Zick and G. M. Homsy, \"Stokes flow through periodic arrays of spheres\",\n",
    "*J. Fluid Mech.* 115, 13-26 (1982), Table 2, simple cubic array: $K^*=2.810$, 4.292, 7.442, 15.4\n",
    "and 28.1 for $c=0.064$, 0.125, 0.216, 0.343 and 0.45. Dilute limit (H. Hasimoto, *J. Fluid\n",
    "Mech.* 5, 317-328, 1959): $K^*=1/(1-1.7601\\,c^{1/3}+c-1.5593\\,c^2)$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import NewtonianFluid\n",
    "from onesim.meshing import LocalRefinement, PeriodicPair, TetrahedralMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, TaylorHood\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.numerics.nonlinear import Newton\n",
    "from onesim.physics.hydrodynamics import (\n",
    "    FreeSlipLaw,\n",
    "    IncompressibleNavierStokes,\n",
    "    NoSlipWall,\n",
    "    WallShear,\n",
    ")\n",
    "from onesim.results.derived import derived_field\n",
    "from onesim.simulation import PeriodicBoundary, Problem, Simulation\n",
    "from onesim.simulation.field_constraints import MeanValue\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",
    "Tetrahedra of a tenth of the cell side, finer on the sphere; the two periodic faces carry the\n",
    "same triangles. The mesh study at $c=0.216$ adds a coarser and a finer mesh."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fractions = (0.064, 0.125, 0.216, 0.343, 0.450)\n",
    "zick_homsy = {0.064: 2.810, 0.125: 4.292, 0.216: 7.442, 0.343: 15.4, 0.450: 28.1}\n",
    "cells = {\n",
    "    fraction: load(f\"periodic_sphere_array_permeability_{round(1000 * fraction)}.step\")\n",
    "    for fraction in fractions\n",
    "}\n",
    "side = cells[0.216].size[0]\n",
    "radius = {\n",
    "    fraction: side * (3 * fraction / (4 * np.pi)) ** (1 / 3) for fraction in fractions\n",
    "}\n",
    "cases = [(fraction, 0.10) for fraction in fractions] + [(0.216, 0.14), (0.216, 0.07)]\n",
    "meshes = {\n",
    "    (fraction, size): TetrahedralMesher(\n",
    "        target_size=size * side,\n",
    "        refinements=(\n",
    "            LocalRefinement(\n",
    "                region=cells[fraction].boundaries[\"sphere.surface\"],\n",
    "                target_size=0.6 * size * side,\n",
    "            ),\n",
    "        ),\n",
    "        periodic_pairs=(\n",
    "            PeriodicPair(\n",
    "                first=cells[fraction].boundaries.x_min,\n",
    "                second=cells[fraction].boundaries.x_max,\n",
    "            ),\n",
    "        ),\n",
    "    ).generate(cells[fraction])\n",
    "    for fraction, size in cases\n",
    "}\n",
    "\n",
    "cell = load(\"periodic_sphere_array_permeability.step\")\n",
    "view = plots.Camera(elevation=28, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(14, 6))\n",
    "plots.geometry(\n",
    "    cell,\n",
    "    selection={\n",
    "        \"sphere\": cell.boundaries[\"sphere.surface\"],\n",
    "        \"periodic pair\": cell.boundaries.x_min | cell.boundaries.x_max,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Quarter of the unit cell, c = 0.216\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[0.216, 0.10],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"{meshes[0.216, 0.10].cell_count} tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "Water and a pressure gradient of 1 Pa/m keep the Reynolds number far below one. The pressure,\n",
    "periodic and fixed only up to a constant, gets the mean value zero."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "water, gradient = NewtonianFluid(density=1000.0, dynamic_viscosity=1.0e-3), 1.0\n",
    "flows = {}\n",
    "for fraction, size in cases:\n",
    "    faces = cells[fraction].boundaries\n",
    "    model = IncompressibleNavierStokes(\n",
    "        domain=cells[fraction].volume, material=water, body_force=(gradient, 0.0, 0.0)\n",
    "    )\n",
    "    problem = Problem(\n",
    "        name=\"Sphere array unit cell\",\n",
    "        geometry=cells[fraction],\n",
    "        physics=(model,),\n",
    "        boundary_conditions=(\n",
    "            NoSlipWall(boundary=faces[\"sphere.surface\"], physics=model),\n",
    "            WallShear(\n",
    "                boundary=faces.y_min | faces.y_max | faces.z_min | faces.z_max,\n",
    "                physics=model,\n",
    "                law=FreeSlipLaw(),\n",
    "            ),\n",
    "            PeriodicBoundary(\n",
    "                pair=PeriodicPair(first=faces.x_min, second=faces.x_max), physics=model\n",
    "            ),\n",
    "        ),\n",
    "        constraints=(MeanValue(model.pressure, 0.0),),\n",
    "    )\n",
    "    numerics = Numerics(\n",
    "        spatial=FiniteElement(element=TaylorHood()),\n",
    "        initial_guess={model.velocity: (0.0, 0.0, 0.0)},\n",
    "        nonlinear_solver=Newton(\n",
    "            linear_solver=SparseDirect(),\n",
    "            absolute_tolerance=1e-20,\n",
    "            relative_tolerance=1e-10,\n",
    "        ),\n",
    "    )\n",
    "    flows[fraction, size] = (\n",
    "        Simulation(problem=problem, mesh=meshes[fraction, size], numerics=numerics)\n",
    "        .solve_stationary()\n",
    "        .field(model.velocity)\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The superficial velocity is the flow rate through the quarter divided by its volume times its\n",
    "length; the porosity is the fluid volume over the cell volume. The flat faces of the tetrahedra\n",
    "make the sphere slightly smaller than drawn, which shows in the porosity. Hasimoto's expansion\n",
    "holds only for dilute arrays."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "volume = side**3 / 4\n",
    "porosity = {\n",
    "    fraction: derived_field(\n",
    "        flows[fraction, 0.10],\n",
    "        lambda u, points: np.ones(len(points)),\n",
    "        name=\"one\",\n",
    "        unit=\"1\",\n",
    "    )\n",
    "    .integrate()\n",
    "    .value\n",
    "    / volume\n",
    "    for fraction in fractions\n",
    "}\n",
    "permeability = {\n",
    "    key: water.dynamic_viscosity * velocity.integrate().value[0] / volume / gradient\n",
    "    for key, velocity in flows.items()\n",
    "}\n",
    "drag = {\n",
    "    (fraction, size): side**3\n",
    "    / (6 * np.pi * radius[fraction] * permeability[fraction, size])\n",
    "    for fraction, size in cases\n",
    "}\n",
    "hasimoto = lambda c: 1 / (1 - 1.7601 * c ** (1 / 3) + c - 1.5593 * c**2)\n",
    "\n",
    "print(\n",
    "    \"  c      porosity  exact    K [m²]        K*      Zick & Homsy   deviation   Hasimoto\"\n",
    ")\n",
    "for fraction in fractions:\n",
    "    print(\n",
    "        f\"{fraction:6.3f} {porosity[fraction]:9.4f} {1 - fraction:7.4f} {permeability[fraction, 0.10]:12.4e} {drag[fraction, 0.10]:8.3f}\"\n",
    "        f\" {zick_homsy[fraction]:10.3f} {100 * (drag[fraction, 0.10] / zick_homsy[fraction] - 1):+10.1f} %\"\n",
    "        + (f\" {hasimoto(fraction):9.3f}\" if fraction < 0.15 else \"    (dilute only)\")\n",
    "    )\n",
    "print(\n",
    "    \"\\nmesh study at c = 0.216: K* = \"\n",
    "    + \", \".join(\n",
    "        f\"{drag[0.216, size]:.4f} ({meshes[0.216, size].cell_count} tetrahedra)\"\n",
    "        for size in (0.14, 0.10, 0.07)\n",
    "    )\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The flow speed on the faces of the quarter cell at $c=0.216$, and the drag coefficient over the\n",
    "solid fraction."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "c = np.linspace(0.001, 0.12, 100)\n",
    "fig = plots.figure(1, 2, size=(15, 6))\n",
    "plots.surface(\n",
    "    flows[0.216, 0.10],\n",
    "    component=lambda u, position: 1e6 * np.linalg.norm(u, axis=1),\n",
    "    limits=\"robust\",\n",
    "    contours=6,\n",
    "    subdivisions=2,\n",
    "    camera=view,\n",
    "    label=\"speed [µm/s]\",\n",
    "    title=\"Speed on the cell faces, c = 0.216\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    c,\n",
    "    reference={\"Hasimoto (1959), dilute\": hasimoto(c)},\n",
    "    y={\"simulation\": (list(fractions), [drag[f, 0.10] for f in fractions])},\n",
    "    points={\"Zick & Homsy (1982)\": (list(zick_homsy), list(zick_homsy.values()))},\n",
    "    markers=True,\n",
    "    scale=\"logy\",\n",
    "    xlimits=(0.0, 0.5),\n",
    "    xlabel=\"solid fraction c\",\n",
    "    ylabel=\"drag coefficient K* = F / (6π μ a U)\",\n",
    "    title=\"Drag on the spheres of a simple cubic array\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Shift the sphere into the corners and the face centres of the cell in\n",
    "`periodic_sphere_array_permeability_geometry.py` to model body-centred and face-centred packings,\n",
    "or let the spheres overlap to model a sintered material. Driving the flow along $y$ and $z$ in\n",
    "turn gives the full permeability tensor of an anisotropic cell."
   ]
  }
 ]
}
