{
 "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": [
    "# Permeability of a square array of fibres\n",
    "\n",
    "Filters, composite preforms and fibrous insulation are porous materials whose pores are far\n",
    "smaller than the part. A model of the whole part uses Darcy's law\n",
    "\n",
    "$$\\langle\\mathbf u\\rangle=-\\frac{K}{\\mu}\\nabla\\langle p\\rangle$$\n",
    "\n",
    "with the superficial velocity $\\langle\\mathbf u\\rangle$ and the permeability $K$. The permeability\n",
    "follows from the flow in one representative volume element (RVE) of the microstructure: a uniform\n",
    "pressure gradient $G$ drives the creeping flow through the periodic cell, and\n",
    "$K=\\mu\\langle u\\rangle/G$.\n",
    "\n",
    "The cells come from CAD files, one per solid fraction $\\phi=\\pi a^2/L^2$ of the fibres of radius\n",
    "$a$ in the square of side $L=1$ mm: `permeability_square_fibre_array.step` ($\\phi=0.3$) and\n",
    "`permeability_square_fibre_array_5.step` to `..._60.step`, written by\n",
    "`permeability_square_fibre_array_geometry.py`. Each cell is a square prism 0.1 mm long along the\n",
    "fibre. The pressure gradient enters as a uniform body force $G$ across the fibres, along $x$; the\n",
    "pressure that remains is periodic.\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` | periodic pair |\n",
    "| `z_min` / `z_max` (along the fibre) | periodic pair |\n",
    "| `fibre.outer_wall` | no slip |\n",
    "\n",
    "**Reference.** A. S. Sangani and A. Acrivos, \"Slow flow past periodic arrays of cylinders with\n",
    "application to heat transfer\", *Int. J. Multiphase Flow* 8, 193-206 (1982), for dilute arrays:\n",
    "\n",
    "$$\\frac{K}{a^2}=\\frac{1}{8\\phi}\\left(-\\ln\\phi-1.476+2\\phi-1.774\\,\\phi^2+4.076\\,\\phi^3\\right);$$\n",
    "\n",
    "B. R. Gebart, \"Permeability of unidirectional reinforcements for RTM\", *J. Compos. Mater.* 26,\n",
    "1100-1133 (1992), from the lubrication flow in the narrow gaps of dense arrays:\n",
    "\n",
    "$$\\frac{K}{a^2}=\\frac{16}{9\\pi\\sqrt2}\\left(\\sqrt{\\frac{\\pi}{4\\phi}}-1\\right)^{5/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 IncompressibleNavierStokes, NoSlipWall\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 $L/20$, on the fibre at most $L/30$ and a fifth of the narrowest gap; the three\n",
    "pairs of opposite faces carry the same triangles. The mesh study at $\\phi=0.3$ scales all sizes by\n",
    "1.5 and by 0.7."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fractions = (0.05, 0.10, 0.20, 0.30, 0.40, 0.50, 0.60)\n",
    "cells = {\n",
    "    fraction: load(f\"permeability_square_fibre_array_{round(100 * fraction)}.step\")\n",
    "    for fraction in fractions\n",
    "}\n",
    "side, _, length = cells[0.30].size\n",
    "radius = {fraction: side * np.sqrt(fraction / np.pi) for fraction in fractions}\n",
    "cases = [(fraction, 1.0) for fraction in fractions] + [(0.30, 1.5), (0.30, 0.7)]\n",
    "meshes = {\n",
    "    (fraction, scale): TetrahedralMesher(\n",
    "        target_size=scale * side / 20,\n",
    "        refinements=(\n",
    "            LocalRefinement(\n",
    "                region=cells[fraction].boundaries[\"fibre.outer_wall\"],\n",
    "                target_size=scale * min(side / 30, (side - 2 * radius[fraction]) / 5),\n",
    "            ),\n",
    "        ),\n",
    "        periodic_pairs=tuple(\n",
    "            PeriodicPair(\n",
    "                first=cells[fraction].boundaries[low],\n",
    "                second=cells[fraction].boundaries[high],\n",
    "            )\n",
    "            for low, high in (\n",
    "                (\"x_min\", \"x_max\"),\n",
    "                (\"y_min\", \"y_max\"),\n",
    "                (\"z_min\", \"z_max\"),\n",
    "            )\n",
    "        ),\n",
    "    ).generate(cells[fraction])\n",
    "    for fraction, scale in cases\n",
    "}\n",
    "\n",
    "cell = load(\"permeability_square_fibre_array.step\")\n",
    "view = plots.Camera(elevation=40, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(13, 6))\n",
    "plots.geometry(\n",
    "    cell,\n",
    "    selection={\n",
    "        \"fibre\": cell.boundaries[\"fibre.outer_wall\"],\n",
    "        \"periodic pair x\": cell.boundaries.x_min | cell.boundaries.x_max,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Unit cell, solid fraction 0.3\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[0.30, 1.0],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"{meshes[0.30, 1.0].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": [
    "gradient, water = 1.0, NewtonianFluid(density=1000.0, dynamic_viscosity=1.0e-3)\n",
    "flows = {}\n",
    "for fraction, scale 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=\"Fibre array unit cell\",\n",
    "        geometry=cells[fraction],\n",
    "        physics=(model,),\n",
    "        boundary_conditions=(\n",
    "            NoSlipWall(boundary=faces[\"fibre.outer_wall\"], physics=model),\n",
    "            *[\n",
    "                PeriodicBoundary(\n",
    "                    pair=PeriodicPair(first=faces[low], second=faces[high]),\n",
    "                    physics=model,\n",
    "                )\n",
    "                for low, high in (\n",
    "                    (\"x_min\", \"x_max\"),\n",
    "                    (\"y_min\", \"y_max\"),\n",
    "                    (\"z_min\", \"z_max\"),\n",
    "                )\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, scale] = (\n",
    "        Simulation(problem=problem, mesh=meshes[fraction, scale], 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 cell divided by its cross-section, i.e. the\n",
    "volume integral of $u_x$ over the cell volume. The dilute series of Sangani and Acrivos holds up\n",
    "to a solid fraction of about 0.3, Gebart's lubrication result for dense arrays."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "volume = side * side * length\n",
    "permeability = {\n",
    "    key: water.dynamic_viscosity * velocity.integrate().value[0] / volume / gradient\n",
    "    for key, velocity in flows.items()\n",
    "}\n",
    "sangani_acrivos = lambda phi: (\n",
    "    -np.log(phi) - 1.476 + 2 * phi - 1.774 * phi**2 + 4.076 * phi**3\n",
    ") / (8 * phi)\n",
    "gebart = (\n",
    "    lambda phi: 16 / (9 * np.pi * np.sqrt(2)) * (np.sqrt(np.pi / (4 * phi)) - 1) ** 2.5\n",
    ")\n",
    "\n",
    "print(\n",
    "    \" solid fraction  tetrahedra     K [m²]      K/a²     Sangani-Acrivos   deviation    Gebart   deviation\"\n",
    ")\n",
    "for fraction in fractions:\n",
    "    scaled = permeability[fraction, 1.0] / radius[fraction] ** 2\n",
    "    print(\n",
    "        f\"{fraction:10.2f} {meshes[fraction, 1.0].cell_count:11d} {permeability[fraction, 1.0]:12.3e} {scaled:9.4f} {sangani_acrivos(fraction):12.4f}\"\n",
    "        f\" {100 * (scaled / sangani_acrivos(fraction) - 1):+10.1f} % {gebart(fraction):9.4f} {100 * (scaled / gebart(fraction) - 1):+8.1f} %\"\n",
    "    )\n",
    "print(\n",
    "    \"\\nmesh study at solid fraction 0.3: K/a² = \"\n",
    "    + \", \".join(\n",
    "        f\"{permeability[0.30, scale] / radius[0.30]**2:.5f} ({meshes[0.30, scale].cell_count} tetrahedra)\"\n",
    "        for scale in (1.5, 1.0, 0.7)\n",
    "    )\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The flow speed on the faces of the cell at $\\phi=0.3$ and $\\phi=0.6$, and the permeability over the\n",
    "solid fraction with both analytical results."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "phi = np.linspace(0.02, 0.78, 200)\n",
    "fig = plots.figure(layout=[[\"dilute\", \"dense\", \"permeability\"]], size=(18, 5.5))\n",
    "for panel, fraction in ((\"dilute\", 0.30), (\"dense\", 0.60)):\n",
    "    plots.surface(\n",
    "        flows[fraction, 1.0],\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=f\"Speed on the cell faces, solid fraction {fraction}\",\n",
    "        ax=fig[panel],\n",
    "    )\n",
    "plots.line(\n",
    "    reference={\n",
    "        \"Sangani & Acrivos (1982), dilute\": (\n",
    "            phi[phi < 0.35],\n",
    "            sangani_acrivos(phi[phi < 0.35]),\n",
    "        ),\n",
    "        \"Gebart (1992), dense\": (phi[phi > 0.15], gebart(phi[phi > 0.15])),\n",
    "    },\n",
    "    points={\n",
    "        \"simulation\": (\n",
    "            list(fractions),\n",
    "            [\n",
    "                permeability[fraction, 1.0] / radius[fraction] ** 2\n",
    "                for fraction in fractions\n",
    "            ],\n",
    "        )\n",
    "    },\n",
    "    scale=\"logy\",\n",
    "    ylimits=(1e-3, 20),\n",
    "    xlabel=\"solid fraction φ\",\n",
    "    ylabel=\"permeability K / a²\",\n",
    "    title=\"Permeability across the fibres\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[\"permeability\"],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Tilt the fibres in the cell or make the cell a rectangle in\n",
    "`permeability_square_fibre_array_geometry.py`: the permeability becomes a tensor, and driving the\n",
    "flow along $x$, $y$ and $z$ in turn gives its columns. The force along $z$ gives the permeability\n",
    "along the fibres, which is several times larger than across them."
   ]
  }
 ]
}
