{
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "name": "python3",
   "language": "python",
   "display_name": "Python 3"
  },
  "language_info": {
   "name": "python"
  },
  "fundamentals": {
   "title": "Weigh a colloid by counting where it spends its time",
   "lead": "Brownian motion spreads a dilute suspension through a cell whilst buoyancy biases its vertical position. Derive the equilibrium concentration, predict counts in finite camera bins and estimate a buoyant mass without measuring how quickly any individual sphere falls.",
   "unit_slug": "sedimentation-profile-and-buoyant-mass"
  }
 },
 "cells": [
  {
   "cell_type": "markdown",
   "id": "ccf907714527",
   "metadata": {},
   "source": [
    "# Weigh a colloid by counting where it spends its time\n",
    "\n",
    "Brownian motion spreads a dilute suspension through a cell whilst buoyancy biases its vertical position. Derive the equilibrium concentration, predict counts in finite camera bins and estimate a buoyant mass without measuring how quickly any individual sphere falls."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3e4fca2c5586",
   "metadata": {
    "fundamentals": {
     "section": "derive-the-model"
    }
   },
   "source": [
    "## Balance drift against diffusion\n",
    "\n",
    "Measure $z$ upwards from the bottom of a closed cell. A sphere of volume $V$ displaces fluid of density $\\rho_f$. The downward gravitational force on the particle exceeds the upward buoyancy force by $m_bg$, where $m_b=V(\\rho_p-\\rho_f)$. Signed buoyant mass is what a concentration profile can reveal. Let $\\mu$ denote mobility, the ratio of speed to applied force. For dilute, independently moving particles at uniform temperature, the total vertical number flux is\n",
    "\n",
    "$$J=-D\\frac{dn}{dz}-\\mu m_b g n. $$\n",
    "\n",
    "At steady state the flux is constant, and impermeable cell ends set that constant to zero. The Einstein relation $D=\\mu k_BT$ eliminates the mobility. Integrating $d\\ln n/dz=-a$ with $a=m_bg/(k_BT)$ gives\n",
    "\n",
    "$$\n",
    "n(z)=n(0)e^{-az}.\n",
    "$$\n",
    "\n",
    "The signed slope changes sign for buoyant particles and vanishes at exact density matching. Viscosity affects the time to reach equilibrium.\n",
    "\n",
    "Suppose the camera counts centres in equal-width horizontal slices of a column with uniform cross-section. A bin centred at $z_i$ has expected count proportional to $e^{-az_i} \\int_{-h/2}^{h/2}e^{-au}du$. The integral is common to all bins, hence normalising the exponential values at their centres yields the exact bin probabilities for this model. Wall exclusion sets the interval accessible to centres. Define the specified cell height as that accessible interval."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c4c1eb75a4ad",
   "metadata": {
    "fundamentals": {
     "section": "worked-prediction"
    }
   },
   "source": [
    "## Infer a mass with its sign\n",
    "\n",
    "Use a radius of 0.50 µm, particle excess density 50 kg/m³ and temperature 293 K. The volume is $5.236\\times10^{-19}$ m³, the buoyant mass is $2.618\\times10^{-17}$ kg and $k_BT/(m_bg)=15.75$ µm. Counts in two equal slices separated by 10 µm should have lower-to-upper ratio $e^{10/15.75}\\simeq1.89$. Doubling the radius at fixed density ratio multiplies the mass by eight and divides the gravitational length by eight.\n",
    "\n",
    "Sampling is important when using the upper part of a steep profile. Suppose bins separated by 10 µm contain 120 and 60 approximately independent particle observations. The estimated slope is $\\ln(2)/10=0.0693$ µm⁻¹. For independent Poisson counts the standard error from propagating the two count variances is $\\sqrt{1/120+1/60}/10=0.0158$ µm⁻¹. Repeatedly imaging the same particle at closely spaced times introduces correlations. Counting all those frames as independent would make the quoted sampling precision too optimistic."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5612e984add2",
   "metadata": {
    "fundamentals": {
     "section": "choose-inputs",
     "notebook_only": true
    }
   },
   "source": [
    "## Set the experimental inputs\n",
    "\n",
    "Edit these values, then run the calculation and both figures again."
   ]
  },
  {
   "cell_type": "code",
   "id": "2eb88f5b2254",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "teal, orange, blue = \"#19596a\", \"#aa462a\", \"#3868a0\"\n",
    "def axes(xlabel, ylabel):\n",
    "    fig, ax = plt.subplots(figsize=(7, 4), constrained_layout=True)\n",
    "    ax.set(xlabel=xlabel, ylabel=ylabel)\n",
    "    ax.grid(alpha=0.2)\n",
    "    return fig, ax"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "97b9bcb93c62",
   "metadata": {},
   "source": [
    "radius_um = .50\n",
    "excess_density_kg_m3 = 50.\n",
    "temperature_K = 293.\n",
    "accessible_height_um = 60.\n",
    "bins = 12\n",
    "observations = 1200\n",
    "seed = 22"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "85de0db6290b",
   "metadata": {},
   "source": [
    "assert radius_um>0 and temperature_K>0 and accessible_height_um>0\n",
    "assert isinstance(bins,int) and bins>=2 and isinstance(observations,int) and observations>0\n",
    "boltzmann = 1.380649e-23\n",
    "volume = 4*np.pi*(radius_um*1e-6)**3/3\n",
    "a = volume*excess_density_kg_m3*9.80665/(boltzmann*temperature_K)*1e-6\n",
    "width = accessible_height_um/bins\n",
    "centres = (np.arange(bins)+.5)*width\n",
    "def bin_probability(slope):\n",
    "    log_weights = -slope*centres\n",
    "    weights = np.exp(log_weights-log_weights.max())\n",
    "    return weights / weights.sum()\n",
    "\n",
    "probability = bin_probability(a)\n",
    "counts = np.random.default_rng(seed).multinomial(observations,probability)\n",
    "assert np.allclose(bin_probability(-a),probability[::-1])\n",
    "assert counts.sum()==observations\n",
    "print(f\"Buoyant mass {volume*excess_density_kg_m3:.4e} kg; signed slope {a:.5f} per µm\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "762f0d5c84ff",
   "metadata": {
    "fundamentals": {
     "figure": {
      "file": "thermodynamics-statistical-physics-statistical-laboratory-1.png",
      "alt": "The equilibrium count distributions for positive, zero and negative buoyant mass slope in opposite directions about a uniform profile.",
      "caption": "The total probability in the cell is one for each curve. Matching the fluid density removes the gravity-induced concentration gradient."
     }
    }
   },
   "source": [
    "fig,ax = axes(\"Height of slice centre (µm)\", \"Probability in a slice\")\n",
    "for slope, label, color in [(abs(a),\"Denser spheres\",teal),(0,\"Density matched\",\"grey\"),(-abs(a),\"Lighter spheres\",orange)]:\n",
    "    ax.plot(centres,bin_probability(slope),\".-\",color=color,label=label)\n",
    "ax.legend()\n",
    "plt.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "29e3af94c61a",
   "metadata": {
    "fundamentals": {
     "notebook_only": true
    }
   },
   "source": [
    "The total probability in the cell is one for each curve. Matching the fluid density removes the gravity-induced concentration gradient."
   ]
  },
  {
   "cell_type": "code",
   "id": "9a56422a5a7f",
   "metadata": {
    "fundamentals": {
     "figure": {
      "file": "thermodynamics-statistical-physics-statistical-laboratory-2.png",
      "alt": "Sampled counts vary around the expected exponential count profile for a finite cell.",
      "caption": "Reduce the number of independent particle observations and change the random seed. Noise is particularly large relative to the expected number in sparsely occupied slices."
     }
    }
   },
   "source": [
    "fig,ax = axes(\"Height of slice centre (µm)\", \"Number of independent observations\")\n",
    "ax.bar(centres,counts,width=.8*width,alpha=.6,color=teal,label=\"Sample counts\")\n",
    "ax.plot(centres,observations*probability,\"o-\",color=orange,label=\"Exact expectation\")\n",
    "ax.legend()\n",
    "plt.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "0c1ec4e63f09",
   "metadata": {
    "fundamentals": {
     "notebook_only": true
    }
   },
   "source": [
    "Reduce the number of independent particle observations and change the random seed. Noise is particularly large relative to the expected number in sparsely occupied slices."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "24c3074d457e",
   "metadata": {
    "fundamentals": {
     "section": "problem-1"
    }
   },
   "source": [
    "## Exercise · determine the size of a density-matched particle\n",
    "\n",
    "A uniform profile persists in a well-equilibrated, isothermal cell. Can gravity alone distinguish two different radii if the particles have the same density as the fluid?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c068443056f5",
   "metadata": {
    "fundamentals": {
     "solution": true
    }
   },
   "source": [
    "At exact density matching, $m_b=V(\\rho_p-\\rho_f)=0$ for either radius, so both profiles are uniform. Their diffusion times can still differ because hydrodynamic mobility depends on size. A time-resolved measurement carries information absent from the equilibrium profile."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d59e03310d4e",
   "metadata": {
    "fundamentals": {
     "section": "problem-2"
    }
   },
   "source": [
    "## Exercise · reverse the measured gradient\n",
    "\n",
    "Two equally wide slices separated vertically by 12 µm contain 80 and 160 observations, in order of increasing height. Estimate $m_b$ at 293 K."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "74b28294e23d",
   "metadata": {
    "fundamentals": {
     "solution": true
    }
   },
   "source": [
    "The signed slope is $\\ln(80/160)/(12\\ \\mathrm{µm})=-0.05776$ µm⁻¹. Converting to metres and multiplying by $k_BT/g$ gives $m_b\\simeq-2.38\\times10^{-17}$ kg. The sign indicates that the displaced fluid is heavier than the particle."
   ]
  }
 ]
}
