{
 "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": [
    "# Moisture uptake and swelling stresses in a paperboard roll\n",
    "\n",
    "Paper and board take up and give off moisture with the humidity of the surrounding air, and they\n",
    "swell and shrink with it: little in the machine direction (MD, wound along the circumference of\n",
    "a roll), more in the cross direction (CD, along its axis) and some ten times more through the\n",
    "thickness (ZD, the radius of the roll). In a roll the moisture moves through the layers only\n",
    "slowly but quickly along them, between the sheets; a roll wrapped around its mantle takes up\n",
    "moisture from its ends. The swelling of the moist end zones against the dry middle of the roll\n",
    "causes stresses that can crush the core, wave the edges or crack the end faces.\n",
    "\n",
    "This wrapped-roll case isolates ingress through the cut ends at a fixed humidity.\n",
    "The assumed material constants and fixed core describe the example specimen.\n",
    "\n",
    "**Setup.** Core radius $a=50$ mm (rigid core), outer radius $b=400$ mm, width 1 m (half computed,\n",
    "symmetry at the mid-plane). Moisture content $w$ (kg/m³) of the board in equilibrium with the air\n",
    "through the sorption isotherm $w=28+56\\,\\varphi$; diffusivity along the sheets $10^{-8}$ m²/s. The roll\n",
    "starts in equilibrium with 50 % and its ends are exposed to 80 % from $t=0$; the wrapping of the\n",
    "mantle and the core are impermeable. Board:\n",
    "$E_r=30$ MPa (ZD), $E_z=2.5$ GPa (CD), $E_\\theta=6$ GPa (MD), $G_{rz}=G_{r\\theta}=80$ MPa, $G_{z\\theta}=2$ GPa,\n",
    "$\\nu_{rz}=\\nu_{r\\theta}=0.01$, $\\nu_{z\\theta}=0.18$; hygroscopic expansion $4.3\\cdot10^{-4}$ (ZD),\n",
    "$4.3\\cdot10^{-5}$ (CD) and $1.4\\cdot10^{-5}$ (MD) per kg/m³. The roll comes from the CAD file\n",
    "`paperboard_roll_moisture_swelling.step`, written by `paperboard_roll_moisture_swelling_geometry.py`\n",
    "with the CAD objects of OneSimulation; both problems use its meridian section.\n",
    "\n",
    "| edge of the section | moisture | mechanics |\n",
    "|---|---|---|\n",
    "| `end` | relative humidity 80 % | free |\n",
    "| `mantle` | impermeable (wrapped) | free |\n",
    "| `core` | impermeable | radial displacement 0 |\n",
    "| `middle` | symmetry | axial displacement 0 |\n",
    "\n",
    "**Checks.** (1) For a constant diffusivity the moisture content obeys the linear diffusion\n",
    "equation; with sealed mantle and core it depends on $z$ only, and the relative unbalance\n",
    "$\\theta=(w-w_\\infty)/(w_0-w_\\infty)$ is the series of the slab open at $z=\\pm W/2$:\n",
    "$\\theta=\\sum_n\\frac{4(-1)^n}{(2n+1)\\pi}\\cos\\frac{(2n+1)\\pi z}{W}\\,e^{-D(2n+1)^2\\pi^2t/W^2}$. (2) With the test displacements $z\\,\\mathbf e_z$ and $r\\,\\mathbf e_r$ the weak form\n",
    "gives two exact identities: $\\int\\sigma_{zz}\\,dV=0$ (no axial force on the half roll) and\n",
    "$\\int(\\sigma_{rr}+\\sigma_{\\theta\\theta})\\,dV=a\\,R_r$ with the radial reaction $R_r$ of the core."
   ],
   "id": "f697af034f4b"
  },
  {
   "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 import Numerics\n",
    "from onesim.numerics.fvm import (\n",
    "    CentralDifference,\n",
    "    FiniteVolume,\n",
    "    LeastSquaresGradient,\n",
    "    RevolvedCellMeshView,\n",
    ")\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.numerics.nonlinear import Newton\n",
    "from onesim.numerics.time import BDF\n",
    "from onesim.physics.hydrodynamics import (\n",
    "    FixedRelativeHumidity,\n",
    "    MoistureTransport,\n",
    "    SorptionIsotherm,\n",
    ")\n",
    "from onesim.physics.solid_mechanics import SmallStrainSolid\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": "40c688026ff8"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "The meridian section uses an 8 mm triangular mesh for the coupled calculation. Compare its cell count\n",
    "with the original 12.5 mm mesh. Each triangle carries one moisture unknown, with\n",
    "quadratic elements for the mechanics."
   ],
   "id": "d56bdb93e080"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "roll = load(\"paperboard_roll_moisture_swelling.step\")\n",
    "faces = roll.boundaries\n",
    "meridian = roll.section((0, 1, 0), origin=(0, 0, 0))\n",
    "edges = meridian.boundaries\n",
    "coarse = TriangularMesher(target_size=0.0125).generate(meridian)\n",
    "mesh = TriangularMesher(target_size=0.008).generate(meridian)\n",
    "print(f\"Meridian mesh: {coarse.cell_count} triangles at 12.5 mm, {mesh.cell_count} at 8 mm\")\n",
    "\n",
    "fig = plots.figure(1, 2, size=(14, 6))\n",
    "plots.geometry(\n",
    "    roll,\n",
    "    selection={\"end (80 %)\": faces.end, \"mantle (wrapped)\": faces.mantle, \"core\": faces.core},\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=25, azimuth=-60),\n",
    "    title=\"Sector of half the roll\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Meridian section: {mesh.cell_count} triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "b640ff41a667"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Moisture transport\n",
    "\n",
    "`MoistureTransport` on finite volumes of the revolved section; second-order BDF steps of 12 hours\n",
    "for 60 days."
   ],
   "id": "daf854b21e78"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "day = 86400.0\n",
    "inner, outer, half_width = 0.05, 0.40, 0.50\n",
    "diffusivity = 1e-8\n",
    "isotherm = SorptionIsotherm(\n",
    "    function=lambda phi: 28.0 + 56.0 * phi,\n",
    "    derivative=lambda phi: 56.0 + 0 * phi,\n",
    "    inverse=lambda w: (w - 28.0) / 56.0,\n",
    ")\n",
    "board = MoistureTransport(\n",
    "    domain=meridian.domain(), sorption_isotherm=isotherm, moisture_diffusivity=diffusivity\n",
    ")\n",
    "initial, ambient = float(isotherm.moisture_content(0.5)), float(isotherm.moisture_content(0.8))\n",
    "moisture = Simulation(\n",
    "    problem=Problem(\n",
    "        name=\"Roll in humid air\",\n",
    "        geometry=meridian,\n",
    "        physics=(board,),\n",
    "        initial_conditions=(InitialValue(board.moisture_content, initial),),\n",
    "        boundary_conditions=(FixedRelativeHumidity(physics=board, boundary=edges.end, value=0.8),),\n",
    "    ),\n",
    "    mesh=mesh,\n",
    "    numerics=Numerics(\n",
    "        spatial=FiniteVolume(\n",
    "            gradient=LeastSquaresGradient(),\n",
    "            diffusion=CentralDifference(),\n",
    "            volume_mesh_view_factory=RevolvedCellMeshView,\n",
    "        ),\n",
    "        time_integrator=BDF(order=2),\n",
    "        nonlinear_solver=Newton(linear_solver=SparseDirect(), absolute_tolerance=1e-9),\n",
    "    ),\n",
    ").run(start_time=0.0, end_time=60 * day, time_step=0.5 * day)\n",
    "content = moisture.field(board.moisture_content)"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "416b742f9153"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Moisture against the series solution\n",
    "\n",
    "400 terms of the slab series, compared at the cell centres."
   ],
   "id": "d47c1d7cbdf5"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "odd = 2 * np.arange(400) + 1\n",
    "slab = lambda z, t: np.cos(np.outer(z, odd * np.pi / (2 * half_width))) @ (\n",
    "    4\n",
    "    * (-1.0) ** np.arange(400)\n",
    "    / (odd * np.pi)\n",
    "    * np.exp(-diffusivity * (odd * np.pi / (2 * half_width)) ** 2 * t)\n",
    ")\n",
    "centres = np.asarray(content.space.dof_coordinates)\n",
    "for days in (3, 10, 30, 60):\n",
    "    computed = np.asarray(content.at(days * day).values)\n",
    "    deviation = np.abs(computed - (ambient + (initial - ambient) * slab(centres[:, 1], days * day)))\n",
    "    print(\n",
    "        f\"t = {days:2d} d: moisture content within {deviation.max():.3f} kg/m³ of the series solution \"\n",
    "        f\"(rms {np.sqrt(np.mean(deviation**2)):.4f}; change at the end {ambient - initial:.1f} kg/m³)\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "e3ad8fb01ba2"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Swelling stresses\n",
    "\n",
    "Orthotropic stiffness in the order $(r, z, \\theta, rz, z\\theta, r\\theta)$ from the compliance, and the\n",
    "eigenstrain $\\beta\\,(w-w_0)$ from the moisture history through `time_interpolant()`."
   ],
   "id": "8ce181e46ac1"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "Er, Ez, Et = 0.03e9, 2.5e9, 6e9\n",
    "compliance = np.diag([1 / Er, 1 / Ez, 1 / Et, 1 / 0.08e9, 1 / 2e9, 1 / 0.08e9])\n",
    "compliance[0, 1] = compliance[1, 0] = -0.01 / Er\n",
    "compliance[0, 2] = compliance[2, 0] = -0.01 / Er\n",
    "compliance[1, 2] = compliance[2, 1] = -0.18 / Ez\n",
    "stiffness = np.linalg.inv(compliance)\n",
    "expansion = np.array([4.3e-4, 4.3e-5, 1.4e-5, 0.0, 0.0, 0.0])\n",
    "history = content.time_interpolant()\n",
    "times = np.array([1, 3, 10, 30, 60]) * day\n",
    "result = SmallStrainSolid(youngs_modulus=Ez, poisson_ratio=0.2, kinematics=\"axisymmetric\").solve(\n",
    "    mesh=mesh,\n",
    "    times=times,\n",
    "    order=2,\n",
    "    elastic_stiffness=stiffness,\n",
    "    displacements=((edges.core, \"r\", 0.0), (edges.middle, \"z\", 0.0)),\n",
    "    eigenstrain=lambda points, time: np.outer(history(points, time) - initial, expansion),\n",
    ")\n",
    "weights = result.quadrature_weights\n",
    "nodes = result.coordinates\n",
    "print(f\"Coupled calculation: {len(centres)} moisture cells, {len(nodes)} quadratic displacement nodes\")\n",
    "core = np.abs(nodes[:, 0] - inner) < 1e-9\n",
    "for k, days in enumerate(times / day):\n",
    "    stress = result.stress[k]\n",
    "    axial_force = np.sum(weights * stress[:, 1, 1])\n",
    "    radial_hoop = np.sum(weights * (stress[:, 0, 0] + stress[:, 2, 2]))\n",
    "    scale = np.sum(weights * np.abs(stress[:, 1, 1]))\n",
    "    print(\n",
    "        f\"t = {days:2.0f} d: ∫σ_zz dV = {axial_force:9.3e} N m (∫|σ_zz| dV = {scale:8.3e}); ∫(σ_rr+σ_θθ) dV = {radial_hoop:10.4e} N m, \"\n",
    "        f\"a R_r = {inner * result.reactions[k][core, 0].sum():10.4e}; largest hoop stress {stress[:, 2, 2].max() / 1e6:6.3f} MPa, \"\n",
    "        f\"radial reaction of the core {result.reactions[k][core, 0].sum() / 1e3:7.3f} kN\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "67fff078d694"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figures\n",
    "\n",
    "Left the moisture content along the axis at several times, computed (cells near mid-radius) and\n",
    "from the series; middle the hoop stress, right the axial stress at the quadrature points after 60\n",
    "days against the axial position, coloured by radius band."
   ],
   "id": "76deb6c256c9"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "z_line = np.linspace(0.0, half_width, 200)\n",
    "band = np.abs(centres[:, 0] - 0.225) < 0.01\n",
    "points = result.quadrature_coordinates\n",
    "bands = {\n",
    "    f\"{1e3 * low:.0f}–{1e3 * high:.0f} mm\": (points[:, 0] >= low) & (points[:, 0] < high)\n",
    "    for low, high in ((0.05, 0.15), (0.15, 0.30), (0.30, 0.37), (0.37, 0.40))\n",
    "}\n",
    "fig = plots.figure(1, 3, size=(20, 6))\n",
    "plots.line(\n",
    "    points={\n",
    "        f\"{d} d\": (1e3 * centres[band, 1], np.asarray(content.at(d * day).values)[band])\n",
    "        for d in (3, 10, 30, 60)\n",
    "    },\n",
    "    reference={\n",
    "        f\"series, {d} d\": (1e3 * z_line, ambient + (initial - ambient) * slab(z_line, d * day))\n",
    "        for d in (3, 10, 30, 60)\n",
    "    },\n",
    "    xlabel=\"axial position z [mm]\",\n",
    "    ylabel=\"moisture content [kg/m³]\",\n",
    "    title=\"Moisture entering from the end\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        name: (1e3 * points[mask, 1], result.stress[-1][mask, 2, 2] / 1e6)\n",
    "        for name, mask in bands.items()\n",
    "    },\n",
    "    xlabel=\"axial position z [mm]\",\n",
    "    ylabel=\"hoop stress σ_θθ [MPa]\",\n",
    "    title=\"Hoop (MD) stress after 60 days\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        name: (1e3 * points[mask, 1], result.stress[-1][mask, 1, 1] / 1e6)\n",
    "        for name, mask in bands.items()\n",
    "    },\n",
    "    xlabel=\"axial position z [mm]\",\n",
    "    ylabel=\"axial stress σ_zz [MPa]\",\n",
    "    title=\"Axial (CD) stress after 60 days\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "8f0ec7f35910"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Let the humidity cycle between day and night with `value=lambda x, y, t: ...`; unwrap the mantle\n",
    "so that moisture also enters through the layers, much more slowly (`direction_factors` of\n",
    "`MoistureTransport` on cells whose faces follow the layers); or let the core give way with a spring\n",
    "support instead of a rigid one."
   ],
   "id": "005fb07c3cb8"
  }
 ]
}
