{
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Effective diffusivity of a porous medium\n",
    "\n",
    "Transport through porous materials is usually described by a homogeneous model with an\n",
    "effective diffusivity $D_\\mathrm{eff}$, because the pores are far smaller than the device. The\n",
    "effective value follows from the microstructure: a representative piece of it is resolved, a\n",
    "concentration difference is applied across it, and the steady flux is measured,\n",
    "\n",
    "$$\\nabla\\cdot(D\\,\\nabla c)=0\\ \\text{in the pores},\\qquad\n",
    "  D_\\mathrm{eff}=\\frac{J\\,L}{H\\,(c_\\mathrm{in}-c_\\mathrm{out})},$$\n",
    "\n",
    "with the molar flux $J$ per unit depth through a strip of length $L$ and height $H$, so that\n",
    "$D_\\mathrm{eff}$ refers to the total cross-section. Here the grains are impermeable cylinders on\n",
    "a square lattice with the solid fraction $f$; OneSimulation solves the pore diffusion with the\n",
    "`SpeciesTransport` model and quadratic triangles on the cross-section of each STEP file.\n",
    "\n",
    "| Boundary | Condition |\n",
    "|---|---|\n",
    "| $x=0$ (`x_min`) | $c=c_\\mathrm{in}=1$ mol/m³ |\n",
    "| $x=L$ (`x_max`) | $c=c_\\mathrm{out}=0$ |\n",
    "| top, bottom, grain surfaces | no flux |\n",
    "\n",
    "By symmetry of the square array the planes between grain rows and columns are planes of\n",
    "symmetry, so a strip of 6 x 2 cells gives the value of the infinite array.\n",
    "\n",
    "**Reference.** Lord Rayleigh, *On the influence of obstacles arranged in rectangular order upon\n",
    "the properties of a medium*, Phil. Mag. 34, 481-502 (1892); W. T. Perrins, D. R. McKenzie and\n",
    "R. C. McPhedran, Proc. R. Soc. Lond. A 369, 207-225 (1979). For impermeable cylinders on a square\n",
    "lattice\n",
    "\n",
    "$$\\frac{D_\\mathrm{eff}}{D}=1-\\frac{2f}{1+f-\\dfrac{0.305827\\,f^4}{1-1.402958\\,f^8}-0.013362\\,f^8},$$\n",
    "\n",
    "which reduces to Maxwell's dilute limit $(1-f)/(1+f)$ for small $f$. The tortuosity factor\n",
    "$\\tau=\\varepsilon D/D_\\mathrm{eff}$ with the porosity $\\varepsilon=1-f$ follows directly."
   ],
   "id": "023569a712ee"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.d1 import Line\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.meshing import StructuredLineMesher, TriangularMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.numerics.nonlinear import Newton\n",
    "from onesim.numerics.time import BDF, BackwardEuler\n",
    "from onesim.physics.chemistry import (\n",
    "    FixedConcentration,\n",
    "    SpeciesTransport,\n",
    "    TransportSpecies,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.simulation.initial_conditions import InitialValue\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "f3717b3a6c89"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "Four strips with solid fractions of 10 % to 70 %, cut at mid-thickness; quadratic triangles\n",
    "with 26 µm bulk and 10 µm grain-edge targets. The 50 % strip also retains the\n",
    "40/15 µm mesh for a direct comparison of the stationary flux."
   ],
   "id": "7993f0376860"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fractions = (0.1, 0.3, 0.5, 0.7)\n",
    "files = {f: f\"porous_effective_diffusivity_{round(100 * f)}.step\" for f in fractions}\n",
    "files[0.5] = \"porous_effective_diffusivity.step\"\n",
    "parts = {f: load(name) for f, name in files.items()}\n",
    "planes = {f: part.section((0, 0, 1), origin=(0, 0, 5e-5)) for f, part in parts.items()}\n",
    "meshes = {\n",
    "    f: TriangularMesher(target_size=2.6e-5, local_sizes={\"grains\": 1e-5}).generate(plane)\n",
    "    for f, plane in planes.items()\n",
    "}\n",
    "coarse = TriangularMesher(target_size=4e-5, local_sizes={\"grains\": 1.5e-5}).generate(planes[0.5])\n",
    "length, height = planes[0.5].size[:2]\n",
    "fig = plots.figure(1, 2, size=(15, 5))\n",
    "plots.geometry(\n",
    "    parts[0.5],\n",
    "    selection={\n",
    "        \"grain surfaces\": parts[0.5].boundaries.grains,\n",
    "        \"inlet face\": parts[0.5].boundaries.x_min,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=35, azimuth=-60),\n",
    "    title=\"Porous strip, solid fraction 50 % (STEP)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[0.5],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Pore space: {meshes[0.5].cell_count} triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "aae3c22548ca"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model and solution\n",
    "\n",
    "One stationary diffusion problem per solid fraction, with the molecular diffusivity of a\n",
    "small solute in water."
   ],
   "id": "b085f5c072b0"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "diffusivity = 1e-9\n",
    "spatial = FiniteElement(element=Lagrange(order=2))\n",
    "fields = {}\n",
    "for fraction, plane in planes.items():\n",
    "    model = SpeciesTransport(\n",
    "        domain=plane.domain(), species=(TransportSpecies(\"A\", diffusivity=diffusivity),)\n",
    "    )\n",
    "    ends = (\n",
    "        FixedConcentration(physics=model, boundary=plane.boundaries.x_min, value=1.0),\n",
    "        FixedConcentration(physics=model, boundary=plane.boundaries.x_max, value=0.0),\n",
    "    )\n",
    "    problem = Problem(name=\"Pore strip\", geometry=plane, physics=(model,), boundary_conditions=ends)\n",
    "    simulation = Simulation(\n",
    "        problem=problem,\n",
    "        mesh=meshes[fraction],\n",
    "        numerics=Numerics(spatial=spatial, linear_solver=SparseDirect()),\n",
    "    )\n",
    "    fields[fraction] = simulation.solve_stationary().field(model.field(\"A\"))\n",
    "    print(f\"Solid fraction {fraction:g}: {meshes[fraction].cell_count} triangles, {len(fields[fraction].space.dof_coordinates)} concentration nodes\")\n",
    "    if fraction == 0.5:\n",
    "        reference = Simulation(problem=problem, mesh=coarse, numerics=Numerics(spatial=spatial, linear_solver=SparseDirect()))\n",
    "        coarse_field = reference.solve_stationary().field(model.field(\"A\"))\n",
    "        coarse_flux = coarse_field.boundary_flux(plane.boundaries.x_max)\n",
    "        fine_flux = fields[fraction].boundary_flux(plane.boundaries.x_max)\n",
    "        print(f\"50 % strip: {coarse.cell_count} to {meshes[fraction].cell_count} triangles, {len(coarse_field.space.dof_coordinates)} to {len(fields[fraction].space.dof_coordinates)} nodes, outlet flux change {100 * (fine_flux / coarse_flux - 1):+.4f} %\")"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "dbf295e6f6b3"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the Rayleigh-Perrins formula\n",
    "\n",
    "The outflow and the inflow must agree (conservation); their mean gives $D_\\mathrm{eff}$."
   ],
   "id": "dfbce12661ef"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "rayleigh = lambda f: 1 - 2 * f / (1 + f - 0.305827 * f**4 / (1 - 1.402958 * f**8) - 0.013362 * f**8)\n",
    "print(\n",
    "    \"  f    porosity   D_eff/D computed   Rayleigh-Perrins   deviation   Maxwell   tortuosity   in/out flux balance\"\n",
    ")\n",
    "ratios = {}\n",
    "for f, field in fields.items():\n",
    "    inflow, outflow = field.boundary_flux(planes[f].boundaries.x_min), field.boundary_flux(\n",
    "        planes[f].boundaries.x_max\n",
    "    )\n",
    "    ratios[f] = 0.5 * (outflow - inflow) * length / (height * diffusivity)\n",
    "    print(\n",
    "        f\"{f:4.1f} {1 - f:9.2f} {ratios[f]:16.5f} {rayleigh(f):17.5f} {100 * (ratios[f] / rayleigh(f) - 1):+10.3f} % \"\n",
    "        f\"{(1 - f) / (1 + f):9.4f} {(1 - f) / ratios[f]:11.3f} {abs(inflow + outflow) / outflow:16.1e}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "16749b493f65"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Does a homogeneous strip fill at the same rate?\n",
    "\n",
    "Initially the pores contain no solute. Fix the left and right end concentrations\n",
    "at one and zero. Compare the resolved 50 % strip with a homogeneous line.\n",
    "Its storage is the pore fraction $\\varepsilon$, so the diffusion coefficient\n",
    "in its concentration equation is $D_\\mathrm{eff}/\\varepsilon$.\n",
    "Normalize both inventories by the available pore volume."
   ],
   "id": "7ae88e530a0f"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "porosity = 0.5\n",
    "line = Line(start=(0, 0, 0), end=(length, 0, 0))\n",
    "plane = planes[0.5]\n",
    "domains = [\n",
    "    (\n",
    "        \"2D pores\",\n",
    "        plane,\n",
    "        plane.domain(),\n",
    "        plane.boundaries.x_min,\n",
    "        plane.boundaries.x_max,\n",
    "        TriangularMesher(target_size=5.5e-5).generate(plane),\n",
    "        diffusivity,\n",
    "        length * height * porosity,\n",
    "    ),\n",
    "    (\n",
    "        \"1D homogeneous\",\n",
    "        line,\n",
    "        line.line,\n",
    "        line.boundaries.start,\n",
    "        line.boundaries.end,\n",
    "        StructuredLineMesher(cells=128).generate(line),\n",
    "        diffusivity * ratios[0.5] / porosity,\n",
    "        length,\n",
    "    ),\n",
    "]\n",
    "inventory = {}\n",
    "for name, geometry, domain, left, right, mesh, coefficient, measure in domains:\n",
    "    model = SpeciesTransport(\n",
    "        domain=domain, species=(TransportSpecies(\"A\", diffusivity=coefficient),)\n",
    "    )\n",
    "    ends = (\n",
    "        FixedConcentration(physics=model, boundary=left, value=1.0),\n",
    "        FixedConcentration(physics=model, boundary=right, value=0.0),\n",
    "    )\n",
    "    problem = Problem(\n",
    "        name=name,\n",
    "        geometry=geometry,\n",
    "        physics=(model,),\n",
    "        boundary_conditions=ends,\n",
    "        initial_conditions=(InitialValue(model.field(\"A\"), 0.0),),\n",
    "    )\n",
    "    numerics = Numerics(\n",
    "        spatial=spatial,\n",
    "        nonlinear_solver=Newton(linear_solver=SparseDirect(), absolute_tolerance=1e-15),\n",
    "        time_integrator=BDF(order=2, startup=BackwardEuler()),\n",
    "    )\n",
    "    history = (\n",
    "        Simulation(problem=problem, mesh=mesh, numerics=numerics)\n",
    "        .run(start_time=0.0, end_time=14400.0, time_step=600.0)\n",
    "        .field(model.field(\"A\"))\n",
    "    )\n",
    "    print(f\"Transient {name}: {mesh.cell_count} elements, {len(history.space.dof_coordinates)} concentration nodes\")\n",
    "    times = history.times[1:]\n",
    "    inventory[name] = np.array([history.at(t).integrate().value / measure for t in times])\n",
    "print(\n",
    "    f\"After 4 h: pore-average concentration {inventory['2D pores'][-1]:.5f} mol/m³; \"\n",
    "    f\"homogeneous model {inventory['1D homogeneous'][-1]:.5f} mol/m³.\"\n",
    ")\n",
    "print(\n",
    "    f\"Largest inventory difference across the recorded steps: \"\n",
    "    f\"{max(abs(inventory['2D pores'] - inventory['1D homogeneous'])):.5f} mol/m³.\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "f0ad072c9d5a"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The concentration in the pores of the 50 % strip, and the effective diffusivity over the solid\n",
    "fraction against the Rayleigh-Perrins formula and Maxwell's dilute limit. The third panel compares\n",
    "the resolved and homogenized inventories over four hours."
   ],
   "id": "e921e1c65d8d"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fine = np.linspace(0.0, 0.75, 151)\n",
    "fig = plots.figure(1, 3, size=(19, 5))\n",
    "plots.surface(\n",
    "    fields[0.5],\n",
    "    limits=(0.0, 1.0),\n",
    "    contours=11,\n",
    "    subdivisions=2,\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"y [m]\",\n",
    "    label=\"c [mol/m³]\",\n",
    "    title=\"Concentration in the pores, f = 50 %\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\"OneSimulation\": (np.array(fractions), np.array([ratios[f] for f in fractions]))},\n",
    "    reference={\n",
    "        \"Rayleigh-Perrins\": (fine, rayleigh(fine)),\n",
    "        \"Maxwell (1 - f) / (1 + f)\": (fine, (1 - fine) / (1 + fine)),\n",
    "    },\n",
    "    xlabel=\"solid fraction f\",\n",
    "    ylabel=\"D_eff / D\",\n",
    "    title=\"Effective diffusivity of the square array\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    times / 3600,\n",
    "    {\"1D homogeneous\": inventory[\"1D homogeneous\"]},\n",
    "    points={\"2D pores\": (times / 3600, inventory[\"2D pores\"])},\n",
    "    xlabel=\"Time [h]\",\n",
    "    ylabel=\"Pore-average concentration [mol/m³]\",\n",
    "    title=\"Filling the 50 % strip\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "be917728e2cf"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Replace the square array by a random packing of grains of different sizes, or let the grains\n",
    "overlap into a connected skeleton: the formula no longer applies, but the same strip gives\n",
    "$D_\\mathrm{eff}$. Shift the array by half a cell between rows (a staggered array) and compare\n",
    "with the hexagonal-array result of Perrins et al.; at high solid fractions the two lattices\n",
    "differ strongly because the narrowest pore throat differs."
   ],
   "id": "edfbc37f3a20"
  }
 ]
}
