{
 "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 hexagonal array of fibres\n",
    "\n",
    "Unidirectional composite preforms, hollow-fibre modules and fibrous filters are often close to a\n",
    "hexagonal packing of parallel fibres. For the flow of resin or fluid across the fibres a model of\n",
    "the part needs the porosity $\\varepsilon$ and the permeability $K$ of Darcy's law. Both follow\n",
    "from one periodic cell of the microstructure (representative volume element): a uniform pressure\n",
    "gradient $G$, applied as a body force, drives the creeping flow, and $K=\\mu\\langle u\\rangle/G$ with\n",
    "the superficial velocity $\\langle u\\rangle$. The tortuosity $\\tau=\\langle|\\mathbf u|\\rangle/\\langle u\\rangle$\n",
    "measures how far the paths wind around the fibres.\n",
    "\n",
    "The cell holds a fibre on its axis and a quarter fibre on each long edge, pitch $L=1$ mm, solid\n",
    "fraction $\\phi=1-\\varepsilon=2\\pi a^2/(\\sqrt3L^2)$. It comes from the CAD files\n",
    "`permeability_hexagonal_fibre_array.step` ($\\phi=0.4$) and `..._10.step` to `..._70.step`, written\n",
    "by `permeability_hexagonal_fibre_array_geometry.py`, as prisms 0.1 mm long along the fibres.\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 fibres) | periodic pair |\n",
    "| `fibre.outer_wall` | no slip |\n",
    "\n",
    "**Reference.** A hexagonal array is isotropic across the fibres: the permeabilities along $x$ and\n",
    "$y$ agree. J. E. Drummond and M. I. Tahir, \"Laminar viscous flow through regular arrays of\n",
    "parallel solid cylinders\", *Int. J. Multiphase Flow* 10, 515-540 (1984), for dilute arrays:\n",
    "\n",
    "$$\\frac{K}{a^2}=\\frac{1}{8\\phi}\\left(-\\ln\\phi-1.498+2\\phi-\\frac{\\phi^2}{2}-0.739\\,\\phi^4\n",
    "  +\\frac{2.534\\,\\phi^5}{1+1.2758\\,\\phi}\\right);$$\n",
    "\n",
    "B. R. Gebart, *J. Compos. Mater.* 26, 1100-1133 (1992), for dense arrays:\n",
    "$K/a^2=\\frac{16}{9\\pi\\sqrt6}\\left(\\sqrt{\\phi_\\max/\\phi}-1\\right)^{5/2}$ with $\\phi_\\max=\\pi/(2\\sqrt3)$."
   ]
  },
  {
   "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.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 $L/20$, on the fibres 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.4$ scales all sizes by\n",
    "1.5."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fractions = (0.10, 0.20, 0.30, 0.40, 0.50, 0.60, 0.70)\n",
    "cells = {\n",
    "    fraction: load(f\"permeability_hexagonal_fibre_array_{round(100 * fraction)}.step\")\n",
    "    for fraction in fractions\n",
    "}\n",
    "pitch, height, length = cells[0.40].size\n",
    "radius = {\n",
    "    fraction: pitch * np.sqrt(fraction * np.sqrt(3) / (2 * np.pi))\n",
    "    for fraction in fractions\n",
    "}\n",
    "pairs = ((\"x_min\", \"x_max\"), (\"y_min\", \"y_max\"), (\"z_min\", \"z_max\"))\n",
    "meshes = {\n",
    "    (fraction, scale): TetrahedralMesher(\n",
    "        target_size=scale * pitch / 20,\n",
    "        refinements=(\n",
    "            LocalRefinement(\n",
    "                region=cells[fraction].boundaries[\"fibre.outer_wall\"],\n",
    "                target_size=scale * min(pitch / 30, (pitch - 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 pairs\n",
    "        ),\n",
    "    ).generate(cells[fraction])\n",
    "    for fraction, scale in [(fraction, 1.0) for fraction in fractions] + [(0.40, 1.5)]\n",
    "}\n",
    "\n",
    "cell = load(\"permeability_hexagonal_fibre_array.step\")\n",
    "view = plots.Camera(elevation=45, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(13, 6))\n",
    "plots.geometry(\n",
    "    cell,\n",
    "    selection={\"fibres\": cell.boundaries[\"fibre.outer_wall\"]},\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Periodic cell, solid fraction 0.4\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[0.40, 1.0],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"{meshes[0.40, 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 across the fibres, along $x$ for all solid fractions, and\n",
    "along $y$ and on the coarser mesh for $\\phi=0.4$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "water, gradient = NewtonianFluid(density=1000.0, dynamic_viscosity=1.0e-3), 1.0\n",
    "cases = [(fraction, \"x\", 1.0) for fraction in fractions] + [\n",
    "    (0.40, \"y\", 1.0),\n",
    "    (0.40, \"x\", 1.5),\n",
    "]\n",
    "flows = {}\n",
    "for fraction, axis, scale in cases:\n",
    "    faces = cells[fraction].boundaries\n",
    "    model = IncompressibleNavierStokes(\n",
    "        domain=cells[fraction].volume,\n",
    "        material=water,\n",
    "        body_force=(gradient, 0.0, 0.0) if axis == \"x\" else (0.0, gradient, 0.0),\n",
    "    )\n",
    "    problem = Problem(\n",
    "        name=\"Hexagonal fibre array 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 pairs\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, axis, 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",
    "Porosity and tortuosity are integrals over the fluid; the superficial velocity is the volume\n",
    "integral of the velocity over the cell volume."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "volume = pitch * height * length\n",
    "permeability = {\n",
    "    key: water.dynamic_viscosity\n",
    "    * velocity.integrate().value[\"xy\".index(key[1])]\n",
    "    / volume\n",
    "    / gradient\n",
    "    for key, velocity in flows.items()\n",
    "}\n",
    "porosity = {\n",
    "    fraction: derived_field(\n",
    "        flows[fraction, \"x\", 1.0],\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",
    "tortuosity = {\n",
    "    fraction: derived_field(\n",
    "        flows[fraction, \"x\", 1.0],\n",
    "        lambda u, points: np.linalg.norm(u, axis=1),\n",
    "        name=\"speed\",\n",
    "        unit=\"m/s\",\n",
    "    )\n",
    "    .integrate()\n",
    "    .value\n",
    "    / flows[fraction, \"x\", 1.0].integrate().value[0]\n",
    "    for fraction in fractions\n",
    "}\n",
    "drummond_tahir = lambda phi: (\n",
    "    -np.log(phi)\n",
    "    - 1.498\n",
    "    + 2 * phi\n",
    "    - phi**2 / 2\n",
    "    - 0.739 * phi**4\n",
    "    + 2.534 * phi**5 / (1 + 1.2758 * phi)\n",
    ") / (8 * phi)\n",
    "gebart = (\n",
    "    lambda phi: 16\n",
    "    / (9 * np.pi * np.sqrt(6))\n",
    "    * (np.sqrt(np.pi / (2 * np.sqrt(3) * phi)) - 1) ** 2.5\n",
    ")\n",
    "\n",
    "print(\n",
    "    \" φ     porosity  exact    K/a²     Drummond-Tahir  deviation   Gebart   deviation   tortuosity\"\n",
    ")\n",
    "for fraction in fractions:\n",
    "    scaled = permeability[fraction, \"x\", 1.0] / radius[fraction] ** 2\n",
    "    print(\n",
    "        f\"{fraction:4.2f} {porosity[fraction]:9.4f} {1 - fraction:7.4f} {scaled:9.4f} {drummond_tahir(fraction):12.4f} {100 * (scaled / drummond_tahir(fraction) - 1):+9.1f} %\"\n",
    "        f\" {gebart(fraction):8.4f} {100 * (scaled / gebart(fraction) - 1):+8.1f} % {tortuosity[fraction]:10.3f}\"\n",
    "    )\n",
    "print(\n",
    "    f\"\\nisotropy at φ = 0.4: K_y / K_x - 1 = {permeability[0.40, 'y', 1.0] / permeability[0.40, 'x', 1.0] - 1:+.1e}\"\n",
    ")\n",
    "print(\n",
    "    f\"mesh study at φ = 0.4: K/a² = {permeability[0.40, 'x', 1.5] / radius[0.40]**2:.5f} ({meshes[0.40, 1.5].cell_count} tetrahedra), \"\n",
    "    f\"{permeability[0.40, 'x', 1.0] / radius[0.40]**2:.5f} ({meshes[0.40, 1.0].cell_count} tetrahedra)\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The flow speed on the cell faces at $\\phi=0.4$ for the flow along $x$ and along $y$, and the\n",
    "permeability over the solid fraction."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "phi = np.linspace(0.05, 0.88, 200)\n",
    "fig = plots.figure(layout=[[\"x\", \"y\", \"permeability\"]], size=(18, 6))\n",
    "for axis in (\"x\", \"y\"):\n",
    "    plots.surface(\n",
    "        flows[0.40, axis, 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\"Flow along {axis}, φ = 0.4\",\n",
    "        ax=fig[axis],\n",
    "    )\n",
    "plots.line(\n",
    "    reference={\n",
    "        \"Drummond & Tahir (1984), dilute\": (\n",
    "            phi[phi < 0.45],\n",
    "            drummond_tahir(phi[phi < 0.45]),\n",
    "        ),\n",
    "        \"Gebart (1992), dense\": (phi[phi > 0.25], gebart(phi[phi > 0.25])),\n",
    "    },\n",
    "    points={\n",
    "        \"simulation\": (\n",
    "            list(fractions),\n",
    "            [permeability[f, \"x\", 1.0] / radius[f] ** 2 for f in fractions],\n",
    "        )\n",
    "    },\n",
    "    scale=\"logy\",\n",
    "    ylimits=(1e-4, 10),\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",
    "Replace the regular array by a random arrangement of fibres in a larger cell in\n",
    "`permeability_hexagonal_fibre_array_geometry.py`: the permeability then scatters around the value\n",
    "of the regular array, and averaging over several cells shows how large a representative volume\n",
    "must be. A force along $z$ gives the permeability along the fibres."
   ]
  }
 ]
}
