TIDY3D
LEARNING CENTER

Inverse design of TFLN fiber-to-chip interface

Coupling an optical fiber to a thin-film lithium niobate (TFLN) chip is difficult: the fiber mode spans several microns while the TFLN rib mode is sub-micron, and the platform’s partially etched rib, slanted sidewalls, and single-layer patterning make conventional tapers bulky and hard to fabricate. Shang et al. [1] sidestep the taper altogether, treating the fiber-to-chip interface as a black box and letting topology optimization discover a short, non-adiabatic structure that scatters and refocuses the beam directly into the rib mode.

This notebook reproduces that workflow in Tidy3D for a coupler between a 2-μm mode-field-diameter (MFD) lensed fiber and a 1-μm-wide TFLN rib waveguide:

  1. Topology optimization: A latent design array is weakly projected into a continuous rib/slab density and optimized with the adjoint method (phase 1: continuous). A low-pass filter sets a target minimum feature size and a ramped projection strength then binarizes it, while an erosion/dilation penalty discourages features below that length scale (phase 2: geometric constraints). Finally, the non-vertical etch sidewall is folded into the forward model (phase 3: sidewall angle).
  2. Fabrication-realistic geometry: The top surface is traced into polygons and extruded into sidewall-angled polyslabs (the GDS reconstruction), whose top face is exported as the GDS mask; both the optimized design and its reconstruction are validated against a straight waveguide over the full band.

In particular, the workflow addresses two traits that set TFLN apart from a typical isotropic photonic platform:

Anisotropy. x-cut TFLN is uniaxial — the ordinary index \(n_o\) (global xz-plane) and extraordinary index \(n_e\) (y) differ enough that an isotropic approximation would mispredict the coupled mode. The density array is therefore mapped independently onto each diagonal permittivity component via td.CustomAnisotropicMedium, so the adjoint optimizer sees and optimizes the true anisotropic response directly.

Sidewall angle. TFLN is patterned in a single, non-selective etch step, so its sidewall is unavoidably slanted rather than vertical. Rather than meshing that slant explicitly, we model it with a differentiable soft morphological dilation that widens the top-surface density by a depth-dependent amount. Concretely, for a disk-shaped neighborhood \(\mathcal{N}_r(\mathbf{x}) = \{\mathbf{x'}: |\mathbf{x}-\mathbf{x'}|<r\}\) of radius \(r\) around each pixel \(\mathbf{x}\), the hard max over the density \(\rho\) is replaced by its LogSumExp (soft-max) relaxation, \[\rho_{\text{soft}}(\mathbf{x}) = \frac{1}{\gamma}\log\left[\frac{1}{|\mathcal{N}_r(\mathbf{x})|}\sum_{\mathbf{x}' \in \mathcal{N}_r(\mathbf{x})} e^{\gamma\,\rho(\mathbf{x}')}\right],\] which is differentiable everywhere and converges to the true morphological dilation \(\max_{\mathbf{x}' \in \mathcal{N}_r(\mathbf{x})} \rho(\mathbf{x}')\) as \(\gamma \to \infty\). This approach is inspired by Ref. [2], though it replaces that work’s exponential smoothing kernel with a soft dilation.

References

  1. C. Shang et al., “Inverse-designed photonic interfaces beyond eigenmode expansion limits,” arXiv:2607.06243 (2026). DOI:10.48550/arXiv.2607.06243.
  2. Y. Qiao et al., “A fabrication-aware inverse design method for thin-film lithium niobate photonic devices,” Optics Communications 596, 132506 (2025). DOI:10.1016/j.optcom.2025.132506.

Schematic of edge coupler

from pathlib import Path
from typing import NamedTuple

# NumPy wrapper for differentiable design-variable ops.
import autograd.numpy as np
import matplotlib.pyplot as plt
import shapely
import tidy3d as td
from autograd import grad_and_aux
from tidy3d import web
from tidy3d.plugins.autograd import adam, apply_updates
from tidy3d.plugins.autograd.invdes import tanh_projection
from tidy3d.plugins.invdes import FilterProject, smooth_polygon_vertices

td.config.logging.level = "ERROR"
td.config.adjoint.local_gradient = True
td.config.adjoint.parallel_run = True
FOLDER_NAME = "TFLNEdgeCoupler"

DATA_DIR = Path("./data")

Simulation Setup

Spectral and Material Parameters

We start by defining the optimization and broadband-characterization wavelengths, the source pulse bandwidth, and the materials: the anisotropic ordinary/extraordinary permittivities of x-cut TFLN and the SiO2 cladding index.

# um -> Hz; weight biases FOM toward these 3 wavelengths.
wls_opt = np.array([1.5, 1.55, 1.6])
freqs_opt = td.C_0 / wls_opt
weight = np.array([0.25, 0.5, 0.25])

# Broadband sweep (paper Fig. 2(e)).
wl_min, wl_max = 1.49, 1.61
wl_sweep = np.linspace(wl_min, wl_max, 61)
freq_sweep = td.C_0 / wl_sweep

# Pulse bandwidth covers the full sweep.
freq_min, freq_max = td.C_0 / wl_max, td.C_0 / wl_min
freq0 = 0.5 * (freq_min + freq_max)
fwidth = 0.55 * (freq_max - freq_min)

# x-cut TFLN: n_o along x/z, n_e along y (paper Results).
n_o, n_e = 2.21, 2.14
LN_o = td.Medium(permittivity=n_o**2, name="LN_o")
LN_e = td.Medium(permittivity=n_e**2, name="LN_e")
LN_bulk = td.AnisotropicMedium(xx=LN_o, yy=LN_e, zz=LN_o, name="LN")
wl_LN = wls_opt[1] / n_o

n_sio2 = 1.444
SiO2 = td.Medium(permittivity=n_sio2**2, name="SiO2")

Geometry Parameters

Next, we set the TFLN layer stack, sidewall angle, design-region footprint and pixel size, and the lensed-fiber mode parameters, which are shared by every simulation in this notebook.

# Layer stack (paper Fig. 2(a)): 500-nm TFLN, 300-nm etch -> 200-nm residual slab.
t_LN = 0.500
t_etch = 0.300
t_slab = t_LN - t_etch

h_clad = 1.0

# Design-region footprint (paper Fig. 2(a)): 25 x 15 um.
design_size = (25.0, 15.0)
min_feature_size = 0.4

buffer = (wl_max / 2, wl_max / 2, 2.25)

sim_size = (
    design_size[0] + 2 * buffer[0],
    design_size[1] + 2 * buffer[1],
    2 * buffer[2],
)

# dilation_radius: sidewall foot-to-top offset at full etch depth.
wg_width = 1.0
sidewall_angle = 30 * np.pi / 180
dilation_radius = t_etch * np.tan(sidewall_angle)

mfd = 2.0
waist_radius = mfd / 2

# Design pixel size; filter_radius enforces min_feature_size.
dl_design = 0.035
filter_radius = min_feature_size * (3**0.5)

nx = int(design_size[0] / dl_design)
ny = int(design_size[1] / dl_design)

# Pixel-center coords, shared by CustomMedium and density plots.
x_design = dl_design * np.arange(-nx / 2 + 0.5, nx / 2)
y_design = dl_design * np.arange(-ny / 2 + 0.5, ny / 2)

x_src = -design_size[0] / 2 - buffer[0] / 2
x_mnt = -x_src

Optimization Hyperparameters

We then define the Adam settings, the projection-strength (beta) ramp, the erosion/dilation penalty weight, and the three-stage schedule itself. Each Stage carries everything that distinguishes it — its per-step beta, filter radius, number of z-layers in the sidewall model, and erosion/dilation penalty offset — so the optimization loop and the result plots below both read the schedule from one place.

LR = 1.5e-2
ADAM_B1 = 0.8
ADAM_B2 = 0.95

N_SUBSTAGE = 4
BETA_INIT = 5
BETA_FIN = 500
BETA_SCHEDULE = np.exp(np.linspace(np.log(BETA_INIT), np.log(BETA_FIN), N_SUBSTAGE + 2))

WEIGHT_PEN = 1.0  # erosion/dilation penalty weight in the FOM

N_STEP_P1, N_STEP_P2, N_STEP_P3 = 4, 16, 20


class Stage(NamedTuple):
    label: str
    color: str  # convergence-plot shading color
    betas: np.ndarray  # projection strength per step
    radius: float  # conic-filter radius; 0 = projection only
    num_layers: int  # z-layers; 1 = vertical sidewall
    deta: float  # erosion/dilation eta offset; 0 disables

    @property
    def num_steps(self):
        return len(self.betas)


STAGES = (
    Stage(
        label="Phase 1: Continuous parameters",
        color="b",
        betas=np.full(N_STEP_P1, BETA_INIT),
        radius=0.0,
        num_layers=1,
        deta=0.0,
    ),
    Stage(
        label="Phase 2: Geometric constraints",
        color="orange",
        # ramp beta in N_SUBSTAGE chunks
        betas=BETA_SCHEDULE[1 + np.arange(N_STEP_P2) * N_SUBSTAGE // N_STEP_P2],
        radius=filter_radius,
        num_layers=1,
        deta=0.01,
    ),
    Stage(
        label="Phase 3: Sidewall angle",
        color="g",
        betas=np.full(N_STEP_P3, BETA_FIN),
        radius=filter_radius,
        num_layers=15,
        deta=0.04,
    ),
)

# per-stage start index; STEP_STARTS[-1] = total steps
STEP_STARTS = np.cumsum([0, *(stage.num_steps for stage in STAGES)])
N_STEP = int(STEP_STARTS[-1])

print(
    f"(Phase 1) Beta initial value: {BETA_SCHEDULE[0]:.1f}"
)
print(
    f"(Phase 2) Beta exponential ramp: {BETA_SCHEDULE[1]:.1f} to {BETA_SCHEDULE[-2]:.1f} over {N_STEP_P2} steps"
)
print(
    f"(Phase 3) Beta final value: {BETA_SCHEDULE[-1]:.1f}"
)
print(
    f"{N_STEP} steps total: " + ", ".join(f"{s.label} ({s.num_steps})" for s in STAGES)
)
(Phase 1) Beta initial value: 5.0
(Phase 2) Beta exponential ramp: 12.6 to 199.1 over 16 steps
(Phase 3) Beta final value: 500.0
40 steps total: Phase 1: Continuous parameters (4), Phase 2: Geometric constraints (16), Phase 3: Sidewall angle (20)

Base Simulation

The base simulation holds the components common to every candidate design: the LN slab/cladding/oxide layers, output waveguide, Gaussian-beam fiber source, and mode/field monitors.

inf = wl_LN * 10000

slab = td.Structure(
    geometry=td.Box.from_bounds(
        rmin=(-design_size[0] / 2, -inf, -t_slab), rmax=(inf, inf, 0)
    ),
    medium=LN_bulk,
    name="slab",
)

box = td.Structure(
    geometry=td.Box.from_bounds(
        rmin=(-design_size[0] / 2, -inf, -t_slab - inf), rmax=(inf, inf, -t_slab)
    ),
    medium=SiO2,
    name="box",
)

cladding = td.Structure(
    geometry=td.Box.from_bounds(
        rmin=(-design_size[0] / 2, -inf, 0), rmax=(inf, inf, h_clad)
    ),
    medium=SiO2,
    name="cladding",
)


def make_output_waveguide(x_left):
    return td.Structure(
        geometry=td.PolySlab(
            axis=2,
            sidewall_angle=sidewall_angle,
            reference_plane="top",
            slab_bounds=(0, t_etch),
            vertices=(
                (x_left, -wg_width / 2),
                (sim_size[0] * 1.1 / 2, -wg_width / 2),
                (sim_size[0] * 1.1 / 2, wg_width / 2),
                (x_left, wg_width / 2),
            ),
        ),
        medium=LN_bulk,
        name="output_waveguide",
    )


# wg: reference device; wg_short stops early for the GDS reconstruction.
wg = make_output_waveguide(-design_size[0] / 2 + dilation_radius)
wg_short = make_output_waveguide(design_size[0] / 2 * 0.9)

gauss_source = td.GaussianBeam(
    center=(x_src, 0, 0),
    size=(0, td.inf, td.inf),
    source_time=td.GaussianPulse(freq0=freq0, fwidth=fwidth),
    direction="+",
    pol_angle=0,
    num_freqs=5,
    waist_radius=waist_radius,
    waist_distance=-buffer[0] / 2,
)

mnt_mode = td.ModeMonitor(
    center=(x_mnt, 0, 0),
    size=(0, wg_width * 5, t_LN * 7),
    freqs=freq_sweep,
    mode_spec=td.ModeSpec(target_neff=n_e, num_modes=1),
    name="mode",
)

# Only 3 opt frequencies needed during optimization.
mnt_mode_reduced = mnt_mode.updated_copy(freqs=freqs_opt)

mnt_field_h = td.FieldMonitor(
    center=(0, 0, 0), size=(inf, inf, 0), name="field_h", freqs=freqs_opt
)

mnt_field_v = td.FieldMonitor(
    center=(0, 0, 0), size=(inf, 0, inf), name="field_v", freqs=freqs_opt
)

grid_spec = td.GridSpec.auto(min_steps_per_wvl=20, wavelength=wl_min)

sim_base = td.Simulation(
    size=sim_size,
    grid_spec=grid_spec,
    structures=[slab, cladding, box, wg],
    sources=[gauss_source],
    monitors=[mnt_mode, mnt_field_h, mnt_field_v],
    boundary_spec=td.BoundarySpec.all_sides(boundary=td.PML()),
    run_time=td.RunTimeSpec(quality_factor=5.0),
    symmetry=(0, -1, 0),
)

Plotting Helper

plot_eps_pair is a small helper that stacks two simulations’ permittivity cross-sections into one figure for side-by-side comparison; it is reused throughout the rest of the notebook.

# Stack two simulations' eps cross-sections for side-by-side comparison.
def plot_eps_pair(sim_a, sim_b, tight_layout=False, figsize=None, **plot_kwargs):
    fig, ax = plt.subplots(
        2, 1, sharex=True, sharey=True, tight_layout=tight_layout, figsize=figsize
    )
    sim_a.plot_eps(ax=ax[0], **plot_kwargs)
    sim_b.plot_eps(ax=ax[1], **plot_kwargs)
    return fig, ax

Topology Optimization

2D Design Parameters to 3D Density Distribution

preprocess maps the raw latent parameters to a density in [0, 1]: it symmetrizes about the propagation axis, low-pass filters with a conic filter of radius radius (minimum feature size), and projects with strength beta. With radius = 0 (phase 1) the filter is skipped and only the projection is applied.

dilate_sidewall models the non-vertical etched sidewall. A slanted sidewall means that, at depth t_etch - z below the top surface, every LN feature is laterally wider by (t_etch - z) * tan(sidewall_angle), i.e. the top-surface density dilated by a disk of that radius. A hard morphological dilation is not differentiable, so it is replaced by a smooth (log-sum-exp) max over the disk, evaluated for all pixels at once as an FFT convolution. Since an FFT convolution is circular, the density is first zero-padded by the kernel radius (and cropped back afterward) so the dilation does not wrap around the array — without this, the input facet and the output-waveguide edge of the design region would bleed into each other. A circular array has only one wraparound seam per axis, so a single one-sided buffer of the kernel radius is enough (no need to pad both sides).

# Latent params -> density in [0, 1]: symmetrize, conic-filter, project.
def preprocess(
    arr, beta=BETA_INIT, eta=0.5, radius=filter_radius, mirror_symmetry=True
):
    if mirror_symmetry:
        arr = (arr + arr[:, ::-1]) / 2
    if radius == 0:
        return tanh_projection(arr, beta=beta, eta=eta)
    fp = FilterProject(radius=radius, beta=beta, eta=eta)
    return fp.evaluate(spatial_data=arr, design_region_dl=dl_design)


# A circular array has one wraparound seam per axis, so a single one-sided
# pad >= kernel radius suffices (no need to pad both sides for a zero fill).
PAD_DILATION = int(np.ceil(dilation_radius / dl_design)) + 2
nx_pad, ny_pad = nx + PAD_DILATION, ny + PAD_DILATION
_X_KERNEL, _Y_KERNEL = np.meshgrid(
    dl_design * np.arange(nx_pad), dl_design * np.arange(ny_pad), indexing="ij"
)
R_KERNEL = np.sqrt(
    (_X_KERNEL - dl_design * int(nx_pad / 2)) ** 2
    + (_Y_KERNEL - dl_design * int(ny_pad / 2)) ** 2
)


# Differentiable soft dilation via log-sum-exp FFT; zero-padded to avoid wraparound.
def dilate_sidewall(
    density,
    dilation_radius=dilation_radius,
    gamma=20,
    eps=1e-12,
    pad=PAD_DILATION,
):
    if dilation_radius <= 0:
        return density

    density_padded = np.pad(density, ((0, pad), (0, pad)), mode="constant")

    mask = np.fft.ifftshift((R_KERNEL <= dilation_radius).astype(float))
    count = np.sum(mask)
    mask_F = np.fft.fft2(mask)

    c = np.max(density_padded)  # for numerical stability; cancels out exactly
    exp_density_F = np.fft.fft2(np.exp(gamma * (density_padded - c)))
    window_sum = np.real(np.fft.ifft2(exp_density_F * mask_F))

    result_padded = c + (np.log(window_sum + eps) - np.log(count)) / gamma
    nx_d, ny_d = density.shape
    return result_padded[:nx_d, :ny_d]

Density to Simulation

get_design_structure turns a density into the anisotropic design region. The density is linearly interpolated between SiO2 and LN per diagonal permittivity component (n_o, n_e, n_o) and assembled into a td.CustomAnisotropicMedium, so the optimizer sees the true anisotropic TFLN response. With num_layers > 1 the region is stacked into that many z-layers, each dilated by the amount appropriate to its depth.

# Build the anisotropic CustomMedium design region from latent params.
def get_design_structure(
    params,
    n_max=(n_o, n_e, n_o),
    n_min=n_sio2,
    beta=BETA_INIT,
    eta=0.5,
    radius=filter_radius,
    num_layers=1,
):
    density = preprocess(params, beta=beta, eta=eta, radius=radius)

    z = [t_etch / 2] if num_layers == 1 else np.linspace(0, t_etch, num_layers)
    coords = {"x": x_design, "y": y_design, "z": z}

    if num_layers == 1:
        density_3d = density.reshape(nx, ny, 1)
    else:
        density_3d = np.stack(
            [
                dilate_sidewall(
                    density, dilation_radius=(t_etch - z_layer) * np.tan(sidewall_angle)
                )
                for z_layer in z
            ],
            axis=2,
        )

    eps_min = np.asarray(n_min) ** 2
    eps_max = np.asarray(n_max) ** 2

    custom_media = [
        td.CustomMedium(
            permittivity=td.SpatialDataArray(
                density_3d * eps_c + (1 - density_3d) * eps_min, coords=coords
            ),
            name=f"LN_custom_{ii}",
        )
        for ii, eps_c in enumerate(eps_max)
    ]
    custom_aniso_medium = td.CustomAnisotropicMedium(
        xx=custom_media[0], yy=custom_media[1], zz=custom_media[2], name="LN_custom"
    )

    return td.Structure(
        geometry=td.Box(center=(0, 0, t_etch / 2), size=(*design_size, t_etch)),
        medium=custom_aniso_medium,
    )


# sim_base plus the design region; reduced_mnt keeps only the mode monitor.
def make_sim(
    params,
    beta=BETA_INIT,
    eta=0.5,
    radius=filter_radius,
    reduced_mnt=True,
    num_layers=1,
):
    design_str = get_design_structure(
        params, beta=beta, eta=eta, radius=radius, num_layers=num_layers
    )
    monitors = [mnt_mode_reduced] if reduced_mnt else sim_base.monitors
    return sim_base.updated_copy(
        structures=[*sim_base.structures, design_str], monitors=monitors
    )

As a sanity check, we render the same random design with a vertical sidewall (single layer) and with the soft-dilation sidewall model (15 layers). The side view shows the expected widening of every LN feature toward the bottom of the etch.

np.random.seed(4)
params_random = np.random.rand(nx, ny)

sim_vertical = make_sim(params_random, beta=BETA_FIN, reduced_mnt=False)
sim_dilated = make_sim(params_random, beta=BETA_FIN, num_layers=15, reduced_mnt=False)

fig, ax = plot_eps_pair(
    sim_vertical, sim_dilated, tight_layout=True, figsize=(8, 8), y=1e-5
)
ax[0].set_title("Vertical sidewall (1 layer)")
ax[1].set_title("Soft-dilated sidewall (15 layers)")
ax[1].set(xlim=(-5, 5), ylim=(-1, 1));

Figure of Merit and Adjoint Gradient

figure_of_merit follows the paper directly: the objective is the weighted average TE0 coupling efficiency over the optimization wavelengths (not a log-sum, since there is a single output channel rather than several competing ones as in a wavelength router). penalty is the erosion/dilation robustness measure. Each design is passed through two filter-project steps with thresholds shifted by ∓deta (at strength sqrt(beta)), giving a morphological closing (dilate then erode) and an opening (erode then dilate); their RMS difference is nonzero only where features are smaller than the filter length scale. It is scaled by WEIGHT_PEN and subtracted from the efficiency whenever deta > 0, i.e. in phases 2 and 3.

param2fom builds and runs the corresponding simulation and evaluates the total FOM. Wrapping it with Autograd’s grad_and_aux returns the adjoint gradient with respect to all nx * ny (714 x 428, roughly 3e5) design pixels at the cost of a single extra (adjoint) simulation, together with the FOM terms and per-wavelength amplitudes used for logging.

# Strip Autograd's box wrapper, if present.
def _value(x):
    return getattr(x, "_value", x)


# Weighted-average TE0 coupling efficiency over the optimization wavelengths.
def figure_of_merit(sim_data, weight=weight):
    S21 = (
        sim_data["mode"]
        .amps.sel(f=freqs_opt, method="nearest")
        .sel(direction="+")
        .values.reshape(-1)
    )
    return np.sum(weight * np.abs(S21) ** 2), S21


# Erosion/dilation robustness penalty: RMS gap between eroded and dilated designs.
def penalty(params, beta=BETA_INIT, radius=filter_radius, eta=0.5, deta=0.001):
    density_d = preprocess(
        preprocess(params, beta=beta**0.5, radius=radius, eta=eta - deta),
        beta=beta**0.5,
        radius=radius,
        eta=eta + deta,
    )
    density_e = preprocess(
        preprocess(params, beta=beta**0.5, radius=radius, eta=eta + deta),
        beta=beta**0.5,
        radius=radius,
        eta=eta - deta,
    )
    diff = density_d - density_e
    return np.sqrt(np.mean(diff**2)), diff


# Run one forward simulation, return (total FOM, aux values for logging).
def param2fom(
    params,
    beta=BETA_INIT,
    radius=filter_radius,
    num_layers=1,
    step=0,
    deta=0.0,
    pen_weight=WEIGHT_PEN,
):
    sim = make_sim(params, beta=beta, radius=radius, num_layers=num_layers)
    sim_data = web.run(
        simulation=sim,
        task_name=f"Step {step}",
        folder_name=FOLDER_NAME,
        path=DATA_DIR / "opt" / f"{step}.hdf5",
        verbose=False,
    )
    fom_n, s21 = figure_of_merit(sim_data)

    if deta > 0:
        de_pen, _ = penalty(params, beta=beta, radius=radius, deta=deta)
        fom_tot = fom_n - pen_weight * de_pen
    else:
        de_pen = 0.0
        fom_tot = fom_n

    return fom_tot, [_value(fom_tot), _value(fom_n), _value(de_pen), _value(s21)]


# Adjoint gradient of FOM w.r.t. params, plus aux FOM/efficiency outputs.
grad_aux_p2f = grad_and_aux(param2fom, argnum=(0,))

Run Topology Optimization

The optimization loop runs the three stages defined in STAGES: each step calls grad_aux_p2f for the forward FOM and adjoint gradient, applies an Adam update (on the negated gradient, since the FOM is maximized), and logs the result to opt_history, which the plots below read from directly.

optimizer = adam(learning_rate=LR, beta1=ADAM_B1, beta2=ADAM_B2)

params_init = 0.5 * np.ones([nx, ny])
params = params_init.copy()
opt_state = optimizer.init(params_init)
opt_history = {
    "grad": [],
    "fom_tot": [],
    "fom_n": [],
    "de_pen": [],
    "params": [],
    "s21": [],
}

HEADER = ("step", "beta", "FOM_tot", "FOM_n", "penalty", "IL(dB)", "max_grad")

for stage, step_start in zip(STAGES, STEP_STARTS):
    print(stage.label)
    print(f"{HEADER[0]:>5}", *(f"{name:>10}" for name in HEADER[1:]))

    for i, beta in enumerate(stage.betas):
        step = step_start + i
        opt_history["params"].append(params.copy())

        (grad,), (fom_tot, fom_n, de_pen, s21) = grad_aux_p2f(
            params,
            beta=beta,
            radius=stage.radius,
            num_layers=stage.num_layers,
            step=step,
            deta=stage.deta,
        )

        updates, opt_state = optimizer.update(-grad, opt_state, params)
        params = apply_updates(params, updates)
        max_grad = np.abs(grad).max()
        IL_center = 20 * np.log10(np.abs(s21[1])).item()

        opt_history["grad"].append(grad)
        opt_history["fom_tot"].append(float(fom_tot))
        opt_history["fom_n"].append(float(fom_n))
        opt_history["de_pen"].append(float(de_pen))
        opt_history["s21"].append(s21)

        print(
            f"{step:>5}",
            f"{beta:>10.1f}",
            f"{fom_tot:>10.3f}",
            f"{fom_n:>10.3f}",
            f"{de_pen:>10.4f}",
            f"{IL_center:>10.2f}",
            f"{max_grad:>10.4f}",
        )

np.savez(DATA_DIR / "opt_history.npz", **opt_history)
Phase 1: Continuous parameters
 step       beta    FOM_tot      FOM_n    penalty     IL(dB)   max_grad
    0        5.0      0.123      0.123     0.0000      -9.10     0.0010
    1        5.0      0.400      0.400     0.0000      -3.90     0.0021
    2        5.0      0.584      0.584     0.0000      -2.22     0.0017
    3        5.0      0.673      0.673     0.0000      -1.64     0.0019
Phase 2: Geometric constraints
 step       beta    FOM_tot      FOM_n    penalty     IL(dB)   max_grad
    4       12.6      0.652      0.681     0.0284      -1.65     0.0012
    5       12.6      0.698      0.726     0.0281      -1.37     0.0008
    6       12.6      0.714      0.742     0.0278      -1.28     0.0007
    7       12.6      0.730      0.757     0.0276      -1.19     0.0005
    8       31.5      0.591      0.674     0.0837      -1.68     0.0017
    9       31.5      0.643      0.724     0.0815      -1.38     0.0014
   10       31.5      0.670      0.749     0.0789      -1.25     0.0009
   11       31.5      0.671      0.747     0.0760      -1.26     0.0016
   12       79.2      0.530      0.689     0.1590      -1.56     0.0064
   13       79.2      0.563      0.703     0.1400      -1.48     0.0052
   14       79.2      0.598      0.717     0.1191      -1.41     0.0029
   15       79.2      0.625      0.728     0.1029      -1.35     0.0040
   16      199.1      0.564      0.704     0.1401      -1.54     0.0055
   17      199.1      0.519      0.649     0.1298      -1.85     0.0208
   18      199.1      0.536      0.659     0.1232      -1.78     0.0145
   19      199.1      0.580      0.696     0.1161      -1.53     0.0104
Phase 3: Sidewall angle
 step       beta    FOM_tot      FOM_n    penalty     IL(dB)   max_grad
   20      500.0      0.292      0.636     0.3441      -1.92     0.0143
   21      500.0      0.357      0.685     0.3273      -1.63     0.0049
   22      500.0      0.396      0.708     0.3113      -1.46     0.0117
   23      500.0      0.379      0.676     0.2967      -1.66     0.0177
   24      500.0      0.433      0.717     0.2840      -1.40     0.0035
   25      500.0      0.435      0.707     0.2727      -1.47     0.0221
   26      500.0      0.381      0.644     0.2629      -1.88     0.0236
   27      500.0      0.446      0.700     0.2543      -1.51     0.0180
   28      500.0      0.433      0.679     0.2463      -1.62     0.0134
   29      500.0      0.447      0.685     0.2386      -1.58     0.0103
   30      500.0      0.478      0.709     0.2312      -1.44     0.0029
   31      500.0      0.484      0.708     0.2243      -1.45     0.0110
   32      500.0      0.495      0.713     0.2179      -1.43     0.0089
   33      500.0      0.513      0.725     0.2120      -1.35     0.0024
   34      500.0      0.518      0.725     0.2065      -1.35     0.0061
   35      500.0      0.523      0.724     0.2014      -1.35     0.0074
   36      500.0      0.534      0.730     0.1968      -1.32     0.0009
   37      500.0      0.534      0.727     0.1927      -1.35     0.0064
   38      500.0      0.543      0.732     0.1890      -1.31     0.0037
   39      500.0      0.549      0.735     0.1857      -1.29     0.0019

Results

Convergence History

The plot below shows the FOM and the center-wavelength coupling efficiency over the run, with the three stages shaded.

fig, ax = plt.subplots(figsize=(6, 3))
ax.plot(opt_history["fom_tot"], "k")
ax.set(xlabel=r"Iteration", ylabel=r"FOM", xlim=(-1, N_STEP), ylim=(0.1, 0.9))

for stage, step_start, step_end in zip(STAGES, STEP_STARTS, STEP_STARTS[1:]):
    ax.fill_betweenx(
        [0, 1],
        step_start - (1 if step_start == 0 else 0),
        step_end,
        color=stage.color,
        alpha=0.1,
        lw=0,
        label=stage.label,
    )
ax.legend()

axt = ax.twinx()
axt.plot(20 * np.log10(np.abs(opt_history["s21"])[:, 1]), "r")
axt.set(ylim=(-4, 0))
axt.set_ylabel("Coupling efficiency (dB)", color="r")
axt.set_yticks(np.linspace(-4, 0, 9))
axt.set_yticklabels(np.linspace(-4, 0, 9), color="r");

Intermediate and Final Parameters

The figure shows the latent parameters and the density they project to at the last step of each stage, each rendered with that stage’s own beta and filter radius. The bottom row is the top-surface density of the final design. The final parameters are also turned into sim_opt, the 15-layer CustomMedium simulation with all monitors, from which the top-surface contour is traced and which is used for validation.

fig, ax = plt.subplots(
    3, 2, figsize=(8, 7), sharex=True, sharey=True, tight_layout=True
)
x_grid, y_grid = np.meshgrid(x_design, y_design, indexing="ij")

for ii, (stage, step_end) in enumerate(zip(STAGES, STEP_STARTS[1:])):
    params_stage = opt_history["params"][step_end - 1]
    density = preprocess(params_stage, beta=stage.betas[-1], radius=stage.radius)

    ax[ii, 0].pcolormesh(
        x_grid, y_grid, params_stage, cmap=plt.cm.Greys, vmin=0, vmax=1
    )
    pc = ax[ii, 1].pcolormesh(
        x_grid, y_grid, density, cmap=plt.cm.Greys, vmin=0, vmax=1
    )
    ax[ii, 0].set(ylabel=r"$y$ (um)")
    for jj in range(2):
        ax[ii, jj].set(aspect="equal")
        ax[-1, jj].set(xlabel=r"$x$ (um)")

ax[0, 0].set_title("Design Parameter")
ax[0, 1].set_title("Density")
ax[2, 1].set_title("Density (Top Surface)")

cax = ax[1, 1].inset_axes([1.05, 0, 0.05, 1])
cbar = plt.colorbar(pc, cax=cax)
cbar.ax.set_yticks([0, 0.5, 1])
cbar.ax.set_yticklabels(["0 (SiO2)", 0.5, "1 (LN)"])

params_opt = opt_history["params"][-1]
sim_opt = make_sim(
    params_opt, beta=BETA_FIN, reduced_mnt=False, num_layers=15
).updated_copy(shutoff=1e-6)

Fabrication-Realistic Geometry

Contour Extraction

Structure.to_gdstk traces the top-surface contour directly from sim_opt: its top layer (z = t_etch, the undilated, binarized top surface) is cut at the 0.5 density level. Since it thresholds a scalar permittivity, only the xx component is used; all components share the same density.

# to_gdstk needs a scalar permittivity.
design_opt_aniso = sim_opt.structures[-1]
design_opt_iso = design_opt_aniso.updated_copy(medium=design_opt_aniso.medium.xx)

# Top surface, 0.5 density level.
polygons = design_opt_iso.to_gdstk(
    z=t_etch, permittivity_threshold=(n_sio2**2 + n_o**2) / 2, frequency=freq0
)

# Raw GDS polygons over the top-surface permittivity.
fig, ax = plt.subplots(figsize=(6, 6))
sim_opt.updated_copy(symmetry=(0, 0, 0)).plot_eps(z=t_etch, freq=freq0, ax=ax)

axins = ax.inset_axes([0, 1.1, 1, 1], xlim=(-8.5, -5.5), ylim=(-1.5, 1.5), xticks=[])
ax.indicate_inset_zoom(axins, edgecolor="c", lw=4)
axins.set_aspect("equal")

for polygon in polygons:
    vertices = polygon.points
    vertices = np.vstack((vertices, vertices[0]))
    ax.plot(vertices[:, 0], vertices[:, 1])
    axins.plot(vertices[:, 0], vertices[:, 1])

The raw polygons follow the design pixel grid. GDS has no holes, so each hole is joined to its outline by a zero-width “keyhole” slit. The inset zooms in near the input facet.

The small hole near the input facet (x ≈ -7 μm) has LN ridges of about 0.25-0.3 μm: the filter and erosion/dilation penalty only encourage, not enforce, the 0.4-μm min_feature_size.

Polyslab Structure

The GDS reconstruction converts the polygons back to 3D in three steps:

  1. Separate each keyhole polygon into islands (LN) and holes (SiO2) with shapely.make_valid.
  2. Smooth each ring, after resampling to dl_design; the raw pixel staircase makes the slanted extrusion fail.
  3. Extrude with td.Geometry.from_shapely from the top plane, so islands widen and holes narrow toward the bottom. No feature splits or closes within the etch depth, so a single extrusion suffices.

The result is clipped at the input facet and paired with wg_short.

# Split keyhole polygons into exterior (island) and interior (hole) rings.
shape = shapely.unary_union(
    [shapely.make_valid(shapely.Polygon(polygon.points)) for polygon in polygons]
)

# Resample so smoothing doesn't cut long straight edges, then smooth away the pixel staircase.
shape = shapely.segmentize(shape, max_segment_length=dl_design)
islands, holes = [], []  # holes[i]: list of hole rings inside islands[i]
for geo in getattr(shape, "geoms", [shape]):
    if geo.geom_type != "Polygon":
        continue  # leftover slit segments
    islands.append(smooth_polygon_vertices(np.array(geo.exterior.coords[:-1]), sigma=4))
    holes.append(
        [
            smooth_polygon_vertices(np.array(ring.coords[:-1]), sigma=4)
            for ring in geo.interiors
        ]
    )
print(f"{len(islands)} islands, {sum(len(h) for h in holes)} holes")

# Islands widen, holes narrow toward the bottom.
geom_gds = td.GeometryGroup(
    geometries=[
        td.Geometry.from_shapely(
            shapely.Polygon(island, island_holes),
            axis=2,
            slab_bounds=(0, t_etch),
            sidewall_angle=sidewall_angle,
            reference_plane="top",
        )
        for island, island_holes in zip(islands, holes)
    ]
)
# Clip LN that the slanted sidewalls push past the input facet.
box_air = td.Box.from_bounds(
    rmin=(-inf, -inf, -inf), rmax=(-design_size[0] / 2, inf, inf)
)
# wg_short: the full-length wg would fill the design's gaps.
sim_opt_gds = sim_base.updated_copy(
    structures=[
        slab,
        cladding,
        box,
        wg_short,
        td.Structure(
            geometry=td.ClipOperation(
                operation="difference", geometry_a=geom_gds, geometry_b=box_air
            ),
            medium=LN_bulk,
        ),
    ]
)

# Islands (red), holes (blue).
fig, ax = plt.subplots(figsize=(6, 6))
sim_opt.updated_copy(symmetry=(0, 0, 0)).plot_eps(z=t_etch, freq=freq0, ax=ax)

axins = ax.inset_axes([0, 1.1, 1, 1], xlim=(-8.5, -5.5), ylim=(-1.5, 1.5), xticks=[])
ax.indicate_inset_zoom(axins, edgecolor="c", lw=4)
axins.set_aspect("equal")

for island, island_holes in zip(islands, holes):
    ax.plot(*np.vstack((island, island[:1])).T, "r")
    axins.plot(*np.vstack((island, island[:1])).T, "r")
    for hole in island_holes:
        ax.plot(*np.vstack((hole, hole[:1])).T, "b")
        axins.plot(*np.vstack((hole, hole[:1])).T, "b")
3 islands, 3 holes

Geometry Comparison

A yz cross-section at x = -1.5 μm, through the enclosed hole near y = 5.5 μm, compares the CustomMedium staircase with the slanted sidewalls of the GDS reconstruction; the second figure is the top surface, with the red line marking the cut.

fig, ax = plot_eps_pair(sim_opt, sim_opt_gds, x=-1.5)
ax[1].set(ylim=(-1, 1), xlim=(0, 8))
ax[0].set_title("CustomMedium")
ax[1].set_title("GDS reconstruction")

fig, ax = plot_eps_pair(
    sim_opt, sim_opt_gds, tight_layout=True, z=t_etch, figsize=(8, 8)
)
ax[0].plot([-1.5, -1.5], [0, 8], "r")
ax[1].plot([-1.5, -1.5], [0, 8], "r")
ax[0].set_title("CustomMedium")
ax[1].set_title("GDS reconstruction")
Text(0.5, 1.0, 'GDS reconstruction')

Validation

We run the reference straight waveguide, the optimized design, and the GDS reconstruction together as one batch simulation across the full 1490-1610 nm characterization sweep.

sims = {
    "ref": sim_base,
    "opt": sim_opt,
    "opt_gds": sim_opt_gds,
}

batch_data = web.run_async(
    simulations=sims, folder_name=FOLDER_NAME, path_dir=DATA_DIR / "result"
)
Uploading data for 3 tasks ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100% 0:00:10

13:33:06 UTC Started working on Batch containing 3 tasks.                       
13:33:12 UTC Maximum FlexCredit cost: 0.598 for the whole batch.                
             Use 'Batch.real_cost()' to get the billed FlexCredit cost after    
             completion.                                                        
13:39:12 UTC Batch complete.                                                    
ref             → success ━━━━━━━━━━━━━━━━━━━━━━━━━ 100% 0:05:58
opt             → success ━━━━━━━━━━━━━━━━━━━━━━━━━ 100% 0:05:58
opt_gds         → success ━━━━━━━━━━━━━━━━━━━━━━━━━ 100% 0:05:58

Comparison

We plot the coupling-efficiency spectrum for all designs, together with the steady-state field distributions of the optimized design and its GDS reconstruction at the 1550-nm center wavelength: \(H_z\) in the horizontal (xy) plane and \(E_y\) in the vertical (xz) plane.

LABELS = {
    "ref": "Ref. (straight waveguide)",
    "opt": "Opt. CustomMedium",
    "opt_gds": "GDS reconstruction",
}

fig, ax = plt.subplots()
for key, label in LABELS.items():
    s21 = batch_data[key]["mode"].amps.sel(direction="+").squeeze()
    ax.plot(wl_sweep, 20 * np.log10(np.abs(s21)), label=label)
ax.set(
    xlabel=r"Wavelength (um)", ylabel=r"Coupling efficiency (dB)", xlim=(wl_min, wl_max)
)
ax.legend()

fig_h, ax_h = plt.subplots(
    2, 1, sharex=True, sharey=True, tight_layout=True, figsize=(7, 7)
)
fig_v, ax_v = plt.subplots(
    2, 1, sharex=True, sharey=True, tight_layout=True, figsize=(7, 7)
)

for ii, key in enumerate(("opt", "opt_gds")):
    batch_data[key].plot_field(
        field_monitor_name="field_h", field_name="Hz", f=freqs_opt[1], ax=ax_h[ii]
    )
    batch_data[key].plot_field(
        field_monitor_name="field_v", field_name="Ey", f=freqs_opt[1], ax=ax_v[ii]
    )
    ax_h[ii].set_title(LABELS[key])
    ax_v[ii].set_title(LABELS[key])

The optimized coupler (sim_opt) reaches -1.27 to -1.53 dB across 1490-1610 nm (-1.29 dB at 1550 nm), 1.2-1.4 dB better than the straight waveguide from a 25-μm-long device. The GDS reconstruction (sim_opt_gds) matches it within 0.01 dB at 1610 nm, with the gap growing to 0.2 dB at 1550 nm and 0.3 dB at 1490 nm, confirming that the anisotropic CustomMedium with soft-dilation sidewalls is a faithful stand-in for the fabricated geometry.

GDS Export

The mask is the top face of the GDS reconstruction, i.e. the smoothed, facet-clipped polygons that were simulated, so the layout and the validated geometry match exactly. It holds only the 2D layout; the sidewall angle comes from the etch.

sim_opt_gds.structures[-1].to_gds_file(
    DATA_DIR / "tfln_edge_coupler_mask.gds", z=t_etch, gds_cell_name="COUPLER"
)