{
 "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": [
    "# Microstrip Wilkinson power divider\n",
    "\n",
    "A Wilkinson divider splits the power entering port 1 equally and in phase between ports 2 and 3\n",
    "while all three ports stay matched and the two outputs isolated from each other. Two arms of\n",
    "$\\sqrt2\\,Z_0=70.71$ Ω, a quarter wavelength long, join the input to the outputs; a resistor of\n",
    "$2Z_0=100$ Ω between the ends of the arms carries no current when port 1 drives both outputs alike,\n",
    "but absorbs the power that one output sends towards the other. Here the arms form a ring of radius\n",
    "5.03 mm on a 0.813 mm substrate of relative permittivity 3.55, for 3 GHz; the resistor bridges a\n",
    "1 mm gap between the arm ends, and 50 Ω lines lead to the sides of a box of air.\n",
    "\n",
    "OneSimulation solves the time-harmonic Maxwell equation\n",
    "\n",
    "$$\\nabla\\times\\big(\\mu_r^{-1}\\nabla\\times\\mathbf E\\big)-k_0^2\\,\\varepsilon_r\\,\\mathbf E=0$$\n",
    "\n",
    "with second-order Nédélec elements. The copper is a sheet without thickness on the substrate\n",
    "(`region_interface` of a thin layer of air shaped like it); the resistor is a `LumpedElement` on the\n",
    "face of the substrate between the arm ends (the top of a thin piece of substrate under the gap): a sheet of uniform current across the gap whose voltage\n",
    "and current obey $V=RI$. The lines end in `TEMPort`s that compute the quasi-TEM mode and the\n",
    "characteristic impedance of their cross-sections; `scattering_matrix` feeds the three ports in turn\n",
    "from one factorization and renormalizes the waves to 50 Ω.\n",
    "\n",
    "| faces | condition |\n",
    "|---|---|\n",
    "| `port_1`, `port_2`, `port_3` | TEM port, signal conductor: the copper |\n",
    "| resistor face | lumped element, $R=100$ Ω across the gap |\n",
    "| `ground`, `wall`, copper | perfect electric conductor |\n",
    "| `lid` | impedance boundary $Y_0=\\sqrt{\\varepsilon_0/\\mu_0}$ (open top) |\n",
    "\n",
    "**Reference** (D. M. Pozar, *Microwave Engineering*, 4th ed., Wiley 2012, §7.3; E. J. Wilkinson,\n",
    "*An N-way hybrid power divider*, IRE Trans. MTT 8 (1960) 116-118). At the centre frequency the\n",
    "ideal divider has\n",
    "\n",
    "$$[S]=\\frac{-\\mathrm j}{\\sqrt2}\\begin{pmatrix}0&1&1\\\\1&0&0\\\\1&0&0\\end{pmatrix}\\quad(e^{\\mathrm j\\omega t}):$$\n",
    "\n",
    "$|S_{21}|=|S_{31}|=-3.01$ dB, all ports matched and $S_{23}=0$; power fed into port 2 goes half to\n",
    "port 1 and half into the resistor. At other frequencies the ideal circuit (two lines of electrical\n",
    "length $\\theta=\\frac\\pi2f/f_0$ and the resistor) is solved by its nodal admittance matrix,\n",
    "$S=(I-Z_0Y)(I+Z_0Y)^{-1}$."
   ]
  },
  {
   "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 VACUUM_PERMEABILITY, VACUUM_PERMITTIVITY\n",
    "from onesim.materials.electromagnetic import (\n",
    "    IsotropicElectromagneticMaterial,\n",
    "    RegionwiseElectromagneticMaterial,\n",
    ")\n",
    "from onesim.meshing import LocalRefinement, TetrahedralMesher, region_interface\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, Nedelec\n",
    "from onesim.numerics.linear import ComplexSparseDirect\n",
    "from onesim.physics.electromagnetics import (\n",
    "    FrequencyDomainMaxwell,\n",
    "    ImpedanceBoundary,\n",
    "    LumpedElement,\n",
    "    PerfectElectricConductor,\n",
    "    TEMPort,\n",
    "    port_values,\n",
    "    scattering_matrix,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()\n",
    "\n",
    "eta0 = np.sqrt(VACUUM_PERMEABILITY / VACUUM_PERMITTIVITY)\n",
    "f0, height = 3e9, 0.813e-3"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`load` reads the box of air with its named faces, the substrate, the thin layer of air shaped like\n",
    "the copper and a thin piece of substrate under the gap whose top face is the resistor; all become\n",
    "regions of one mesh. Second-order tetrahedra of\n",
    "1 mm follow the copper, 0.5 mm the resistor, 1.6 mm the substrate and 5 mm the air."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "box = load(\"microstrip_wilkinson_power_divider.step\")\n",
    "substrate = load(\"microstrip_wilkinson_power_divider_substrate.step\").named(\"substrate\")\n",
    "strips = load(\"microstrip_wilkinson_power_divider_strips.step\").named(\"strips\")\n",
    "resistor = load(\"microstrip_wilkinson_power_divider_resistor.step\").named(\"resistor\")\n",
    "faces = box.boundaries\n",
    "mesh = TetrahedralMesher(\n",
    "    target_size=5e-3,\n",
    "    embedded_regions=(substrate, strips, resistor),\n",
    "    refinements=(\n",
    "        LocalRefinement(region=strips, target_size=1e-3),\n",
    "        LocalRefinement(region=resistor, target_size=0.5e-3),\n",
    "        LocalRefinement(region=substrate, target_size=1.6e-3),\n",
    "    ),\n",
    ").generate(box)\n",
    "copper, film = region_interface(mesh, strips, substrate), region_interface(\n",
    "    mesh, resistor\n",
    ")\n",
    "\n",
    "view = plots.Camera(elevation=45, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(14, 6))\n",
    "plots.geometry(\n",
    "    [substrate, strips, resistor],\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Substrate, copper and resistor (STEP)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"{mesh.cell_count} quadratic tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "`simulation` builds the model at one frequency with the three TEM ports and the resistor; the sweep\n",
    "runs from 2 to 4 GHz."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "material = RegionwiseElectromagneticMaterial(\n",
    "    {\n",
    "        name: IsotropicElectromagneticMaterial(relative_permittivity=3.55)\n",
    "        for name in (\"substrate\", \"resistor\")\n",
    "    },\n",
    "    default=IsotropicElectromagneticMaterial(),\n",
    ")\n",
    "simulation = lambda f, fed=None: (\n",
    "    Simulation(\n",
    "        problem=Problem(\n",
    "            name=\"Wilkinson divider\",\n",
    "            geometry=box,\n",
    "            physics=(\n",
    "                m := FrequencyDomainMaxwell(\n",
    "                    domain=box.volume,\n",
    "                    frequency=f,\n",
    "                    material=material,\n",
    "                    phasor_convention=\"exp(-i*omega*t)\",\n",
    "                    amplitude_convention=\"peak\",\n",
    "                ),\n",
    "            ),\n",
    "            boundary_conditions=tuple(\n",
    "                TEMPort(\n",
    "                    physics=m,\n",
    "                    boundary=getattr(faces, f\"port_{k}\"),\n",
    "                    signal=copper,\n",
    "                    incident_power=float(k == fed),\n",
    "                )\n",
    "                for k in (1, 2, 3)\n",
    "            )\n",
    "            + (\n",
    "                LumpedElement(physics=m, boundary=film, resistance=100.0),\n",
    "                PerfectElectricConductor(\n",
    "                    physics=m, boundary=faces.ground | faces.wall | copper\n",
    "                ),\n",
    "                ImpedanceBoundary(physics=m, boundary=faces.lid, admittance=1 / eta0),\n",
    "            ),\n",
    "        ),\n",
    "        mesh=mesh,\n",
    "        numerics=Numerics(\n",
    "            spatial=FiniteElement(element=Nedelec(order=2)),\n",
    "            linear_solver=ComplexSparseDirect(),\n",
    "        ),\n",
    "    ),\n",
    "    m,\n",
    ")\n",
    "frequencies = np.round(np.linspace(2e9, 4e9, 5), -6)\n",
    "sweep = {\n",
    "    f: scattering_matrix(*simulation(f), reference_impedance=50.0) for f in frequencies\n",
    "}\n",
    "\n",
    "\n",
    "def ideal(f):\n",
    "    theta, e, c = np.pi / 2 * f / f0, np.eye(3), 1 / (50 * np.sqrt(2))\n",
    "    y = (\n",
    "        sum(\n",
    "            c\n",
    "            * (\n",
    "                1j / np.tan(theta) * (np.outer(e[i], e[i]) + np.outer(e[j], e[j]))\n",
    "                - 1j / np.sin(theta) * (np.outer(e[i], e[j]) + np.outer(e[j], e[i]))\n",
    "            )\n",
    "            for i, j in ((0, 1), (0, 2))\n",
    "        )\n",
    "        + np.outer(e[1] - e[2], e[1] - e[2]) / 100\n",
    "    )\n",
    "    return (np.eye(3) - 50 * y) @ np.linalg.inv(np.eye(3) + 50 * y)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The characteristic impedance of the lines, the S-matrix at 3 GHz against the ideal divider, the\n",
    "power that the resistor takes when an output is fed, and the S-parameters over the band."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "centre = sweep[f0]\n",
    "result, m = (lambda run: (run[0].solve_stationary(), run[1]))(simulation(f0, fed=1))\n",
    "dB = lambda x: 20 * np.log10(max(abs(x), 1e-3))\n",
    "print(\n",
    "    \"lines (TEM ports): Z0 = \"\n",
    "    + \", \".join(\n",
    "        f\"{v['characteristic_impedance'].real:.2f}\" for v in port_values(result, m)\n",
    "    )\n",
    "    + \" ohm (Hammerstad-Jensen 50.00 ohm)\"\n",
    ")\n",
    "print(f\"at {f0 / 1e9:.1f} GHz, |S| (dB):   computed\" + \" \" * 30 + \"ideal\")\n",
    "for i in range(3):\n",
    "    print(\n",
    "        f\"  row {i + 1}:  \"\n",
    "        + \"  \".join(f\"{dB(centre[i, j]):7.2f}\" for j in range(3))\n",
    "        + \"        \"\n",
    "        + \"  \".join(\n",
    "            f\"{dB(ideal(f0)[i, j]) if abs(ideal(f0)[i, j]) > 1e-12 else -np.inf:7.2f}\"\n",
    "            for j in range(3)\n",
    "        )\n",
    "    )\n",
    "print(\n",
    "    f\"  arg S21 - arg S31 = {np.degrees(np.angle(centre[1, 0] / centre[2, 0])):.2f} deg (in phase), |S21|^2 + |S31|^2 = \"\n",
    "    f\"{abs(centre[1, 0]) ** 2 + abs(centre[2, 0]) ** 2:.3f} (1)\"\n",
    ")\n",
    "print(\n",
    "    f\"port 2 fed: to port 1 {abs(centre[0, 1]) ** 2:.3f}, reflected {abs(centre[1, 1]) ** 2:.3f}, to port 3 {abs(centre[2, 1]) ** 2:.4f}, \"\n",
    "    f\"into the resistor and the open top {1 - np.sum(np.abs(centre.matrix[:, 1]) ** 2):.3f} of the power (ideal 0.5, 0, 0, 0.5)\"\n",
    ")\n",
    "print(\n",
    "    f\"port 1 fed: lost {1 - np.sum(np.abs(centre.matrix[:, 0]) ** 2):.4f} of the power (resistor and open top; ideal 0)\"\n",
    ")\n",
    "print(\n",
    "    f\"reciprocity max |S - S^T| over the band: {max(np.abs(S.matrix - S.matrix.T).max() for S in sweep.values()):.1e}\"\n",
    ")\n",
    "print(\n",
    "    \"f [GHz]  |S11| dB  |S21| dB  |S22| dB  |S32| dB    ideal: |S11| dB  |S21| dB  |S22| dB  |S32| dB\"\n",
    ")\n",
    "for f, S in sweep.items():\n",
    "    print(\n",
    "        f\"{f / 1e9:6.2f} \"\n",
    "        + \"\".join(f\"{dB(S[i, j]):9.2f} \" for i, j in ((0, 0), (1, 0), (1, 1), (2, 1)))\n",
    "        + \"  \"\n",
    "        + \"\".join(\n",
    "            f\"{dB(ideal(f)[i, j]):9.2f} \" for i, j in ((0, 0), (1, 0), (1, 1), (2, 1))\n",
    "        )\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Left: input match, transmission, output match and isolation over the band against the ideal\n",
    "divider. Right: the electric field in the substrate at 3 GHz with port 1 fed: equal waves in both\n",
    "arms, no voltage across the resistor."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fine = np.linspace(2e9, 4e9, 121)\n",
    "labels = {(0, 0): \"|S11|\", (1, 0): \"|S21|\", (1, 1): \"|S22|\", (2, 1): \"|S32|\"}\n",
    "fig = plots.figure(1, 2, size=(18, 7))\n",
    "plots.line(\n",
    "    points={\n",
    "        name: (frequencies / 1e9, [dB(S[i, j]) for S in sweep.values()])\n",
    "        for (i, j), name in labels.items()\n",
    "    },\n",
    "    reference={\n",
    "        f\"ideal {name}\": (fine / 1e9, [dB(ideal(f)[i, j]) for f in fine])\n",
    "        for (i, j), name in labels.items()\n",
    "    },\n",
    "    xlabel=\"frequency [GHz]\",\n",
    "    ylabel=\"[dB]\",\n",
    "    ylimits=(-45, 2),\n",
    "    title=\"S-parameters of the divider\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.section(\n",
    "    result.field(m.electric_field),\n",
    "    plane=Plane(origin=(0.0, 0.0, 0.6 * height), normal=(0.0, 0.0, 1.0)),\n",
    "    component=lambda E, p: np.linalg.norm(np.abs(E), axis=1),\n",
    "    limits=\"robust\",\n",
    "    subdivisions=1,\n",
    "    length_unit=\"mm\",\n",
    "    label=\"|E| [V/m]\",\n",
    "    title=\"Electric field in the substrate, 3 GHz, port 1 fed\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Change the resistor in the model (`resistance=`) to see how the isolation depends on it, or add\n",
    "a series inductance (`inductance=`) for the parasitics of a real chip resistor. In\n",
    "`microstrip_wilkinson_power_divider_geometry.py` unequal arm impedances give an unequal split."
   ]
  }
 ]
}
