{
 "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 rat-race coupler\n",
    "\n",
    "The rat-race or hybrid ring is a ring of characteristic impedance $\\sqrt2\\,Z_0$ and circumference\n",
    "$\\tfrac32\\lambda_g$ with four ports: three spaced a quarter wavelength apart and the fourth three\n",
    "quarters of a wavelength further on. Waves running both ways round the ring add or cancel at the\n",
    "ports: power fed into port 2 leaves equally and in phase at ports 1 and 3 (the sum), power fed into\n",
    "port 4 equally and in antiphase (the difference), and ports 2 and 4 are isolated from each other.\n",
    "Here the ring (70.71 Ω, mean radius 14.62 mm) is etched for 3 GHz on a 0.813 mm substrate of\n",
    "relative permittivity 3.55, with 50 Ω feeds leaving it at 0°, 60°, 120° and 180° (ports 1 to 4)\n",
    "towards the sides of a hexagonal 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: the faces between the\n",
    "substrate and a thin layer of air shaped like the conductors (`region_interface`) are perfect\n",
    "electric conductors. Every port is a `TEMPort` that computes the quasi-TEM mode of its\n",
    "cross-section from the electrostatic potential; `scattering_matrix` feeds the four ports in turn\n",
    "from one factorization, renormalizes the waves to 50 Ω and moves the reference planes to the ring.\n",
    "\n",
    "| faces | condition |\n",
    "|---|---|\n",
    "| `port_1` ... `port_4` | TEM port, signal conductor: the copper |\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.8; E. Hammerstad and\n",
    "Ø. Jensen, IEEE MTT-S Digest 1980, 407-409). At the centre frequency the ideal ring has\n",
    "$|S_{12}|=|S_{32}|=|S_{14}|=|S_{34}|=1/\\sqrt2$, $\\arg S_{12}=\\arg S_{32}$,\n",
    "$\\arg S_{14}-\\arg S_{34}=180°$, and $S_{ii}=S_{42}=S_{13}=0$. At other frequencies the ideal circuit\n",
    "of four ring sections of electrical lengths $\\theta,\\theta,\\theta,3\\theta$, $\\theta=\\frac\\pi2f/f_0$,\n",
    "is solved by its nodal admittance matrix, $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",
    "    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, feed, height = 3e9, 5.495e-3, 0.813e-3"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`load` reads the hexagonal box of air with its named faces, the substrate and the thin layer shaped\n",
    "like the copper. Second-order tetrahedra of 1 mm follow the copper, 1.6 mm the substrate and\n",
    "4 mm the air."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "box = load(\"microstrip_rat_race_coupler.step\")\n",
    "substrate = load(\"microstrip_rat_race_coupler_substrate.step\").named(\"substrate\")\n",
    "strips = load(\"microstrip_rat_race_coupler_strips.step\").named(\"strips\")\n",
    "faces = box.boundaries\n",
    "mesh = TetrahedralMesher(\n",
    "    target_size=5e-3,\n",
    "    embedded_regions=(substrate, strips),\n",
    "    refinements=(\n",
    "        LocalRefinement(region=strips, target_size=1e-3),\n",
    "        LocalRefinement(region=substrate, target_size=1.6e-3),\n",
    "    ),\n",
    ").generate(box)\n",
    "copper = region_interface(mesh, strips, substrate)\n",
    "\n",
    "view = plots.Camera(elevation=45, azimuth=-70)\n",
    "fig = plots.figure(1, 2, size=(14, 6))\n",
    "plots.geometry(\n",
    "    [substrate, strips],\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Substrate and copper pattern (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 four TEM ports; the sweep runs from 2.4 to\n",
    "3.6 GHz."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "material = RegionwiseElectromagneticMaterial(\n",
    "    {\"substrate\": IsotropicElectromagneticMaterial(relative_permittivity=3.55)},\n",
    "    default=IsotropicElectromagneticMaterial(),\n",
    ")\n",
    "simulation = lambda f, fed=None: (\n",
    "    Simulation(\n",
    "        problem=Problem(\n",
    "            name=\"Rat-race coupler\",\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, 4)\n",
    "            )\n",
    "            + (\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(2.4e9, 3.6e9, 5), -6)\n",
    "sweep = {\n",
    "    f: scattering_matrix(\n",
    "        *simulation(f), reference_impedance=50.0, reference_planes=(feed,) * 4\n",
    "    )\n",
    "    for f in frequencies\n",
    "}\n",
    "\n",
    "\n",
    "def ideal(\n",
    "    f,\n",
    "    admittances=np.full(4, 1 / (50 * np.sqrt(2))),\n",
    "    lengths=np.array([1.0, 1.0, 1.0, 3.0]),\n",
    "):\n",
    "    theta, e = np.pi / 2 * f / f0 * lengths, np.eye(4)\n",
    "    pairs = [(0, 1), (1, 2), (2, 3), (3, 0)]\n",
    "    y = sum(\n",
    "        c\n",
    "        * (\n",
    "            1j / np.tan(t) * (np.outer(e[i], e[i]) + np.outer(e[j], e[j]))\n",
    "            - 1j / np.sin(t) * (np.outer(e[i], e[j]) + np.outer(e[j], e[i]))\n",
    "        )\n",
    "        for c, t, (i, j) in zip(admittances, theta, pairs)\n",
    "    )\n",
    "    return (np.eye(4) - 50 * y) @ np.linalg.inv(np.eye(4) + 50 * y)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The characteristic impedance of the feeds, the sum and difference excitations at 3 GHz against\n",
    "the ideal ring, reciprocity, and the isolation and balance 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=4))\n",
    "dB = lambda x: 20 * np.log10(max(abs(x), 1e-3))\n",
    "print(\n",
    "    \"feed 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",
    "for fed, name in ((1, \"sum, port 2 fed\"), (3, \"difference, port 4 fed\")):\n",
    "    print(\n",
    "        f\"{name}: |S| at ports 1..4 = \"\n",
    "        + \", \".join(f\"{abs(centre[i, fed]):.4f}\" for i in range(4))\n",
    "        + \"   ideal \"\n",
    "        + \", \".join(f\"{abs(ideal(f0)[i, fed]):.4f}\" for i in range(4))\n",
    "    )\n",
    "    print(\n",
    "        f\"    arg S1{fed + 1} - arg S3{fed + 1} = {np.degrees(np.angle(centre[0, fed] / centre[2, fed])):7.1f} deg \"\n",
    "        f\"(ideal {np.degrees(np.angle(ideal(f0)[0, fed] / ideal(f0)[2, fed])):6.1f} deg), split |S1{fed + 1}|^2 - |S3{fed + 1}|^2 = \"\n",
    "        f\"{abs(centre[0, fed]) ** 2 - abs(centre[2, fed]) ** 2:+.3f}\"\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]  |S22| dB  |S42| dB  |S12| dB  |S32| dB  |S13| dB   ideal: |S22| dB  |S42| dB  |S12| dB  |S13| dB\"\n",
    ")\n",
    "for f, S in sweep.items():\n",
    "    print(\n",
    "        f\"{f / 1e9:6.2f} \"\n",
    "        + \"\".join(\n",
    "            f\"{dB(S[i, j]):9.2f} \" for i, j in ((1, 1), (3, 1), (0, 1), (2, 1), (0, 2))\n",
    "        )\n",
    "        + \"  \"\n",
    "        + \"\".join(\n",
    "            f\"{dB(ideal(f)[i, j]):9.2f} \" for i, j in ((1, 1), (3, 1), (0, 1), (0, 2))\n",
    "        )\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Left: the sum port 2 over the band against the ideal ring. Middle: the phase difference of the two\n",
    "outputs for the sum and the difference excitation. Right: the electric field in the substrate at\n",
    "3 GHz with the difference port 4 fed: a standing wave on the ring with a null at port 2."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fine = np.linspace(2.4e9, 3.6e9, 121)\n",
    "fig = plots.figure(1, 3, size=(24, 6.5))\n",
    "plots.line(\n",
    "    points={\n",
    "        f\"|S{i + 1}2|\": (frequencies / 1e9, [dB(S[i, 1]) for S in sweep.values()])\n",
    "        for i in range(4)\n",
    "    },\n",
    "    reference={\n",
    "        f\"ideal |S{i + 1}2|\": (fine / 1e9, [dB(ideal(f)[i, 1]) for f in fine])\n",
    "        for i in range(4)\n",
    "    },\n",
    "    xlabel=\"frequency [GHz]\",\n",
    "    ylabel=\"[dB]\",\n",
    "    ylimits=(-45, 2),\n",
    "    title=\"Port 2 fed (sum)\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        \"sum: arg S12 - arg S32\": (\n",
    "            frequencies / 1e9,\n",
    "            [np.degrees(np.angle(S[0, 1] / S[2, 1])) for S in sweep.values()],\n",
    "        ),\n",
    "        \"difference: arg S14 - arg S34\": (\n",
    "            frequencies / 1e9,\n",
    "            [np.degrees(np.angle(S[0, 3] / S[2, 3])) % 360 for S in sweep.values()],\n",
    "        ),\n",
    "    },\n",
    "    reference={\n",
    "        \"ideal sum\": (\n",
    "            fine / 1e9,\n",
    "            [np.degrees(np.angle(ideal(f)[0, 1] / ideal(f)[2, 1])) for f in fine],\n",
    "        ),\n",
    "        \"ideal difference\": (\n",
    "            fine / 1e9,\n",
    "            [np.degrees(np.angle(ideal(f)[0, 3] / ideal(f)[2, 3])) % 360 for f in fine],\n",
    "        ),\n",
    "    },\n",
    "    xlabel=\"frequency [GHz]\",\n",
    "    ylabel=\"phase difference [deg]\",\n",
    "    title=\"Balance of the outputs\",\n",
    "    legend=\"center right\",\n",
    "    ax=fig[1],\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 4 fed\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Change the ring impedance in `microstrip_rat_race_coupler_geometry.py` to make an unequal split,\n",
    "or feed the sum and difference ports at once (two `incident_power` values) to see the outputs\n",
    "add and cancel."
   ]
  }
 ]
}
