{
 "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": [
    "# Spinodal decomposition benchmark\n",
    "\n",
    "The first benchmark of the phase-field community (Jokisaari et al., 2017) follows a\n",
    "concentration $c$ that starts close to 0.5 and decomposes, by the **Cahn-Hilliard equation**,\n",
    "\n",
    "$$\\frac{\\partial c}{\\partial t}=\\nabla\\cdot\\Big(M\\,\\nabla\\big(f'(c)-\\kappa\\nabla^2c\\big)\\Big),\\qquad\n",
    "  f(c)=\\varrho_s\\,(c-c_\\alpha)^2\\,(c_\\beta-c)^2 ,$$\n",
    "\n",
    "into the two phases $c_\\alpha=0.3$ and $c_\\beta=0.7$, with $\\varrho_s=5$, $\\kappa=2$ and $M=5$\n",
    "in the dimensionless units of the benchmark. Variant b uses the square $200\\times200$ with\n",
    "no-flux walls:\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| all walls | no flux, $\\mathbf n\\cdot M\\nabla\\mu=0$, and $\\mathbf n\\cdot\\nabla c=0$ |\n",
    "| initial state | $c=0.5+0.01\\,[\\cos 0.105x\\cos 0.11y+(\\cos 0.13x\\cos 0.087y)^2+\\cos(0.025x-0.15y)\\cos(0.07x-0.02y)]$ |\n",
    "\n",
    "The double well is written in the order parameter $\\varphi=(c-0.5)/0.2$, which runs from $-1$ to\n",
    "$+1$: $f=\\tfrac{\\beta}{4}(\\varphi^2-1)^2$ with $\\beta=4\\varrho_s\\,0.2^4$, the gradient coefficient\n",
    "becomes $\\kappa\\,0.2^2$ and the mobility $M/0.2^2$; the free energy is unchanged.\n",
    "\n",
    "The square comes from the CAD file `spinodal_decomposition_benchmark.step`, written by\n",
    "`spinodal_decomposition_benchmark_geometry.py` with the CAD objects of OneSimulation.\n",
    "\n",
    "**Reference.** A. M. Jokisaari, P. W. Voorhees, J. E. Guyer, J. Warren, O. G. Heinonen,\n",
    "*Benchmark problems for numerical implementations of phase field models*, Comput. Mater. Sci. 126\n",
    "(2017) 139-151. The benchmark states the interface energy $\\sigma=0.01508\\sqrt{\\kappa\\varrho_s}$\n",
    "and the interface width $l=4.47$; the mean concentration must stay at its initial value, and\n",
    "the total free energy must decrease. At equilibrium every interface stores half of its energy\n",
    "in $f$ and half in $\\tfrac{\\kappa}{2}|\\nabla c|^2$ (equipartition of a Ginzburg-Landau interface)."
   ]
  },
  {
   "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.fem import FiniteElement, Lagrange\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.numerics.nonlinear import Newton\n",
    "from onesim.numerics.time import ConvexSplitting\n",
    "from onesim.physics.hydrodynamics import (\n",
    "    CahnHilliard,\n",
    "    CompositionGradient,\n",
    "    DoubleWellFreeEnergy,\n",
    "    PhaseFlux,\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": [
    "## Geometry and mesh\n",
    "\n",
    "`section` cuts the loaded square at half thickness. Quadratic triangles of 2.5 units resolve the\n",
    "interface width 4.47 with two to three elements."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "solid = load(\"spinodal_decomposition_benchmark.step\")\n",
    "square = solid.section((0, 0, 1), origin=(0, 0, 0.5))\n",
    "mesh = TriangularMesher(target_size=2.5).generate(square)\n",
    "\n",
    "fig = plots.figure(1, 2, size=(13, 5.5))\n",
    "plots.geometry(\n",
    "    solid,\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=35, azimuth=-60),\n",
    "    title=\"Benchmark square from the STEP file\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Mid-plane: {mesh.cell_count} triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "The benchmark parameters in the order parameter $\\varphi$; `DoubleWellFreeEnergy` takes the\n",
    "equivalent interface tension and width. `ConvexSplitting` keeps the free energy decreasing for\n",
    "every step size, so 100 steps of 10 time units cover the decomposition and the start of the\n",
    "coarsening up to $t=1000$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "rho, c_alpha, c_beta, kappa, mobility = 5.0, 0.3, 0.7, 2.0, 5.0\n",
    "half = (c_beta - c_alpha) / 2\n",
    "beta, gradient = 4 * rho * half**4, kappa * half**2\n",
    "energy = DoubleWellFreeEnergy(\n",
    "    surface_tension=2 * np.sqrt(2) / 3 * np.sqrt(beta * gradient),\n",
    "    interface_width=np.sqrt(gradient / beta),\n",
    ")\n",
    "alloy = CahnHilliard(\n",
    "    domain=square.domain(), free_energy=energy, mobility=mobility / half**2\n",
    ")\n",
    "initial = (\n",
    "    lambda x, y: (\n",
    "        0.01\n",
    "        * (\n",
    "            np.cos(0.105 * x) * np.cos(0.11 * y)\n",
    "            + (np.cos(0.13 * x) * np.cos(0.087 * y)) ** 2\n",
    "            + np.cos(0.025 * x - 0.15 * y) * np.cos(0.07 * x - 0.02 * y)\n",
    "        )\n",
    "    )\n",
    "    / half\n",
    ")\n",
    "problem = Problem(\n",
    "    name=\"Spinodal decomposition\",\n",
    "    geometry=square,\n",
    "    physics=(alloy,),\n",
    "    initial_conditions=(InitialValue(alloy.composition, initial),),\n",
    "    boundary_conditions=(\n",
    "        PhaseFlux(physics=alloy, boundary=square.boundaries.all),\n",
    "        CompositionGradient(physics=alloy, boundary=square.boundaries.all),\n",
    "    ),\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2), quadrature_order=4),\n",
    "    linear_solver=SparseDirect(),\n",
    "    nonlinear_solver=Newton(\n",
    "        linear_solver=SparseDirect(), relative_tolerance=1e-9, absolute_tolerance=1e-12\n",
    "    ),\n",
    "    time_integrator=ConvexSplitting(),\n",
    ")\n",
    "result = Simulation(problem=problem, mesh=mesh, numerics=numerics).run(\n",
    "    start_time=0.0, end_time=1000.0, time_step=10.0\n",
    ")\n",
    "phase = result.field(alloy.composition)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "Mean concentration, free energy and the two parts of the interface energy are integrated over the\n",
    "square; the concentration is $c=0.5+0.2\\,\\varphi$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "times = np.asarray(phase.times)\n",
    "area = square.size[0] * square.size[1]\n",
    "mean = 0.5 + half * np.asarray(phase.integrate().values) / area\n",
    "free_energy = np.asarray(result.field(alloy.free_energy_density).integrate().values)\n",
    "bulk = np.asarray(\n",
    "    phase.derive(lambda p, x: energy.density(p), name=\"bulk\", unit=\"J/m^3\")\n",
    "    .integrate()\n",
    "    .values\n",
    ")\n",
    "interface = np.asarray(\n",
    "    phase.derive(\n",
    "        lambda g, x: 0.5 * gradient * np.sum(g * g, axis=-1),\n",
    "        name=\"gradient\",\n",
    "        unit=\"J/m^3\",\n",
    "        uses=\"gradient\",\n",
    "    )\n",
    "    .integrate()\n",
    "    .values\n",
    ")\n",
    "print(\n",
    "    f\"interface energy: sigma = {energy.surface_tension:.5f} (benchmark 0.01508 sqrt(kappa rho_s) = {0.01508 * np.sqrt(kappa * rho):.5f}), \"\n",
    "    f\"width 2 sqrt(2) W = {2 * np.sqrt(2) * energy.interface_width:.2f} (benchmark 4.47)\"\n",
    ")\n",
    "print(\n",
    "    f\"mean concentration: {mean[0]:.12f} at t = 0, largest change {np.max(np.abs(mean - mean[0])):.1e}\"\n",
    ")\n",
    "print(\"    t      free energy   bulk / gradient part\")\n",
    "for t in (10.0, 30.0, 50.0, 100.0, 200.0, 500.0, 1000.0):\n",
    "    i = int(np.argmin(np.abs(times - t)))\n",
    "    print(f\"{times[i]:7.0f} {free_energy[i]:14.3f} {bulk[i] / interface[i]:12.3f}\")\n",
    "print(\n",
    "    f\"free energy steps with an increase: {int(np.sum(np.diff(free_energy) > 1e-12 * free_energy[0]))}\"\n",
    ")\n",
    "print(\n",
    "    f\"phases at t = {times[-1]:.0f}: c from {0.5 + half * phase.values.min():.4f} to {0.5 + half * phase.values.max():.4f} \"\n",
    "    f\"(equilibrium {c_alpha} and {c_beta})\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The concentration at four times, and the free energy with its bulk and gradient parts."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "nearest = lambda t: float(times[np.argmin(np.abs(times - t))])\n",
    "fig = plots.figure(\n",
    "    layout=[[\"early\", \"spinodal\", \"energy\"], [\"coarse\", \"late\", \"energy\"]],\n",
    "    size=(19, 11.5),\n",
    ")\n",
    "for panel, t in zip(\n",
    "    (fig[\"early\"], fig[\"spinodal\"], fig[\"coarse\"], fig[\"late\"]),\n",
    "    (30.0, 50.0, 200.0, 1000.0),\n",
    "):\n",
    "    plots.surface(\n",
    "        phase,\n",
    "        time=nearest(t),\n",
    "        limits=(-1.05, 1.05),\n",
    "        subdivisions=2,\n",
    "        xlabel=\"x\",\n",
    "        ylabel=\"y\",\n",
    "        label=\"(c - 0.5) / 0.2\",\n",
    "        title=f\"t = {nearest(t):.0f}\",\n",
    "        ax=panel,\n",
    "    )\n",
    "plots.line(\n",
    "    y={\n",
    "        \"free energy\": (times[1:], free_energy[1:]),\n",
    "        \"bulk part\": (times[1:], bulk[1:]),\n",
    "        \"gradient part\": (times[1:], interface[1:]),\n",
    "    },\n",
    "    scale=\"loglog\",\n",
    "    xlabel=\"time\",\n",
    "    ylabel=\"energy\",\n",
    "    title=\"Free energy and its two parts\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[\"energy\"],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Variant a of the benchmark uses periodic walls, variants c and d a T-shaped domain and the surface\n",
    "of a sphere; run longer to reach the late coarsening stage, where only a few large domains remain."
   ]
  }
 ]
}
