{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "08e84a46f78c",
   "metadata": {},
   "source": [
    "# What a four-point probe measures\n",
    "Drive a current between two outer point contacts. Measure the open-circuit voltage between the equal-spaced inner contacts. Predict whether doubling all spacings changes the measured resistance before comparing the thin-film and bulk limits."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d1ac1a0da183",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "rho_ohm_m = 2.0e-5\n",
    "thickness_um = 20.\n",
    "spacing_um = 80.\n",
    "current_mA = 5.\n",
    "assert rho_ohm_m > 0 and thickness_um > 0 and current_mA>0\n",
    "s_over_h = spacing_um/thickness_um\n",
    "assert .04 <= s_over_h <= 15, \"Use spacing/thickness between 0.04 and 15\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c34fe253957b",
   "metadata": {},
   "source": [
    "## Sum the image sources before subtracting large potentials\n",
    "In units of the thickness, a pair of mirror distances is a and b. Compute 1/a − 1/b by rationalising it. The resulting terms decay as the inverse cube of image index."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b24e8cde0ec3",
   "metadata": {},
   "outputs": [],
   "source": [
    "def scaled_resistance(z, images=6000):\n",
    "    z=np.atleast_1d(np.asarray(z,dtype=float))\n",
    "    n=2*np.arange(1,images+1,dtype=float)\n",
    "    a=np.hypot(z[:,None],n); b=np.hypot(2*z[:,None],n)\n",
    "    diff=3*z[:,None]**2/(a*b*(a+b))\n",
    "    return (1/(2*z)+2*diff.sum(axis=1))/np.pi\n",
    "\n",
    "sheet=rho_ohm_m/(thickness_um*1e-6)\n",
    "ratio=scaled_resistance(s_over_h)[0]\n",
    "voltage_mV=current_mA*sheet*ratio\n",
    "print(f\"Sheet resistance {sheet:.6g} ohm per square, voltage {voltage_mV:.6g} mV.\")\n",
    "print(f\"Apparent sheet resistance from thin-film formula {np.pi*voltage_mV/(current_mA*np.log(2)):.6g} ohm per square.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2ef4dae2bcf1",
   "metadata": {},
   "source": [
    "## View the current geometry and the thickness crossover\n",
    "The left panel shows equipotentials of the ideal sheet geometry in the plane. The right panel solves the finite-thickness image problem and compares two asymptotes. The point contacts themselves lie outside the model's finite potential range."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cbc990eaa46b",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig,axes=plt.subplots(1,2,figsize=(9,3.9),layout=\"constrained\")\n",
    "x=np.linspace(-2.6,2.6,190); y=np.linspace(-1.55,1.55,130); X,Y=np.meshgrid(x,y)\n",
    "phi=np.log(np.hypot(X-1.5,Y)/np.hypot(X+1.5,Y))\n",
    "axes[0].contour(X,Y,phi,levels=[-2,-1.2,-.7,-.35,0,.35,.7,1.2,2],colors=\"#175868\",linewidths=1.1)\n",
    "for pos,label,colour in zip([-1.5,-.5,.5,1.5],[\"+I\",\"V₂\",\"V₃\",\"−I\"],[\"#a23d21\",\"#375b9a\",\"#375b9a\",\"#a23d21\"]):\n",
    "    axes[0].plot(pos,0,\"o\",color=colour);axes[0].text(pos,.17,label,ha=\"center\",bbox=dict(fc=\"white\",ec=\"none\",pad=1))\n",
    "axes[0].set(xlabel=\"Along probes  x/s\",ylabel=\"Across probes  y/s\",aspect=\"equal\",title=\"Infinite-sheet equipotentials\")\n",
    "z=np.geomspace(.08,15,180)\n",
    "axes[1].loglog(z,scaled_resistance(z),label=\"Finite thickness\",color=\"#175868\",lw=2.4)\n",
    "axes[1].loglog(z,1/(2*np.pi*z),\"--\",label=\"Bulk\",color=\"#375b9a\")\n",
    "axes[1].axhline(np.log(2)/np.pi,ls=\":\",label=\"Thin sheet\",color=\"#a23d21\")\n",
    "axes[1].plot(s_over_h,ratio,\"o\",color=\"#a23d21\");axes[1].legend(fontsize=9)\n",
    "axes[1].set(xlabel=\"Spacing / thickness  s/h\",ylabel=\"Scaled resistance  (V/I)h/ρ\",title=\"What the voltmeter measures\")\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9806f4b13bbc",
   "metadata": {},
   "source": [
    "## Challenge the approximations\n",
    "Increase the image cutoff and compare the numerical uncertainty with the thin-sheet bias. At small spacing the voltage drop decreases approximately as 1/s. Explain why this also changes how a fixed voltmeter uncertainty propagates into a resistivity estimate."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a9638bb389aa",
   "metadata": {},
   "outputs": [],
   "source": [
    "value2=scaled_resistance(s_over_h,12000)[0]\n",
    "assert abs(value2-ratio) < 5e-6\n",
    "assert np.isclose(scaled_resistance(.005)[0],1/(2*np.pi*.005),rtol=1e-5)\n",
    "assert abs(scaled_resistance(12)[0]-np.log(2)/np.pi) < 2e-6\n",
    "print(\"Fractional thin-sheet bias:\",np.pi*ratio/np.log(2)-1)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1e9b3cfd2ee5",
   "metadata": {},
   "source": [
    "## Optional OneSimulation fit with a thermoelectric offset\n",
    "A constant voltage offset should enter as a separate fit coefficient. The positive and negative current readings below share the same physical resistance and offset. The synthetic voltages have no random error, so an independent linear solve must recover the input parameters."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e51c3b09f573",
   "metadata": {},
   "outputs": [],
   "source": [
    "try:\n",
    "    from onesim.numerics.linear.matrices.dense_linear_algebra import least_squares_dense\n",
    "except ImportError:\n",
    "    print(\"The optional sensor fit runs in a local OneSimulation installation.\")\n",
    "else:\n",
    "    spacings=np.array([.2,.5,1.,2.])\n",
    "    k=np.repeat(scaled_resistance(spacings),2)*np.tile([current_mA,-current_mA],len(spacings))\n",
    "    design=np.column_stack([k,np.ones(len(k))])\n",
    "    readings=k*sheet+0.012\n",
    "    recovered=least_squares_dense(design,readings)\n",
    "    print(\"Estimated sheet resistance in ohms and offset in mV:\",recovered)\n",
    "    assert np.allclose(recovered,[sheet,.012])"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
