Topology optimization of a layer: a band-stop line#

Question. A parallel-plate line carries a TEM wave between two ports. Its middle 20 mm is a dielectric layer we may pattern freely with a ceramic (\(\varepsilon_r = 10\)) or leave as air. Which pattern, fabricable with a minimum feature size of about 1.5 mm and tolerant to over- and under-etching, passes 5 GHz and blocks 8 GHz?

We let gradients find it. The design is a planar pixel image of the layer, so the pattern is constant through the layer’s thickness, as a lithographic process makes it. The chain from pixels to the objective is differentiable end to end:

pixels \(\rho\) → Helmholtz filter (length scale) → projection (towards ceramic / air) → layer grid to the mesh → material field \(\varepsilon_r\) → gfem.solve() → \(S_{21}\).

The optimizer is not part of gfem: here it is optax’s Adam.

Assumptions.

  • Perfectly conducting plates, with the electric field along z between them and uniform across the gap. The line is then a 2D model in top view, in the \((x, y)\) plane with polarization="Ez", and the plates leave the model.

  • The side walls are left unassigned, so they are magnetic walls (PMC) and the empty line carries an exact TEM wave.

  • Lossless media; each port launches and absorbs the TEM mode of the empty line, so it is matched to it.

  • The mesh (0.5 mm × 1 mm cells, two triangles each, second-order elements) resolves the guided wavelength (≥ 12 mm in ceramic at 8 GHz) well enough for a design study. Check a final design on a finer mesh.

Conventions. SI units at the API (the mesh file is in mm), time dependence \(e^{+i\omega t}\). A 2D model’s powers and fields are per metre along z: each port is fed 1 W/m of mode power, and S-parameters are power waves normalized to it. \(|S_{21}|^2\) is then the fraction of the incident power delivered to port 2. See gfem.conventions.

from pathlib import Path

import jax
import jax.numpy as jnp
import matplotlib.pyplot as plt
import numpy as np
import optax
from contourpy import contour_generator

import gfem
from gfem import design

GHz, mm = 1e9, 1e-3

The line#

The mesh is the line in top view, a 40 mm × 6 mm rectangle of triangles: area "design" between \(x = 10\) mm and 30 mm, "feed" on both sides, port lines "port1" (\(x = 0\)) and "port2" (\(x = 40\) mm) across the width, and "side", the two long edges. The notebook reads it from data/line2d.msh. Each port’s mode is the TEM mode, uniform across the width, so its effective index in air is 1.

mesh = gfem.Mesh.from_gmsh(Path("data/line2d.msh"), length_unit="mm")

AIR = gfem.Material(name="air")
CERAMIC = gfem.Material(eps_r=10.0, name="ceramic")

line = gfem.Model(
    mesh,
    materials={"feed": AIR, "design": AIR},
    ports=[gfem.WavePort("p1", "port1"), gfem.WavePort("p2", "port2")],
)
mode = gfem.solve(line, gfem.PortMode("p1", 5 * GHz, polarization="Ez"))
print(f"n_eff (p1, 5 GHz) = {float(np.real(mode.n_eff[0])):.6f}")
line
n_eff (p1, 5 GHz) = 1.000000
Model(Mesh(567 nodes, 960 triangles, volumes=['feed', 'design'], surfaces=['side', 'port1', 'port2'], length_unit='mm')
  materials:
    feed: Material(name='air')
    design: Material(name='air')
  ports:
    WavePort(name='p1', surface='port1', mode=1, offset=0.0, voltage_path=None, pec_edges=())
    WavePort(name='p2', surface='port2', mode=1, offset=0.0, voltage_path=None, pec_edges=())
  default PMC (electromagnetic problems): side)

The mesh: the design area (light) between the air feeds (dark), every triangle drawn, and the two port lines (red).

xy = np.asarray(mesh.nodes) / mm
shade = np.zeros(len(mesh.volume_elements))
shade[mesh.elements("feed")], shade[mesh.elements("design")] = 0.2, 0.8
fig, ax = plt.subplots(figsize=(7, 1.6))
ax.tripcolor(
    *xy.T,
    mesh.volume_elements,
    facecolors=shade,
    cmap="gray",
    vmin=0,
    vmax=1,
    edgecolors="#c4c4c4",
    linewidth=0.3,
)
for port in ("port1", "port2"):
    ends = xy[mesh.surface_elements[mesh.elements(port)]].reshape(-1, 2)
    lo, hi = ends.min(axis=0), ends.max(axis=0)
    ax.plot([lo[0], hi[0]], [lo[1], hi[1]], color="#b5262f", ls="-", lw=3)
ax.set_aspect("equal")
ax.grid(False)
ax.set_xlabel("x (mm)")
ax.set_ylabel("y (mm)");
Plot of y (mm) against x (mm) Plot of y (mm) against x (mm)

From pixels to a material#

LayerGrid lays square pixels of side pitch over the design area; the solve reads the bilinear interpolation of the pixel values at several points inside each triangle. Pixels no point reaches would get no gradient, and the grid warns about them.

The Helmholtz filter smooths the pixel image over radius (it solves \(-r^2 \nabla^2\tilde{\rho} + \tilde{\rho} = \rho\) with \(r = \mathrm{radius} / 2\sqrt{3}\)): features much smaller than the radius cannot appear. robust then projects the filtered image at three thresholds: the eroded (over-etched), nominal and dilated (under-etched) designs. Optimizing the worst of the three makes the design tolerate the etch, and guarantees the length scale on both the ceramic and the air.

grid = design.LayerGrid(mesh, "design", pitch=0.5 * mm)
blur = design.helmholtz_filter(grid, radius=1.5 * mm)
grid
LayerGrid('design', pitch=0.0005 m, shape=(12, 40), 480 elements)

The objective#

For one design density we solve at the pass and the stop frequency and read \(S_{21}\). The loss is the power that misses its target: \(1 - |S_{21}(5\,\mathrm{GHz})|^2 + |S_{21}(8\,\mathrm{GHz})|^2\), zero for an ideal band-stop.

jax.vmap() runs the three robust designs through gfem.solve (one after the other); the worst one is the objective. A direct solver suits these small, repeated solves.

PASS, STOP = 5 * GHz, 8 * GHz
problem = gfem.Driven(frequency=(PASS, STOP), excite="p1", polarization="Ez")
options = gfem.SolverOptions(linear_solver="direct")


def material(density):
    """The design area's permittivity field: 0 air, 1 ceramic, per pixel."""
    return gfem.MaterialField.interpolate(grid.to_elements(density), AIR, CERAMIC)


def s21_of_field(eps):
    result = gfem.solve(line.with_material("design", eps), problem, options=options)
    return result.s["p2", "p1"]  # (2,): at PASS, STOP


def s21(density):
    return s21_of_field(material(density))


def missed_power(t):
    """The power that misses the band-stop target, from S21 at (PASS, STOP)."""
    return 1 - jnp.abs(t[..., 0]) ** 2 + jnp.abs(t[..., 1]) ** 2


DELTA = 0.15  # the etch: thresholds 0.5 - DELTA (dilated), 0.5 + DELTA (eroded)


def loss(rho, beta):
    designs = jnp.stack(design.robust(blur(rho), beta=beta, delta=DELTA))
    t = jax.vmap(s21)(designs)  # (3, 2): eroded, nominal, dilated
    missed = missed_power(t)
    return jnp.max(missed), missed


value_and_grad = jax.jit(jax.value_and_grad(loss, has_aux=True))

Optimize#

Adam on the raw pixels, clipped to [0, 1], starting from a grey layer with a little noise to break the symmetry. The projection sharpness \(\beta\) is doubled every 12 steps (continuation): a soft projection first lets material move, a sharp one at the end makes the design binary. A few minutes on a laptop.

rho0 = 0.5 + 0.01 * jax.random.normal(jax.random.key(0), grid.shape)
BETAS, STEPS_PER_BETA = (2.0, 4.0, 8.0, 16.0), 12
rho = rho0
optimizer = optax.adam(0.05)
state = optimizer.init(rho)
history = []
for beta in BETAS:
    for _ in range(STEPS_PER_BETA):
        (worst, missed), g = value_and_grad(rho, beta)
        updates, state = optimizer.update(g, state)
        rho = jnp.clip(optax.apply_updates(rho, updates), 0.0, 1.0)
        history.append(np.asarray(missed))
    print(
        f"beta = {beta:4.0f}: missed power (eroded, nominal, dilated) = "
        f"{np.array2string(np.asarray(missed), precision=4)}"
    )
beta =    2: missed power (eroded, nominal, dilated) = [0.0452 0.0462 0.0694]
beta =    4: missed power (eroded, nominal, dilated) = [0.0262 0.0254 0.049 ]
beta =    8: missed power (eroded, nominal, dilated) = [0.0266 0.0183 0.0196]
beta =   16: missed power (eroded, nominal, dilated) = [0.0202 0.0173 0.0167]
fig, ax = plt.subplots(figsize=(6, 3))
ax.semilogy(np.array(history), label=["eroded", "nominal", "dilated"])
ax.set_xlabel("iteration")
ax.set_ylabel("missed power fraction")
ax.legend()
ax.grid(alpha=0.3);
Plot of missed power fraction against iteration Plot of missed power fraction against iteration

The design#

The final pixels, filtered and projected at a sharp \(\beta\), give the three fabricated variants. White is ceramic, black is air; the wave travels along x.

final = design.robust(blur(rho), beta=64.0, delta=DELTA)
extent = (
    np.array(
        [
            grid.origin[0],
            grid.origin[0] + grid.shape[1] * grid.pitch,
            grid.origin[1],
            grid.origin[1] + grid.shape[0] * grid.pitch,
        ]
    )
    / mm
)
fig, axes = plt.subplots(3, 1, figsize=(7, 4.5), sharex=True)
for ax, name, image in zip(axes, final._fields, final, strict=True):
    ax.imshow(image, origin="lower", extent=extent, cmap="gray", vmin=0, vmax=1)
    ax.set_title(name, fontsize=10)
    ax.set_ylabel("y (mm)")
axes[-1].set_xlabel("x (mm)")
fig.tight_layout()
Plot of eroded; nominal; dilated: y (mm) against x (mm) Plot of eroded; nominal; dilated: y (mm) against x (mm)

The transmission spectrum#

A sweep of the nominal design (and of its eroded and dilated variants) shows the stop band around 8 GHz while 5 GHz passes. The check here is physical: the line is lossless and both ports are matched, so \(|S_{11}|^2 + |S_{21}|^2 = 1\) at every frequency.

sweep = gfem.Driven(
    frequency=np.linspace(2, 10, 33) * GHz, excite="p1", polarization="Ez"
)
fig, ax = plt.subplots(figsize=(6, 3.5))
for name, image in zip(final._fields, final, strict=True):
    eps = gfem.MaterialField.interpolate(grid.to_elements(image), AIR, CERAMIC)
    s = gfem.solve(line.with_material("design", eps), sweep, options=options).s
    s11, s21_ = np.asarray(s["p1", "p1"]), np.asarray(s["p2", "p1"])
    ax.plot(np.asarray(sweep.frequency) / GHz, 20 * np.log10(np.abs(s21_)), label=name)
    if name == "nominal":
        balance = np.max(np.abs(np.abs(s11) ** 2 + np.abs(s21_) ** 2 - 1))
for f in (PASS, STOP):
    ax.axvline(f / GHz, color="k", lw=0.8, ls=":")
ax.set_xlabel("frequency (GHz)")
ax.set_ylabel("|S21| (dB)")
ax.legend()
ax.grid(alpha=0.3)
print(f"max | |S11|^2 + |S21|^2 - 1 | (nominal) = {balance:.1e}")
max | |S11|^2 + |S21|^2 - 1 | (nominal) = 6.7e-12
Plot of |S21| (dB) against frequency (GHz) Plot of |S21| (dB) against frequency (GHz)

The fields#

One more solve of the nominal design keeps the electric fields (keep_fields=True). Below is \(E_z\) at \(t = 0\), \(\mathrm{Re}(E_z)\), sampled with Field.at on the plane, for 1 W/m incident at port 1, from black (negative) to white (positive); the blue lines are the ceramic’s edge, the pixels’ 0.5 contour. At 5 GHz the wave crosses the line at full amplitude. At 8 GHz the ceramic stack reflects it: a standing wave on the port 1 side, decaying through the stack. The field is uniform across y, as the TEM mode is, so the optimizer had no reason to pattern the layer along y: the result is a 1D stack, a Bragg reflector.

eps = gfem.MaterialField.interpolate(grid.to_elements(final.nominal), AIR, CERAMIC)
keep = gfem.Driven(
    frequency=(PASS, STOP), excite="p1", keep_fields=True, polarization="Ez"
)
fields = gfem.solve(line.with_material("design", eps), keep, options=options)
X, Y = np.meshgrid(np.linspace(0, 40, 321) * mm, np.linspace(0, 6, 49) * mm)
plane = np.stack([X.ravel(), Y.ravel()], axis=1)  # (x, y) points of the 2D model
edge = contour_generator(grid.x / mm, grid.y / mm, np.asarray(final.nominal)).lines(0.5)

fig, axes = plt.subplots(2, 1, figsize=(7, 3.4), sharex=True, layout="constrained")
for ax, e, (f, _) in zip(axes, fields.e_fields, fields.kept, strict=True):
    ez = np.asarray(e.at(plane)).real.reshape(X.shape)
    peak = np.abs(ez).max()
    image = ax.imshow(
        ez, origin="lower", extent=(0, 40, 0, 6), cmap="gray", vmin=-peak, vmax=peak
    )
    for segment in edge:
        ax.plot(*segment.T, color="C0", ls="-", lw=0.8)
    ax.set_title(f"{f / GHz:.0f} GHz", fontsize=10)
    ax.set_ylabel("y (mm)")
    ax.grid(False)
    fig.colorbar(image, ax=ax, label="Re E_z (V/m)")
axes[-1].set_xlabel("x (mm)");
Plot of 5 GHz; 8 GHz: y (mm) against x (mm); Re E_z (V/m); Re E_z (V/m) Plot of 5 GHz; 8 GHz: y (mm) against x (mm); Re E_z (V/m); Re E_z (V/m)

Limits#

  • The design is only as good as the mesh: the optimizer exploits discretization error. Re-check the final design on a refined mesh (and with order=3).

  • The 2D model holds while nothing varies between the plates. Posed in 3D, between plates 1 mm apart with lumped ports matched to the line, the empty line and a uniform ceramic section give the same S to \(10^{-3}\) (How gfem is checked). Fringing fields, a finite plate width and a layer thinner than the gap need the 3D model.

  • radius sets a length scale through the filter and the robust thresholds, not a hard design rule; hold a foundry’s minimum width and spacing with design.length_scale_constraints and confirm them with LayerPattern.check (Optimize a design for fabrication: etch, blur and minimum features).

  • jax.vmap over gfem.solve runs the three designs one after the other. Every iteration costs three solves per frequency.

  • Recipes on the pixel array: pin regions with jnp.where(mask, 1.0, rho) before the filter (feed connections), or exactly, as area fractions of the real neighbours (grid.area_fraction), impose a mirror symmetry with (rho + rho[:, ::-1]) / 2, and mask pixels outside a non-rectangular footprint with grid.sampled.

Next#