{
 "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": [
    "# Contact impedance of a thin resistive shell\n",
    "\n",
    "Thin layers of poorly conducting material — oxide films, paint, a resistive coating — are much\n",
    "thinner than the parts around them. Resolving them needs many small elements. A **contact\n",
    "impedance** replaces the layer by a face: the potential may jump across it, and the current\n",
    "density through it is proportional to the jump,\n",
    "\n",
    "$$J_n=\\frac{\\sigma_2}{d}\\,\\big(V_1-V_2\\big),$$\n",
    "\n",
    "while no current flows along the face. This is exact when the layer is thin and much less\n",
    "conducting than its surroundings; when the layer conducts as well as the bulk, the condition\n",
    "wrongly blocks the current that would flow along the layer.\n",
    "\n",
    "A plate of conductivity $\\sigma_1=1$ S/m, 4 m × 4 m, carries a current from its top edge to its\n",
    "bottom edge. In its centre sits a tube of outer radius $b=0.25$ m with a wall of $d=1$ cm and\n",
    "conductivity $\\sigma_2$; inside the tube the material is the same as the plate. The steady current\n",
    "solves\n",
    "\n",
    "$$\\nabla\\cdot(\\sigma\\,\\nabla V)=0 .$$\n",
    "\n",
    "| edge | condition |\n",
    "|---|---|\n",
    "| `terminal`, top | $V=4$ V |\n",
    "| `ground`, bottom | $V=0$ |\n",
    "| `insulated`, left and right | $J_n=0$ |\n",
    "\n",
    "Far from the tube the field is $E_0=1$ V/m. Two models are solved for\n",
    "$\\sigma_2=1,\\;10^{-2},\\;10^{-4}$ S/m: the **resolved model** meshes the wall as its own region,\n",
    "the **thin model** puts the contact impedance on the circle $r=b-d/2$ in the middle of the wall.\n",
    "\n",
    "The plate and the tube come from the CAD files `contact_impedance_resistive_shell*.step`; the\n",
    "script `contact_impedance_resistive_shell_geometry.py` builds them with the CAD objects of\n",
    "OneSimulation. The two-dimensional model is their mid-plane section.\n",
    "\n",
    "**Reference.** A coated cylinder in a uniform field of an unbounded medium has a uniform field\n",
    "inside (Jackson, *Classical Electrodynamics*, 3rd ed., problem 4.10, with conductivities in place of\n",
    "permittivities). With core and surroundings of $\\sigma_1$ and a shell of $\\sigma_2$ between\n",
    "$a=b-d$ and $b$,\n",
    "\n",
    "$$\\frac{E_\\text{in}}{E_0}=\\frac{4\\,\\sigma_1\\sigma_2}{(\\sigma_1+\\sigma_2)^2-(\\sigma_2-\\sigma_1)^2\\,a^2/b^2}.$$\n",
    "\n",
    "The plate is 16 tube radii wide, so its edges change the field inside the tube by less than a\n",
    "percent."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import regionwise\n",
    "from onesim.meshing import TriangularMesher, 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",
    "    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 part, `section` its mid-plane cross-section. The resolved mesh follows the\n",
    "wall with elements of half its thickness; the thin model needs only the circle of the mid-line,\n",
    "with elements of 2 cm around the tube."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "name = \"contact_impedance_resistive_shell\"\n",
    "mid = lambda part: load(f\"{name}{part}.step\").section((0, 0, 1), origin=(0, 0, 0.05))\n",
    "plate, wall, core, midline = (\n",
    "    mid(\"\"),\n",
    "    mid(\"_wall\").named(\"wall\"),\n",
    "    mid(\"_core\").named(\"core\"),\n",
    "    mid(\"_midline\").named(\"core\"),\n",
    ")\n",
    "edges = plate.boundaries\n",
    "radius, thickness = wall.size[0] / 2, wall.size[0] / 2 - core.size[0] / 2\n",
    "resolved_mesh = TriangularMesher(\n",
    "    target_size=0.2,\n",
    "    embedded_regions=(core, wall),\n",
    "    region_sizes={\"wall\": thickness / 2, \"core\": 0.04},\n",
    ").generate(plate)\n",
    "thin_mesh = TriangularMesher(\n",
    "    target_size=0.2, embedded_regions=(midline,), region_sizes={\"core\": 0.02}\n",
    ").generate(plate)\n",
    "contact = interface(thin_mesh, \"background_core\")\n",
    "\n",
    "fig = plots.figure(1, 3, size=(18, 6))\n",
    "plots.geometry(\n",
    "    [load(f\"{name}.step\").named(\"plate\"), load(f\"{name}_wall.step\").named(\"tube wall\")],\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=55, azimuth=-70),\n",
    "    title=\"Plate with the resistive tube\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    resolved_mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Resolved wall: {resolved_mesh.cell_count} triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.mesh(\n",
    "    thin_mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Contact impedance: {thin_mesh.cell_count} triangles\",\n",
    "    ax=fig[2],\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 wall of the resolved model its conductivity; `ContactImpedance`\n",
    "acts on the faces between the two regions of the thin mesh, which `interface` returns."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "bulk, conductivities = 1.0, (1.0, 1e-2, 1e-4)\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)), linear_solver=SparseDirect()\n",
    ")\n",
    "models, results = {}, {}\n",
    "for sigma in conductivities:\n",
    "    for kind, mesh in ((\"resolved\", resolved_mesh), (\"contact impedance\", thin_mesh)):\n",
    "        law = (\n",
    "            regionwise({\"wall\": sigma}, default=bulk, unit=\"S/m\")\n",
    "            if kind == \"resolved\"\n",
    "            else regionwise((), default=bulk, unit=\"S/m\")\n",
    "        )\n",
    "        model = PoissonEquation(domain=plate.domain(), permittivity=law)\n",
    "        layer = (\n",
    "            (\n",
    "                ContactImpedance(\n",
    "                    physics=model,\n",
    "                    boundary=contact,\n",
    "                    thickness=thickness,\n",
    "                    conductivity=sigma,\n",
    "                ),\n",
    "            )\n",
    "            if kind != \"resolved\"\n",
    "            else ()\n",
    "        )\n",
    "        problem = Problem(\n",
    "            name=f\"Plate with a tube, {kind}\",\n",
    "            geometry=plate,\n",
    "            physics=(model,),\n",
    "            boundary_conditions=(\n",
    "                FixedPotential(boundary=edges.terminal, physics=model, value=4.0),\n",
    "                FixedPotential(boundary=edges.ground, physics=model, value=0.0),\n",
    "                ZeroNormalElectricDisplacement(boundary=edges.insulated, physics=model),\n",
    "            )\n",
    "            + layer,\n",
    "        )\n",
    "        models[sigma, kind] = model\n",
    "        results[sigma, kind] = Simulation(\n",
    "            problem=problem, mesh=mesh, numerics=numerics\n",
    "        ).solve_stationary()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The field in the centre of the tube against the coated-cylinder formula, and the current per metre\n",
    "of depth through the terminal edge."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "inner = radius - thickness\n",
    "exact = (\n",
    "    lambda sigma: 4\n",
    "    * bulk\n",
    "    * sigma\n",
    "    / ((bulk + sigma) ** 2 - (sigma - bulk) ** 2 * inner**2 / radius**2)\n",
    ")\n",
    "centre = np.array([[0.0, 0.0]])\n",
    "field = {\n",
    "    key: -result.field(models[key].electric_field).evaluate(centre)[0, 1]\n",
    "    for key, result in results.items()\n",
    "}\n",
    "current = {\n",
    "    key: result.field(models[key].potential).reaction(edges.terminal)\n",
    "    for key, result in results.items()\n",
    "}\n",
    "print(\n",
    "    \"sigma_2 [S/m]   E_in/E_0 exact   resolved   contact impedance   current resolved [A/m]   contact impedance [A/m]   difference\"\n",
    ")\n",
    "for sigma in conductivities:\n",
    "    a, b = current[sigma, \"resolved\"], current[sigma, \"contact impedance\"]\n",
    "    print(\n",
    "        f\"{sigma:12.0e} {exact(sigma):16.4f} {field[sigma, 'resolved']:10.4f} {field[sigma, 'contact impedance']:19.4f} \"\n",
    "        f\"{a:24.5f} {b:25.5f} {100 * (b / a - 1):+10.3f} %\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For the poorly conducting walls the contact impedance reproduces the resolved wall: the current\n",
    "goes around the tube, and inside it only a small field is left. With $\\sigma_2=\\sigma_1$ the\n",
    "resolved wall is invisible ($E_\\text{in}=E_0$), but the contact impedance still blocks the current\n",
    "along the circle, which marks the limit of the condition.\n",
    "\n",
    "## Figure\n",
    "\n",
    "The potential with the wall of $10^{-4}$ S/m in both models, and the potential along the vertical\n",
    "line through the tube for all three conductivities."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 3, size=(20, 6))\n",
    "for panel, kind in enumerate((\"resolved\", \"contact impedance\")):\n",
    "    plots.surface(\n",
    "        results[1e-4, kind].field(models[1e-4, kind].potential),\n",
    "        limits=(1.4, 2.6),\n",
    "        contours=13,\n",
    "        subdivisions=2,\n",
    "        xlimits=(-0.6, 0.6),\n",
    "        ylimits=(-0.6, 0.6),\n",
    "        xlabel=\"x [m]\",\n",
    "        ylabel=\"y [m]\",\n",
    "        label=\"V [V]\",\n",
    "        title=f\"Potential, {kind}, σ₂ = 1e-4 S/m\",\n",
    "        ax=fig[panel],\n",
    "    )\n",
    "y = np.linspace(-0.6, 0.6, 481)\n",
    "line = np.column_stack((np.zeros_like(y), y))\n",
    "plots.line(\n",
    "    points={\n",
    "        f\"contact impedance, σ₂ = {sigma:g} S/m\": (\n",
    "            y[::12],\n",
    "            results[sigma, \"contact impedance\"]\n",
    "            .field(models[sigma, \"contact impedance\"].potential)\n",
    "            .evaluate(line[::12]),\n",
    "        )\n",
    "        for sigma in conductivities\n",
    "    },\n",
    "    reference={\n",
    "        f\"resolved, σ₂ = {sigma:g} S/m\": (\n",
    "            y,\n",
    "            results[sigma, \"resolved\"]\n",
    "            .field(models[sigma, \"resolved\"].potential)\n",
    "            .evaluate(line),\n",
    "        )\n",
    "        for sigma in conductivities\n",
    "    },\n",
    "    vlines=[-radius, radius],\n",
    "    xlabel=\"y [m]\",\n",
    "    ylabel=\"V [V]\",\n",
    "    title=\"Potential along x = 0\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Replace the contact impedance by `ThinConductiveLayer`, which carries current across and along\n",
    "the layer and so also covers walls that conduct as well as or better than the plate; or change\n",
    "the wall thickness in `contact_impedance_resistive_shell_geometry.py` to see where the thin model\n",
    "starts to deviate."
   ]
  }
 ]
}
