Shape optimization of a coplanar line: matching it to 50 Ω#
Question. A conductor-backed coplanar waveguide (CPW) on a 100 µm substrate (\(\varepsilon_r = 4\)) has a 50 µm signal strip and 30 µm gaps. Fed and terminated by 50 Ω lumped ports, it reflects part of the power: its characteristic impedance is not 50 Ω. How should the gaps change along the line so that it reflects as little as possible between 20 and 60 GHz?
We let gradients find it. The design moves the signal strip’s sidewalls through
gfem.shape.boundary_morph(): a fixed linear map, built once on the imported mesh,
from normal displacements of the wall’s nodes to the node coordinates of a moved
mesh. jax.grad differentiates the whole chain, from a few design parameters
through the morph and the driven solve to \(|S_{11}|^2\). The mesh is never regenerated, so
each step is checked against the mesh quality before it is taken.
The page goes: the line → how a few numbers move its walls → the objective → the optimization → the optimized strip next to the initial one, in plan and in 3D → the reflection spectrum → the fields on the line before and after.
import warnings
from pathlib import Path
import jax
import jax.numpy as jnp
import matplotlib.pyplot as plt
import numpy as np
import pyvista as pv
from matplotlib.patches import Rectangle
import gfem
from gfem import shape
pv.set_jupyter_backend("static")
GHz, um = 1e9, 1e-6
METAL, PORT = "C3", "#b5262f" # plots: conductors (amber) and ports (red)
GOLD = "#d4a017" # the conductors in the 3D views
The line#
The mesh, data/cpw.msh, is a 1.5 mm long line along x, 600 µm wide and
300 µm tall. The cross-section below is the same all along the initial line. The
metal layer (\(100\,\mu\mathrm{m} < z < 105\,\mu\mathrm{m}\)) holds the signal strip (\(|y| < 25\) µm) and the
ground planes (\(|y| > 55\) µm); the backside (\(z = 0\)) is a third ground. Each port is a
pair of 50 Ω lumped elements across the two gaps at one end (\(x = 0\) for p1,
\(x = 1.5\) mm for p2), excited from the signal towards the grounds.
fig, ax = plt.subplots(figsize=(7, 3.2))
ax.add_patch(Rectangle((-150, 0), 300, 100, color="C0", alpha=0.25, lw=0))
ax.text(-140, 50, "substrate\nε_r = 4", va="center")
ax.text(-140, 140, "air", va="center")
for y0, width in ((-25, 50), (55, 95), (-150, 95)): # signal, two grounds
ax.add_patch(Rectangle((y0, 100), width, 5, color=METAL, lw=0))
ax.plot([-150, 150], [0, 0], color=METAL, lw=4)
for y0, name in ((0, "signal"), (100, "ground"), (-100, "ground")):
ax.text(y0, 110, name, ha="center", va="bottom")
ax.text(0, -10, "backside ground (z = 0)", ha="center", va="top")
def dimension(a, b, at, text, vertical=False):
start, end = ((at, a), (at, b)) if vertical else ((a, at), (b, at))
ax.annotate("", start, end, arrowprops={"arrowstyle": "<->", "lw": 0.8})
if vertical:
ax.text(at - 3, (a + b) / 2, text, ha="right", va="center", fontsize=8)
else:
ax.text((a + b) / 2, at - 3, text, ha="center", va="top", fontsize=8)
dimension(-25, 25, 92, "50 µm")
dimension(25, 55, 92, "30 µm")
dimension(-55, -25, 92, "30 µm")
dimension(0, 100, 135, "100 µm", vertical=True)
for a, b in ((25, 55), (-25, -55)): # the lumped elements, signal -> ground
ax.annotate(
"",
(b, 102.5),
(a, 102.5),
arrowprops={"arrowstyle": "->", "color": PORT, "lw": 1.5},
)
ax.text(30, 150, "port: 50 Ω across each gap,\nsignal → ground", color=PORT, fontsize=8)
ax.set(
xlim=(-150, 150), ylim=(-25, 165), aspect="equal", xlabel="y (um)", ylabel="z (um)"
)
ax.grid(False);
mesh = gfem.Mesh.from_gmsh(Path("data/cpw.msh"), length_unit="um")
line = gfem.Model(
mesh,
materials={"substrate": gfem.Material(eps_r=4.0), "air": gfem.Material()},
excluded=("signal_metal", "ground_metal"),
boundaries=[
gfem.PEC("signal"),
gfem.PEC("signal_wall"),
gfem.PEC("ground"),
gfem.PEC("backside"),
gfem.Absorbing("top"),
gfem.Absorbing("side"),
],
ports=[
gfem.LumpedPort("p1", ("p1a", "p1b"), ("+y", "-y"), impedance=50.0),
gfem.LumpedPort("p2", ("p2a", "p2b"), ("+y", "-y"), impedance=50.0),
],
)
line
Model(Mesh(495 nodes, 1920 tetrahedra, volumes=['substrate', 'ground_metal', 'air', 'signal_metal'], surfaces=['ends', 'side', 'backside', 'ground', 'top', 'p1b', 'substrate_top', 'signal', 'signal_wall', 'p1a', 'p2b', 'p2a'], length_unit='um')
materials:
substrate: Material(eps_r=4.0)
air: Material()
excluded (electromagnetic): ground_metal entity 2, signal_metal entity 4 (from 'signal_metal', 'ground_metal')
boundaries:
PEC(surface='signal')
PEC(surface='signal_wall')
PEC(surface='ground')
PEC(surface='backside')
Absorbing(surface='top', order=1)
Absorbing(surface='side', order=1)
ports:
LumpedPort(name='p1', surface=('p1a', 'p1b'), direction=((0.0, 1.0, 0.0), (0.0, -1.0, 0.0)), resistance=None, inductance=None, capacitance=None, impedance=50.0)
LumpedPort(name='p2', surface=('p2a', 'p2b'), direction=((0.0, 1.0, 0.0), (0.0, -1.0, 0.0)), resistance=None, inductance=None, capacitance=None, impedance=50.0)
default PMC (electromagnetic problems): ends)
The same line in 3D: the substrate (blue, see-through), the conductors (gold) and the four lumped-element faces of the ports (red, 30 µm × 5 µm, in the gaps at both ends: zoom in on an end to see them). The box around it is the air; its top and sides absorb, and its two ends are the default PMC.
VIEW = (-1.0, -0.55, 0.55) # the camera's direction: from the p1 end, above
def part(region, on=mesh):
"""A region of a mesh as a PyVista grid, in um."""
grid = pv.from_meshio(on.to_meshio()) # tetrahedra first, then triangles
grid.points /= um
cells = on.elements(region)
if region in on.surfaces:
cells = cells + len(on.tetrahedra)
return grid.extract_cells(cells)
view = pv.Plotter(window_size=(900, 450))
view.add_mesh(part("substrate"), color="#7fa7c9", opacity=0.3)
view.add_mesh(part("signal_metal"), color=GOLD)
for region in ("ground_metal", "backside"):
view.add_mesh(part(region), color=GOLD, opacity=0.7)
for face in ("p1a", "p1b", "p2a", "p2b"):
view.add_mesh(part(face), color=PORT)
view.add_mesh(part("air").outline(), color="black")
view.view_vector(VIEW, viewup=(0, 0, 1))
view.camera.zoom(1.5)
view.show()
The shape design#
boundary_morph moves the nodes of one surface, here "signal_wall", the strip’s
two sidewalls, each along its outward normal: a positive displacement moves the wall
into the gap, so the strip grows and the gap shrinks. The rest of the mesh follows a
stiffened elastic extension, and the surfaces play roles:
the port surfaces are held (always: gfem holds the model’s ports), so the wall’s nodes on them are not parameters and the ports keep their geometry;
fixed=("ground",)also holds the ground planes, so the gaps change only through the strip;every other named surface slides in its own plane: the substrate top, the strip’s top and bottom, the line’s ends and the outer box keep their planes.
One parameter per wall node is far too many to optimize directly, and a jagged wall would wreck the mesh. Four control values of the half-width change, spaced along the line and interpolated linearly at each node, make a smooth design.
morph = shape.boundary_morph(line, "signal_wall", fixed=("ground",))
x = morph.points[:, 0]
knots = np.linspace(x.min(), x.max(), 4)
def displacements(q):
# q: half-width changes in um at the knots -> t: metres at every wall node
return jnp.interp(x, knots, q) * um
print(f"{morph.n_params} moving nodes on {morph.surface!r}")
28 moving nodes on 'signal_wall'
What the four numbers do, on an example \(q = (6, -4, 2, 8)\) µm: the strip’s upper edge in plan (its lower edge is the mirror image). The control values (orange) sit on wall nodes; between them, and down to the held port ends at \(x = 0\) and \(x = 1.5\) mm, each wall node moves by the linear interpolation. The ground edge does not move, so the gap is 55 µm minus the strip’s half-width.
LENGTH = 1500 * um
along = np.linspace(0, LENGTH, 601)
def half_width(q, at):
# The strip's half-width (m) at x = at: 25 um plus the change, which ramps
# to zero at the held port ends.
return 25 * um + np.interp(at, np.r_[0, knots, LENGTH], np.r_[0, q, 0] * um)
example = np.array([6.0, -4.0, 2.0, 8.0])
upper = morph.points[:, 1] > 0 # wall nodes on the upper edge
moved = np.asarray(morph.points[upper, 1] + displacements(example)[upper])
fig, ax = plt.subplots(figsize=(7, 2.8))
ax.fill_between(along / um, 0, 25, color=METAL, alpha=0.35, lw=0, label="initial strip")
ax.plot(along / um, half_width(example, along) / um, color="C0", label="moved edge")
ax.plot(
x[upper] / um, moved / um, "o", ms=4, mfc="none", color="C0", label="wall nodes"
)
ax.plot(knots / um, 25 + example, "D", color="C1", label="control values q")
ax.axhline(55, color=METAL, lw=3)
ax.text(750, 56, "ground edge (held)", ha="center", va="bottom", fontsize=8)
ax.set(ylim=(15, 62), xlabel="x (um)", ylabel="y (um)")
ax.legend(loc="lower center", ncol=4, fontsize=7);
The objective#
The mean of \(|S_{11}|^2\) at 20, 40 and 60 GHz, with port 1 excited. A direct solver suits these small, repeated solves.
problem = gfem.Driven(frequency=(20 * GHz, 40 * GHz, 60 * GHz), excite="p1")
options = gfem.SolverOptions(linear_solver="direct")
def reflection(q):
designed = line.replace(mesh=morph(displacements(q)))
s11 = gfem.solve(designed, problem, options=options).s["p1", "p1"]
return jnp.mean(jnp.abs(s11) ** 2)
value_and_grad = jax.value_and_grad(reflection)
q = jnp.zeros(4)
j, g = value_and_grad(q)
print(f"reflected power {float(j):.4f}, gradient {np.asarray(g)} per um")
reflected power 0.0106, gradient [-0.00094833 -0.00117662 -0.00066771 -0.00032316] per um
Optimize, accepting steps on mesh quality#
A plain normalized gradient descent with a step radius \(r\) in µm. A trial step is taken only if
the mesh stays good:
gfem.shape.quality(), the scaled Jacobian of every tetrahedron, stays above a quarter of each element’s imported quality. Below that threshold gfem would warn (MeshQualityWarning), and an inverted element would raiseMeshQualityError;the objective decreases.
A rejected step halves \(r\); an accepted one lets it grow again. The quality check runs
before any solve, so a step that would degrade the mesh costs nothing. Called with
concrete values, the morph checks the moved mesh itself. It raises
MeshQualityError on an inverted element and warns below a quarter of the
imported quality; acceptable turns that error into a rejection. The first
trial step below is deliberately wider than the gaps.
q0 = shape.quality(line.mesh)
def acceptable(q):
try:
with warnings.catch_warnings():
warnings.simplefilter("ignore", gfem.MeshQualityWarning)
trial_mesh = morph(displacements(q))
except gfem.MeshQualityError: # the morph itself refuses inverted elements
return False
quality = shape.quality(trial_mesh)
return bool(jnp.all(quality > shape.WARN_QUALITY_RATIO * q0))
radius, history = 48.0, [float(j)] # a first step wider than the gap
for iteration in range(12):
direction = -g / jnp.linalg.norm(g)
rejected = []
while radius > 0.05:
trial = q + radius * direction
if not acceptable(trial):
rejected.append("quality")
elif float(reflection(trial)) >= j:
rejected.append("no decrease")
else:
break
radius /= 2
else:
print("no acceptable step: stop (or remesh and restart, see the recipe)")
break
q = trial
j, g = value_and_grad(q)
history.append(float(j))
note = f" (rejected first: {', '.join(rejected)})" if rejected else ""
print(
f"{iteration:2d}: reflected power {float(j):.2e}, "
f"half-width change {np.round(np.asarray(q), 2)} um{note}"
)
radius = min(1.5 * radius, 8.0)
0: reflected power 5.29e-03, half-width change [3.38 4.19 2.38 1.15] um (rejected first: quality, no decrease, no decrease)
1: reflected power 4.56e-03, half-width change [5.85 0.45 2.47 7.78] um
2: reflected power 8.98e-04, half-width change [8.2 3.27 2.28 6.19] um (rejected first: no decrease)
3: reflected power 5.02e-04, half-width change [8.18 3.24 3.21 7.36] um (rejected first: no decrease, no decrease)
4: reflected power 3.09e-04, half-width change [9.2 3.61 2.92 7.48] um (rejected first: no decrease)
5: reflected power 1.97e-04, half-width change [9.17 3.34 3.28 8.2 ] um (rejected first: no decrease)
6: reflected power 1.35e-04, half-width change [9.73 3.59 3.12 8.2 ] um (rejected first: no decrease)
7: reflected power 9.93e-05, half-width change [9.71 3.44 3.32 8.6 ] um (rejected first: no decrease)
8: reflected power 7.96e-05, half-width change [10.03 3.58 3.24 8.6 ] um (rejected first: no decrease)
9: reflected power 6.86e-05, half-width change [10.01 3.49 3.35 8.82] um (rejected first: no decrease)
10: reflected power 6.24e-05, half-width change [10.19 3.56 3.31 8.81] um (rejected first: no decrease)
11: reflected power 5.90e-05, half-width change [10.18 3.51 3.38 8.93] um (rejected first: no decrease)
fig, ax = plt.subplots(figsize=(6, 3))
ax.semilogy(history, marker="o")
ax.set_xlabel("accepted step")
ax.set_ylabel("mean |S11|²")
ax.grid(alpha=0.3);
The design#
The optimized strip in plan (gold, solid edges) over the initial one (dashed): it widens most near the two ends and a little in the middle. The ports at both ends keep their 30 µm gaps.
designed = morph(displacements(q))
fig, ax = plt.subplots(figsize=(7, 3))
for side in (1, -1):
ax.fill_between(along / um, side * 55, side * 75, color=METAL, lw=0)
h = half_width(np.asarray(q), along) / um
ax.fill_between(along / um, -h, h, color=METAL, lw=0)
for style, edge, label in (
("-", h, "optimized"),
("--", np.full_like(h, 25), "initial"),
):
ax.plot(along / um, edge, style, color="k", lw=1, label=label)
ax.plot(along / um, -edge, style, color="k", lw=1)
ax.set(ylim=(-75, 75), xlabel="x (um)", ylabel="y (um)")
ax.legend(loc="center right")
ax.grid(False)
print(f"half-width change at the knots: {np.round(np.asarray(q), 2)} um")
print(f"narrowest gap: {30 - np.asarray(q).max():.1f} um")
ratio = np.asarray(shape.quality(designed) / q0)
print(f"worst element quality: {ratio.min():.2f} x its imported quality")
half-width change at the knots: [10.18 3.51 3.38 8.93] um
narrowest gap: 19.8 um
worst element quality: 0.65 x its imported quality
The moved mesh in 3D, the near half of the line from the p1 end: the substrate’s surface coloured by how far each node moved, the optimized strip in gold and the initial strip’s edges in black. The wall’s nodes move the most; the elastic extension spreads a smaller move into the substrate around them, which keeps the elements in the gap from being crushed.
moved_by = np.linalg.norm(np.asarray(designed.nodes) - np.asarray(mesh.nodes), axis=1)
substrate = part("substrate", on=designed).extract_surface(algorithm="dataset_surface")
substrate["node move (um)"] = moved_by[substrate["vtkOriginalPointIds"]] / um
view = pv.Plotter(window_size=(900, 450))
view.add_mesh(
substrate.clip_box((0, 800, -120, 120, 0, 110), invert=False),
scalars="node move (um)",
cmap="viridis",
show_edges=True,
)
view.add_mesh(
part("signal_metal", on=designed).clip_box(
(0, 800, -120, 120, 0, 110), invert=False
),
color=GOLD,
)
view.add_mesh(
part("signal_metal")
.extract_feature_edges()
.clip_box((0, 800, -120, 120, 0, 110), invert=False),
color="black",
line_width=2,
)
view.view_vector((-0.6, -1, 1.2), viewup=(0, 0, 1))
view.camera.zoom(1.4)
view.show()
The reflection spectrum#
A sweep of the initial and the optimized line. The match is broadband: a narrower gap lowers the line impedance towards 50 Ω at every frequency of the band.
sweep = gfem.Driven(frequency=np.linspace(10, 70, 13) * GHz, excite="p1")
fig, ax = plt.subplots(figsize=(6, 3.5))
for label, mesh_ in (("initial", line.mesh), ("optimized", designed)):
s = gfem.solve(line.replace(mesh=mesh_), sweep, options=options).s
s11 = np.asarray(s["p1", "p1"])
ax.plot(np.asarray(sweep.frequency) / GHz, 20 * np.log10(np.abs(s11)), label=label)
for f in problem.frequency:
ax.axvline(f / GHz, color="gray", lw=0.5)
ax.set_xlabel("frequency (GHz)")
ax.set_ylabel("|S11| (dB)")
ax.legend()
ax.grid(alpha=0.3);
The fields#
One more solve of each line at the three design frequencies, keeping the fields, with 1 W incident at p1. The voltage across the gap, \(V(x) = \int E_y \, dy\) from the strip’s edge to the ground’s edge, in the middle of the metal layer, is the line’s voltage: on a matched line its amplitude is flat along x, and a reflected wave makes it a standing wave. Along the initial line, the largest \(|V|\) exceeds the smallest by 14 to 17 %; along the optimized line, by 2 to 3 % at 20 and 40 GHz and 7 % at 60 GHz.
keep = gfem.Driven(frequency=problem.frequency, excite="p1", keep_fields=True)
lines = {
"initial": (np.zeros(4), gfem.solve(line, keep, options=options)),
"optimized": (
np.asarray(q),
gfem.solve(line.replace(mesh=designed), keep, options=options),
),
}
stations = np.linspace(0, LENGTH, 151)
def gap_voltage(field, q):
# |V(x)| across the upper gap, at mid-height of the metal layer.
v = []
for xi in stations:
ys = np.linspace(half_width(q, xi), 55 * um, 40)
points = np.c_[np.full_like(ys, xi), ys, np.full_like(ys, 102.5 * um)]
v.append(np.trapezoid(np.asarray(field.at(points))[:, 1], ys))
return np.abs(v)
fig, axes = plt.subplots(1, 3, figsize=(9, 2.8), sharey=True, layout="constrained")
for ax, f in zip(axes, problem.frequency, strict=True):
for label, (q_line, result) in lines.items():
ax.plot(
stations / um,
gap_voltage(result.e_field(f, excite="p1"), q_line),
label=label,
)
ax.set_title(f"{f / GHz:.0f} GHz")
ax.set_xlabel("x (um)")
axes[0].set_ylabel("|V| across the gap (V)")
axes[0].legend();
The field itself at 40 GHz, \(|E|\) on the plane through the middle of the metal layer, for the initial and the optimized line on one colour scale. The field lives in the gaps; where the optimized strip widens, its gaps narrow and the field there grows, at the same voltage.
F_SHOW = 40 * GHz
planes = {}
for label, (_, result) in lines.items():
field = result.e_field(F_SHOW, excite="p1").to_pyvista()
field.points /= um
field["E (kV/m)"] = (
np.linalg.norm(field["E_real"] + 1j * field["E_imag"], axis=1) / 1e3
)
planes[label] = field.slice(normal="z", origin=(0, 0, 102.5))
peak = max(plane["E (kV/m)"].max() for plane in planes.values())
for label, plane in planes.items():
on = designed if label == "optimized" else mesh
view = pv.Plotter(window_size=(900, 450))
view.add_mesh(
plane,
scalars="E (kV/m)",
cmap="magma",
clim=(0, peak),
scalar_bar_args={"title": f"field magnitude (kV/m), {label}", "fmt": "%.0f"},
)
for region in ("signal_metal", "ground_metal"):
view.add_mesh(part(region, on=on), color=GOLD)
view.view_vector((-0.5, -1, 1.6), viewup=(0, 0, 1))
view.camera.zoom(1.5)
view.show()
When the mesh runs out#
This design moved the walls by up to about 10 µm into 30 µm gaps, on cells 15 µm wide. Larger moves eventually degrade the mesh: the quality check above then rejects every step, and every solve warns. Then remesh at the current geometry with gsim and restart the optimizer from the current parameters, as the recipe remesh and restart shows.