{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "307363be",
   "metadata": {},
   "source": [
    "# Watch a wetting front approach the capillary height\n",
    "\n",
    "Guess whether a wider vertical tube fills faster during the first few millimetres and whether it eventually rises higher. Edit the first cell, then compare the exact viscous trajectory against the early-time square-root law. The assumed tube is slender, the contact angle constant and the reservoir large."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3c2d1f34",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "radius = 100e-6       # inner radius, m\n",
    "mu, rho = .012, 1000. # viscosity, Pa s; density, kg/m³\n",
    "sigma = .060          # surface tension, N/m\n",
    "angle = 30.           # static advancing angle, degrees\n",
    "g = 9.81              # m/s²\n",
    "assert min(radius,mu,rho,sigma,g)>0 and 0 <= angle < 90"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "056df568",
   "metadata": {},
   "source": [
    "## Recover time from the meniscus-force balance\n",
    "Use the fraction of equilibrium height as the independent coordinate. The formula for time is monotone and avoids starting an ODE solver at the formal infinite initial speed of this viscous approximation. The series at very small fractions avoids subtracting nearly equal numbers."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8c64e402",
   "metadata": {},
   "outputs": [],
   "source": [
    "def scales(a):\n",
    "    head = 2*sigma*np.cos(np.deg2rad(angle))/(rho*g*a)\n",
    "    mobility = rho*g*a*a/(8*mu)\n",
    "    return head, head/mobility\n",
    "\n",
    "def scaled_time(s):\n",
    "    s = np.asarray(s,dtype=float)\n",
    "    if np.any((s<0)|(s>=1)): raise ValueError(\"Require 0 ≤ height fraction < 1.\")\n",
    "    return np.where(s<1e-4,s*s*(.5+s/3+s*s/4),-s-np.log1p(-s))\n",
    "\n",
    "H,tau = scales(radius)\n",
    "for frac in (.25,.5,.9):\n",
    "    print(f\"{100*frac:.0f}% of {1000*H:.2f} mm at {tau*scaled_time(frac):.2f} s\")\n",
    "assert np.isclose(scaled_time(.5), np.log(2)-.5)\n",
    "assert np.isclose(scaled_time(.00001)/(.00001**2/2),1.,rtol=1e-5)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ae23268c",
   "metadata": {},
   "source": [
    "## Reconstruct height as a function of laboratory time\n",
    "When time is given, monotone bisection finds the height fraction. Each iteration halves the remaining interval independently for every entry in the requested time vector."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "66b88f53",
   "metadata": {},
   "outputs": [],
   "source": [
    "def height_at(times, a):\n",
    "    h, t = scales(a)\n",
    "    times = np.asarray(times)\n",
    "    lo, hi = np.zeros_like(times,dtype=float), np.ones_like(times,dtype=float)\n",
    "    for _ in range(50):\n",
    "        mid = (lo+hi)/2\n",
    "        smaller = scaled_time(mid) < times/t\n",
    "        lo,hi = np.where(smaller,mid,lo), np.where(smaller,hi,mid)\n",
    "    return h*(lo+hi)/2\n",
    "\n",
    "assert np.isclose(height_at(np.array([tau*scaled_time(.5)]),radius)[0], H/2)\n",
    "sec = np.linspace(0,tau*2.5,400)\n",
    "fig, ax = plt.subplots(1,2,figsize=(9,3.5),layout=\"constrained\")\n",
    "for a,style in [(radius,\"-\"),(1.5*radius,\"--\")]:\n",
    "    h,t = scales(a)\n",
    "    ax[0].plot(sec,1000*height_at(sec,a),style,label=f\"Radius {a*1e6:.0f} µm\")\n",
    "    ax[0].axhline(h*1000,ls=\":\",lw=.8,color=\"0.6\")\n",
    "f = np.linspace(.002,.93,240)\n",
    "ax[1].plot(f,scaled_time(f)/(f*f/2),label=\"Gravity / early-law time\")\n",
    "ax[1].axhline(1,ls=\":\",color=\"0.5\")\n",
    "ax[0].set(xlabel=\"Elapsed time (s)\",ylabel=\"Meniscus height (mm)\",title=\"Two wetting tubes\")\n",
    "ax[1].set(xlabel=\"Fraction of static rise\",ylabel=\"Time ratio\",title=\"When the early approximation fails\")\n",
    "for p in ax:\n",
    "    p.grid(alpha=.22); p.legend(fontsize=8)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d330af58",
   "metadata": {},
   "source": [
    "## Infer an unknown and challenge the model\n",
    "Choose a radius, record the time to 50% height, and hide the viscosity. Recover it from that single time using the known static head. A contaminated surface may change the contact angle. Decide which second observation would let you separate a change of viscosity from a change of capillary pressure."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fb2cdc68",
   "metadata": {},
   "source": [
    "## Set the camera clock and invert the time law\n",
    "The film gives elapsed time and the theory gives time as a function of height. Invert that map for an entire list of frames using OneSimulation's vectorised bracketed inverse when it is installed. The browser uses the previously derived bisection. Compare the recovered heights to the dimensional marks."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a40661e2",
   "metadata": {},
   "outputs": [],
   "source": [
    "camera_times = tau * np.array([0.1, 0.5, 1.0])\n",
    "try:\n",
    "    from onesim.numerics.nonlinear.kernels.local_solvers.inversion.bracketed_inverse import bisect_increasing\n",
    "except ImportError:\n",
    "    checked_heights = height_at(camera_times, radius)\n",
    "    method = \"Notebook bisection\"\n",
    "else:\n",
    "    target_times = camera_times / tau\n",
    "    fractions = bisect_increasing(scaled_time, target_times, 0.0, 0.999)\n",
    "    checked_heights = H * fractions\n",
    "    method = \"OneSimulation bracketed inverse\"\n",
    "\n",
    "assert np.allclose(tau * scaled_time(checked_heights/H), camera_times)\n",
    "print(f\"{method}: camera heights (mm)\", np.round(1000 * checked_heights, 3))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
