DRC-safe updates for a dual-layer focused grating coupler#
Gradient-based inverse design with adjoint gradients is a powerful way to improve a photonic device using many parameters at once. However, an optimizer can propose a design that improves the optical objective while violating a design rule, such as a minimum feature or gap size.
One way to prevent this is to hardcode design rules directly in the parameterization via constraints. That can become cumbersome when the parameterization is flexible, the rules interact, or verification is performed by an external tool that is hard to model. A penalty function or filtering technique can encourage compliant designs, but does not generally guarantee that every proposal passes verification. Direct constraints can also be overly restrictive when the simplest constraint that guarantees compliance removes useful design freedom. This notebook instead treats verification as a black-box check: given any parameterization and a function that reports whether a candidate design passes, BacktrackingSafeUpdate selects a valid optimizer update. Starting from a DRC-clean initial design, it accepts only updates that pass the verification function.
We demonstrate the workflow with a dual-layer Si/SiN focused grating coupler. Tidy3D supplies adjoint gradients for the optical objective, while KLayout evaluates the exported layouts. The same safe-update interface can use another DRC engine, a geometry service, or any other verification function that returns a pass/fail response.
This workflow builds on the autograd quickstart and the KLayout DRC plugin quickstart.
Method#
Let \(\mathbf{p}_{\mathrm{old}}\) be a DRC-clean parameter vector and \(\mathbf{p}_{\mathrm{new}}\) be the optimizer proposal. For each scale \(\alpha\), the line search checks
The full proposal can be invalid while a shorter update remains valid. The line search below checks the full remaining update first, then reduces it by the factor \(\gamma\) after a failed check. It stops after at most max_backtracks reductions; if no candidate passes, that update is not applied.
Each iteration applies this line search first to a global update, moving every parameter together from its current value toward the optimizer proposal. Starting from the best DRC-clean global candidate, it then applies the same line search to each remaining parameter update. The verification function can be any black-box function that returns a design-verification response.
Candidate updates#
The parameter-space diagram below gives another view of the candidate designs checked by the line search. Each point on the line corresponds to a complete parameter vector; the method accepts the longest candidate update that the verification function reports as clean.
Imports and Parameters#
The initial non-uniform tooth widths, gaps, and radial offsets are taken from the fabrication-aware adjoint optimization example.
[1]:
from pathlib import Path
import autograd.numpy as anp
import gdstk
import matplotlib.pyplot as plt
import numpy as np
import tidy3d as td
import tidy3d.web as web
from matplotlib.patches import Patch, Polygon, Rectangle
from tidy3d.plugins.autograd import (
BacktrackingSafeUpdate,
CoordinateRecovery,
adam,
apply_updates,
value_and_grad,
)
from tidy3d.plugins.klayout import BatchedDRCChecker
td.config.logging.level = "ERROR"
wavelength = 1.55 # Design wavelength in µm.
freq0 = td.C_0 / wavelength # Design frequency in Hz.
num_teeth = 15 # Number of teeth on each material layer.
num_half_controls = 5 # Independent angular sites from y=0 to one grating edge.
num_full_controls = 2 * num_half_controls - 1 # Physical sites after reflection about y=0.
# Initial tooth widths and gaps in µm.
width_si = np.array(
[0.483, 0.521, 0.456, 0.464, 0.444, 0.473, 0.490, 0.434, 0.547, 0.361, 0.351, 0.252, 0.229, 0.218, 0.587]
)
gap_si = np.array(
[0.661, 0.715, 0.676, 0.763, 0.696, 0.649, 0.727, 0.657, 0.743, 0.891, 0.920, 0.888, 0.844, 0.788, 0.799]
)
width_sin = np.array(
[0.789, 0.644, 0.522, 0.314, 0.604, 0.571, 0.610, 0.567, 0.591, 0.551, 0.676, 0.424, 0.492, 0.599, 0.704]
)
gap_sin = np.array(
[0.454, 0.480, 0.308, 0.491, 0.548, 0.603, 0.656, 0.593, 0.478, 0.448, 0.733, 0.630, 0.488, 0.356, 0.514]
)
first_gap_si = -0.672 # Radial position of the first Si tooth in µm.
first_gap_sin = 0.504 # Radial position of the first SiN tooth in µm.
h_box = 2.0 # Buried oxide thickness in µm.
h_si = 0.09 # Silicon tooth thickness in µm.
h_spacer = 0.30 # Oxide spacing between Si and SiN in µm.
h_sin = 0.40 # Silicon-nitride tooth thickness in µm.
wg_width = 1.0 # SiN input-waveguide width in µm.
wg_feed_length = 3.0 # Straight input-waveguide length in µm.
input_extension = 2.0 # Extra input-waveguide length extending through the x boundary PML in µm.
sector_offset = 7.8 # Radial offset from focus to the grating sector in µm.
half_angle = np.deg2rad(41.0) / 2 # Focused-grating half aperture angle.
beam_offset_x = 5.0 # Fiber-beam position relative to the sector offset in µm.
beam_height = 2.0 # Beam height above the SiN layer in µm.
beam_mfd = 10.0 # Gaussian beam mode-field diameter in µm.
beam_angle = np.deg2rad(10.0) # Beam tilt from surface normal.
substrate_medium = td.Medium(permittivity=12.04) # Relative permittivity of the silicon substrate.
oxide_medium = td.Medium(permittivity=2.25) # Relative permittivity of the oxide background and cladding.
si_medium = td.Medium(permittivity=12.04) # Relative permittivity of the silicon teeth.
sin_medium = td.Medium(permittivity=4.00) # Relative permittivity of the silicon-nitride teeth and feed.
sin_center_z = h_box + h_si + h_spacer + h_sin / 2 # SiN layer center height.
si_center_z = h_box + h_si / 2 # Si layer center height.
arc_angles = np.linspace(-half_angle, half_angle, 181) # Samples used for each curved tooth.
half_control_angles = np.linspace(0, half_angle, num_half_controls) # Optimized sites on y≥0.
control_angles = np.concatenate((-half_control_angles[1:][::-1], half_control_angles)) # Physical angular sites after reflection.
control_to_arc = np.column_stack(
[np.interp(arc_angles, control_angles, np.eye(num_full_controls)[:, index]) for index in range(num_full_controls)]
) # Linear interpolation from controls to curved-tooth samples.
DRC Runset#
The KLayout runset checks each mapped layer independently for a 150 nm minimum width and a 100 nm minimum space. The initial layout must pass these checks before safe updates can begin.
[2]:
drc_runset = Path("assets") / "rules.drc"
gds_layers = {"si": (0, 0), "sin": (2, 0)} # KLayout layer/datatype mapping.
min_width = 0.15 # Minimum allowed tooth width on each layer in µm.
min_space = 0.10 # Minimum allowed tooth space on each layer in µm.
drc_args = {
"layer_si": gds_layers["si"][0],
"datatype_si": gds_layers["si"][1],
"layer_sin": gds_layers["sin"][0],
"datatype_sin": gds_layers["sin"][1],
"min_width_si": min_width,
"min_width_sin": min_width,
"min_space_si": min_space,
"min_space_sin": min_space,
}
Parameterization#
Every angular profile is defined only on the \(y\geq0\) half of a tooth and reflected to the \(y<0\) half. The optical simulation also uses symmetry=(0, -1, 0).
The parameterization has separate inner and outer edge controls at five angular sites for each of 15 Si teeth and 15 SiN teeth: \(2\times2\times15\times5=300\) parameters. Reflection produces nine physical sites per tooth while preserving y symmetry. At zero controls, the parameterization reproduces the non-uniform legacy layout.
Each marker in the schematic represents an independently optimized additive radial edge offset from the baseline radius. The profiles between markers are linearly interpolated and sampled at 181 angular positions before export.
A width-and-gap parameterization with transformed variables could enforce conservative radial minimum widths and gaps for this particular rule set. With these independent edge controls, however, checking only the five controls does not certify the curved layout: the interpolated arc samples must also preserve edge ordering and minimum feature and gap sizes. Encoding that directly would require reparameterizing the controls and enforcing the constraints along every interpolated arc. This example instead retains the flexible edge controls and has KLayout evaluate the Euclidean width and space of the exported curved polygons.
[3]:
params0 = anp.zeros(2 * 2 * num_teeth * num_half_controls)
def base_edges(widths, gaps, first_gap):
inner = first_gap + wg_feed_length + np.concatenate(([0.0], np.cumsum(widths[:-1] + gaps[:-1])))
return inner, inner + widths
base_inner_si, base_outer_si = base_edges(width_si, gap_si, first_gap_si)
base_inner_sin, base_outer_sin = base_edges(width_sin, gap_sin, first_gap_sin)
def reflect_controls(half_controls):
return anp.concatenate((half_controls[:, 1:][:, ::-1], half_controls), axis=1)
def position_profiles(params):
controls = anp.reshape(params, (2, 2, num_teeth, num_half_controls))
si_inner, si_outer = reflect_controls(controls[0, 0]), reflect_controls(controls[0, 1])
sin_inner, sin_outer = reflect_controls(controls[1, 0]), reflect_controls(controls[1, 1])
return (base_inner_si[:, None] + si_inner, base_outer_si[:, None] + si_outer), (base_inner_sin[:, None] + sin_inner, base_outer_sin[:, None] + sin_outer)
Dual-Layer Simulation#
The geometry, layer stack, source, monitor, aperture, and non-uniform seed follow the legacy dual-layer setup. A full y-symmetric layout is supplied to Tidy3D; the symmetry boundary reduces the simulated domain by half.
[4]:
def tooth_vertices(inner_profile, outer_profile):
center_x = -wg_feed_length
inner = inner_profile + sector_offset
outer = outer_profile + sector_offset
return anp.concatenate(
(
anp.column_stack((center_x + outer * anp.cos(arc_angles), outer * anp.sin(arc_angles))),
anp.column_stack((center_x + inner[::-1] * anp.cos(arc_angles[::-1]), inner[::-1] * anp.sin(arc_angles[::-1]))),
)
)
def teeth_geometry(profiles, thickness, center_z):
inner, outer = profiles
geometries = []
for tooth_index in range(num_teeth):
inner_control = anp.full(num_full_controls, inner[tooth_index]) if anp.ndim(inner) == 1 else inner[tooth_index]
inner_profile = anp.dot(control_to_arc, inner_control)
outer_profile = anp.dot(control_to_arc, outer[tooth_index])
geometries.append(
td.PolySlab(
vertices=tooth_vertices(inner_profile, outer_profile),
axis=2,
slab_bounds=(center_z - thickness / 2, center_z + thickness / 2),
)
)
return td.GeometryGroup(geometries=geometries)
def sin_base_geometry():
center_x = -wg_feed_length
radius = wg_feed_length + sector_offset
sector = np.vstack((np.c_[center_x + radius * np.cos(arc_angles), radius * np.sin(arc_angles)], [[center_x, 0.0]]))
return td.GeometryGroup(
geometries=[
td.PolySlab(vertices=sector, axis=2, slab_bounds=(sin_center_z - h_sin / 2, sin_center_z + h_sin / 2)),
td.Box(
center=(-wg_feed_length / 2 - input_extension / 2, 0, sin_center_z),
size=(wg_feed_length + input_extension, wg_width, h_sin),
),
]
)
def make_simulation(si_profiles, sin_profiles, with_fields=False):
max_outer_radius = max(base_outer_si[-1], base_outer_sin[-1])
lateral_margin = 2.5
max_tooth_y = (max_outer_radius + sector_offset) * np.sin(half_angle)
structure_end = -wg_feed_length + max_outer_radius + sector_offset + lateral_margin
source = td.GaussianBeam(
center=(beam_offset_x + sector_offset, 0, sin_center_z + h_sin / 2 + beam_height),
size=(td.inf, td.inf, 0),
source_time=td.GaussianPulse(freq0=freq0, fwidth=freq0 / 10),
pol_angle=np.pi / 2,
angle_theta=beam_angle,
direction="-",
waist_radius=beam_mfd / 2,
)
monitor = td.ModeMonitor(
center=(-2.5, 0, sin_center_z),
size=(0, 4 * wg_width, 3 * max(h_si, h_sin)),
freqs=[freq0],
mode_spec=td.ModeSpec(num_modes=1),
name="coupling_mode",
)
monitors = [monitor]
if with_fields:
monitors.extend(
[
td.FieldMonitor(center=(0, 0, sin_center_z), size=(td.inf, td.inf, 0), freqs=[freq0], name="field_xy"),
td.FieldMonitor(center=(0, 0, si_center_z), size=(td.inf, 0, td.inf), freqs=[freq0], name="field_xz"),
]
)
z_min, z_max = -4.0, sin_center_z + h_sin / 2 + beam_height + 0.5
x_min, x_max = -3.0, structure_end
return td.Simulation(
center=((x_min + x_max) / 2, 0, (z_min + z_max) / 2),
size=(x_max - x_min, 2 * (max_tooth_y + lateral_margin), z_max - z_min),
medium=oxide_medium,
structures=[
td.Structure(geometry=td.Box.from_bounds((-1000, -1000, -1000), (1000, 1000, 0)), medium=substrate_medium),
td.Structure(geometry=sin_base_geometry(), medium=sin_medium),
td.Structure(geometry=teeth_geometry(si_profiles, h_si, si_center_z), medium=si_medium),
td.Structure(geometry=teeth_geometry(sin_profiles, h_sin, sin_center_z), medium=sin_medium),
],
sources=[source],
monitors=monitors,
run_time=1.2e-12,
grid_spec=td.GridSpec.auto(min_steps_per_wvl=20),
boundary_spec=td.BoundarySpec.all_sides(boundary=td.PML()),
symmetry=(0, -1, 0),
)
These small plotting helpers visualize the initial and final layouts with consistent material colors.
[5]:
material_colors = {"Si": "tab:blue", "SiN": "tab:orange"}
def layout_tooth_vertices(profiles, layer_index):
inner, outer = profiles
inner_controls = np.full(num_full_controls, inner[layer_index]) if np.ndim(inner) == 1 else inner[layer_index]
inner_profile = control_to_arc @ np.asarray(inner_controls, dtype=float)
outer_profile = control_to_arc @ np.asarray(outer[layer_index], dtype=float)
return np.asarray(tooth_vertices(inner_profile, outer_profile), dtype=float)
def plot_teeth(profiles, ax, color, alpha=1):
for tooth_index in range(num_teeth):
ax.add_patch(Polygon(layout_tooth_vertices(profiles, tooth_index), facecolor=color, alpha=alpha))
def plot_sin_base(ax, alpha=1, include_waveguide=True):
center_x = -wg_feed_length
radius = wg_feed_length + sector_offset
sector = np.vstack((np.c_[center_x + radius * np.cos(arc_angles), radius * np.sin(arc_angles)], [[center_x, 0.0]]))
ax.add_patch(Polygon(sector, facecolor=material_colors["SiN"], alpha=alpha))
if include_waveguide:
ax.add_patch(
Rectangle(
(-wg_feed_length - input_extension, -wg_width / 2),
wg_feed_length + input_extension,
wg_width,
facecolor=material_colors["SiN"],
alpha=alpha,
)
)
def format_layout(ax, title):
ax.set_aspect("equal")
ax.set_xlabel("x (µm)")
ax.set_ylabel("y (µm)")
ax.set_title(title)
ax.autoscale_view()
si_profiles0, sin_profiles0 = position_profiles(params0)
fig = plt.figure(figsize=(8, 7), layout="constrained")
grid = fig.add_gridspec(2, 2, wspace=0.05)
ax_overlay = fig.add_subplot(grid[0, :])
ax_si = fig.add_subplot(grid[1, 0])
ax_sin = fig.add_subplot(grid[1, 1])
plot_sin_base(ax_overlay, alpha=0.5, include_waveguide=False)
plot_teeth(si_profiles0, ax_overlay, material_colors["Si"], alpha=0.5)
plot_teeth(sin_profiles0, ax_overlay, material_colors["SiN"], alpha=0.5)
ax_overlay.legend(handles=[Patch(color=color, label=name) for name, color in material_colors.items()])
format_layout(ax_overlay, "Initial overlay")
plot_teeth(si_profiles0, ax_si, material_colors["Si"])
format_layout(ax_si, "Initial Si")
plot_sin_base(ax_sin)
plot_teeth(sin_profiles0, ax_sin, material_colors["SiN"])
format_layout(ax_sin, "Initial SiN")
plt.show()
Initial Performance#
Before optimization, we evaluate the coupling efficiency of the DRC-clean initial design. The non-uniform seed, including its taper angle, was tuned in the linked 2D reference optimization. Its coupling is lower in this 3D simulation because the full vertical stack, finite lateral aperture, and tilted Gaussian input introduce effects absent from the 2D model. We retain this transferred starting point rather than retuning the taper angle, and optimize the grating edge controls below.
[6]:
sim0 = make_simulation(*position_profiles(params0))
def coupling_efficiency(simulation, task_name):
data = web.run(simulation, task_name=task_name, verbose=False)
amplitude = data["coupling_mode"].amps.sel(direction="-", mode_index=0).values
return float(np.sum(np.abs(amplitude) ** 2))
efficiency0 = coupling_efficiency(sim0, "dual-layer-inner-outer-initial")
print(f"Initial coupling efficiency: {efficiency0:.2%} ({10 * np.log10(efficiency0):.2f} dB)")
Initial coupling efficiency: 22.97% (-6.39 dB)
Batched DRC-Safe Updates#
BacktrackingSafeUpdate first validates the current design, then checks the full Adam update and progressively shorter global updates from largest to smallest scale. A global update moves every design parameter together from its current value toward its Adam-proposed value using one shared scale factor. It next recovers the remaining update one parameter at a time. This notebook uses the default deterministic parameter order; candidate_order="random" instead randomizes that order, and
random_seed can make it reproducible. The global candidates and each parameter’s backtracking candidates are checked together by KLayout. With a fixed number of backtracks, the number of candidate designs scales linearly with the number of parameters.
[7]:
def export_candidate(params, path):
library = gdstk.Library()
cell = library.new_cell("dual_layer_grating")
simulation = make_simulation(*position_profiles(params))
gds_layer_dtype_map = {
si_medium: gds_layers["si"],
sin_medium: gds_layers["sin"],
}
simulation.to_gds(cell, z=si_center_z, gds_layer_dtype_map=gds_layer_dtype_map)
simulation.to_gds(cell, z=sin_center_z, gds_layer_dtype_map=gds_layer_dtype_map)
library.write_gds(path)
drc_checker = BatchedDRCChecker(
export_candidate,
drc_runset,
drc_args=drc_args,
)
The checker can be replaced by any function that returns a design-verification response. BatchedDRCChecker implements the checker interface used directly by BacktrackingSafeUpdate. Here, CoordinateRecovery() recovers the remaining update one parameter at a time after the global search.
Optimize While Enforcing DRC#
Our objective is the negative coupled power, so minimizing it increases coupling into the fundamental input-waveguide mode. The initial design is checked before its optimization begins.
Each per-step report shows the coupling efficiency, gradient norm, and DRC-safe update statistics. retained is the ratio of the accepted update norm to the proposed update norm. update = full means the entire optimizer proposal passed unchanged; corrected means a shorter DRC-clean update was accepted; and rejected means no update was accepted. The individual-parameter counts classify each control: full reaches its proposed value, partial takes a shortened update, and
none remains unchanged.
[8]:
num_steps = 50 # Number of DRC-safe Adam updates.
learning_rate = 0.01 # Adam learning rate.
max_backtracks = 12 # Maximum reductions after each full proposed update.
safe_update = BacktrackingSafeUpdate(
drc_checker,
max_backtracks=max_backtracks,
recovery=CoordinateRecovery(),
)
def objective(params):
simulation = make_simulation(*position_profiles(params))
data = web.run(simulation, task_name="dual-layer-inner-outer", verbose=False)
amplitude = data["coupling_mode"].amps.sel(direction="-", mode_index=0).values
return -anp.sum(anp.abs(amplitude) ** 2)
initial_drc_clean = drc_checker.check_candidates([params0])[0]
print(f"Initial KLayout DRC clean: {initial_drc_clean}")
params = params0
safe_update(current=params, proposed=params)
optimizer = adam(learning_rate=learning_rate)
state = optimizer.init(params)
value_and_grad_fn = value_and_grad(objective)
history = {
"objective_fn_val": [],
"grad_norm": [],
"safe_update_retained_fraction": [],
"safe_update_full_parameter_updates": [],
"safe_update_partial_parameter_updates": [],
"safe_update_rejected_parameter_updates": [],
}
for step in range(num_steps):
objective_value, grad = value_and_grad_fn(params)
grad_norm = float(np.linalg.norm(grad))
history["objective_fn_val"].append(float(objective_value))
history["grad_norm"].append(grad_norm)
updates, state = optimizer.update(grad, state, params)
safe_result = safe_update(current=params, proposed=apply_updates(params, updates))
params = safe_result.params
retained = safe_result.metrics["retained_fraction"]
full = safe_result.metrics["full_parameter_updates"]
partial = safe_result.metrics["partial_parameter_updates"]
rejected = safe_result.metrics["rejected_parameter_updates"]
history["safe_update_retained_fraction"].append(retained)
history["safe_update_full_parameter_updates"].append(full)
history["safe_update_partial_parameter_updates"].append(partial)
history["safe_update_rejected_parameter_updates"].append(rejected)
status = "full" if np.isclose(retained, 1) else "corrected" if retained > 0 else "rejected"
prefix = f"Step {step + 1}: "
print(
f"{prefix}coupling efficiency = {-float(objective_value):.2%}, "
f"gradient norm = {grad_norm:.3e}\n"
f"{' ' * len(prefix)}update = {status}, retained = {retained:.0%}; "
f"updated parameters: full={full:.0f}, partial={partial:.0f}, none={rejected:.0f}"
)
params_final = params
Initial KLayout DRC clean: True
Step 1: coupling efficiency = 22.97%, gradient norm = 4.177e-01
update = full, retained = 100%; updated parameters: full=300, partial=0, none=0
Step 2: coupling efficiency = 26.32%, gradient norm = 3.607e-01
update = full, retained = 100%; updated parameters: full=300, partial=0, none=0
Step 3: coupling efficiency = 28.85%, gradient norm = 2.567e-01
update = full, retained = 100%; updated parameters: full=300, partial=0, none=0
Step 4: coupling efficiency = 30.30%, gradient norm = 1.620e-01
update = full, retained = 100%; updated parameters: full=300, partial=0, none=0
Step 5: coupling efficiency = 30.80%, gradient norm = 2.119e-01
update = full, retained = 100%; updated parameters: full=300, partial=0, none=0
Step 6: coupling efficiency = 31.02%, gradient norm = 2.891e-01
update = full, retained = 100%; updated parameters: full=300, partial=0, none=0
Step 7: coupling efficiency = 31.58%, gradient norm = 3.254e-01
update = full, retained = 100%; updated parameters: full=300, partial=0, none=0
Step 8: coupling efficiency = 32.43%, gradient norm = 3.199e-01
update = full, retained = 100%; updated parameters: full=300, partial=0, none=0
Step 9: coupling efficiency = 33.39%, gradient norm = 2.817e-01
update = corrected, retained = 100%; updated parameters: full=298, partial=2, none=0
Step 10: coupling efficiency = 34.19%, gradient norm = 2.360e-01
update = corrected, retained = 99%; updated parameters: full=296, partial=4, none=0
Step 11: coupling efficiency = 34.68%, gradient norm = 2.068e-01
update = corrected, retained = 99%; updated parameters: full=296, partial=2, none=2
Step 12: coupling efficiency = 35.05%, gradient norm = 1.987e-01
update = corrected, retained = 99%; updated parameters: full=296, partial=1, none=3
Step 13: coupling efficiency = 35.52%, gradient norm = 2.143e-01
update = corrected, retained = 99%; updated parameters: full=295, partial=1, none=4
Step 14: coupling efficiency = 35.98%, gradient norm = 2.228e-01
update = corrected, retained = 98%; updated parameters: full=292, partial=4, none=4
Step 15: coupling efficiency = 36.36%, gradient norm = 2.235e-01
update = corrected, retained = 98%; updated parameters: full=290, partial=6, none=4
Step 16: coupling efficiency = 36.60%, gradient norm = 2.029e-01
update = corrected, retained = 98%; updated parameters: full=290, partial=5, none=5
Step 17: coupling efficiency = 37.03%, gradient norm = 1.755e-01
update = corrected, retained = 98%; updated parameters: full=290, partial=3, none=7
Step 18: coupling efficiency = 37.32%, gradient norm = 1.492e-01
update = corrected, retained = 98%; updated parameters: full=290, partial=3, none=7
Step 19: coupling efficiency = 37.54%, gradient norm = 1.444e-01
update = corrected, retained = 98%; updated parameters: full=292, partial=3, none=5
Step 20: coupling efficiency = 37.71%, gradient norm = 1.539e-01
update = corrected, retained = 98%; updated parameters: full=296, partial=0, none=4
Step 21: coupling efficiency = 37.85%, gradient norm = 1.605e-01
update = corrected, retained = 98%; updated parameters: full=296, partial=0, none=4
Step 22: coupling efficiency = 37.99%, gradient norm = 1.537e-01
update = corrected, retained = 98%; updated parameters: full=296, partial=0, none=4
Step 23: coupling efficiency = 38.11%, gradient norm = 1.375e-01
update = corrected, retained = 98%; updated parameters: full=296, partial=0, none=4
Step 24: coupling efficiency = 38.25%, gradient norm = 1.237e-01
update = corrected, retained = 98%; updated parameters: full=296, partial=0, none=4
Step 25: coupling efficiency = 38.37%, gradient norm = 1.200e-01
update = corrected, retained = 98%; updated parameters: full=296, partial=0, none=4
Step 26: coupling efficiency = 38.50%, gradient norm = 1.192e-01
update = corrected, retained = 98%; updated parameters: full=296, partial=0, none=4
Step 27: coupling efficiency = 38.64%, gradient norm = 1.148e-01
update = corrected, retained = 98%; updated parameters: full=296, partial=0, none=4
Step 28: coupling efficiency = 38.78%, gradient norm = 1.056e-01
update = corrected, retained = 98%; updated parameters: full=296, partial=1, none=3
Step 29: coupling efficiency = 38.89%, gradient norm = 9.772e-02
update = corrected, retained = 98%; updated parameters: full=296, partial=0, none=4
Step 30: coupling efficiency = 38.98%, gradient norm = 9.446e-02
update = corrected, retained = 97%; updated parameters: full=296, partial=0, none=4
Step 31: coupling efficiency = 39.09%, gradient norm = 9.486e-02
update = corrected, retained = 97%; updated parameters: full=296, partial=0, none=4
Step 32: coupling efficiency = 39.23%, gradient norm = 9.083e-02
update = corrected, retained = 97%; updated parameters: full=296, partial=1, none=3
Step 33: coupling efficiency = 39.33%, gradient norm = 7.804e-02
update = corrected, retained = 97%; updated parameters: full=296, partial=1, none=3
Step 34: coupling efficiency = 39.43%, gradient norm = 7.133e-02
update = corrected, retained = 97%; updated parameters: full=297, partial=1, none=2
Step 35: coupling efficiency = 39.46%, gradient norm = 6.912e-02
update = corrected, retained = 97%; updated parameters: full=297, partial=1, none=2
Step 36: coupling efficiency = 39.59%, gradient norm = 7.185e-02
update = corrected, retained = 97%; updated parameters: full=297, partial=1, none=2
Step 37: coupling efficiency = 39.67%, gradient norm = 6.523e-02
update = corrected, retained = 97%; updated parameters: full=297, partial=1, none=2
Step 38: coupling efficiency = 39.76%, gradient norm = 6.402e-02
update = corrected, retained = 97%; updated parameters: full=297, partial=1, none=2
Step 39: coupling efficiency = 39.85%, gradient norm = 6.999e-02
update = corrected, retained = 97%; updated parameters: full=296, partial=3, none=1
Step 40: coupling efficiency = 39.99%, gradient norm = 6.643e-02
update = corrected, retained = 96%; updated parameters: full=296, partial=3, none=1
Step 41: coupling efficiency = 40.08%, gradient norm = 5.670e-02
update = corrected, retained = 96%; updated parameters: full=295, partial=4, none=1
Step 42: coupling efficiency = 40.02%, gradient norm = 5.228e-02
update = corrected, retained = 96%; updated parameters: full=294, partial=3, none=3
Step 43: coupling efficiency = 40.19%, gradient norm = 4.937e-02
update = corrected, retained = 95%; updated parameters: full=294, partial=2, none=4
Step 44: coupling efficiency = 40.22%, gradient norm = 5.174e-02
update = corrected, retained = 95%; updated parameters: full=293, partial=4, none=3
Step 45: coupling efficiency = 40.27%, gradient norm = 5.710e-02
update = corrected, retained = 95%; updated parameters: full=293, partial=3, none=4
Step 46: coupling efficiency = 40.40%, gradient norm = 5.526e-02
update = corrected, retained = 95%; updated parameters: full=293, partial=3, none=4
Step 47: coupling efficiency = 40.51%, gradient norm = 4.599e-02
update = corrected, retained = 95%; updated parameters: full=293, partial=1, none=6
Step 48: coupling efficiency = 40.59%, gradient norm = 4.373e-02
update = corrected, retained = 94%; updated parameters: full=293, partial=1, none=6
Step 49: coupling efficiency = 40.60%, gradient norm = 4.913e-02
update = corrected, retained = 94%; updated parameters: full=293, partial=1, none=6
Step 50: coupling efficiency = 40.67%, gradient norm = 5.030e-02
update = corrected, retained = 94%; updated parameters: full=293, partial=0, none=7
Results#
The optical objective is shown over the optimization iterations and grows continuously as coupling improves. Most controls accept their full proposed update; only five to ten controls per iteration are partially updated or left unchanged by the DRC-safe search.
[9]:
fig, (ax_efficiency, ax_updates) = plt.subplots(1, 2, figsize=(11, 3.5), tight_layout=True)
steps = np.arange(1, len(history["objective_fn_val"]) + 1)
efficiency_db = 10 * np.log10(-np.asarray(history["objective_fn_val"]))
ax_efficiency.plot(steps, efficiency_db, marker="o")
ax_efficiency.set(xlabel="Optimization step", ylabel="Coupling efficiency (dB)", title="Optical objective")
ax_efficiency.grid(alpha=0.3)
ax_updates.plot(steps, history["safe_update_partial_parameter_updates"], marker="o", label="Partial")
ax_updates.plot(steps, history["safe_update_rejected_parameter_updates"], marker="o", label="None")
ax_updates.set(xlabel="Optimization step", ylabel="Parameters", title="Corrected parameters")
ax_updates.legend()
plt.show()
Final Design#
The overlay and individual layer views visualize the final Si and SiN gratings. Several teeth have widths and spaces pushed close to the DRC limits, and the tooth widths are no longer uniform along the arc.
[10]:
si_profiles, sin_profiles = position_profiles(params_final)
fig = plt.figure(figsize=(8, 7), layout="constrained")
grid = fig.add_gridspec(2, 2, wspace=0.05)
ax_overlay = fig.add_subplot(grid[0, :])
ax_si = fig.add_subplot(grid[1, 0])
ax_sin = fig.add_subplot(grid[1, 1])
plot_sin_base(ax_overlay, alpha=0.5, include_waveguide=False)
plot_teeth(si_profiles, ax_overlay, material_colors["Si"], alpha=0.5)
plot_teeth(sin_profiles, ax_overlay, material_colors["SiN"], alpha=0.5)
ax_overlay.legend(handles=[Patch(color=color, label=name) for name, color in material_colors.items()])
format_layout(ax_overlay, "Overlay")
plot_teeth(si_profiles, ax_si, material_colors["Si"])
format_layout(ax_si, "Si")
plot_sin_base(ax_sin)
plot_teeth(sin_profiles, ax_sin, material_colors["SiN"])
format_layout(ax_sin, "SiN")
plt.show()
final_drc_clean = drc_checker.check_candidates([params_final])[0]
print(f"Final KLayout DRC clean: {final_drc_clean}")
Final KLayout DRC clean: True
Final Field#
With the optimized design in hand, we can visualize optical propagation in horizontal and vertical slices through the coupler.
[11]:
final_data = web.run(
make_simulation(*position_profiles(params_final), with_fields=True),
task_name="dual-layer-inner-outer-final-fields",
verbose=False,
)
fig, axes = plt.subplots(1, 2, figsize=(10, 4), layout="constrained")
final_data.plot_field("field_xy", "E", f=freq0, val="abs", ax=axes[0])
axes[0].set_title("XY slice")
final_data.plot_field("field_xz", "E", f=freq0, val="abs", ax=axes[1])
axes[1].set_title("XZ slice")
plt.show()
Conclusion#
BacktrackingSafeUpdate maintains DRC-clean designs throughout optimization without expressing the DRC rules as optimizer constraints or restricting the parameterization to a pre-defined safe form. Starting from a clean design, it can use the same black-box verification interface for local width and space checks, enclosure rules, minimum-area rules, spacing or overlap rules between different layers, and other global layout checks. The specific rules remain in the verification function, while
the optimizer remains free to use the parameterization that is best to optimize with.