{
 "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": [
    "# Phase separation of a quenched binary mixture\n",
    "\n",
    "A thin film of a binary mixture with equal amounts of both components is quenched below its\n",
    "critical temperature. The uniform state is unstable: small composition fluctuations grow, the\n",
    "film separates into regions rich in one or the other component, and these regions then coarsen\n",
    "to lower the interface energy. The order parameter $c$ runs from $-1$ (pure A) to $+1$ (pure B)\n",
    "and obeys the **Cahn-Hilliard equation**\n",
    "\n",
    "$$\\frac{\\partial c}{\\partial t}=\\nabla\\cdot\\big(M\\,\\nabla\\mu\\big),\\qquad\n",
    "  \\mu=\\psi'(c)-\\kappa\\,\\nabla^2 c,\\qquad \\psi(c)=\\frac{\\beta}{4}\\,(c^2-1)^2 ,$$\n",
    "\n",
    "with the mobility $M$, the double-well energy $\\psi$ and the gradient coefficient $\\kappa$. Both\n",
    "follow from the interface tension $\\sigma=0.05$ N/m and the interface width $W=10$ µm.\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| all edges | no flux, $\\mathbf n\\cdot M\\nabla\\mu=0$ |\n",
    "| all edges | neutral wetting, $\\mathbf n\\cdot\\nabla c=0$ |\n",
    "| initial state | $c=0.01\\cos(8\\pi x/L)\\cos(8\\pi y/L)$ plus noise of amplitude 0.002 |\n",
    "\n",
    "The film, 0.5 mm wide, comes from the CAD file `binary_alloy_phase_separation.step`, written by\n",
    "`binary_alloy_phase_separation_geometry.py` with the CAD objects of OneSimulation.\n",
    "\n",
    "**Reference.** J. W. Cahn, *On spinodal decomposition*, Acta Metall. 9 (1961) 795-801. A\n",
    "composition wave of wave number $k$ on the uniform state $c=0$ grows as $e^{\\omega t}$ with\n",
    "\n",
    "$$\\omega(k)=M\\,k^2\\,\\big(\\beta-\\kappa k^2\\big),$$\n",
    "\n",
    "fastest at $k^2=\\beta/(2\\kappa)$. The wave of the initial state is chosen there. A time step\n",
    "$\\Delta t$ of convex splitting multiplies the wave by $g=(1+\\Delta t\\,M\\beta k^2)/(1+\\Delta t\\,M\\kappa k^4)$,\n",
    "so the scheme itself grows at the rate $\\ln g/\\Delta t$, slightly below $\\omega$. The total free\n",
    "energy $\\int\\psi+\\tfrac{\\kappa}{2}|\\nabla c|^2\\,\\mathrm dA$ must decrease and the amount of each\n",
    "component must stay constant."
   ]
  },
  {
   "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 film at half thickness. Linear triangles of 5 µm resolve the\n",
    "interfaces, which are about four widths $W$ thick."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "film = load(\"binary_alloy_phase_separation.step\")\n",
    "plane = film.section((0, 0, 1), origin=(0, 0, 1e-5))\n",
    "side = plane.size[0]\n",
    "mesh = TriangularMesher(target_size=5e-6).generate(plane)\n",
    "\n",
    "fig = plots.figure(1, 2, size=(13, 5.5))\n",
    "plots.geometry(\n",
    "    film,\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=35, azimuth=-60),\n",
    "    title=\"Film 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",
    "`CahnHilliard` solves composition and chemical potential together (mixed form). `ConvexSplitting`\n",
    "treats the convex part of the energy implicitly and the concave part explicitly, so the free\n",
    "energy decreases for every step size. 300 steps of 0.1 s follow the first 30 seconds."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "energy = DoubleWellFreeEnergy(surface_tension=0.05, interface_width=10e-6)\n",
    "mixture = CahnHilliard(domain=plane.domain(), free_energy=energy, mobility=3.75e-14)\n",
    "waves = 8\n",
    "rng = np.random.default_rng(2054)\n",
    "problem = Problem(\n",
    "    name=\"Phase separation\",\n",
    "    geometry=plane,\n",
    "    physics=(mixture,),\n",
    "    initial_conditions=(\n",
    "        InitialValue(\n",
    "            mixture.composition,\n",
    "            lambda x, y: 0.01\n",
    "            * np.cos(waves * np.pi * x / side)\n",
    "            * np.cos(waves * np.pi * y / side)\n",
    "            + 0.002 * rng.standard_normal(np.shape(x)),\n",
    "        ),\n",
    "    ),\n",
    "    boundary_conditions=(\n",
    "        PhaseFlux(physics=mixture, boundary=plane.boundaries.all),\n",
    "        CompositionGradient(physics=mixture, boundary=plane.boundaries.all),\n",
    "    ),\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=1), quadrature_order=3),\n",
    "    linear_solver=SparseDirect(),\n",
    "    nonlinear_solver=Newton(\n",
    "        linear_solver=SparseDirect(), relative_tolerance=1e-9, absolute_tolerance=1e-24\n",
    "    ),\n",
    "    time_integrator=ConvexSplitting(),\n",
    ")\n",
    "result = Simulation(problem=problem, mesh=mesh, numerics=numerics).run(\n",
    "    start_time=0.0, end_time=30.0, time_step=0.1\n",
    ")\n",
    "composition = result.field(mixture.composition)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The amplitude of the initial wave is its projection $\\int c\\,\\phi\\,\\mathrm dA/\\int\\phi^2\\,\\mathrm dA$\n",
    "on $\\phi=\\cos(8\\pi x/L)\\cos(8\\pi y/L)$; its growth rate in the linear stage is compared with\n",
    "Cahn's $\\omega(k)$. The amount of component B and the free energy are integrated over the film."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "k = np.sqrt(2) * waves * np.pi / side\n",
    "growth = (\n",
    "    mixture.mobility\n",
    "    * k**2\n",
    "    * (energy.bulk_coefficient - energy.gradient_coefficient * k**2)\n",
    ")\n",
    "mode = composition.derive(\n",
    "    lambda c, p: c\n",
    "    * np.cos(waves * np.pi * p[:, 0] / side)\n",
    "    * np.cos(waves * np.pi * p[:, 1] / side),\n",
    "    name=\"mode\",\n",
    "    unit=\"1\",\n",
    ").integrate()\n",
    "times, amplitude = np.asarray(mode.times), np.asarray(mode.values) / (side**2 / 4)\n",
    "early = (amplitude > 0.012) & (amplitude < 0.05)\n",
    "first, last = np.flatnonzero(early)[[0, -1]]\n",
    "measured = np.log(amplitude[last] / amplitude[first]) / (times[last] - times[first])\n",
    "amount = np.asarray(composition.integrate().values)\n",
    "free_energy = np.asarray(result.field(mixture.free_energy_density).integrate().values)\n",
    "step = times[1] - times[0]\n",
    "discrete = (\n",
    "    np.log(\n",
    "        (1 + step * mixture.mobility * energy.bulk_coefficient * k**2)\n",
    "        / (1 + step * mixture.mobility * energy.gradient_coefficient * k**4)\n",
    "    )\n",
    "    / step\n",
    ")\n",
    "print(\n",
    "    f\"growth rate of the 8 x 8 wave: simulation {measured:.4f} 1/s, Cahn's linear theory {growth:.4f} 1/s ({100 * (measured / growth - 1):+.2f} %), \"\n",
    "    f\"convex-splitting rate ln(g)/dt {discrete:.4f} 1/s ({100 * (measured / discrete - 1):+.2f} %)\"\n",
    ")\n",
    "print(\n",
    "    f\"amount of component B: largest change {np.max(np.abs(amount - amount[0])) / side**2:.1e} of the film average\"\n",
    ")\n",
    "print(\n",
    "    f\"free energy: {free_energy[0]:.3e} J/m -> {free_energy[-1]:.3e} J/m, steps with an increase: {int(np.sum(np.diff(free_energy) > 0))}\"\n",
    ")\n",
    "print(\n",
    "    f\"composition after {times[-1]:.0f} s: {composition.values.min():.4f} to {composition.values.max():.4f}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The composition at four times: the growing wave, the separated pattern and its coarsening; then\n",
    "the amplitude of the wave against the linear theory and the decreasing free energy."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "nearest = lambda t: float(times[np.argmin(np.abs(times - t))])\n",
    "fig = plots.figure(2, 3, size=(19, 11.5))\n",
    "for panel, t in zip((fig[0], fig[1], fig[2], fig[3]), (4.0, 8.0, 15.0, 30.0)):\n",
    "    plots.surface(\n",
    "        composition,\n",
    "        time=nearest(t),\n",
    "        limits=(-1.05, 1.05),\n",
    "        subdivisions=2,\n",
    "        xlabel=\"x [m]\",\n",
    "        ylabel=\"y [m]\",\n",
    "        label=\"c\",\n",
    "        title=f\"Composition after {nearest(t):.1f} s\",\n",
    "        ax=panel,\n",
    "    )\n",
    "plots.line(\n",
    "    points={\"simulation\": (times[amplitude < 0.5], amplitude[amplitude < 0.5])},\n",
    "    reference={\n",
    "        \"Cahn's linear theory\": (\n",
    "            times[times < 12],\n",
    "            0.01 * np.exp(growth * times[times < 12]),\n",
    "        ),\n",
    "        \"rate of the convex-splitting step\": (\n",
    "            times[times < 12],\n",
    "            0.01 * np.exp(discrete * times[times < 12]),\n",
    "        ),\n",
    "    },\n",
    "    scale=\"logy\",\n",
    "    xlabel=\"time [s]\",\n",
    "    ylabel=\"amplitude of the initial wave\",\n",
    "    title=\"Linear stage of the decomposition\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[4],\n",
    ")\n",
    "plots.line(\n",
    "    y={\"free energy\": (times[1:], free_energy[1:])},\n",
    "    scale=\"logx\",\n",
    "    xlabel=\"time [s]\",\n",
    "    ylabel=\"free energy per unit thickness [J/m]\",\n",
    "    title=\"The free energy decreases in every step\",\n",
    "    ax=fig[5],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Shift the mean composition away from zero, for example to $c=-0.4$, to see droplets nucleate\n",
    "instead of a connected pattern, or take a larger step limit: convex splitting stays stable, only\n",
    "the coarsening is followed less accurately."
   ]
  }
 ]
}
