# Terminal (multi-pin) wave ports: a coupled line, end to end

A wave port reports **modal** S-parameters: one port per propagating mode of the port cross-section. For two signal lines over a common ground the two modes are an even-like and an odd-like one, each with its own propagation constant and with voltage on *both* lines. **Terminal** S-parameters have one port per conductor instead: the voltage of each conductor is measured against a reference conductor, with a reference impedance you choose. That is what a circuit simulator, a VNA with one probe per line or a multi-pin port of another solver gives you, and what you need for differential and common-mode analysis, crosstalk, or cascading the line with other networks in scikit-rf.

**When to use which.** One signal over one reference (a microstrip, or a CPW whose grounds are tied so that no slotline-like mode propagates) has one mode, and that mode already is the terminal S-parameter up to its impedance: wave-port S is power-normalized, so a chosen `z_ref` still needs the mode impedance. Stay modal there. Use terminal S-parameters when the port face holds two or more signal conductors, or when a downstream tool wants one port per conductor. Modal S stays the right tool for mode-resolved questions (`n_eff` per mode, mode conversion).

The two are related by a linear map built from the voltage and current each mode puts on each terminal. With \\(T\_V\\) and \\(T\_I\\) the block-diagonal matrices whose column \\(k\\) holds the terminal voltages and currents (into the network) of mode \\(k\\) for a unit forward wave, \\(S\_m\\) the modal S-matrix and \\(Z\_{ref}\\) the reference impedance of each terminal,

\\\[ S\_t = (B + A\\,S\_m)\\,(A + B\\,S\_m)^{-1}, \\qquad A,\\,B = F\\,\\bigl(T\_V \\pm Z\_{ref}\\,T\_I\\bigr), \\qquad F = \\mathrm{diag}\\!\\left(\\frac{1}{2\\sqrt{Z\_{ref}}}\\right). \\\]

Palace has no terminal wave port, so gsim builds it in post-processing (method and limits in the guide [Terminal (multi-pin) Wave Ports](<https://gdsfactory.com/gsim/terminal_wave_ports/index.md>)):

1. a 2D `BoundaryModeSim` of the port plane gives \\(T\_V\\) and \\(T\_I\\) of every mode;
2. a 3D `DrivenSim` with one **multimode wave port** per end (several Palace modes on one face) gives \\(S\_m\\);
3. `build_terminal_s` pairs the 2D and 3D modes, brings \\(T\_V\\) and \\(T\_I\\) into the gauge of Palace's port modes and applies the formula.

**The line.** A GSSG pair on the generic PDK: `metal3`, signals 10 um wide, 6 um gap to the grounds, 20 um between the signals, 300 um long. The outer grounds are tied by a `metal1` plane and via walls, so the port has two terminals (S1, S2) and one reference (the plane): two modes.

**Cost.** Two cloud jobs, submitted together: one 2D mode solve (a few thousand triangles) and one 3D driven run (about a hundred thousand tetrahedra, 5 frequencies). Everything else runs locally. It needs a [GDSFactory+](<https://gdsfactory.com>) account for the two jobs; the results are kept in a folder, so the notebook can be re-run without the cloud.

```python
import json
import os
import shutil
import tempfile
from pathlib import Path

import gdsfactory as gf
import matplotlib.pyplot as plt
import matplotlib.tri as mtri
import numpy as np

import gsim
from gsim.common.cross_section import extract_plane_section
from gsim.common.modes import Conductor
from gsim.common.stack import get_stack
from gsim.palace import (
    BoundaryModeSim,
    DrivenSim,
    TerminalPortSpec,
    build_terminal_s,
    declare_terminal_paths,
    load_boundary_mode_field,
    load_modal_run,
    mixed_mode,
    modal_to_terminal_s,
    plot_plane_section,
    port_mode_reference_voltages,
    port_modes_2d,
    terminal_paths,
    uniform_line_modal_s,
)
from gsim.palace.ports.modes import read_port_modes
from gsim.palace.results import load_text_results

gf.gpdk.PDK.activate()
LAYER = gf.gpdk.LAYER

# The cloud results of the two jobs are kept here (RESULTS/2d and RESULTS/3d); meshes and configs go to WORK.
RESULTS = Path(os.environ.get("GSSG_RESULTS", "terminal_gssg_results"))
WORK = Path(tempfile.mkdtemp(prefix="palace-multipin-"))
C0 = 299_792_458.0
```

## 1\. Geometry and terminals

The ports sit at the two ends of the line, centred between the two signals, with `max_size=True`, so each port face is the whole simulation domain and holds every conductor. A `TerminalPortSpec` names the terminals and the reference as rectangles of the port cross-section. `terminal_paths` draws one voltage path per terminal, from the terminal to the reference, that never crosses a conductor: straight across the gap when the two face each other, otherwise out of the terminal and over the metal.

```python
LENGTH = 300.0  # um, along x
S_W, GAP, SS, G_W = (
    10.0,
    6.0,
    20.0,
    40.0,
)  # signal width, gap, edge-to-edge S-S spacing, ground width
WALL_W = 4.0  # width of the via walls under the outer grounds
FREQS = np.linspace(10e9, 50e9, 5)  # the 3D sweep (Hz)
F_2D = 30e9  # frequency of the 2D solve; one of the 3D points, where the 3D run saves Palace's own port-mode fields
assert np.isclose(FREQS, F_2D).any()

S_IN = SS / 2
STRIPS = {  # (y0, y1) of every strip on metal3
    "G1": (-(S_IN + S_W + GAP + G_W), -(S_IN + S_W + GAP)),
    "S1": (-(S_IN + S_W), -S_IN),
    "S2": (S_IN, S_IN + S_W),
    "G2": (S_IN + S_W + GAP, S_IN + S_W + GAP + G_W),
}
Y_EDGE = STRIPS["G2"][1]

stack = get_stack()
Z = {n: (stack.layers[n].zmin, stack.layers[n].zmax) for n in ("metal1", "metal3")}
MARGIN_Y, Z_ABOVE, Z_BELOW = 60.0, 60.0, 20.0  # airbox margins (um)
Z_OXIDE = (-2.0, 5.2)  # the oxide slab of set_stack(substrate_thickness=2.0)
# the meshed domain of every run below: the port face and the 2D cross-section, as (h, v) = (y, z)
DOMAIN = (
    (-(Y_EDGE + MARGIN_Y), Y_EDGE + MARGIN_Y),
    (Z_OXIDE[0] - Z_BELOW, Z_OXIDE[1] + Z_ABOVE),
)


def _rect(c, y0, y1, layer):
    c.add_polygon(
        [(-LENGTH / 2, y0), (LENGTH / 2, y0), (LENGTH / 2, y1), (-LENGTH / 2, y1)],
        layer=layer,
    )


def build_component():
    # Four strips on metal3, a metal1 plane under them and a via wall under each outer ground.
    c = gf.Component()
    for y0, y1 in STRIPS.values():
        _rect(c, y0, y1, LAYER.M3)
    _rect(c, -Y_EDGE, Y_EDGE, LAYER.M1)
    for name in ("G1", "G2"):
        y_mid = sum(STRIPS[name]) / 2
        for layer in (LAYER.VIA1, LAYER.M2, LAYER.VIA2):
            _rect(c, y_mid - WALL_W / 2, y_mid + WALL_W / 2, layer)
    for name, x, angle in (("o1", -LENGTH / 2, 180), ("o2", LENGTH / 2, 0)):
        c.add_port(
            name=name,
            center=(x, 0),
            width=S_W,
            orientation=angle,
            port_type="electrical",
            layer=LAYER.M3,
        )
    return c


def make_spec(port):
    # Terminals S1 and S2, reference the metal1 plane, as rectangles (h = y, v = z, um) of the x = const section.
    z3 = Z["metal3"]
    return TerminalPortSpec(
        name=port,
        terminals=[Conductor(n, (STRIPS[n], z3)) for n in ("S1", "S2")],
        reference=Conductor("PLANE", ((-Y_EDGE, Y_EDGE), Z["metal1"])),
    )


component = build_component()
N = len(make_spec("o1").terminals)  # terminals = modes per port
```

```python
fig, ax = plt.subplots(figsize=(10, 3.6))
section = extract_plane_section(component.copy(), stack, axis="x", value=0.0)
plot_plane_section(
    section,
    h_range=(-80, 80),
    v_range=(0, 12),
    title="cross-section x = 0",
    ax=ax,
    legend=False,
)
for name, points in terminal_paths(make_spec("o1"), DOMAIN).items():
    h, v = zip(*points, strict=True)
    ax.plot(h, v, "-o", ms=2.5, lw=1.2, label=f"voltage path: {name} to the plane")
ax.legend(loc="upper right", fontsize=7)
plt.tight_layout()
plt.show()
```

![svg](<https://gdsfactory.com/gsim/nbs/palace_terminal_waveport_gssg_files/palace_terminal_waveport_gssg_4_0.svg>)

## 2\. The 2D port-mode check

Before any 3D run, a `BoundaryModeSim` on the plane `x = 0` shows the modes the 3D port will carry. Palace's 3D port eigenproblem treats every conductor surface as a perfect conductor, so the 2D solve does the same (`conductor_boundary = "pec"`, and `metallic_boundaries = True` for the outer wall). Its modes are lossless, their \\(T\_V\\) and \\(T\_I\\) hardly move with frequency, and one solve is enough here (at 30 GHz, a point of the 3D sweep; the 3D frequencies outside it use the same matrices, `extrapolate=True` below).

The shielded domain has the outer wall as one more conductor, so one mode more than terminals is solved and saved; the mode between the metal and the wall has the lowest `n_eff` and is dropped.

The solve itself needs Palace and runs on the cloud (section 4). `declare_terminal_paths` also registers the voltage paths on the solve, so that Palace writes the voltage of every mode on every path to `mode-V.csv` as a cross-check.

```python
MESH_2D = {
    "preset": "default",
    "refined_mesh_size": 1.0,
    "max_mesh_size": 20.0,
    "fmax": 50e9,
}


def build_2d(freq_hz, out):
    # A configured, meshed BoundaryModeSim on x = 0 with the terminal paths declared.
    sim = BoundaryModeSim()
    sim.set_output_dir(str(out))
    sim.set_geometry(component)
    sim.set_stack(substrate_thickness=2.0)
    sim.set_airbox(margin_x=0.0, margin_y=MARGIN_Y, z_above=Z_ABOVE, z_below=Z_BELOW)
    sim.set_cross_section("x=0")
    # one mode more than terminals: the outer wall is one more conductor
    sim.set_boundary_mode(freq=freq_hz, num_modes=N + 1, save=N + 1)
    sim.metallic_boundaries = True
    sim.conductor_boundary = "pec"  # the conductors of the 3D port eigenproblem
    mesh = sim.mesh(verbose=False, **MESH_2D)
    # Palace controls its path integration; mode-V.csv is a separate cross-check.
    declare_terminal_paths(sim, make_spec("o1"), sim.mesh_extent)
    return sim, mesh


sim_2d, mesh_2d = build_2d(F_2D, WORK / "2d")
assert np.allclose(np.array(sim_2d.mesh_extent), np.array(DOMAIN))
print("2D domain (h, v):", sim_2d.mesh_extent)
print(
    "2D mesh:",
    {
        k: v
        for k, v in mesh_2d.mesh_stats.items()
        if k in ("nodes", "elements", "triangles")
    },
)
print("validate_config:", sim_2d.validate_config().valid)
```

```text
The stack's substrate layer 'substrate' (10 um, z=-13 to -3) is not part of the domain because include_substrate=False, so its thickness does not move the domain bottom. The bottom is z=-2 um (stack bottom) minus set_airbox(z_below=20). Use set_stack(include_substrate=True) to mesh the substrate, or set substrate_thickness / z_below to move the bottom.


2D domain (h, v): ((-126.0, 126.0), (-22.0, 65.2))
2D mesh: {'nodes': 2401, 'elements': 6148}
validate_config: True
```

## 3\. The 3D run: multimode wave ports

`add_multimode_wave_port` keeps one boundary surface per end and writes one Palace `WavePort` entry per mode on it. Palace terminates a face for one mode only, the *active* mode, which must have the lowest index of its face; the other mode is observed (`"Active": false`). A `port_modes.json` file records which Palace index is which mode. Each entry carries the voltage path of the terminal `S1` (the pilot terminal), which fixes the sign of the mode. Both modes of this symmetric line have a large voltage on `S1`, so one pilot terminal serves both and the 3D run does not wait for the 2D result.

This is a **single run**: mode 1 active, both entries excited. The mode-1 columns of the modal S are exact; the mode-2 columns are measured with the face terminated for mode 1, so they carry a reflection error of the order of the relative difference of the two wave numbers (guide, section 4; `ModalS.exact` flags them). Running a second job with mode 2 active makes them exact too (*cycling*); one job is enough for an example.

The mesh is 2 um near the conductors (the 4 um via walls and the 10 um signals need a few cells across) and 60 um in the dielectric, and the sweep has 5 points. Adaptive sampling is off: `build_terminal_s` reads the wave numbers of the port modes from the points that were solved. The run also saves Palace's own port-mode fields at 30 GHz, which `build_terminal_s` uses to fit the gauge of the 2D modes.

**Perfect conductors on both sides, on purpose.** By default gsim gives the metal of a driven run a finite conductivity (here aluminium, \\(\\sigma = 3.77\\times10^{7}\\) S/m) through a surface-impedance condition, while the 2D solve above and Palace's own port eigenproblem treat the metal as perfect. A real metal does not only dissipate: its fields penetrate a skin depth

\\\[ \\delta = \\sqrt{\\frac{2}{\\omega\\,\\mu\\,\\sigma}} \\\]

(\\(0.8\\ \\mu\\)m at 10 GHz and \\(0.4\\ \\mu\\)m at 50 GHz for this \\(\\sigma\\)) into the conductor. The surface impedance is \\(Z\_s = (1+j)\\,R\_s\\) with \\(R\_s = 1/(\\sigma\\delta)\\), and its imaginary part is an *internal inductance* of \\(R\_s/\\omega = \\mu\\delta/2\\) per square of surface, in series with the external inductance of the line. The line is slower: \\(n\_\\mathrm{eff}\\) is higher than for a perfect conductor, and the excess grows towards low frequency, where \\(\\delta\\) is larger (\\(\\delta \\propto 1/\\sqrt{f}\\)). A uniform-line check that compared such a 3D run with a perfect-conductor 2D solve would show a phase and an amplitude difference that comes from the model and not from the method.

So the 3D run uses perfect conductors too: `PECDrivenSim` below moves exactly the conductor surfaces that gsim writes under `Boundaries.Conductivity` to `Boundaries.PEC` (the same move that `BoundaryModeSim.conductor_boundary = "pec"` does in 2D) and changes nothing else (the same surfaces leave the `WavePortPEC` list, because `PEC` already makes them Dirichlet in the port solve). The one exception is the vias: in 3D they are volumes of finite conductivity (in the 2D cross-section they are perfect-conductor surfaces); they only tie the outer grounds to the plane and carry little of the line's field. The line then has no conductor loss outside the vias, and the comparison of section 9 tests the terminal-S machinery against the same physics. The loss and the surface inductance of real metal are a separate effect that this example leaves out.

```python
MESH_3D = {
    "preset": "default",
    "refined_mesh_size": 2.0,
    "max_mesh_size": 60.0,
    "fmax": 50e9,
}
PORT_X = {"o1": -LENGTH / 2, "o2": LENGTH / 2}
PILOT = {1: "S1", 2: "S1"}  # mode -> pilot terminal, for both ports
ACTIVE_MODE = 1


class PECDrivenSim(DrivenSim):
    # A DrivenSim whose conductor surfaces are perfect conductors, like the 2D solve and the port eigenproblem.
    # gsim writes the metal of a driven run under Boundaries.Conductivity (finite conductivity); here exactly those
    # attributes are moved to Boundaries.PEC, and dropped from WavePortPEC (PEC is Dirichlet in the port solve already).
    # Every write of config.json (write_config, and so every upload) goes through this.
    def write_config(self, **kwargs):
        path = Path(super().write_config(**kwargs))
        config = json.loads(path.read_text())
        boundaries = config["Boundaries"]
        moved = {
            a
            for entry in boundaries.pop("Conductivity", [])
            for a in entry["Attributes"]
        }
        boundaries["PEC"] = {
            "Attributes": sorted(
                moved | set(boundaries.get("PEC", {}).get("Attributes", []))
            )
        }
        if "WavePortPEC" in boundaries:
            rest = sorted(set(boundaries["WavePortPEC"]["Attributes"]) - moved)
            if rest:
                boundaries["WavePortPEC"] = {"Attributes": rest}
            else:
                del boundaries["WavePortPEC"]
        path.write_text(json.dumps(config, indent=4))
        return path


def pilot_paths_3d(port):
    # {mode: [(x, y, z), ...]}: the 2D voltage path of the pilot terminal of each mode, on the port plane.
    paths = terminal_paths(make_spec(port), DOMAIN)
    return {
        mode: [[PORT_X[port], h, v] for h, v in paths[name]]
        for mode, name in PILOT.items()
    }


def build_3d(out):
    # A configured, meshed PECDrivenSim: two multimode wave ports, N modes on each, mode 1 active, all excited.
    sim = PECDrivenSim()
    sim.set_output_dir(str(out))
    sim.set_geometry(component)
    sim.set_stack(substrate_thickness=2.0)
    sim.set_airbox(margin_x=0.0, margin_y=MARGIN_Y, z_above=Z_ABOVE, z_below=Z_BELOW)
    for port in ("o1", "o2"):
        sim.add_multimode_wave_port(
            port,
            layer="metal3",
            modes=tuple(range(1, N + 1)),
            active_mode=ACTIVE_MODE,
            excite="all",
            max_size=True,
            pilot_paths=pilot_paths_3d(port),
        )
    sim.set_driven(
        fmin=FREQS[0],
        fmax=FREQS[-1],
        num_points=len(FREQS),
        adaptive_tol=0.0,
        save_fields_at=[F_2D],
    )
    mesh = sim.mesh(verbose=False, **MESH_3D)
    return sim, mesh


sim_3d, mesh_3d = build_3d(WORK / "3d")
assert sim_3d.validate_config().valid
entries = json.loads(Path(sim_3d.write_config()).read_text())["Boundaries"]["WavePort"]
print("3D mesh tetrahedra:", mesh_3d.mesh_stats["tetrahedra"])
print(
    "WavePort entries:",
    len(entries),
    "| excitations:",
    sum(bool(e.get("Excitation")) for e in entries),
)
print("\nPalace index -> (port, mode, active, excited), from port_modes.json:")
for row in read_port_modes(WORK / "3d"):
    print(
        f"  {row.index}: {row.port} mode {row.mode}  active={row.active}  excited={row.excited}"
    )
```

```text
The stack's substrate layer 'substrate' (10 um, z=-13 to -3) is not part of the domain because include_substrate=False, so its thickness does not move the domain bottom. The bottom is z=-2 um (stack bottom) minus set_airbox(z_below=20). Use set_stack(include_substrate=True) to mesh the substrate, or set substrate_thickness / z_below to move the bottom.


Info    : Reading 'palace.msh'...
Info    : 26831 nodes
Info    : 197477 elements
Info    : [  0%] Reading elements
```

Info : \[ 10%\] Reading elements  
Info : \[ 20%\] Reading elements  
Info : \[ 30%\] Reading elements  
Info : \[ 40%\] Reading elements  
Info : \[ 50%\] Reading elements  
Info : \[ 60%\] Reading elements  
Info : \[ 70%\] Reading elements  
Info : \[ 80%\] Reading elements  
Info : \[ 90%\] Reading elements

```text
Info    : Done reading 'palace.msh'
3D mesh tetrahedra: 144791
WavePort entries: 4 | excitations: 4

Palace index -> (port, mode, active, excited), from port_modes.json:
  1: o1 mode 1  active=True  excited=True
  2: o2 mode 1  active=True  excited=True
  3: o1 mode 2  active=False  excited=True
  4: o2 mode 2  active=False  excited=True
```

## 4\. Run the two jobs

The two jobs are submitted together and their results are saved under `RESULTS` (`2d/` and `3d/`, plus the `port_modes.json` of the 3D run). If both folders are already there, nothing is submitted. The same code is in `launch_cloud.py` for running it from a terminal.

```python
def folder_files(folder):
    # {file name: path} of a downloaded results folder, as sim.run() returns it
    return {
        p.name: p
        for p in sorted(Path(folder).rglob("*"))
        if p.is_file() and not p.name.startswith(".")
    }


def results_ready():
    return all((RESULTS / key / "DONE").exists() for key in ("2d", "3d"))


def run_on_cloud(sims):
    # Submit every job first (they run side by side), then wait for each one and keep its files in RESULTS/<key>.
    for sim in sims.values():
        sim.run(wait=False)
    for key, sim in sims.items():
        folder = RESULTS / key
        shutil.rmtree(folder, ignore_errors=True)
        sim.wait_for_results(parent_dir=folder)
        for name in ("config.json", "port_modes.json"):
            source = Path(sim.output_dir) / name
            if source.exists():
                shutil.copy2(source, folder / name)
        (folder / "DONE").write_text("ok")
```

```python
if results_ready():
    print("Results found in", RESULTS.resolve(), "- nothing submitted.")
else:
    run_on_cloud({"2d": sim_2d, "3d": sim_3d})
```

```text
  palace-e886f8eb  [####################]  Job completed  elapsed 1m 33s


Extracting results.tar.gz...


Downloaded 49 files to terminal_gssg_results/3d/sim-data-palace-e886f8eb
```

## 5\. The 2D modes: `n_eff`, shapes, `T_V` and `T_I`

The saved modes give \\(T\_V\\) and \\(T\_I\\) (voltage integrals of \\(E\\) along the terminal paths, Ampere contour integrals of \\(H\\) around each terminal). The two kept modes are told apart by the sign of the voltage on `S2` relative to `S1`: the same sign for the **common** (even) mode, opposite for the **differential** (odd) mode.

```python
def mode_kinds(t_v):
    # 'common' when the two terminals carry the same voltage sign (even mode), else 'differential' (odd mode)
    return [
        "common" if (t_v[0, k] * np.conj(t_v[1, k])).real > 0 else "differential"
        for k in range(t_v.shape[1])
    ]


def plot_mode_fields(fields, titles, h_range=(-85, 85), v_range=(-4, 14)):
    # Vertical electric field E_v (the second transverse component, (h, v) = (y, z)) of each mode in the plane
    # of the line, scaled to 1 and phase-rotated so that the largest value is real.
    fig, axes = plt.subplots(
        len(fields), 1, figsize=(10, 2.9 * len(fields)), squeeze=False
    )
    for ax, field, title in zip(axes[:, 0], fields, titles, strict=True):
        tri = mtri.Triangulation(
            field.points_um[:, 0], field.points_um[:, 1], field.cells[:, :3]
        )
        e_v = field.e_t[:, 1]
        pivot = e_v[np.argmax(np.abs(e_v))]
        e_v = e_v * np.conj(pivot) / abs(pivot)
        image = ax.tripcolor(
            tri,
            e_v.real / np.abs(e_v).max(),
            cmap="RdBu_r",
            vmin=-1,
            vmax=1,
            shading="gouraud",
            rasterized=True,
        )
        for name, (hh, vv) in {n: (STRIPS[n], Z["metal3"]) for n in STRIPS}.items():
            ax.plot(
                [hh[0], hh[1], hh[1], hh[0], hh[0]],
                [vv[0], vv[0], vv[1], vv[1], vv[0]],
                "k-",
                lw=0.8,
            )
        ax.set_xlim(*h_range)
        ax.set_ylim(*v_range)
        ax.set_aspect("equal")
        ax.set_title(title, fontsize=9)
        ax.set_ylabel("z (um)")
        fig.colorbar(image, ax=ax, pad=0.01, label="Re E_v (normalised)")
    axes[-1, 0].set_xlabel("y (um)")
    plt.tight_layout()
    return fig
```

```python
files_2d = folder_files(RESULTS / "2d")
text = load_text_results(files_2d)
n_all = {m: v["n_eff"].real for m, v in text.modes.items()}
print(
    "n_eff of every saved mode (PEC conductors):",
    {m: round(n, 4) for m, n in n_all.items()},
)
# keep the N modes with the largest n_eff: the last one lives between the metal and the outer wall
mode_ids = sorted(n_all, key=lambda m: -n_all[m])[:N]
print("modes kept:", mode_ids)

spec_o1 = make_spec("o1")
paths_2d = terminal_paths(spec_o1, DOMAIN)
fields = [
    load_boundary_mode_field(Path(files_2d["mode-kn.csv"]).parent, mode_id=m)
    for m in mode_ids
]
modes_2d = [
    port_modes_2d(
        fields,
        spec_o1,
        freq_ghz=F_2D / 1e9,
        n_eff=[n_all[m] for m in mode_ids],
        paths=paths_2d,
    )
]
kinds_2d = mode_kinds(modes_2d[0].t_v)
for m, kind, n_eff in zip(mode_ids, kinds_2d, modes_2d[0].n_eff, strict=True):
    print(f"mode {m}: {kind:>12s}, n_eff = {n_eff:.4f}")
print(
    "T_V (rows S1, S2; columns the kept modes), volts:\n", np.round(modes_2d[0].t_v, 4)
)
print("T_I (amperes):\n", np.round(modes_2d[0].t_i, 5))

# The pilot terminal S1 of the 3D ports needs a large voltage in both modes (it is |V_S1| >= 0.5 max |V| here)
assert all(
    np.abs(modes_2d[0].t_v[0, k]) >= 0.5 * np.abs(modes_2d[0].t_v[:, k]).max()
    for k in range(N)
)

# cross-check against Palace's own line integrals in mode-V.csv: same shape up to one factor per mode
from gsim.palace.mode_fields import voltage_line_integral  # noqa: E402

for k, m in enumerate(mode_ids):
    csv = np.array([text.mode_voltage(index=i + 1, mode=m) for i in range(N)])
    own = np.array(
        [
            voltage_line_integral(fields[k], paths_2d[n]) * 1e-6
            for n in spec_o1.terminal_names
        ]
    )
    ratio = csv / own
    print(
        f"mode {m}: mode-V.csv over line integral, spread {np.ptp(np.abs(ratio)) / np.abs(ratio).mean():.1e}"
    )

plot_mode_fields(
    fields,
    [
        f"mode {m}: {kind}, n_eff = {n:.4f}"
        for m, kind, n in zip(mode_ids, kinds_2d, modes_2d[0].n_eff, strict=True)
    ],
)
plt.show()
```

```text
n_eff of every saved mode (PEC conductors): {1: 1.9289, 2: 1.9114, 3: 1.0391}
modes kept: [1, 2]


mode 1:       common, n_eff = 1.9289
mode 2: differential, n_eff = 1.9114
T_V (rows S1, S2; columns the kept modes), volts:
 [[ 2.9899+0.j -2.9615-0.j]
 [ 2.9823+0.j  2.9689+0.j]]
T_I (amperes):
 [[ 0.16152-0.j -0.16213-0.j]
 [ 0.16075+0.j  0.16215-0.j]]


mode 1: mode-V.csv over line integral, spread 5.9e-09


mode 2: mode-V.csv over line integral, spread 5.2e-09
```

![svg](<https://gdsfactory.com/gsim/nbs/palace_terminal_waveport_gssg_files/palace_terminal_waveport_gssg_14_4.svg>)

## 6\. Terminal S-parameters

`build_terminal_s` returns the terminal S with the pieces it was built from (`terminal_s` returns the scikit-rf network only). Terminal ports are named `"{port}:{terminal}"`. The gauge of \\(T\_V\\) and \\(T\_I\\) is fitted to Palace's own saved port-mode fields (`reference_voltages`). Two numbers say how well the 2D and 3D modes agree: the relative difference of `n_eff` after pairing, and the residual of that fit.

The pairing tolerance on `n_eff` is kept open at 2 % (default 0.5 %) as a safety margin. This does not make the two modes harder to tell apart: they are paired by an optimal assignment, and the tolerance for treating two 3D modes as degenerate stays at 0.5 %. With perfect conductors on both sides and a 2 um mesh the printed mismatch should be far below 0.5 %; if it is, `PAIRING_RTOL` can go back to the default.

```python
PAIRING_RTOL = 0.02


def assemble(runs, modes_2d, reference_voltages=None):
    # Terminal S of the two multimode ports from the driven run(s) and the 2D solve(s).
    return build_terminal_s(
        runs,
        [make_spec("o1"), make_spec("o2")],
        {"o1": modes_2d, "o2": modes_2d},
        z_ref=50.0,
        reference_voltages=reference_voltages,
        rtol=PAIRING_RTOL,
        extrapolate=True,  # one 2D solve: its T_V and T_I are held for the other frequencies
    )


def table(s, labels):
    # |S| in dB, one row per output port
    print(" " * 14 + "".join(f"{lab:>14s}" for lab in labels))
    for i, lab in enumerate(labels):
        print(
            f"{lab:>14s}"
            + "".join(f"{20 * np.log10(abs(v) + 1e-15):14.1f}" for v in s[i])
        )
```

```python
files_3d = folder_files(RESULTS / "3d")
sidecar = RESULTS / "3d" / "port_modes.json"
runs = [load_modal_run(files_3d, sidecar=sidecar, log=files_3d["palace.log"])]

# Palace's own port-mode fields (saved at F_2D: ParaView cycle 1) integrated along the terminal paths: the gauge reference
reference_voltages = {
    port: port_mode_reference_voltages(
        files_3d, make_spec(port), sidecar, cycles=[1], domain=DOMAIN
    )
    for port in ("o1", "o2")
}
result = assemble(runs, modes_2d, reference_voltages)
net = result.network("coupled-gssg-terminal")
print(net)
for port, aligned in result.aligned.items():
    print(
        f"{port}: n_eff pairing mismatch {aligned.mismatch:.2%}, gauge fit residual {aligned.gauge_residual.max():.1e}, "
        f"gauge scale {np.round(aligned.gauge_scale, 3).tolist()}"
    )
modal_labels = [f"{it.port} mode {it.mode}" for it in result.modal.order]
print(
    "modal columns from a run in which the mode is active (exact):",
    dict(zip(modal_labels, result.modal.exact, strict=True)),
)
touchstone = result.write_touchstone(WORK / "coupled_gssg")
print("Touchstone:", touchstone.name)
```

```text
4-Port Network: 'coupled-gssg-terminal',  10000000000.0-50000000000.0 Hz, 5 pts, z0=[50.+0.j 50.+0.j 50.+0.j 50.+0.j]
o1: n_eff pairing mismatch 0.07%, gauge fit residual 4.6e-03, gauge scale [[0.996, 0.996]]
o2: n_eff pairing mismatch 0.07%, gauge fit residual 2.1e-03, gauge scale [[0.996, 0.996]]
modal columns from a run in which the mode is active (exact): {'o1 mode 1': True, 'o1 mode 2': False, 'o2 mode 1': True, 'o2 mode 2': False}
Touchstone: coupled_gssg.s4p
```

```python
k = int(np.argmin(np.abs(result.freq_ghz - 30.0)))
print(
    f"modal S at {result.freq_ghz[k]:g} GHz (dB): the ports are waves, not conductors"
)
table(result.modal.s_modal[k], modal_labels)
print(
    f"\nterminal S at {result.freq_ghz[k]:g} GHz (dB, z_ref = 50 ohm): one port per conductor"
)
table(net.s[k], list(net.port_names))
```

```text
modal S at 30 GHz (dB): the ports are waves, not conductors
                   o1 mode 1     o1 mode 2     o2 mode 1     o2 mode 2
     o1 mode 1         -47.3         -80.0          -0.0         -43.5
     o1 mode 2         -80.3         -40.4         -43.5          -0.1
     o2 mode 1          -0.0         -43.5         -47.3         -79.2
     o2 mode 2         -43.5          -0.1         -78.6         -40.5

terminal S at 30 GHz (dB, z_ref = 50 ohm): one port per conductor
                       o1:S1         o1:S2         o2:S1         o2:S2
         o1:S1          -8.2         -40.6          -0.8         -35.8
         o1:S2         -40.7          -8.3         -45.9          -0.8
         o2:S1          -0.8         -45.9          -8.2         -40.6
         o2:S2         -35.8          -0.8         -40.7          -8.3
```

The same run in both languages at one frequency. The modal S is indexed by mode: each mode goes through to the same mode at the other end and the two modes hardly couple. The terminal S is indexed by conductor: the through path is S1 to S1, and what leaks from S1 into S2 is the crosstalk. The two tables describe the same line.

```python
def plot_terminal(net):
    freq_ghz = net.f / 1e9
    idx = {name: i for i, name in enumerate(net.port_names)}
    curves = {
        "S11  (reflection, S1)": ("o1:S1", "o1:S1"),
        "S21  (through, S1 to S1)": ("o2:S1", "o1:S1"),
        "near-end crosstalk, S1 to S2": ("o1:S2", "o1:S1"),
        "far-end crosstalk, S1 to S2": ("o2:S2", "o1:S1"),
    }
    fig, ax = plt.subplots(figsize=(8, 4))
    for label, (out, inp) in curves.items():
        ax.plot(
            freq_ghz,
            20 * np.log10(np.abs(net.s[:, idx[out], idx[inp]]) + 1e-15),
            "o-",
            label=label,
        )
    ax.set_xlabel("f (GHz)")
    ax.set_ylabel("|S| (dB)")
    ax.set_title("Terminal S-parameters, 50 ohm per terminal")
    ax.legend(fontsize=8)
    ax.grid(alpha=0.3)
    return fig
```

```python
plot_terminal(net)
plt.show()
```

![svg](<https://gdsfactory.com/gsim/nbs/palace_terminal_waveport_gssg_files/palace_terminal_waveport_gssg_21_0.svg>)

## 7\. Passivity and reciprocity

A passive, reciprocal network has \\(S = S^T\\) and a largest singular value of \\(S\\) not above 1 (it is close to 1 here: with perfect conductors outside the vias and lossless dielectrics the line dissipates little). The mode-2 columns of the single run carry the face-mismatch error of section 3, so reciprocity is the number that suffers most; the two tolerances below are my choice for a single run, not a property of the method.

```python
TOL_PASSIVITY = 1e-3  # largest singular value may exceed 1 by this much (solver noise)
TOL_RECIPROCITY = 2e-2  # max |S - S^T|; looser than a cycled run, which the validation put at 1e-4 or below


def check_network(net):
    # Reciprocity, passivity and the power balance of a terminal network.
    s = net.s
    reciprocity = float(np.abs(s - s.transpose(0, 2, 1)).max())
    sigma_max = float(np.linalg.svd(s, compute_uv=False).max())
    power_out = (np.abs(s) ** 2).sum(
        axis=1
    )  # power leaving the network per unit power into each port
    return {
        "reciprocity": reciprocity,
        "sigma_max": sigma_max,
        "power_out": (float(power_out.min()), float(power_out.max())),
        "passive": sigma_max <= 1.0 + TOL_PASSIVITY,
        "reciprocal": reciprocity <= TOL_RECIPROCITY,
    }


def print_checks(report):
    print(
        f"reciprocity, max |S - S^T|:             {report['reciprocity']:.2e}   (limit {TOL_RECIPROCITY:g}: {'ok' if report['reciprocal'] else 'CHECK'})"
    )
    print(
        f"passivity, largest singular value of S: {report['sigma_max']:.5f}   (limit {1 + TOL_PASSIVITY:g}: {'ok' if report['passive'] else 'CHECK'})"
    )
    print(
        f"power out per power in, per port:       {report['power_out'][0]:.3f} to {report['power_out'][1]:.3f}"
    )
```

```python
print_checks(check_network(net))
```

```text
reciprocity, max |S - S^T|:             5.94e-05   (limit 0.02: ok)
passivity, largest singular value of S: 1.00000   (limit 1.001: ok)
power out per power in, per port:       0.977 to 0.986
```

## 8\. Mixed-mode (differential and common) S-parameters

`mixed_mode` turns pairs of terminals into a differential port (voltage difference, reference impedance 2 Z) and a common port (mean voltage, Z / 2). The differential ports come first, then the common ports. The line is mirror-symmetric, so the conversion between the two should be small.

```python
PAIRS = [("o1:S1", "o1:S2"), ("o2:S1", "o2:S2")]
DD1, DD2, CC1, CC2 = range(
    4
)  # port order of mixed_mode: differential o1, o2, then common o1, o2


def plot_mixed(mm):
    freq_ghz = mm.f / 1e9
    fig, axes = plt.subplots(1, 2, figsize=(11, 4))
    for name, (i, j) in {"differential": (DD2, DD1), "common": (CC2, CC1)}.items():
        axes[0].plot(
            freq_ghz,
            20 * np.log10(np.abs(mm.s[:, i, j]) + 1e-15),
            "o-",
            label=f"|S21|, {name}",
        )
        axes[0].plot(
            freq_ghz,
            20 * np.log10(np.abs(mm.s[:, j, j]) + 1e-15),
            "s--",
            label=f"|S11|, {name}",
        )
        axes[1].plot(
            freq_ghz,
            np.degrees(np.unwrap(np.angle(mm.s[:, i, j]))),
            "o-",
            label=f"arg S21, {name}",
        )
    axes[0].plot(
        freq_ghz,
        20 * np.log10(np.abs(mm.s[:, CC1, DD1]) + 1e-15),
        "k:",
        label="|S_cd11|, mode conversion",
    )
    axes[0].set_xlabel("f (GHz)")
    axes[0].set_ylabel("dB")
    axes[1].set_xlabel("f (GHz)")
    axes[1].set_ylabel("phase (deg)")
    for ax in axes:
        ax.legend(fontsize=7)
        ax.grid(alpha=0.3)
    plt.tight_layout()
    return fig


def conversion_db(mm):
    # largest |S_cd11| (common out, differential in) in dB
    return float(20 * np.log10(np.abs(mm.s[:, CC1, DD1]).max() + 1e-15))
```

```python
mm = mixed_mode(net, PAIRS)
print("mixed-mode ports:", mm.port_names)
print("reference impedances (ohm):", np.round(mm.z0[0].real, 1))
plot_mixed(mm)
plt.show()
print(f"largest |S_cd11| (common out, differential in): {conversion_db(mm):.1f} dB")
```

```text
mixed-mode ports: ['d(o1:S1,o1:S2)', 'd(o2:S1,o2:S2)', 'c(o1:S1,o1:S2)', 'c(o2:S1,o2:S2)']
reference impedances (ohm): [100. 100.  25.  25.]
```

![svg](<https://gdsfactory.com/gsim/nbs/palace_terminal_waveport_gssg_files/palace_terminal_waveport_gssg_27_1.svg>)

```text
largest |S_cd11| (common out, differential in): -65.9 dB
```

## 9\. Check against a uniform line

The line is uniform and mirror-symmetric, so it decouples into its differential and common modes, each a section of line with \\(S\_{21} = e^{-\\gamma L}\\). Two comparisons use only the 2D solve, so they cost no extra job:

- **Propagation constant.** \\(\\gamma\\) of each mixed-mode two-port follows from its ABCD parameters (\\(A = \\cosh \\gamma L\\), independent of the reference impedance), valid while \\(\\beta L \< \\pi\\) (here \\(\\beta L\\) stays below 1 rad up to 50 GHz). It is compared with \\(j k\_0 n\_\\mathrm{eff}\\) of the 2D solve. Both sides have perfect conductors (section 3), so the comparison is like for like: the line has no conductor loss outside the vias, and a difference is a numerical one (mesh, mode pairing, terminal-S machinery), not a difference of physics. Each mode gives the difference of the phase of \\(S\_{21}\\) (degrees) and \\(|\\Delta S\_{21}|\\), where \\(S\_{21} = e^{-\\gamma L}\\) is taken from the 3D run and from the 2D solve.
- **Terminal S.** The lossless uniform line built from the 2D data alone, `modal_to_terminal_s(uniform_line_modal_s(gamma_2D, L), T_V, T_I)`, against the terminal S of the 3D run.

The pass criteria are the level of the method's validation on a tied GSSG line (phase within 0.3 degrees and \\(|\\Delta S\_{21}|\\) within about \\(6\\times10^{-3}\\)), with a little room: **phase within 1 degree, \\(|\\Delta S\_{21}|\\) within 0.02** (`TOL_PHASE_DEG`, `TOL_DS21`). They are printed as `ok` or `CHECK`.

```python
def line_gamma(mm, length_m):
    # gamma (1/m) of the differential and common mode from the ABCD parameters of their two-ports
    out = {}
    for name, ports in (("differential", [DD1, DD2]), ("common", [CC1, CC2])):
        a = mm.subnetwork(ports).a[:, 0, 0]
        out[name] = np.arccosh(a + 0j) / length_m
    return out


def uniform_line_terminal_s(result, modes_2d, length_m):
    # Terminal S of the lossless uniform line described by the 2D solve, in the gauge and mode order of the 3D run.
    n_modes = modes_2d[0].n_eff.size
    pairing = np.array(
        result.aligned["o1"].pairing[0]
    )  # 2D mode paired with each 3D mode
    k0 = 2 * np.pi * result.freq_ghz * 1e9 / C0
    gamma = 1j * k0[:, None] * modes_2d[0].n_eff[pairing][None, :]
    s_modal = uniform_line_modal_s(gamma, length_m)
    assert s_modal.shape[1] == 2 * n_modes
    return modal_to_terminal_s(
        s_modal,
        [result.aligned["o1"].t_v, result.aligned["o2"].t_v],
        [result.aligned["o1"].t_i, result.aligned["o2"].t_i],
        z_ref=result.z_ref,
    )


def uniform_line_report(mm, net, result, modes_2d, length_m):
    # Rows of (f_GHz, mode, n_eff 3D, n_eff 2D PEC, S21 phase difference in degrees, |dS21|) and the worst terminal-S gap.
    kinds = mode_kinds(modes_2d[0].t_v)
    n_2d = {kind: float(n) for kind, n in zip(kinds, modes_2d[0].n_eff, strict=True)}
    gamma = line_gamma(mm, length_m)
    rows = []
    for i, f in enumerate(mm.f):
        k0 = 2 * np.pi * f / C0
        for name, g3 in gamma.items():
            g2 = 1j * k0 * n_2d[name]
            s3, s2 = np.exp(-g3[i] * length_m), np.exp(-g2 * length_m)
            rows.append(
                (
                    f / 1e9,
                    name,
                    float((g3[i] / (1j * k0)).real),
                    n_2d[name],
                    float(np.degrees(np.angle(s3 / s2))),
                    float(abs(s3 - s2)),
                )
            )
    s_ref = uniform_line_terminal_s(result, modes_2d, length_m)
    gap = float(np.abs(net.s - s_ref).max())
    return rows, gap


TOL_PHASE_DEG = 1.0  # largest |phase(S21 3D / S21 2D)| over modes and frequencies; the method's validation gave <= 0.3
TOL_DS21 = 0.02  # largest |S21 3D - S21 2D|; the validation gave <= 6e-3


def uniform_line_verdict(rows):
    # Worst phase and amplitude difference of the rows of uniform_line_report, with ok / CHECK against the tolerances.
    phase = max(abs(r[4]) for r in rows)
    ds21 = max(r[5] for r in rows)
    return {
        "phase": phase,
        "ds21": ds21,
        "phase_ok": phase <= TOL_PHASE_DEG,
        "ds21_ok": ds21 <= TOL_DS21,
    }


def print_verdict(verdict):
    flag = lambda ok: "ok" if ok else "CHECK"  # noqa: E731
    print(
        f"largest S21 phase difference: {verdict['phase']:.2f} deg   (limit {TOL_PHASE_DEG:g}: {flag(verdict['phase_ok'])})"
    )
    print(
        f"largest |dS21|:               {verdict['ds21']:.1e}   (limit {TOL_DS21:g}: {flag(verdict['ds21_ok'])})"
    )
```

```python
rows, gap = uniform_line_report(mm, net, result, modes_2d, LENGTH * 1e-6)
print(
    f"{'f (GHz)':>8s} {'mode':>13s} {'n_eff 3D':>9s} {'n_eff 2D':>9s} {'dphase (deg)':>13s} {'|dS21|':>9s}"
)
for f, name, n3, n2, dphase, ds21 in rows:
    print(f"{f:8g} {name:>13s} {n3:9.4f} {n2:9.4f} {dphase:+13.2f} {ds21:9.1e}")
print()
print_verdict(uniform_line_verdict(rows))
print(
    f"largest |S_terminal(3D) - S_terminal(uniform line from the 2D solve)|: {gap:.2e}"
)
```

```text
 f (GHz)          mode  n_eff 3D  n_eff 2D  dphase (deg)    |dS21|
      10  differential    1.9228    1.9114         -0.04   8.8e-03
      10        common    1.9352    1.9289         -0.02   4.0e-04
      20  differential    1.9182    1.9114         -0.05   9.0e-03
      20        common    1.9345    1.9289         -0.04   7.0e-04
      30  differential    1.9173    1.9114         -0.06   9.1e-03
      30        common    1.9343    1.9289         -0.06   1.0e-03
      40  differential    1.9170    1.9114         -0.08   9.2e-03
      40        common    1.9343    1.9289         -0.08   1.4e-03
      50  differential    1.9169    1.9114         -0.10   9.2e-03
      50        common    1.9343    1.9289         -0.10   1.7e-03

largest S21 phase difference: 0.10 deg   (limit 1: ok)
largest |dS21|:               9.2e-03   (limit 0.02: ok)
largest |S_terminal(3D) - S_terminal(uniform line from the 2D solve)|: 1.84e-02
```

## Notes and limits

- **Mesh.** The 3D mesh is 2 um near the metal, which resolves the 4 um via walls (at 5 um gsim warns that they are under-resolved). The 2D `n_eff` (PEC conductors) must match the 3D port `n_eff` within the pairing tolerance (`PAIRING_RTOL`, 2 % here, 0.5 % by default) or `build_terminal_s` refuses to pair the modes; refine `refined_mesh_size` if it does.
- **Metal model.** Both the 2D solve and the 3D run use perfect conductors (section 3). With the finite conductivity gsim uses by default for a driven run, \\(n\_\\mathrm{eff}\\) is higher (internal inductance) and the line has conductor loss; for that line compare with a lossy 2D solve at every frequency instead, which costs one 2D job per frequency.
- **Single run or cycling.** The columns of the modal S come from the run in which the mode is active. This notebook uses one run (mode 1 active, both entries excited), so only its mode-1 columns are exact. For exact columns for every mode, run once per mode with that mode active and `excite="active"`, and pass all the runs to `build_terminal_s`.
- **Grounds.** Floating outer grounds are extra conductors and need their own terminal (a GSSG line with floating grounds has three terminals and three modes). Tying the grounds, as here, gives two.
- **Adaptive sampling** interpolates S between solved points but the wave numbers come only from solved points, so keep `adaptive_tol=0` for the runs that feed `build_terminal_s`.
- **One 2D solve.** The \\(T\_V\\) and \\(T\_I\\) of PEC modes hardly depend on frequency; with several solves `build_terminal_s` interpolates them in \\(1/f\\).
- **Reference impedance** must be real and positive; `mixed_mode` needs equal values on the two terminals of a pair.
- The terminal S is written as a Touchstone file (`coupled_gssg.s4p`) that scikit-rf and circuit simulators read.
