{
 "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 branch-line coupler\n",
    "\n",
    "A branch-line (quadrature) hybrid divides the power entering port 1 equally between ports 2 and 3,\n",
    "with a phase difference of 90°, and leaves port 4 isolated. It is a square of four lines, each a\n",
    "quarter wavelength long at the centre frequency: two series arms of $Z_0/\\sqrt2=35.36$ Ω and two\n",
    "shunt arms of $Z_0=50$ Ω. Here it is etched for 3 GHz on a 0.813 mm substrate of relative\n",
    "permittivity 3.55; 50 Ω feed lines run from the corners to the four 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",
    "in the substrate and the air with second-order Nédélec elements. The copper is a sheet without\n",
    "thickness: the faces between the substrate and a thin layer of air shaped like the conductors\n",
    "(`region_interface`) are perfect electric conductors. Each side of the box is a `TEMPort`: it solves\n",
    "the electrostatic potential of its cross-section, $\\nabla\\cdot(\\varepsilon\\nabla V)=0$ with the\n",
    "strip at 1 V, for the quasi-TEM mode, its effective permittivity and its characteristic impedance.\n",
    "`scattering_matrix` feeds the four ports in turn from one factorization, renormalizes the waves to\n",
    "50 Ω and moves the reference planes from the sides of the box to the corners of the square.\n",
    "\n",
    "| faces | condition |\n",
    "|---|---|\n",
    "| `port_1` ... `port_4` | TEM port, signal conductor: the copper |\n",
    "| `ground`, 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.5; E. Hammerstad and\n",
    "Ø. Jensen, *Accurate models for microstrip computer-aided design*, IEEE MTT-S Digest 1980,\n",
    "407-409). At the centre frequency the ideal coupler has\n",
    "\n",
    "$$[S]=\\frac{-1}{\\sqrt2}\\begin{pmatrix}0&\\mathrm j&1&0\\\\ \\mathrm j&0&0&1\\\\ 1&0&0&\\mathrm j\\\\\n",
    "  0&1&\\mathrm j&0\\end{pmatrix}\\quad(e^{\\mathrm j\\omega t}),$$\n",
    "\n",
    "i.e. $|S_{21}|=|S_{31}|=-3.01$ dB, $S_{11}=S_{41}=0$ and $\\arg S_{31}-\\arg S_{21}=\\mp90°$\n",
    "(the sign depends on the phasor convention). Away from it the ideal circuit of four lines of\n",
    "electrical length $\\theta=\\frac\\pi2 f/f_0$ is solved by its nodal admittance matrix\n",
    "$Y=\\sum Y_c\\,(\\mathrm i\\cot\\theta\\,(\\mathbf e_i\\mathbf e_i^T+\\mathbf e_j\\mathbf e_j^T)-\\mathrm i\\csc\\theta\\,(\\mathbf e_i\\mathbf e_j^T+\\mathbf e_j\\mathbf e_i^T))$\n",
    "($e^{-\\mathrm i\\omega t}$), $S=(I-Z_0Y)(I+Z_0Y)^{-1}$. The strip widths (1.819 mm and 3.049 mm) and\n",
    "lengths come from the Hammerstad-Jensen formulas, 50 Ω with $\\varepsilon_{\\rm eff}=2.766$."
   ]
  },
  {
   "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_modes,\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",
    "light, eta0 = 1 / np.sqrt(VACUUM_PERMEABILITY * VACUUM_PERMITTIVITY), np.sqrt(\n",
    "    VACUUM_PERMEABILITY / VACUUM_PERMITTIVITY\n",
    ")\n",
    "f0, feed, height = 3e9, 6e-3, 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 and the thin layer shaped like the\n",
    "copper; both become regions of one mesh. Second-order tetrahedra of 1 mm follow the copper,\n",
    "1.6 mm the substrate and 5 mm the air."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "box = load(\"microstrip_branch_line_coupler.step\")\n",
    "substrate = load(\"microstrip_branch_line_coupler_substrate.step\").named(\"substrate\")\n",
    "strips = load(\"microstrip_branch_line_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=40, azimuth=-60)\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: the substrate takes $\\varepsilon_r=3.55$, every\n",
    "side of the box is a TEM port of the copper. The sweep runs from 2.4 to 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=\"Branch-line 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(physics=m, boundary=faces.ground | copper),\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, admittances=np.array([np.sqrt(2), 1.0, np.sqrt(2), 1.0]) / 50, lengths=np.ones(4)\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 TEM ports report the characteristic impedance and effective permittivity of the feed lines.\n",
    "Then the S-parameters (50 Ω, reference planes at the corners of the square) at the centre\n",
    "frequency against the ideal coupler, and over the band against the ideal circuit; reciprocity and\n",
    "the power that leaves the box through the open top."
   ]
  },
  {
   "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",
    "    \"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), effective permittivity \"\n",
    "    + f\"{port_modes(result, m)[0]['effective_index'][0].real ** 2:.3f} (2.766)\"\n",
    ")\n",
    "print(f\"at {f0 / 1e9:.1f} GHz:   computed            ideal\")\n",
    "for i in range(4):\n",
    "    print(\n",
    "        f\"  S{i + 1}1   {abs(centre[i, 0]):.4f} ({dB(centre[i, 0]):6.2f} dB)   {abs(ideal(f0)[i, 0]):.4f}\"\n",
    "    )\n",
    "print(\n",
    "    f\"  arg S31 - arg S21 = {np.degrees(np.angle(centre[2, 0] / centre[1, 0])):.1f} deg (ideal {np.degrees(np.angle(ideal(f0)[2, 0] / ideal(f0)[1, 0])):.1f} deg); \"\n",
    "    f\"|S21|^2 - |S31|^2 = {abs(centre[1, 0]) ** 2 - abs(centre[2, 0]) ** 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",
    "    f\"power not returned at the ports (open top), port 1 fed: {1 - np.sum(np.abs(centre.matrix[:, 0]) ** 2):.3f}\"\n",
    ")\n",
    "print(\n",
    "    \"f [GHz]  |S11| dB  |S21| dB  |S31| dB  |S41| dB    ideal circuit: |S11| dB  |S21| dB  |S31| dB  |S41| dB\"\n",
    ")\n",
    "for f, S in sweep.items():\n",
    "    print(\n",
    "        f\"{f / 1e9:6.2f} \"\n",
    "        + \"\".join(f\"{dB(S[i, 0]):9.2f} \" for i in range(4))\n",
    "        + \"   \"\n",
    "        + \"\".join(f\"{dB(ideal(f)[i, 0]):9.2f} \" for i in range(4))\n",
    "    )\n",
    "best = min(sweep, key=lambda f: abs(sweep[f][3, 0]))\n",
    "print(\n",
    "    f\"best isolation of the sweep at {best / 1e9:.2f} GHz: |S41| {dB(sweep[best][3, 0]):.1f} dB, |S11| {dB(sweep[best][0, 0]):.1f} dB, \"\n",
    "    f\"|S21| {dB(sweep[best][1, 0]):.2f} dB, |S31| {dB(sweep[best][2, 0]):.2f} dB (design frequency {f0 / 1e9:.1f} GHz)\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The split, the quadrature and the reciprocity are those of the ideal coupler; the band of best\n",
    "match and isolation lies about 10 % above the design frequency. The arms are a quarter wavelength\n",
    "long between the centres of the corner junctions, and the junctions, squares of 1.8 mm by 3 mm,\n",
    "shorten them electrically; in practice the arms are lengthened to compensate.\n",
    "\n",
    "## Figure\n",
    "\n",
    "Left: the four S-parameters of port 1 over the band against the ideal circuit. Right: the\n",
    "electric field just below the copper at 3 GHz with port 1 fed: the wave splits at the first corner\n",
    "and cancels at port 4."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 2, size=(18, 7))\n",
    "plots.line(\n",
    "    points={\n",
    "        f\"|S{i + 1}1|\": (frequencies / 1e9, [dB(S[i, 0]) for S in sweep.values()])\n",
    "        for i in range(4)\n",
    "    },\n",
    "    reference={\n",
    "        f\"ideal |S{i + 1}1|\": (\n",
    "            np.linspace(2.4, 3.6, 121),\n",
    "            [dB(ideal(f * 1e9)[i, 0]) for f in np.linspace(2.4, 3.6, 121)],\n",
    "        )\n",
    "        for i in range(4)\n",
    "    },\n",
    "    xlabel=\"frequency [GHz]\",\n",
    "    ylabel=\"[dB]\",\n",
    "    ylimits=(-45, 2),\n",
    "    title=\"S-parameters of port 1\",\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 design frequency or the substrate in `microstrip_branch_line_coupler_geometry.py`;\n",
    "cascading two branch-line sections widens the band of good isolation. Replace the impedance\n",
    "boundary on the lid by a metal cover to see the box resonances of a shielded circuit."
   ]
  }
 ]
}
