{
 "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": [
    "# Electric shielding by a thin conductive shell\n",
    "\n",
    "A thin sheet of metal shields what lies behind it: the current prefers the sheet and flows\n",
    "around the shielded region. Meshing a sheet of a few millimetres in a part of metres takes many\n",
    "small elements. A **thin conductive layer** replaces the sheet by a face that carries a current\n",
    "along it with the sheet conductance $\\sigma_2 d$,\n",
    "\n",
    "$$\\nabla_t\\cdot\\big(\\sigma_2\\,d\\,\\nabla_t V\\big)=-\\big[\\!\\big[J_n\\big]\\!\\big],$$\n",
    "\n",
    "and that lets the potential jump with the normal conductance $\\sigma_2/d$. For a sheet much more\n",
    "conducting than its surroundings the jump vanishes and the tangential path is what shields.\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=0.1,\\;10,\\;1000$ S/m: the **resolved model** meshes the wall as its own region, the\n",
    "**thin model** puts the conductive layer 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 `conductive_shell_current_shielding*.step`; the\n",
    "script `conductive_shell_current_shielding_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 about a 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",
    "    FixedPotential,\n",
    "    PoissonEquation,\n",
    "    ThinConductiveLayer,\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 = \"conductive_shell_current_shielding\"\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",
    "sheet = 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 conductive 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\"Thin conductive layer: {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;\n",
    "`ThinConductiveLayer` acts on the faces between the two regions of the thin mesh, which\n",
    "`interface` returns."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "bulk, conductivities = 1.0, (0.1, 10.0, 1000.0)\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), (\"thin layer\", 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",
    "                ThinConductiveLayer(\n",
    "                    physics=model,\n",
    "                    boundary=sheet,\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   thin layer   current resolved [A/m]   thin layer [A/m]   difference\"\n",
    ")\n",
    "for sigma in conductivities:\n",
    "    a, b = current[sigma, \"resolved\"], current[sigma, \"thin layer\"]\n",
    "    print(\n",
    "        f\"{sigma:12g} {exact(sigma):16.4f} {field[sigma, 'resolved']:10.4f} {field[sigma, 'thin layer']:12.4f} \"\n",
    "        f\"{a:24.5f} {b:18.5f} {100 * (b / a - 1):+10.3f} %\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The thin layer follows the resolved wall from a sheet that conducts ten times less than the plate\n",
    "to one that conducts a thousand times more, where the inside keeps only 5 % of the applied field.\n",
    "It also passes the normal current with its own resistance, so the poorly conducting wall of\n",
    "0.1 S/m, which a purely tangential shielding condition would miss, is reproduced as well.\n",
    "\n",
    "## Figure\n",
    "\n",
    "The potential with the wall of 1000 S/m in both models, and the potential along the vertical line\n",
    "through the tube for all three conductivities."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 3, size=(21, 6))\n",
    "for panel, kind in enumerate((\"resolved\", \"thin layer\")):\n",
    "    plots.surface(\n",
    "        results[1000.0, kind].field(models[1000.0, 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}, σ₂ = 1000 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\"thin layer, σ₂ = {sigma:g} S/m\": (\n",
    "            y[::12],\n",
    "            results[sigma, \"thin layer\"]\n",
    "            .field(models[sigma, \"thin layer\"].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",
    "Make the wall thicker in `conductive_shell_current_shielding_geometry.py` to find where the thin\n",
    "model starts to deviate from the resolved wall, or give the layer a conductivity that varies along\n",
    "the circle (a callable of the position) to model a damaged coating."
   ]
  }
 ]
}
