{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "soil_freezing_lunardini_1d-1",
   "source": [
    "# Freezing fronts in a soil column\n",
    "\n",
    "Cooling warm soil at the surface produces two moving isotherms. Below −4 °C the freezable pore water is frozen, above 0 °C it is liquid, and between them it releases latent heat. The two interfaces in Lunardini’s three-zone solution move as $\\sqrt t$. This is the −4 °C solidus case of InterFrost T1. Soil properties and the published dimensionless front positions come from [Tubini, Gruber and Rigon, Appendix F](https://doi.org/10.5194/tc-15-2541-2021)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "id": "soil_freezing_lunardini_1d-2",
   "source": [
    "import numpy as np\n",
    "from scipy.special import erf, erfc\n",
    "from onesim.cad.d1 import Line\n",
    "from onesim.materials import TabulatedLaw, ThermalFluid\n",
    "from onesim.meshing import NonuniformLineMesher\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 AdaptiveTimeStep, BackwardEuler\n",
    "from onesim.physics.heat_transfer import FixedTemperature, HeatConduction, HeatFlux\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": {},
   "id": "soil_freezing_lunardini_1d-3",
   "source": [
    "## Material and boundary conditions\n",
    "\n",
    "The 10 m column starts at 4 °C. Its surface is held at −6 °C and its deep end is insulated. The apparent heat capacity includes the latent heat released between −4 °C and 0 °C. Linear ramps of width 0.3 K round the two property jumps and preserve the area under the latent-heat peak. The material supplies bulk thermal properties to a conduction-only model."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "id": "soil_freezing_lunardini_1d-4",
   "source": [
    "day, kelvin = 86400, 273.15\n",
    "rho, sensible = 1680 * 1.2, 690030.0\n",
    "latent = 1680 * (0.2 - 0.0782) * 334560\n",
    "conductivity = np.array([3.462696, 2.939946, 2.417196])\n",
    "capacity = np.array([sensible, sensible + latent / 4, sensible])\n",
    "knots = tuple(kelvin + np.array([-4.15, -3.85, -0.15, 0.15]))\n",
    "soil = ThermalFluid(density=rho, dynamic_viscosity=1.0,\n",
    "    specific_heat_capacity=TabulatedLaw(knots, tuple(capacity[[0, 1, 1, 2]] / rho), \"J/kg/K\"),\n",
    "    thermal_conductivity=TabulatedLaw(knots, tuple(conductivity[[0, 1, 1, 2]]), \"W/m/K\"))\n",
    "column = Line(start=(0, 0, 0), end=(10, 0, 0))\n",
    "heat = HeatConduction(domain=column.line, material=soil)\n",
    "problem = Problem(name=\"InterFrost T1\", geometry=column, physics=(heat,), boundary_conditions=(\n",
    "    FixedTemperature(physics=heat, boundary=column.boundaries.start, value=kelvin-6),\n",
    "    HeatFlux(physics=heat, boundary=column.boundaries.end, value=0)),\n",
    "    initial_conditions=(InitialValue(heat.temperature, kelvin+4),))\n",
    "method = Numerics(spatial=FiniteElement(element=Lagrange(order=1), quadrature_order=4),\n",
    "    time_integrator=BackwardEuler(), linear_solver=SparseDirect(),\n",
    "    nonlinear_solver=Newton(linear_solver=SparseDirect(), relative_tolerance=1e-7, maximum_iterations=70))"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "soil_freezing_lunardini_1d-5",
   "source": [
    "## Compare both moving boundaries\n",
    "\n",
    "Lunardini gives the depths $2\\psi\\sqrt{\\alpha_f t}$ and $2\\gamma\\sqrt{\\alpha_m t}$ for the −4 °C and 0 °C isotherms. Here $\\psi=0.061$, $\\gamma=1.397$ and the three diffusivities are the ratios of conductivity to volumetric heat capacity. Adaptive time steps follow the phase change on the finest mesh. On each of three meshes we interpolate the numerical isotherms and compare the whole profile between zero and three metres with the analytical temperature."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "id": "soil_freezing_lunardini_1d-6",
   "source": [
    "depth = np.linspace(0, 3, 601)\n",
    "points = np.column_stack((depth, np.zeros((len(depth), 2))))\n",
    "scale = 2 * np.sqrt(day * np.array([1, 2, 3])[:, None] * (conductivity / capacity))\n",
    "fronts = scale[:, :2] * [0.061, 1.397]\n",
    "exact = []\n",
    "for (frozen, thawed), (cold, mixed, warm) in zip(fronts, scale):\n",
    "    middle = (erfc(depth/mixed) - erfc(thawed/mixed)) / (erfc(frozen/mixed) - erfc(thawed/mixed))\n",
    "    exact.append(np.select([depth <= frozen, depth < thawed],\n",
    "        [-6 + 2*erf(depth/cold)/erf(frozen/cold), -4*middle], 4*(1-erfc(depth/warm)/erfc(thawed/warm))))\n",
    "for n in (1, 2, 4):\n",
    "    nodes = np.r_[np.linspace(0, 0.9, 55*n, endpoint=False), np.linspace(0.9, 3, 30*n, endpoint=False), np.linspace(3, 10, 10*n+1)]\n",
    "    mesh = NonuniformLineMesher(arclength_faces=tuple(nodes)).generate(column)\n",
    "    steps = 900/n if n < 4 else AdaptiveTimeStep(initial=0.1, minimum=1e-4, maximum=400,\n",
    "                                                relative_tolerance=0, absolute_tolerance=0.02)\n",
    "    T = Simulation(problem=problem, mesh=mesh, numerics=method).run(start_time=0, end_time=3*day, time_step=steps).field(heat.temperature)\n",
    "    history = T.time_interpolant()\n",
    "    profile = np.array([history(points, d*day)-kelvin for d in (1, 2, 3)])\n",
    "    observed = np.array([np.interp([-4, 0], row, depth) for row in profile])\n",
    "    rms = np.sqrt(np.mean((profile-exact)**2, axis=1))\n",
    "    print(f\"{len(mesh.faces)} nodes, {len(nodes)-1} cells: worst daily RMS {max(rms):.3f} K; largest front error {1000*np.max(abs(observed-fronts)):.1f} mm\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "metadata": {},
   "id": "soil_freezing_lunardini_1d-7",
   "source": [
    "days = np.arange(1, 4)\n",
    "fig = plots.figure(1, 2, size=(11, 4.4))\n",
    "plots.line(depth, {f\"Day {d}\": profile[d-1] for d in days}, reference={\"Exact, day 3\": exact[-1]},\n",
    "           xlabel=\"Depth [m]\", ylabel=\"Temperature [°C]\", title=\"Cooling below the surface\", ax=fig[0])\n",
    "plots.line(days, {\"−4 °C\": observed[:, 0], \"0 °C\": observed[:, 1]},\n",
    "           reference={\"Frozen front, exact\": fronts[:, 0], \"Thawed front, exact\": fronts[:, 1]},\n",
    "           xlabel=\"Time [days]\", ylabel=\"Depth [m]\", title=\"The two freezing fronts\", ax=fig[1])\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
