{
 "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": [
    "# Current through a thin resistive film in a layered device\n",
    "\n",
    "Layered devices — sensors, resistive heaters, electrodes with an oxide skin — often contain one\n",
    "layer that is much thinner than the others but holds most of the resistance. Meshing it in 3D\n",
    "multiplies the number of elements. A **contact impedance** replaces the film by the face between\n",
    "its neighbours: the potential jumps across it and the normal current density follows the jump,\n",
    "\n",
    "$$J_n=\\frac{\\sigma_f}{d}\\,\\big(V_\\text{base}-V_\\text{cover}\\big),$$\n",
    "\n",
    "with no current along the face. This holds when the film is thin and conducts much less than the\n",
    "plates, so that the current crosses it almost perpendicularly.\n",
    "\n",
    "The device is 1 m × 1 m. A base plate of 0.1 m and conductivity $\\sigma=1$ S/m, a film of\n",
    "$d=20$ mm and $\\sigma_f=0.01$ S/m and a cover plate of 0.1 m and 1 S/m are stacked; a round pad of\n",
    "0.3 m radius and 0.1 m height sits on the cover off the centre. The steady current solves\n",
    "\n",
    "$$\\nabla\\cdot(\\sigma\\,\\nabla V)=0 .$$\n",
    "\n",
    "| face | condition |\n",
    "|---|---|\n",
    "| `inlet`, bottom of the base | inflowing current density $J_n=0.3$ A/m² |\n",
    "| `contact`, top of the pad | $V=0$ |\n",
    "| all other faces | $J_n=0$ |\n",
    "\n",
    "The **resolved model** meshes the film as its own body. The **thin model** lets base and cover\n",
    "meet in the middle plane of the film and puts the contact impedance there.\n",
    "\n",
    "The two stacks come from the CAD files `thin_resistive_film_stack_resolved.step` and\n",
    "`thin_resistive_film_stack_thin.step`; the script `thin_resistive_film_stack_geometry.py` builds\n",
    "them with the CAD objects of OneSimulation. Both are three-dimensional models.\n",
    "\n",
    "**Reference.** If the current crossed the film uniformly, the film alone would drop\n",
    "$V_f=J\\,d/\\sigma_f=0.6$ V and the base $J\\,t/\\sigma=0.03$ V (Ohm's law of the layers in series).\n",
    "The current gathers towards the pad, so more of it crosses the film there and the cover adds a\n",
    "spreading resistance; the resolved 3D model gives all of this and is the reference of the thin\n",
    "model, the series value a lower bound."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.d2 import Plane\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import regionwise\n",
    "from onesim.meshing import TetrahedralMesher, interface\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.physics.electrostatics import (\n",
    "    ContactImpedance,\n",
    "    FixedPotential,\n",
    "    NormalElectricDisplacement,\n",
    "    PoissonEquation,\n",
    "    ZeroNormalElectricDisplacement,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation\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",
    "`load` returns each stack with its parts as material regions and with the named faces\n",
    "`base.inlet` and `cover.contact`. Tetrahedra of 30 mm fill the film and its surroundings, 0.1 m\n",
    "elsewhere; the thin model needs the same size only to resolve the current entering the cover."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "stacks = {\n",
    "    kind: load(f\"thin_resistive_film_stack_{kind}.step\")\n",
    "    for kind in (\"resolved\", \"thin\")\n",
    "}\n",
    "fine = lambda points: np.where(np.abs(points[:, 2] + 0.01) < 0.03, 0.03, 0.1)\n",
    "meshes = {\n",
    "    kind: TetrahedralMesher(target_size=0.1, size_field=fine).generate(stack)\n",
    "    for kind, stack in stacks.items()\n",
    "}\n",
    "\n",
    "fig = plots.figure(1, 2, size=(14, 6))\n",
    "plots.geometry(\n",
    "    stacks[\"resolved\"],\n",
    "    selection={\n",
    "        \"inlet, 0.3 A/m²\": stacks[\"resolved\"].boundaries[\"base.inlet\"],\n",
    "        \"contact, 0 V\": stacks[\"resolved\"].boundaries[\"cover.contact\"],\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=25, azimuth=-60),\n",
    "    title=\"Base, film and cover with the pad\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[\"resolved\"],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Resolved film: {meshes['resolved'].cell_count} tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Models\n",
    "\n",
    "`PoissonEquation` with the conductivity in place of the permittivity is the steady current\n",
    "equation; `regionwise` gives the film of the resolved model its conductivity. `ContactImpedance` acts on the faces\n",
    "between base and cover of the thin model, which `interface` returns."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "sigma, film, thickness, inflow = 1.0, 0.01, 0.02, 0.3\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)), linear_solver=SparseDirect()\n",
    ")\n",
    "models, results = {}, {}\n",
    "for kind, stack in stacks.items():\n",
    "    faces = stack.boundaries\n",
    "    model = PoissonEquation(\n",
    "        domain=stack.domain(),\n",
    "        permittivity=regionwise(\n",
    "            {\"film\": film} if kind == \"resolved\" else (), default=sigma, unit=\"S/m\"\n",
    "        ),\n",
    "        charge_density=0.0,\n",
    "    )\n",
    "    layer = (\n",
    "        (\n",
    "            ContactImpedance(\n",
    "                physics=model,\n",
    "                boundary=interface(meshes[kind], \"base_cover\"),\n",
    "                thickness=thickness,\n",
    "                conductivity=film,\n",
    "            ),\n",
    "        )\n",
    "        if kind == \"thin\"\n",
    "        else ()\n",
    "    )\n",
    "    problem = Problem(\n",
    "        name=f\"Layered device, {kind}\",\n",
    "        geometry=stack,\n",
    "        physics=(model,),\n",
    "        boundary_conditions=(\n",
    "            NormalElectricDisplacement(\n",
    "                boundary=faces[\"base.inlet\"], physics=model, value=-inflow\n",
    "            ),\n",
    "            FixedPotential(boundary=faces[\"cover.contact\"], physics=model, value=0.0),\n",
    "            ZeroNormalElectricDisplacement(\n",
    "                boundary=faces.all - faces[\"base.inlet\"] - faces[\"cover.contact\"],\n",
    "                physics=model,\n",
    "            ),\n",
    "        )\n",
    "        + layer,\n",
    "    )\n",
    "    models[kind] = model\n",
    "    results[kind] = Simulation(\n",
    "        problem=problem, mesh=meshes[kind], numerics=numerics\n",
    "    ).solve_stationary()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The current through the contact, the voltage of the inlet face (its mean potential) and the jump\n",
    "across the film below the pad and at the far corner."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "grid = np.linspace(0.02, 0.98, 25)\n",
    "inlet = np.array([(x, y, -0.12) for x in grid for y in grid])\n",
    "potential = {\n",
    "    kind: result.field(models[kind].potential) for kind, result in results.items()\n",
    "}\n",
    "voltage = {kind: field.evaluate(inlet).mean() for kind, field in potential.items()}\n",
    "current = {\n",
    "    kind: -field.reaction(stacks[kind].boundaries[\"cover.contact\"])\n",
    "    for kind, field in potential.items()\n",
    "}\n",
    "jump = {\n",
    "    kind: [\n",
    "        field.evaluate(np.array([[x, y, -0.02 + 1e-6]]))[0]\n",
    "        - field.evaluate(np.array([[x, y, -1e-6]]))[0]\n",
    "        for x, y in ((0.4, 0.6), (0.95, 0.05))\n",
    "    ]\n",
    "    for kind, field in potential.items()\n",
    "}\n",
    "print(\n",
    "    f\"series layers (film and base): {inflow * (thickness / film + 0.1 / sigma):.4f} V\"\n",
    ")\n",
    "print(\n",
    "    \"model        current [A]   inlet voltage [V]   jump across the film below the pad [V]   at the far corner [V]   tetrahedra\"\n",
    ")\n",
    "for kind in (\"resolved\", \"thin\"):\n",
    "    print(\n",
    "        f\"{kind:10s} {current[kind]:12.5f} {voltage[kind]:19.5f} {jump[kind][0]:40.5f} {jump[kind][1]:23.5f} {meshes[kind].cell_count:12d}\"\n",
    "    )\n",
    "print(\n",
    "    f\"thin model against the resolved film: inlet voltage {100 * (voltage['thin'] / voltage['resolved'] - 1):+.2f} %\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The contact impedance gives the voltage of the resolved film within a fraction of a percent on\n",
    "fewer elements. The jump across the film is not uniform — below the pad it is half as large again\n",
    "as at the far corner, because the thin cover plate does not spread the current fully — and the\n",
    "whole device needs about 50 % more than the series layers. Yet the current crosses the film\n",
    "perpendicularly everywhere, which is all the contact impedance assumes.\n",
    "\n",
    "## Figure\n",
    "\n",
    "The potential of the resolved model on the plane $y=0.6$ m through the pad, the voltage across the\n",
    "film along that plane in both models (the pad spans $x=0.1$ to $0.7$ m), and the potential along\n",
    "the vertical line through the centre of the pad."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 3, size=(21, 6))\n",
    "plots.section(\n",
    "    potential[\"resolved\"],\n",
    "    plane=Plane(origin=(0, 0.6, 0), normal=(0, 1, 0)),\n",
    "    limits=(0, 1.0),\n",
    "    contours=21,\n",
    "    subdivisions=2,\n",
    "    aspect=2.0,\n",
    "    label=\"V [V]\",\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"z [m]\",\n",
    "    title=\"Potential at y = 0.6 m, resolved film\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "x = np.linspace(0.005, 0.995, 199)\n",
    "across = {\n",
    "    kind: field.evaluate(\n",
    "        np.column_stack((x, np.full_like(x, 0.6), np.full_like(x, -0.02 + 1e-6)))\n",
    "    )\n",
    "    - field.evaluate(np.column_stack((x, np.full_like(x, 0.6), np.full_like(x, -1e-6))))\n",
    "    for kind, field in potential.items()\n",
    "}\n",
    "plots.line(\n",
    "    points={\"contact impedance\": (x[::6], across[\"thin\"][::6])},\n",
    "    reference={\"resolved film\": (x, across[\"resolved\"])},\n",
    "    vlines=[0.1, 0.7],\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"voltage across the film [V]\",\n",
    "    title=\"Jump across the film at y = 0.6 m\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "z = np.linspace(-0.12, 0.2, 641)\n",
    "axis = np.column_stack((np.full_like(z, 0.4), np.full_like(z, 0.6), z))\n",
    "plots.line(\n",
    "    points={\"contact impedance\": (z[::16], potential[\"thin\"].evaluate(axis[::16]))},\n",
    "    reference={\"resolved film\": (z, potential[\"resolved\"].evaluate(axis))},\n",
    "    vlines=[-0.02, 0.0],\n",
    "    xlabel=\"z [m]\",\n",
    "    ylabel=\"V [V]\",\n",
    "    title=\"Potential through the pad centre\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Raise the film conductivity towards that of the plates to see where the current starts to flow\n",
    "along the film and the contact impedance no longer holds, or move the pad in\n",
    "`thin_resistive_film_stack_geometry.py` to the corner."
   ]
  }
 ]
}
