Topology optimization of a waveguide bend: a 90° turn in a 3 µm square#
Question. Two waveguides 0.55 µm wide, core index 2.25 in a cladding of index 1.444, meet at a right angle. In the 3 µm × 3 µm square where they meet, each point may be core or cladding. Which pattern carries the most power at 1.55 µm from the fundamental mode of one guide into the fundamental mode of the other?
We let gradients find it. The design is a pixel image of the square, and the chain from pixels to the objective is differentiable end to end:
pixels \(\rho\) → Helmholtz filter (length scale) → projection (towards core /
cladding) → 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, as in the topology tutorial. At the end the design leaves the pixels: its drawn pattern, the polygons of core, is checked against a minimum width and spacing, written to a GDS file and solved again.
Assumptions.
A top view in effective indices: 2.25 and 1.444 stand for the vertical stack. gfem poses it as a 2D model in the \((x, y)\) plane: nothing varies along z, and the electric field is along z (
polarization="Ez").A second-order absorbing boundary closes the cladding 1 µm from the design square, instead of a PML.
Wave ports on the two guide ends, each a 2.2 µm line with conducting ends, launch and measure the fundamental mode.
Lossless media.
The mesh (triangles of at most 0.1 µm, second-order elements) resolves the guided wavelength (0.75 µm) 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 µm), 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 carried out of port 2 in its
fundamental mode, the same as for a structure of any height. See
gfem.conventions.
import tempfile
import time
from pathlib import Path
import jax
import jax.numpy as jnp
import matplotlib.pyplot as plt
import numpy as np
import optax
from scipy.constants import c
from scipy.optimize import brentq
import gfem
from gfem import design
um = 1e-6
WAVELENGTH = 1.55 * um
F0 = c / WAVELENGTH # 193.4 THz
The bend#
The mesh is a 5 µm × 5 µm square of triangles centred on the bend. Its areas are
"design" (\(|x|, |y| < 1.5\) µm), "core" (the input guide along \(x < -1.5\) µm and the
output guide along \(y < -1.5\) µm, both centred and 0.55 µm wide) and "cladding", the
rest. Its lines are the port lines "port1" (\(x = -2.5\) µm, \(|y| < 1.1\) µm) and
"port2" (\(y = -2.5\) µm, \(|x| < 1.1\) µm), and "outer", every other side. The
triangles are at most 0.1 µm, with node lines on the guide edges and the design
square’s sides. The notebook reads it from data/bend2d.msh.
The design area starts as cladding; the optimization replaces its material. Each
wave port solves a port mode problem on its line, whose ends on "outer" are
conducting (pec_edges). The guide’s fundamental mode, even with E along z, has a
closed form: \(\tan(\kappa w/2) = \gamma/\kappa\) with \(\kappa = k_0\sqrt{n_\mathrm{core}^2 - n_\mathrm{eff}^2}\) and
\(\gamma = k_0\sqrt{n_\mathrm{eff}^2 - n_\mathrm{cladding}^2}\). The port mode should give the same \(n_\mathrm{eff}\).
mesh = gfem.Mesh.from_gmsh(Path("data/bend2d.msh"), length_unit="um")
N_CORE, N_CLADDING, WIDTH = 2.25, 1.444, 0.55 * um
CLADDING = gfem.Material(eps_r=N_CLADDING**2, name="cladding")
CORE = gfem.Material(eps_r=N_CORE**2, name="core")
bend = gfem.Model(
mesh,
materials={"cladding": CLADDING, "core": CORE, "design": CLADDING},
boundaries=[gfem.Absorbing("outer", order=2)],
ports=[
gfem.WavePort("p1", "port1", pec_edges=("outer",)),
gfem.WavePort("p2", "port2", pec_edges=("outer",)),
],
)
def slab_index(n_core, n_cladding, width, wavelength):
# Even mode of a symmetric slab: tan(kappa w / 2) = gamma / kappa, on the
# fundamental branch kappa w / 2 < pi / 2.
k0 = 2 * np.pi / wavelength
def dispersion(n):
kappa = k0 * np.sqrt(n_core**2 - n**2)
gamma = k0 * np.sqrt(n**2 - n_cladding**2)
return np.tan(kappa * width / 2) - gamma / kappa
lowest = max(np.sqrt(n_core**2 - (wavelength / (2 * width)) ** 2), n_cladding)
return brentq(dispersion, lowest + 1e-9, n_core - 1e-9)
mode = gfem.solve(bend, gfem.PortMode("p1", F0, polarization="Ez"))
print(
f"n_eff (p1) = {float(np.real(mode.n_eff[0])):.6f}, analytic slab mode = "
f"{slab_index(N_CORE, N_CLADDING, WIDTH, WAVELENGTH):.6f}"
)
bend
n_eff (p1) = 2.057537, analytic slab mode = 2.057557
Model(Mesh(2809 nodes, 5408 triangles, volumes=['cladding', 'core', 'design'], surfaces=['outer', 'port1', 'port2'], length_unit='um')
materials:
cladding: Material(eps_r=2.085136, name='cladding')
core: Material(eps_r=5.0625, name='core')
design: Material(eps_r=2.085136, name='cladding')
boundaries:
Absorbing(surface='outer', order=2)
ports:
WavePort(name='p1', surface='port1', mode=1, offset=0.0, voltage_path=None, pec_edges=('outer',))
WavePort(name='p2', surface='port2', mode=1, offset=0.0, voltage_path=None, pec_edges=('outer',)))
The design square takes its permittivity from a layer grid: 60 × 60 pixels of 0.05 µm over the area’s footprint (more on it in the next section). A pixel value of 0 is cladding, 1 is core, and the material field interpolates \(\varepsilon_r\) linearly in between.
Below, the layout as the solver sees it: white is core, black is cladding, and the design square is at 0.5, where the optimization starts. The port lines are read from the mesh, p1 solid and p2 dashed. Every other side is an absorbing boundary.
grid = design.LayerGrid(mesh, "design", pitch=0.05 * um)
HALF = 2.5 * um # the box's half-width
def coverage(inside, x, y, pitch, samples=8):
# For the picture of the whole box only: per pixel centred at (x[j], y[i]), the
# fraction of its area where inside(x, y), from samples x samples points.
offsets = ((np.arange(samples) + 0.5) / samples - 0.5) * pitch
xs = x[None, :, None, None] + offsets[None, None, None, :]
ys = y[:, None, None, None] + offsets[None, None, :, None]
return inside(xs, ys).mean(axis=(2, 3))
def in_arms(x, y):
# The fixed guides: the input along x < -1.5 um, the output along y < -1.5 um.
guide = WIDTH / 2
return ((x < -1.5 * um) & (np.abs(y) <= guide)) | (
(y < -1.5 * um) & (np.abs(x) <= guide)
)
centres = -HALF + (np.arange(round(2 * HALF / grid.pitch)) + 0.5) * grid.pitch
corner_pixel = round((grid.origin[0] + HALF) / grid.pitch) # same in x and y
inside_design = np.s_[
corner_pixel : corner_pixel + grid.shape[0],
corner_pixel : corner_pixel + grid.shape[1],
]
EXTENT = np.array([-HALF, HALF, -HALF, HALF]) / um
def window(density):
# The whole 5 um x 5 um box as a pixel image: the guides around a design density.
image = coverage(in_arms, centres, centres, grid.pitch)
image[inside_design] = np.asarray(density)
return image
def port_line(face):
# The two ends of a port line, in um.
xy = nodes[mesh.surface_elements[mesh.elements(face)]].reshape(-1, 2)
return xy.min(axis=0), xy.max(axis=0)
start = np.full(grid.shape, 0.5)
nodes = np.asarray(mesh.nodes) / um
fig, ax = plt.subplots(figsize=(6, 3))
ax.imshow(window(start), origin="lower", extent=EXTENT, cmap="gray", vmin=0, vmax=1)
ports = (("p1", "port1", "C0", "-"), ("p2", "port2", "C1", "--")) # solid, dashed
for port, face, colour, style in ports:
lo, hi = port_line(face)
ax.plot([lo[0], hi[0]], [lo[1], hi[1]], color=colour, ls=style, lw=3)
# The label sits 0.4 um beyond the line's middle, outside the image.
middle = (lo + hi) / 2
ax.text(*middle * (1 + 0.4 / 2.5), port, color=colour, ha="center", va="center")
ax.set_xlim(EXTENT[0] - 0.8, EXTENT[1]) # room for the labels
ax.set_ylim(EXTENT[2] - 0.8, EXTENT[3])
ax.set_xlabel("x (um)")
ax.set_ylabel("y (um)");
The mesh itself: every triangle, shaded by area (the guides light, the design square grey, the cladding dark), and the two port lines (red).
SHADES = {"cladding": 0.2, "design": 0.55, "core": 0.9} # grey level of each area
def mesh_view(ax, mesh, scale, shades, ports):
# The triangles of a 2D mesh shaded by area, and its port lines in red.
xy = np.asarray(mesh.nodes) / scale
shade = np.zeros(len(mesh.volume_elements))
for area, level in shades.items():
shade[mesh.elements(area)] = level
ax.tripcolor(
*xy.T,
mesh.volume_elements,
facecolors=shade,
cmap="gray",
vmin=0,
vmax=1,
edgecolors="#c4c4c4",
linewidth=0.2,
)
for face in ports:
ends = xy[mesh.surface_elements[mesh.elements(face)]].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)
fig, ax = plt.subplots(figsize=(4.5, 4.5))
mesh_view(ax, mesh, um, SHADES, ("port1", "port2"))
ax.set_xlabel("x (um)")
ax.set_ylabel("y (um)");
Two hand-drawn bends set the scale before any optimization. The arc design is a
quarter ring 0.55 µm wide, of radius 1.5 µm about the corner (-1.5, -1.5) µm, that
joins the two guides. The corner design extends both guides until they meet in a
sharp L. Each is drawn as a polygon, a layer pattern
(gfem.design.LayerPattern), in metres, and grid.area_fraction turns
it into pixels: each pixel holds the exact share of its area that the polygon
covers. The two feed guides are drawn the same way, from the box’s edge to the
design square’s, for the pictures and the GDS file below.
One driven problem at 1.55 µm with excite=None excites each port in turn and gives
the full 2 × 2 S-matrix. The media are lossless, so the remainder
\(1 - |S_{11}|^2 - |S_{21}|^2\) is the power that leaves port 1’s mode for neither port’s
fundamental mode. It is radiated through the absorbing boundary, or carried out in
the guide’s second (odd) mode, which the 0.55 µm guide also supports at 1.55 µm. A direct solver suits these
repeated solves; between solves gfem keeps what the gradients and the next design
reuse, within SolverOptions.retain_memory, by default half of the memory the
process may use.
problem = gfem.Driven(frequency=F0, excite=None, polarization="Ez")
options = gfem.SolverOptions(linear_solver="direct")
def material(density, grid=grid):
# The design area's permittivity: 0 cladding, 1 core, per pixel of the grid.
return gfem.MaterialField.interpolate(grid.to_elements(density), CLADDING, CORE)
def s_matrix(density):
return gfem.solve(
bend.with_material("design", material(density)), problem, options=options
).s
def transmission(s):
# |S21|^2 at the first frequency: the power out of p2 in its fundamental mode.
return abs(complex(s["p2", "p1"][0])) ** 2
def report(name, s):
sent, back = transmission(s), abs(complex(s["p1", "p1"][0])) ** 2
print(
f"{name}: |S21|^2 = {sent:.4f}, |S11|^2 = {back:.1e}, "
f"remainder = {1 - sent - back:.4f}"
)
return sent
def ring_sector(centre, radius, width, segments=64):
# A quarter ring from 0 to 90 degrees about centre: the outer arc, the inner back.
angle = np.linspace(0, np.pi / 2, segments + 1)
unit = np.stack([np.cos(angle), np.sin(angle)], axis=1)
outer = centre + (radius + width / 2) * unit
inner = centre + (radius - width / 2) * unit[::-1]
return np.concatenate([outer, inner])
g, edge = WIDTH / 2, 1.5 * um # the guide's half-width, the design square's half-side
arc_pattern = design.LayerPattern.from_polygons(
[ring_sector(np.array([-edge, -edge]), 1.5 * um, WIDTH)]
)
corner_pattern = design.LayerPattern.from_polygons( # both guides extended to an L
[np.array([[-edge, -g], [-g, -g], [-g, -edge], [g, -edge], [g, g], [-edge, g]])]
)
guide_in = np.array([[-HALF, -g], [-edge, -g], [-edge, g], [-HALF, g]]) # along x
guide_out = guide_in[:, ::-1] # its mirror about y = x, along y
guides = design.LayerPattern.from_polygons([guide_in, guide_out])
arc = grid.area_fraction(arc_pattern)
corner = grid.area_fraction(corner_pattern)
arc_result = gfem.solve( # the arc keeps its fields, for a field map
bend.with_material("design", material(arc)),
gfem.Driven(frequency=F0, excite=None, keep_fields=F0, polarization="Ez"),
options=options,
)
t_arc = report("arc design", arc_result.s)
t_corner = report("corner design", s_matrix(corner))
arc design: |S21|^2 = 0.6837, |S11|^2 = 1.6e-04, remainder = 0.3161
corner design: |S21|^2 = 0.0005, |S11|^2 = 4.0e-02, remainder = 0.9593
From pixels to a material#
The optimizer works on design parameters \(\rho\), one per pixel in [0, 1], not on the
density the solve sees. physical maps one to the other in three steps on the grid:
Mirror about \(y = x\):
0.5 * (rho + rho.T). Row i of the grid is at y[i] and column j at x[j], and the grid is square, so the transpose is the mirror \((x, y) \to (y, x)\). It swaps the two guides, and p1 with p2; the mesh has the same symmetry, so the design keeps it and \(S_{11} = S_{22}\).Helmholtz filter of radius 0.3 µm.
radiusis the cone-equivalent radius: the filter solves \(-r^2\nabla^2\tilde{\rho} + \tilde{\rho} = \rho\) with \(r = \mathrm{radius} / 2\sqrt{3} = 0.087\) µm, about 1.7 pixels. At a 0.1 µm pitch, \(r\) would be smaller than one pixel and the filter would barely act; hence the 0.05 µm pitch. The pixel count does not enter the solve.Projection towards 0 or 1 at threshold 0.5, with a sharpness \(\beta\) that the optimization raises step by step.
The solve reads the bilinear interpolation of the pixels at several points inside
each triangle, more of them at a higher element order. At 0.05 µm pixels on
triangles of at most 0.1 µm, every pixel is reached by some point, so the grid
raises no warning. The snapshots below come from physical; the design evaluated
at the end is drawn from the same filtered density.
blur = design.helmholtz_filter(grid, radius=0.3 * um)
def physical(rho, beta):
# Design parameters -> physical density: mirror about y = x, filter, project.
return design.project(blur(0.5 * (rho + rho.T)), beta)
grid
LayerGrid('design', pitch=5e-08 m, shape=(60, 60), 2048 elements)
The objective#
For one design we solve the driven problem at 1.55 µm and read \(S_{21}\). The objective is the power that misses the output guide’s fundamental mode, \(1 - |S_{21}|^2\). The media are reciprocal, so \(S_{12} = S_{21}\) and \(|S_{21}|^2\) is the same in both directions.
The objective counts only the power in the output guide’s fundamental mode, so power
lost to the guide’s second (odd) mode already counts against it: no penalty on the
core fraction is needed to keep the design away from multimode regions. has_aux returns \(|S_{21}|^2\) and the core fraction with the gradient, and the
loop records both.
def loss(rho, beta):
density = physical(rho, beta)
t = jnp.abs(s_matrix(density)["p2", "p1"][0]) ** 2
return 1 - t, (t, jnp.mean(density)) # missed power; aux: |S21|^2, core fraction
value_and_grad = jax.jit(jax.value_and_grad(loss, has_aux=True))
Optimize#
Adam on the raw pixels with step 0.1, clipped to [0, 1], from a uniform 0.5. The start needs no noise: the gradient there is non-zero, and the mirror keeps it symmetric. The projection sharpness \(\beta\) doubles from 1 to 32 every 7 steps (continuation), 42 iterations in all, each one driven solve and its gradient. The loop keeps four snapshots of the physical density, at iterations 0, 14, 27 and 41.
BETAS, STEPS_PER_BETA = (1.0, 2.0, 4.0, 8.0, 16.0, 32.0), 7
n_steps = len(BETAS) * STEPS_PER_BETA
snapshot_at = [round(i * (n_steps - 1) / 3) for i in range(4)] # 0, 14, 27, 41
rho = jnp.full(grid.shape, 0.5)
optimizer = optax.adam(0.1)
state = optimizer.init(rho)
history, snapshots = [], {}
tic = time.perf_counter()
for beta in BETAS:
for _ in range(STEPS_PER_BETA):
(_, (t_last, fraction_last)), g = value_and_grad(rho, beta)
if len(history) in snapshot_at:
snapshots[len(history)] = np.asarray(physical(rho, beta))
updates, state = optimizer.update(g, state)
rho = jnp.clip(optax.apply_updates(rho, updates), 0.0, 1.0)
t_last, fraction_last = float(t_last), float(fraction_last)
history.append((t_last, fraction_last))
print(
f"beta = {beta:4.0f}: |S21|^2 = {t_last:.4f}, "
f"core fraction = {fraction_last:.3f}"
)
print(f"{n_steps} iterations in {time.perf_counter() - tic:.0f} s")
beta = 1: |S21|^2 = 0.7185, core fraction = 0.519
beta = 2: |S21|^2 = 0.8429, core fraction = 0.486
beta = 4: |S21|^2 = 0.9249, core fraction = 0.465
beta = 8: |S21|^2 = 0.9648, core fraction = 0.458
beta = 16: |S21|^2 = 0.9750, core fraction = 0.456
beta = 32: |S21|^2 = 0.9777, core fraction = 0.456
42 iterations in 16 s
\(|S_{21}|^2\) and the core fraction per iteration. The dotted black line is the arc design’s \(|S_{21}|^2\); the thin grey lines mark where \(\beta\) doubles.
t_history, core_history = np.array(history).T
fig, ax = plt.subplots(figsize=(6, 3))
ax.plot(t_history, label="|S21|²")
ax.plot(core_history, label="core fraction")
ax.axhline(t_arc, color="k", ls=":", lw=1, label="arc design |S21|²")
for k in range(STEPS_PER_BETA, n_steps, STEPS_PER_BETA):
ax.axvline(k - 0.5, color="gray", lw=0.5)
ax.set_ylim(0, 1)
ax.set_xlabel("iteration")
ax.set_ylabel("fraction")
ax.legend(loc="lower right");
The design#
The physical density at the four snapshots, white core and black cladding. The design grows from the uniform start into curved strips of core about the inner corner; by iteration 41 (\(\beta = 32\)) it is nearly binary.
fig, axes = plt.subplots(1, 4, figsize=(8, 2.6), sharey=True)
for ax, k in zip(axes, snapshot_at, strict=True):
ax.imshow(
window(snapshots[k]), origin="lower", extent=EXTENT, cmap="gray", vmin=0, vmax=1
)
ax.set_title(f"iteration {k}\n|S21|² = {history[k][0]:.3f}")
ax.set_xlabel("x (um)")
axes[0].set_ylabel("y (um)")
fig.tight_layout();
From pixels to a layer pattern#
The design we evaluate is the drawn pattern: the polygons where the filtered last
iterate reaches 0.5, the \(\beta \to \infty\) limit of the projection.
grid.pattern contours the filtered density, before the projection, so its edges
fall between pixel centres to a few hundredths of a pixel. grid.area_fraction
rasterizes it back onto the pixels, each holding the share of its area the polygons
cover, and final is that raster. Every number after this comes from it.
Below, the pattern, \(|S_{21}|^2\) of iteration 41 next to that of the drawn pattern,
and the share of pixels the last iterate had within 0.05 of 0 or 1. The two
\(|S_{21}|^2\) differ because the iterate is a \(\beta = 32\) projection, not a sharp
edge, and the solve reads the pixels bilinearly, so the permittivity it sees from
final stays fractional along the core edge. The cell asserts that the pattern
transmits within 0.02 of the last iterate (here 0.9762 against 0.9777). A broken
chain from pixels to polygons and back (a half-pixel shift, swapped axes, lengths
in µm instead of metres) moves \(|S_{21}|^2\) by far more.
last = physical(rho, BETAS[-1])
drawn = grid.pattern(blur(0.5 * (rho + rho.T)), eta=0.5) # the filtered density
final = grid.area_fraction(drawn)
s_final = s_matrix(final)
t_pattern = transmission(s_final)
binary = float(jnp.mean((last < 0.05) | (last > 0.95)))
print(drawn)
print(f"iteration {n_steps - 1}: |S21|^2 = {t_last:.4f} at beta = {BETAS[-1]:.0f}")
print(f"drawn pattern: |S21|^2 = {t_pattern:.4f}, {final.mean():.1%} core")
print(f"{100 * binary:.1f} % of the pixels lie within 0.05 of 0 or 1")
np.testing.assert_array_less(abs(t_pattern - t_last), 0.02)
LayerPattern('design', 6 polygons, 0 holes, 812 vertices, solid 45.7 % of 9e-12 m^2, eta=0.5)
iteration 41: |S21|^2 = 0.9777 at beta = 32
drawn pattern: |S21|^2 = 0.9762, 45.7% core
94.4 % of the pixels lie within 0.05 of 0 or 1
A foundry refuses lines of core narrower than its minimum width and spaces
narrower than its minimum spacing. drawn.check measures the pattern’s facing edges against
both, here against an example rule of 0.15 µm each: the effective-index model stands
for no particular process. The filter gives the design a length scale, not a
guaranteed minimum (see Limits), so the check is a report, not an assertion: it
prints the narrowest width and spacing, and each place below the rule. Two places,
mirror images about \(y = x\), are 132 nm wide; the narrowest spacing is 174 nm.
Edges on the design square’s boundary are not measured, since the guides and the
cladding go on beyond them.
check = drawn.check(min_width=0.15 * um, min_spacing=0.15 * um) # an example rule
print(check)
for site in check.violations:
x, y = site.location / um
print(f"{site.kind}: {site.distance / 1e-9:.0f} nm at ({x:.2f}, {y:.2f}) um")
PatternCheck('design', min_width 150 nm: 2 violations, narrowest 132 nm at (-1.212, -0.06278) um; min_spacing 150 nm: passed, narrowest 174.4 nm)
width: 132 nm at (-1.21, -0.06) um
width: 132 nm at (-0.06, -1.21) um
The drawn pattern on the mesh: final’s pixels (white core, black cladding), the
triangles of the design square (grey), the pattern’s polygons (blue) and the check’s
markers (red), each a segment across a place narrower than the rule. The edge cuts
through triangles: the mesh does not follow the design, the solve reads the pixels
inside each triangle.
DESIGN_EXTENT = np.array(grid.bounds)[[0, 2, 1, 3]] / um # xmin, xmax, ymin, ymax
def draw_rings(ax, pattern, **style):
# Every ring of a layer pattern, outer edges and holes, in um.
for exterior, holes in pattern:
for ring in (exterior, *holes):
ax.plot(*ring.T / um, **style)
fig, ax = plt.subplots(figsize=(4.5, 4.5))
ax.imshow(final, origin="lower", extent=DESIGN_EXTENT, cmap="gray", vmin=0, vmax=1)
design_triangles = mesh.volume_elements[mesh.elements("design")]
ax.triplot(*nodes.T, design_triangles, color="#c4c4c4", lw=0.4)
draw_rings(ax, drawn, color="C0", ls="-", lw=1)
for site in check.violations:
for marker in site.markers:
ax.plot(*marker.T / um, color="#b5262f", lw=2)
ax.set_xlim(DESIGN_EXTENT[:2])
ax.set_ylim(DESIGN_EXTENT[2:])
ax.set_xlabel("x (um)")
ax.set_ylabel("y (um)");
A GDS file is what a layout tool and a foundry read. design.write_gds writes the
drawn pattern and the two feed guides on one layer and datatype, (1, 0); the
numbers are an example, a real layout takes them from the foundry’s layer map. The
polygons keep the mesh’s frame: the design square spans -1.5 to 1.5 µm in the file
as in the mesh, and the guides abut it on its edge. Every vertex sits on a 1 nm
grid. The file goes to a temporary directory, not next to the notebook; open it in
any GDS viewer.
out = Path(tempfile.mkdtemp()) # a run leaves no file in the docs folder
gds = design.write_gds(out / "bend.gds", {(1, 0): (drawn, guides)})
print(
f"{gds.name}: {gds.stat().st_size} bytes, layer (1, 0): "
f"{len(drawn)} drawn + {len(guides)} guide polygons"
)
bend.gds: 6778 bytes, layer (1, 0): 6 drawn + 2 guide polygons
Power balance and reciprocity#
From here on every number is about final, the drawn pattern’s pixels, except the
eroded and dilated variants in the mesh and box checks below, which perturb the
filtered design the pattern is drawn from. One driven problem at 1.55 µm with both
ports excited gives its full S-matrix, and keeps both fields for the maps below.
Three properties of the model must show in it:
Power balance. The media are lossless and the model is passive, so \(|S_{11}|^2 + |S_{21}|^2 \le 1\). The remainder \(1 - |S_{11}|^2 - |S_{21}|^2\) is power radiated through the absorbing boundary or carried out in the guide’s second (odd) mode; one fundamental-mode port per guide does not tell the two apart.
Reciprocity. The media are reciprocal, so \(S_{12} = S_{21}\): \(|S_{21}|^2\) is the transmission in both directions at once.
Symmetry. The design and the mesh are mirror images about \(y = x\), so \(|S_{11}|^2 = |S_{22}|^2\).
Wave ports are checked on straight guides (How gfem is checked).
trust = gfem.solve(
bend.with_material("design", material(final)),
gfem.Driven(frequency=F0, excite=None, keep_fields=F0, polarization="Ez"),
options=options,
)
def powers(s):
# Per frequency: |S21|^2, |S11|^2, |S22|^2 and |S12 - S21|.
s21, s12 = np.asarray(s["p2", "p1"]), np.asarray(s["p1", "p2"])
s11, s22 = np.asarray(s["p1", "p1"]), np.asarray(s["p2", "p2"])
return np.abs(s21) ** 2, np.abs(s11) ** 2, np.abs(s22) ** 2, np.abs(s12 - s21)
t_trust, r11, r22, recip = (float(v[0]) for v in powers(trust.s))
print(f"final at F0: |S21|^2 = {t_trust:.4f}, |S11|^2 = {r11:.1e}, |S22|^2 = {r22:.1e}")
print(f"reciprocity: |S12 - S21| = {recip:.1e}")
print(f"power balance: |S11|^2 + |S21|^2 = {r11 + t_trust:.6f}, at most 1")
print(
"remainder, radiated or carried out in the second (odd) mode: "
f"{1 - r11 - t_trust:.4f}"
)
final at F0: |S21|^2 = 0.9762, |S11|^2 = 7.9e-05, |S22|^2 = 7.9e-05
reciprocity: |S12 - S21| = 7.8e-16
power balance: |S11|^2 + |S21|^2 = 0.976234, at most 1
remainder, radiated or carried out in the second (odd) mode: 0.0238
The spectrum#
The objective sees one wavelength. A uniform sweep of 13 wavelengths, 1.2 to 1.8 µm in 0.05 µm steps with 1.55 µm among them, shows what the design does around it. Both ports are excited at every wavelength, so the checks above repeat across the band. Each wavelength costs its own factorization; the port modes come from one sweep over the band.
wavelengths = np.linspace(1.2, 1.8, 13) * um
spectrum = gfem.solve(
bend.with_material("design", material(final)),
gfem.Driven(frequency=c / wavelengths, excite=None, polarization="Ez"),
options=options,
)
t_band, r11_band, r22_band, recip_band = powers(spectrum.s)
remainder = 1 - r11_band - t_band
in_um = np.round(wavelengths / um, 2)
claimed = in_um >= 1.3 # 1.3-1.8 um
low, high = np.argmin(np.where(claimed, t_band, 2)), np.argmax(t_band * claimed)
print(f"band: max |S12 - S21| = {recip_band.max():.1e}")
print(f"band: max |S11|^2 + |S21|^2 = {(r11_band + t_band).max():.4f}")
print(f"band: max |S11|^2 = {r11_band.max():.1e}, max |S22|^2 = {r22_band.max():.1e}")
print(
f"|S21|^2 over 1.3-1.8 um: min {t_band[low]:.4f} at {in_um[low]} um, "
f"max {t_band[high]:.4f} at {in_um[high]} um"
)
print("wavelength (um) |S21|^2 |S11|^2 remainder")
for lam, sent, back, rest in zip(in_um, t_band, r11_band, remainder, strict=True):
print(f"{lam:15.2f} {sent:7.4f} {back:7.1e} {rest:9.4f}")
band: max |S12 - S21| = 3.3e-15
band: max |S11|^2 + |S21|^2 = 0.9762
band: max |S11|^2 = 5.7e-02, max |S22|^2 = 5.7e-02
|S21|^2 over 1.3-1.8 um: min 0.5956 at 1.8 um, max 0.9762 at 1.55 um
wavelength (um) |S21|^2 |S11|^2 remainder
1.20 0.5296 5.7e-02 0.4138
1.25 0.6073 2.6e-02 0.3663
1.30 0.6868 1.2e-03 0.3120
1.35 0.7006 6.6e-04 0.2987
1.40 0.7994 3.5e-03 0.1971
1.45 0.8831 1.8e-03 0.1151
1.50 0.9565 7.4e-05 0.0435
1.55 0.9762 7.9e-05 0.0238
1.60 0.9452 5.7e-04 0.0542
1.65 0.8973 1.8e-03 0.1009
1.70 0.8383 9.3e-04 0.1608
1.75 0.7327 1.1e-04 0.2672
1.80 0.5956 1.7e-03 0.4027
\(|S_{21}|^2\) (solid) and the remainder (dashed) against wavelength; the dotted line marks 1.55 µm. \(|S_{11}|^2\) is in the table above, not plotted: away from 1.55 µm, most of what \(|S_{21}|^2\) loses goes into the remainder.
fig, ax = plt.subplots(figsize=(6, 3))
ax.plot(wavelengths / um, t_band, marker="o", ms=3, label="|S21|²")
ax.plot(wavelengths / um, remainder, ls="--", marker="o", ms=3, label="remainder")
ax.axvline(WAVELENGTH / um, color="k", ls=":", lw=1)
ax.set_ylim(0, 1)
ax.set_xlabel("wavelength (um)")
ax.set_ylabel("fraction of incident power")
ax.legend(loc="center right");
The fields#
\(|E_z|\) with 1 W/m incident in the fundamental mode at p1, for the arc design and
for final, on one grey scale. Of the arc and corner designs, the arc is the one
that guides, so it is the one shown. Each map samples the kept field at
200 × 200 points with Field.at, and the blue lines are the core edges: the arc’s
or the drawn pattern’s polygons, and the feed guides.
This is the frequency-domain amplitude at 1.55 µm, not the power flow. An amplitude is the square root of a power, so the arc design’s radiation, a third of the input spread thinly over the box, still shows as lobes leaving the bend.
step = 2 * HALF / 200
along = -HALF + (np.arange(200) + 0.5) * step
X, Y = np.meshgrid(along, along)
plane = np.stack([X.ravel(), Y.ravel()], axis=1) # (x, y) points of the 2D model
def ez(result):
# E_z in kV/m, port p1 fed with 1 W/m.
return np.asarray(result.e_field(F0, excite="p1").at(plane)).reshape(X.shape) / 1e3
def core_edge(ax, pattern):
# The core edges in the box: a design's polygons and the feed guides, in um.
for part in (pattern, guides):
draw_rings(ax, part, color="C0", ls="-", lw=0.8)
maps = {
f"arc design: |S21|² = {t_arc:.3f}": (arc_pattern, ez(arc_result)),
f"optimized: |S21|² = {t_trust:.3f}": (drawn, ez(trust)),
}
vmax = max(np.abs(field).max() for _, field in maps.values())
fig, axes = plt.subplots(1, 2, figsize=(7, 3.2), sharey=True, layout="constrained")
for ax, (title, (pattern, field)) in zip(axes, maps.items(), strict=True):
image = ax.imshow(
np.abs(field), origin="lower", extent=EXTENT, cmap="gray", vmin=0, vmax=vmax
)
core_edge(ax, pattern)
ax.set_title(title)
ax.set_xlabel("x (um)")
ax.grid(False)
axes[0].set_ylabel("y (um)")
fig.colorbar(image, ax=axes, label="|E_z| (kV/m), 1 W/m incident at p1");
The same two solves as \(E_z\) at \(t = 0\), \(\mathrm{Re}(E_z)\), with 1 W/m incident at p1, on
one scale from black (negative) to white (positive). The blue line is the core
edge, as above. Where the amplitude maps show how strong the field is, the phase
fronts show where it goes. In the arc design they curve out of the ring into the
cladding; in final they turn with the core.
peak = max(np.abs(field.real).max() for _, field in maps.values())
fig, axes = plt.subplots(1, 2, figsize=(7, 3.2), sharey=True, layout="constrained")
for ax, (title, (pattern, field)) in zip(axes, maps.items(), strict=True):
image = ax.imshow(
field.real, origin="lower", extent=EXTENT, cmap="gray", vmin=-peak, vmax=peak
)
core_edge(ax, pattern)
ax.set_title(title.split(":")[0])
ax.set_xlabel("x (um)")
ax.grid(False)
axes[0].set_ylabel("y (um)")
fig.colorbar(image, ax=axes, label="Re E_z (kV/m), 1 W/m incident at p1");
Etch, box and element order#
Three checks bound what the design’s and the model’s choices cost: an etch, the box and the element order.
Eroded and dilated. The filter gives the design a length scale, not a minimum feature size.
design.robustprojects the filtered last iterate at thresholds 0.6, 0.5 and 0.4 (\(\beta = 64\), \(\delta = 0.1\)). This is the filtered design whose \(\eta = 0.5\) contour is the drawn pattern: the robust nominal, at 0.5, is its \(\beta = 64\) projection. The eroded and dilated variants thin or widen every core strip, as an over- or under-etch would. All three are projected densities, not drawn patterns, so their \(|S_{21}|^2\) is read against the robust nominal’s.The box.
data/bend2d_7um.mshis the same mesh grown to 7 µm × 7 µm, the port lines on \(x = -3.5\) µm and \(y = -3.5\) µm. Inside the 5 µm box it is identical node for node, so the same layer grid and pixels apply, and the absorbing boundary sits 2 µm from the design instead of 1 µm. The guides are lossless, so the longer feeds do not change \(|S_{21}|^2\). It prints the change \(\Delta T\) of \(|S_{21}|^2\) againstfinal’s.The order. Third-order elements on the same mesh, again as \(\Delta T\) against
final. They resolve the field better and also read the pixels at more points per triangle, so \(\Delta T\) bounds both at a fixed mesh.
variants = design.robust(blur(0.5 * (rho + rho.T)), beta=64.0, delta=0.1)
t_eroded = report("eroded", s_matrix(variants.eroded))
t_robust = report("robust nominal", s_matrix(variants.nominal))
t_dilated = report("dilated", s_matrix(variants.dilated))
print(f"drawn pattern (its 0.5 contour): |S21|^2 = {t_pattern:.4f}")
eroded: |S21|^2 = 0.8695, |S11|^2 = 6.0e-02, remainder = 0.0703
robust nominal: |S21|^2 = 0.9778, |S11|^2 = 2.9e-04, remainder = 0.0220
dilated: |S21|^2 = 0.9046, |S11|^2 = 7.2e-04, remainder = 0.0947
drawn pattern (its 0.5 contour): |S21|^2 = 0.9762
mesh_7um = gfem.Mesh.from_gmsh(Path("data/bend2d_7um.msh"), length_unit="um")
bend_7um = gfem.Model(
mesh_7um, materials=bend.materials, boundaries=bend.boundaries, ports=bend.ports
)
grid_7um = design.LayerGrid(mesh_7um, "design", pitch=grid.pitch)
print(
f"layer grid: {grid_7um.shape} pixels from {np.asarray(grid_7um.origin) / um} um, "
f"against {grid.shape} from {np.asarray(grid.origin) / um} um"
)
s_7um = gfem.solve(
bend_7um.with_material("design", material(final, grid=grid_7um)),
problem,
options=options,
).s
t_7um = transmission(s_7um)
print(f"7 x 7 um box: |S21|^2 = {t_7um:.4f}, delta T = {t_7um - t_pattern:+.1e}")
layer grid: (60, 60) pixels from [-1.5 -1.5] um, against (60, 60) from [-1.5 -1.5] um
7 x 7 um box: |S21|^2 = 0.9756, delta T = -5.6e-04
order3 = gfem.solve(
bend.with_material("design", material(final)),
problem,
options=gfem.SolverOptions(linear_solver="direct", order=3),
)
t_order3 = transmission(order3.s)
print(f"order 3: |S21|^2 = {t_order3:.4f}, delta T = {t_order3 - t_pattern:+.1e}")
order 3: |S21|^2 = 0.9765, delta T = +3.1e-04
Limits#
The 2D model. A top view in effective indices, with nothing varying along z. No vertical stack, substrate leakage or out-of-plane loss enters; 2.25 and 1.444 are taken as given. The same bend posed as a slab one cell thick between conducting plates gives the same S to \(2\times10^{-3}\) (How gfem is checked).
An absorbing boundary, not a PML. A second-order absorbing boundary 1 µm from the design. The 7 µm × 7 µm re-solve moves \(|S_{21}|^2\) by \(-5.6\times10^{-4}\): a bound for this design, not a guarantee for others.
The mesh is part of the material model. The solve reads the pixel image at points inside each triangle, so a finer mesh or a higher order changes the permittivity as well as the field. The order-3 re-solve (\(\Delta T = +3.1 \times 10^{-4}\)) bounds both at this mesh, and only at 1.55 µm; towards 1.2 µm the mesh has fewer cells per guided wavelength. Re-check a design on a finer mesh before trusting the third digit.
The remainder is not split. \(1 - |S_{11}|^2 - |S_{21}|^2\) (0.024 at 1.55 µm) lumps radiation and the guide’s second (odd) mode, which the 0.55 µm guide supports at 1.55 µm. Each port is matched to the fundamental mode only, so part of the odd mode that reaches it is reflected back into the bend. Separating the two, and absorbing both, needs a second port mode per port (the
modekeyword ofgfem.WavePort).One wavelength. The objective is \(|S_{21}|^2\) at 1.55 µm; the spectrum is evaluated, not optimized, and \(|S_{21}|^2\) falls to 0.596 at 1.8 µm. A broadband design would sum the objective over wavelengths, as the topology tutorial does over a pass and a stop frequency.
A length scale from the filter only. The 0.3 µm filter radius gives the design a length scale but no guaranteed minimum width, of core strips or of the spaces between them. The eroded and dilated variants printed above transmit 0.870 and 0.905, against 0.978 for the robust nominal, and the drawn pattern has two places 132 nm wide. Optimizing the worst of the three, as the topology tutorial does, costs three solves per iteration; a minimum width and spacing can also be held as constraints in the gradient (Optimize a design for fabrication: etch, blur and minimum features).
The design square’s edge. The filter treats the square’s edge as a mirror, and the check does not measure along it, since the guides are drawn outside the grid. The guides meet the square at right angles, so the mirror image is the guide itself and the filter loses little; a sliver of core or cladding along the edge would still pass the check unseen. Meshing the design region a margin into the guides, with the guides pinned as pixels, fixes both (Optimize a design for fabrication: etch, blur and minimum features, “Real neighbours”).
The pattern is a top view. The 2D model’s plane is the wafer’s, so the drawn pattern is the layer pattern on the wafer, what the GDS file holds. On a cross-section model the same call would give the cross-section’s profile, not a pattern on the wafer.
Next#
The 3D bend: the same recipe on a real stack, a 220 nm silicon guide in SiO2, with the out-of-plane loss this 2D model leaves out. It was computed once on a larger machine; the page reads its results.
Solve a structure that does not vary along one axis: when a 2D model fits, its two polarizations, and what it leaves to the slab or to 3D.
Optimize a design for fabrication: etch, blur and minimum features: eroded, nominal and dilated designs in the loop, a fabrication model, and minimum width and spacing as constraints.
Export a design’s layer pattern to GDS: the drawn pattern, its width and spacing check, the GDS file and the re-solve, step by step.
Differentiate S-parameters and driven fields: what is differentiable in a driven solve.
Measure fields after the solve:
Field.at, the probe behind the field maps.gfem.designreference:LayerGrid,helmholtz_filter,project,robust,LayerPattern,write_gds.