{
 "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": [
    "# HAMSTAD benchmark 2: moisture redistribution in a homogeneous wall\n",
    "\n",
    "The moisture content $w$ (kg/m³) of a porous material is in equilibrium with the relative\n",
    "humidity $\\varphi$ of its pore air through the sorption isotherm $w(\\varphi)$. Moisture moves as\n",
    "liquid (adsorbed films and capillary water) and as vapour,\n",
    "\n",
    "$$\\frac{\\partial w}{\\partial t}+\\nabla\\cdot\\mathbf g=0,\\qquad\n",
    "  \\mathbf g=-D_w\\,\\nabla w-\\delta_p\\,p_{sat}\\,\\nabla\\varphi ,$$\n",
    "\n",
    "with the moisture diffusivity $D_w$ and the vapour permeability $\\delta_p$. At a surface the\n",
    "vapour exchange with the ambient air is\n",
    "$\\mathbf g\\cdot\\mathbf n=\\beta\\,p_{sat}\\,(\\varphi_s-\\varphi_a)$. OneSimulation's\n",
    "`MoistureTransport` solves this balance with the moisture content as conserved state and the\n",
    "relative humidity from the isotherm; `VapourSurfaceTransfer` states the surface law.\n",
    "\n",
    "| Quantity | Value |\n",
    "|---|---|\n",
    "| thickness | 200 mm |\n",
    "| temperature | 20 °C, isothermal |\n",
    "| sorption isotherm | $w=116\\,\\big(1-\\ln\\varphi/0.118\\big)^{-0.869}$ kg/m³ |\n",
    "| moisture diffusivity $D_w$ | $6\\cdot10^{-10}$ m²/s |\n",
    "| vapour permeability $\\delta_p$ | $10^{-15}$ s |\n",
    "| initial state | $\\varphi=95\\,\\%$ |\n",
    "| ambient air | $\\varphi_a=45\\,\\%$ at $x=0$, $65\\,\\%$ at $x=0.2$ m |\n",
    "| vapour transfer coefficient $\\beta$ | $10^{-3}$ s/m on both sides |\n",
    "\n",
    "**Reference.** C.-E. Hagentoft et al., Assessment method of numerical prediction models for\n",
    "combined heat, air and moisture transfer in building components: benchmarks for one-dimensional\n",
    "cases, *J. Thermal Envelope and Building Science* 27 (2004) 327-352. With the constant\n",
    "diffusivity the moisture content obeys the linear diffusion equation, the surface resistance is\n",
    "negligible ($\\beta\\,p_{sat}\\,L/(D_w\\,dw/d\\varphi)\\sim10^5$) and the vapour part is four to five\n",
    "orders smaller than the liquid part. The analytical solution is then the Fourier series of the\n",
    "slab between the surface equilibria $w_0=w(0.45)$ and $w_L=w(0.65)$, starting from $w_i=w(0.95)$:\n",
    "\n",
    "$$w(x,t)=w_0+(w_L-w_0)\\frac{x}{L}+\\sum_{n\\ge1}b_n\\sin\\frac{n\\pi x}{L}\\,e^{-D_w(n\\pi/L)^2t},\\qquad\n",
    "  b_n=\\frac{2}{n\\pi}\\Big[(w_i-w_0)\\big(1-(-1)^n\\big)+(w_L-w_0)(-1)^n\\Big].$$"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.d1 import Line\n",
    "from onesim.meshing import StructuredLineMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fvm import CentralDifference, FiniteVolume, LeastSquaresGradient\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",
    "    HansenIsotherm,\n",
    "    MoistureTransport,\n",
    "    VapourSurfaceTransfer,\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": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "The isotherm of the benchmark is a Hansen isotherm\n",
    "$w=w_h\\,(1-\\ln\\varphi/a)^{-1/n}$ with $w_h=116$ kg/m³, $a=0.118$ and $1/n=0.869$. The wall is a\n",
    "line through its thickness; the initial moisture content is the equilibrium with 95 %."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "thickness, diffusivity, hour = 0.2, 6e-10, 3600.0\n",
    "isotherm = HansenIsotherm(saturation_content=116.0, a=0.118, n=1 / 0.869)\n",
    "wall = Line(start=(0.0, 0.0, 0.0), end=(thickness, 0.0, 0.0))\n",
    "moisture = MoistureTransport(\n",
    "    domain=wall.line,\n",
    "    sorption_isotherm=isotherm,\n",
    "    moisture_diffusivity=diffusivity,\n",
    "    vapour_permeability=1e-15,\n",
    "    temperature=293.15,\n",
    ")\n",
    "problem = Problem(\n",
    "    name=\"HAMSTAD benchmark 2\",\n",
    "    geometry=wall,\n",
    "    physics=(moisture,),\n",
    "    initial_conditions=(\n",
    "        InitialValue(moisture.moisture_content, float(isotherm.moisture_content(0.95))),\n",
    "    ),\n",
    "    boundary_conditions=(\n",
    "        VapourSurfaceTransfer(\n",
    "            physics=moisture,\n",
    "            boundary=wall.boundaries.start,\n",
    "            ambient_relative_humidity=0.45,\n",
    "            transfer_coefficient=1e-3,\n",
    "        ),\n",
    "        VapourSurfaceTransfer(\n",
    "            physics=moisture,\n",
    "            boundary=wall.boundaries.end,\n",
    "            ambient_relative_humidity=0.65,\n",
    "            transfer_coefficient=1e-3,\n",
    "        ),\n",
    "    ),\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Simulation\n",
    "\n",
    "Finite volumes on 50 and 200 cells with the second-order BDF method, 4 h and 1 h steps over\n",
    "1000 hours; Newton's method solves each step."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "runs = {\n",
    "    (cells, step): Simulation(\n",
    "        problem=problem,\n",
    "        mesh=StructuredLineMesher(cells=cells).generate(wall),\n",
    "        numerics=Numerics(\n",
    "            spatial=FiniteVolume(\n",
    "                gradient=LeastSquaresGradient(), diffusion=CentralDifference()\n",
    "            ),\n",
    "            time_integrator=BDF(order=2),\n",
    "            nonlinear_solver=Newton(\n",
    "                linear_solver=SparseDirect(), absolute_tolerance=1e-9\n",
    "            ),\n",
    "        ),\n",
    "    )\n",
    "    .run(start_time=0.0, end_time=1000 * hour, time_step=step * hour)\n",
    "    .field(moisture.moisture_content)\n",
    "    for cells, step in ((50, 4.0), (200, 1.0))\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the analytical solution\n",
    "\n",
    "The moisture content in every cell after 100, 300 and 1000 hours against the Fourier series."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "w0, wl, wi = (float(isotherm.moisture_content(phi)) for phi in (0.45, 0.65, 0.95))\n",
    "modes = np.arange(1, 4001)\n",
    "wavenumbers = modes * np.pi / thickness\n",
    "amplitudes = (\n",
    "    2\n",
    "    / (modes * np.pi)\n",
    "    * ((wi - w0) * (1 - (-1.0) ** modes) + (wl - w0) * (-1.0) ** modes)\n",
    ")\n",
    "print(\n",
    "    f\"surface equilibria w(45 %) = {w0:.3f}, w(65 %) = {wl:.3f}, initial w(95 %) = {wi:.3f} kg/m³\"\n",
    ")\n",
    "print(\n",
    "    \" cells   step [h]   time [h]   largest deviation [kg/m³]   relative to the drop w_i - w_0\"\n",
    ")\n",
    "for (cells, step), field in runs.items():\n",
    "    x = np.asarray(field.space.dof_coordinates)[:, 0]\n",
    "    for hours in (100, 300, 1000):\n",
    "        exact = (\n",
    "            w0\n",
    "            + (wl - w0) * x / thickness\n",
    "            + np.sin(np.outer(x, wavenumbers))\n",
    "            @ (amplitudes * np.exp(-diffusivity * wavenumbers**2 * hours * hour))\n",
    "        )\n",
    "        deviation = np.max(np.abs(np.asarray(field.at(hours * hour).values) - exact))\n",
    "        print(\n",
    "            f\"{cells:6d} {step:9.0f} {hours:10d} {deviation:22.4f} {deviation / (wi - w0):27.1e}\"\n",
    "        )\n",
    "fine = runs[(200, 1.0)]\n",
    "times = np.arange(0, 1001, 20)\n",
    "stored = np.array([fine.integrate(time=t * hour).value for t in times])\n",
    "analytical_store = thickness * (\n",
    "    (w0 + wl) / 2\n",
    "    + np.exp(-diffusivity * np.outer(times * hour, wavenumbers**2))\n",
    "    @ (amplitudes * (1 - (-1.0) ** modes) / (modes * np.pi))\n",
    ")\n",
    "print(\n",
    "    f\"stored moisture after 1000 h: {stored[-1]:.4f} kg/m², analytical {analytical_store[-1]:.4f} kg/m², \"\n",
    "    f\"largest deviation over the run {np.max(np.abs(stored - analytical_store)):.4f} kg/m²\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Left: the moisture content profiles on 200 cells (markers, every fourth cell) and the analytical\n",
    "solution (dashed). Middle: the relative humidity in the pores from the isotherm, which carries\n",
    "the strong nonlinearity of the problem. Right: the moisture stored in the wall over time."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "x = np.asarray(fine.space.dof_coordinates)[:, 0]\n",
    "profiles = {\n",
    "    f\"{hours} h\": np.asarray(fine.at(hours * hour).values) for hours in (100, 300, 1000)\n",
    "}\n",
    "fig = plots.figure(1, 3, size=(18, 5))\n",
    "plots.line(\n",
    "    points={label: (1e3 * x[::4], values[::4]) for label, values in profiles.items()},\n",
    "    reference={\n",
    "        f\"{hours} h\": (\n",
    "            1e3 * x,\n",
    "            w0\n",
    "            + (wl - w0) * x / thickness\n",
    "            + np.sin(np.outer(x, wavenumbers))\n",
    "            @ (amplitudes * np.exp(-diffusivity * wavenumbers**2 * hours * hour)),\n",
    "        )\n",
    "        for hours in (100, 300, 1000)\n",
    "    },\n",
    "    hlines={\"initial\": wi},\n",
    "    xlabel=\"position x [mm]\",\n",
    "    ylabel=\"moisture content w [kg/m³]\",\n",
    "    title=\"Moisture content (dashed: analytical)\",\n",
    "    legend=\"lower center\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    y={\n",
    "        label: (1e3 * x, 100 * isotherm.relative_humidity(values))\n",
    "        for label, values in profiles.items()\n",
    "    },\n",
    "    xlabel=\"position x [mm]\",\n",
    "    ylabel=\"relative humidity [%]\",\n",
    "    title=\"Relative humidity in the pores\",\n",
    "    legend=\"lower center\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    y={\"OneSimulation\": (times, stored)},\n",
    "    reference={\"analytical\": (times, analytical_store)},\n",
    "    xlabel=\"time [h]\",\n",
    "    ylabel=\"stored moisture [kg/m²]\",\n",
    "    title=\"Moisture in the wall\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Give the material a humidity-dependent diffusivity, `moisture_diffusivity=` any function of the\n",
    "relative humidity, or a `SorptionIsotherm` from measured data: the model stays the same and only\n",
    "the analytical comparison is lost. The same declaration runs on planar and revolved sections and\n",
    "in three dimensions, for example a corner of the wall or a drying timber column, and\n",
    "`FixedRelativeHumidity` and `MoistureFlux` state other surface conditions."
   ]
  }
 ]
}
