Author: Sulaiman Al Ghadani, West Virginia University
Grating couplers provide an optical interface between free-space beams and on-chip waveguides. They are particularly useful when we want to couple light into or collect light from different locations on a chip. However, designing a grating that works efficiently at normal incidence is challenging, since it can also cause significant unwanted reflections back into the waveguide.
To address this challenge, we use adjoint shape optimization in Tidy3D (ver. 2.10.1) to design a fully etched vertical grating coupler. We apply this approach to a suspended AlGaAs membrane with a target wavelength of 798 nm. Our design is inspired by the work of Hansen et al. in Optics Express 31, 17424–17436 (2023), in which they demonstrated a low-reflection vertical grating coupler for suspended silicon photonics.
In our optimization, the grating geometry is described by a set of design variables that control the widths of the etched trenches and the gaps between them. This reduces the number of optimization variables compared with topology optimization, while allowing minimum fabrication feature sizes to be enforced directly through the parameterization.
To evaluate the grating performance, we use two simulation configurations. The first launches a normally incident Gaussian beam and measures its coupling into the waveguide. The second launches the waveguide mode toward the grating to evaluate back-reflection, upward radiation, and far-field directionality. The results from both configurations are combined in the objective function used for optimization.
The optimization is carried out in three stages, starting with a 2D cross-section model before moving to the more computationally expensive 3D simulations.
Stage 1: 2D adjoint optimization. Starting from an initial uniform grating design, we optimize the trench and gap widths in 2D to improve coupling efficiency, reduce reflection, and direct the radiation toward normal incidence.
Stage 2: 3D model and placement sweep. The optimized 2D grating is converted into a 3D focusing grating with curved trenches. A small parameter sweep is then performed to adjust the grating apex position and the distance shift relative to the waveguide, providing a better starting point for 3D optimization.
Stage 3: 3D adjoint optimization. The selected design is further refined by optimizing the trench and gap widths directly in 3D. The optimized design is then inspected and exported as a GDS file for fabrication.
Table of Contents¶
2D Model Construction and Validation¶
We start by importing the packages used in the notebook. Tidy3D is used to build and run the simulations, the adjoint plugin is used to compute gradients, and the remaining packages are used for optimization, plotting, saving histories, and exporting the final design.
# Imports
import pickle
from pathlib import Path
import autograd.numpy as anp
import gdstk
import matplotlib.pyplot as plt
import numpy as np
import optax
import pandas as pd
import plotly.graph_objects as go
import tidy3d as td
from IPython.display import clear_output, display
from plotly.subplots import make_subplots
from tidy3d import web
from tidy3d.plugins.autograd import value_and_grad
from tidy3d.plugins.mode import ModeSolver
td.config.logging.level = "ERROR"
plt.rcParams["font.size"] = 12
Design Parameters¶
The design targets a wavelength of 798 nm in a suspended AlGaAs membrane with a refractive index of approximately 3.3925 at the design wavelength. The membrane thickness is 150 nm, and the input waveguide width is 300 nm. The grating contains 25 fully etched trenches. A minimum trench width and gap size of 70 nm are enforced directly through the shape parameterization to maintain the chosen fabrication constraint throughout the optimization. The remaining parameters below define the grating geometry, simulation-domain padding, source and monitor positions, and free-space beam and collection settings.
These parameters are used throughout both the 2D and 3D parts of the workflow so that the optimized 2D grating can be transferred consistently into the 3D suspended device.
# All lengths are in microns
# Design wavelength and materials
lambda0_um = 0.798 # design wavelength, 798 nm
n_AlGaAs = 3.3925 # AlGaAs refractive index at the design wavelength
AlGaAs_simple = td.Medium(permittivity=n_AlGaAs**2) # AlGaAs membrane material
air = td.Medium(permittivity=1.0) # surrounding air
device_medium = AlGaAs_simple # material used for the suspended membrane and waveguide
background = air # background medium of the suspended structure
# Suspended membrane and input waveguide geometry & placement
t_mem = 0.150 # suspended membrane thickness
w_wg = 0.300 # input waveguide width
wg_L = 4.0 # straight input waveguide length before the grating
x_apex = 0.0 # radial grating apex reference position
wg_center_x = (
x_apex - wg_L / 2
) # waveguide center; chosen so the right end reaches x_apex
wg_left_end_x = wg_center_x - wg_L / 2 # left end of the straight input waveguide
wg_right_end_x = wg_center_x + wg_L / 2 # right end of the straight input waveguide
z_mem_center = 0.0 # membrane center in z
z_mem_bot = z_mem_center - t_mem / 2 # bottom surface of the membrane
z_mem_top = z_mem_center + t_mem / 2 # top surface of the membrane
# Grating and fabrication settings
num_trenches = 25 # number of etched trenches in the grating
slot_radius_min = 2.0 # inner radius of the first etched trench
min_feature = 0.070 # minimum trench/gap feature size, 70 nm
max_feature = 1.5 # maximum trench/gap feature size
# Simulation padding and source/monitor placement
Ly = w_wg # effective 2D simulation width, matched to the waveguide width
z_top = 1.0 # air padding above the membrane
z_bot = 1.0 # air padding below the membrane
beam_center_z = 2.0 * t_mem # z-position of the free-space source
mode_x = -0.5 * wg_L # x-position of the waveguide mode source plane
pad_left = 0.500 # x-padding before the input waveguide
pad_right = 3.0 # x-padding after the grating region
# Free-space beam and collection settings
beam_waist = 1.5 # Gaussian beam waist size
collection_angle_deg = 15.0 # collection cone half-angle
2D Wavelength Grid and Target Bands¶
Next, we define the wavelength grid used for the 2D simulations. The grid is centered around the target wavelength and covers a wider range than the actual optimization band.
The band masks are used to tell the objective which wavelength points should be included in the coupling and reflection terms. The remaining wavelength points are saved as diagnostic points so we can check how the design behaves outside the main target band.
# 2D wavelength grid and target bands
num_lambda_2d = 11 # number of 2D wavelength samples
lambda_span_2d_um = 0.100 # full simulated wavelength span
# Default band used to initialize the notebook before the optimization loop.
# The optimization loop will update this automatically for each stage.
DEFAULT_BAND_HALF_WIDTH_2D_UM = 0.025 # 50 nm total band
def make_wavelength_grid_2d(lambda0_um, lambda_span_um, num_lambda):
"""
Create the fixed 2D wavelength grid.
The full wavelength grid stays fixed during the optimization.
Different optimization stages only change which wavelengths are included
in the objective.
"""
if num_lambda % 2 == 0:
raise ValueError("num_lambda must be odd so the design wavelength is included.")
lams_um = np.linspace(
lambda0_um - lambda_span_um / 2,
lambda0_um + lambda_span_um / 2,
num_lambda,
)
freqs = td.C_0 / lams_um
idx_c = int(np.argmin(np.abs(lams_um - lambda0_um)))
return lams_um, freqs, idx_c
lams_um_2d, freqs_2d, idx_c_2d = make_wavelength_grid_2d(
lambda0_um=lambda0_um,
lambda_span_um=lambda_span_2d_um,
num_lambda=num_lambda_2d,
)
lams_nm_2d = lams_um_2d * 1000
def set_target_band_2d(band_half_width_um, verbose=True):
"""
Update the 2D target-band masks used by the objective.
This is called once here to initialize the notebook, and later it will
be called automatically by the staged 2D optimization loop.
"""
global band_half_width_2d_um
global target_band_mask_2d
global mask_T_band_2d, mask_R_band_2d
global mask_outside_T_band_2d
global N_T_BAND_2D, N_R_BAND_2D
band_half_width_2d_um = float(band_half_width_um)
target_band_mask_2d = (
np.abs(lams_um_2d - lambda0_um) <= band_half_width_2d_um + 1e-12
)
mask_T_band_2d = target_band_mask_2d.copy()
mask_R_band_2d = target_band_mask_2d.copy()
mask_outside_T_band_2d = ~mask_T_band_2d
N_T_BAND_2D = float(np.sum(mask_T_band_2d))
N_R_BAND_2D = float(np.sum(mask_R_band_2d))
if N_T_BAND_2D < 1:
raise ValueError(
"The 2D transmission band does not include any wavelength points."
)
if N_R_BAND_2D < 1:
raise ValueError(
"The 2D reflection band does not include any wavelength points."
)
if verbose:
print("2D objective bands:")
print(f" band half-width = {band_half_width_2d_um * 1000:.1f} nm")
print(
f" T-band wavelengths = {np.round(lams_um_2d[mask_T_band_2d] * 1000, 3)} nm"
)
print(
f" R-band wavelengths = {np.round(lams_um_2d[mask_R_band_2d] * 1000, 3)} nm"
)
print(
f" diagnostic wavelengths = {np.round(lams_um_2d[mask_outside_T_band_2d] * 1000, 3)} nm"
)
print("2D wavelength grid:")
print(f" full wavelength span = {lambda_span_2d_um * 1000:.1f} nm")
print(f" number of wavelengths = {num_lambda_2d}")
print(f" all wavelengths = {np.round(lams_um_2d * 1000, 3)} nm")
print(f" center index = {idx_c_2d}")
print(f" center wavelength = {lams_um_2d[idx_c_2d] * 1000:.3f} nm")
print()
set_target_band_2d(DEFAULT_BAND_HALF_WIDTH_2D_UM)
2D wavelength grid: full wavelength span = 100.0 nm number of wavelengths = 11 all wavelengths = [748. 758. 768. 778. 788. 798. 808. 818. 828. 838. 848.] nm center index = 5 center wavelength = 798.000 nm 2D objective bands: band half-width = 25.0 nm T-band wavelengths = [778. 788. 798. 808. 818.] nm R-band wavelengths = [778. 788. 798. 808. 818.] nm diagnostic wavelengths = [748. 758. 768. 828. 838. 848.] nm
Waveguide Effective Index¶
We start by calculating the effective index of the suspended straight waveguide using the Tidy3D mode solver. This value is used to estimate a reasonable starting period for the grating.
The effective index is only used to initialize the design. The trench and gap widths are later updated during the adjoint optimization.
MODE_SOLVER_Y_SIZE = 4.0 # mode-solver domain size in y
MODE_SOLVER_Z_SIZE = 3.0 # mode-solver domain size in z
MODE_SOLVER_NUM_MODES = 4 # number of waveguide modes to compute
MODE_SOLVER_MIN_STEPS_PER_WVL = 25 # grid resolution for the mode solve
MODE_SOLVER_TARGET_NEFF = 0.85 * n_AlGaAs # TE-like mode search target
def compute_waveguide_neff_tidy3d(
lambda_um,
wg_width,
membrane_thickness,
y_size=4.0,
z_size=3.0,
num_modes=4,
target_neff=None,
min_steps_per_wvl=25,
plot_modes=True,
):
"""Compute the effective index of the straight suspended waveguide."""
freq0 = td.C_0 / lambda_um
if target_neff is None:
target_neff = 0.85 * n_AlGaAs
wg_for_mode = td.Structure(
geometry=td.Box(
center=(0.0, 0.0, 0.0),
size=(td.inf, wg_width, membrane_thickness),
),
medium=AlGaAs_simple,
)
sim_mode = td.Simulation(
center=(0.0, 0.0, 0.0),
size=(2.0, y_size, z_size),
grid_spec=td.GridSpec.auto(
wavelength=lambda_um,
min_steps_per_wvl=min_steps_per_wvl,
),
structures=[wg_for_mode],
medium=background,
boundary_spec=td.BoundarySpec.all_sides(boundary=td.PML()),
run_time=1e-12,
)
mode_plane = td.Box(
center=(0.0, 0.0, 0.0),
size=(0.0, y_size, z_size),
)
mode_spec = td.ModeSpec(
num_modes=num_modes,
target_neff=target_neff,
filter_pol="te",
precision="double",
)
mode_solver = ModeSolver(
simulation=sim_mode,
plane=mode_plane,
mode_spec=mode_spec,
freqs=[freq0],
)
mode_data = mode_solver.solve()
neff_all = np.real(np.array(mode_data.n_eff)).squeeze()
neff_flat = np.ravel(neff_all)
print("Mode-solver effective indices:")
for mode_index, neff in enumerate(neff_flat):
print(f" mode {mode_index}: n_eff = {float(neff):.8f}")
selected_mode_index = 0
n_eff_selected = float(neff_flat[selected_mode_index])
if plot_modes:
try:
mode_solver.plot_field(
"E",
"abs",
f=freq0,
mode_index=selected_mode_index,
)
plt.title(
f"Selected TE-like mode {selected_mode_index}, "
f"n_eff = {n_eff_selected:.6f}"
)
plt.show()
except (ValueError, KeyError, TypeError, AttributeError) as err:
print(f"Mode field plot skipped: {type(err).__name__}: {err}")
return n_eff_selected, mode_data, mode_solver
n_eff_wg, _, _ = compute_waveguide_neff_tidy3d(
lambda_um=lambda0_um,
wg_width=w_wg,
membrane_thickness=t_mem,
y_size=MODE_SOLVER_Y_SIZE,
z_size=MODE_SOLVER_Z_SIZE,
num_modes=MODE_SOLVER_NUM_MODES,
target_neff=MODE_SOLVER_TARGET_NEFF,
min_steps_per_wvl=MODE_SOLVER_MIN_STEPS_PER_WVL,
plot_modes=True,
)
print()
print("Selected waveguide effective index:")
print(f" lambda0_um = {lambda0_um:.6f} um")
print(f" w_wg = {w_wg:.6f} um")
print(f" t_mem = {t_mem:.6f} um")
print(f" n_eff_wg = {n_eff_wg:.8f}")
/Users/jungmin/miniconda3/envs/tidy3d-2.10.1/lib/python3.12/site-packages/tidy3d/components/mode/derivatives.py:17: FutureWarning: Input has data type int64, but the output has been cast to float64. In the future, the output data type will match the input. To avoid this warning, set the `dtype` parameter to `None` to have the output dtype match the input, or set it to the desired output data type. dxf = sp.csr_matrix(sp.diags([-1, 1], [0, 1], shape=(Nx, Nx))) /Users/jungmin/miniconda3/envs/tidy3d-2.10.1/lib/python3.12/site-packages/tidy3d/components/mode/derivatives.py:32: FutureWarning: Input has data type int64, but the output has been cast to float64. In the future, the output data type will match the input. To avoid this warning, set the `dtype` parameter to `None` to have the output dtype match the input, or set it to the desired output data type. dxb = sp.csr_matrix(sp.diags([1, -1], [0, -1], shape=(Nx, Nx))) /Users/jungmin/miniconda3/envs/tidy3d-2.10.1/lib/python3.12/site-packages/tidy3d/components/mode/derivatives.py:49: FutureWarning: Input has data type int64, but the output has been cast to float64. In the future, the output data type will match the input. To avoid this warning, set the `dtype` parameter to `None` to have the output dtype match the input, or set it to the desired output data type. dyf = sp.csr_matrix(sp.diags([-1, 1], [0, 1], shape=(Ny, Ny))) /Users/jungmin/miniconda3/envs/tidy3d-2.10.1/lib/python3.12/site-packages/tidy3d/components/mode/derivatives.py:64: FutureWarning: Input has data type int64, but the output has been cast to float64. In the future, the output data type will match the input. To avoid this warning, set the `dtype` parameter to `None` to have the output dtype match the input, or set it to the desired output data type. dyb = sp.csr_matrix(sp.diags([1, -1], [0, -1], shape=(Ny, Ny)))
Mode-solver effective indices: mode 0: n_eff = 2.61381416 mode 1: n_eff = 1.45096494 mode 2: n_eff = 2.02818521 mode 3: n_eff = 1.36353577
<Figure size 640x480 with 2 Axes>
Selected waveguide effective index: lambda0_um = 0.798000 um w_wg = 0.300000 um t_mem = 0.150000 um n_eff_wg = 2.61381416
2D Radial-Slot Parameterization¶
The radial grating is parameterized by the widths of the etched trenches and the gaps between them. We initialize the grating period with the effective index calculated above using the approximate phase-matching condition for vertical radiation: $$\Lambda \approx \frac{\lambda_0}{n_{\mathrm{eff}}},$$
Together with a 50% fill factor, this defines the initial sequence of trench and gap widths.
During optimization, the design variables remain unconstrained for the optimizer, but they are mapped through a smooth projection function to physical widths within the allowed bounds. The code then accumulates the trench and gap widths from the inner grating radius to determine the inner and outer radii of each etched trench. This gives a compact radial-slot parameterization while keeping the minimum feature-size constraint enforced throughout the optimization.
# Initial grating scale
period_len = lambda0_um / n_eff_wg # initial period estimate from the guided wavelength
N = num_trenches # number of etched grating trenches
fill = 0.50 # initial trench fill fraction
w0 = fill * period_len # initial trench width
g0 = (1.0 - fill) * period_len # initial gap width
w_min, w_max = min_feature, max_feature # trench-width bounds
g_min, g_max = min_feature, max_feature # gap-width bounds
# Angular span of each radial trench
slot_half_angle = np.deg2rad(20.0) # half-angle of each curved trench
num_slot_angles = 181 # number of vertices along each trench arc
slot_angles = np.linspace(
-slot_half_angle,
slot_half_angle,
num_slot_angles,
)
unit_verts = np.array([[np.cos(angle), np.sin(angle)] for angle in slot_angles])
def project(u, lo, hi):
"""Map unconstrained variables to bounded physical values in [lo, hi]."""
s = 0.5 * (anp.tanh(u) + 1.0)
return lo + (hi - lo) * s
def inv_project(x, lo, hi):
"""Map a bounded physical value back to the unconstrained variable."""
s = (x - lo) / (hi - lo)
s = np.clip(s, 1e-6, 1.0 - 1e-6)
return np.arctanh(2.0 * s - 1.0)
def params_to_wgaps(params_u):
"""Convert the optimization vector into trench widths and gap widths."""
u_w = params_u[:N]
u_g = params_u[N:]
w = project(u_w, w_min, w_max)
g = project(u_g, g_min, g_max)
return w, g
def edges_from_wgaps(w, g, slot_rmin=slot_radius_min):
"""Convert trench widths and gaps into inner and outer trench radii."""
xL, xR = [], []
radius = slot_rmin
for i in range(len(w)):
xL.append(radius)
radius = radius + w[i]
xR.append(radius)
if i < len(g):
radius = radius + g[i]
return anp.array(xL), anp.array(xR)
# Initial optimization vector
u_w0 = inv_project(w0, w_min, w_max) * np.ones(N)
u_g0 = inv_project(g0, g_min, g_max) * np.ones(N - 1)
params_init = np.concatenate([u_w0, u_g0])
w_init, g_init = params_to_wgaps(anp.array(params_init))
xL_init, xR_init = edges_from_wgaps(w_init, g_init)
# Initial grating span and 2D simulation size
x_gc_center = 0.5 * (xL_init[0] + xR_init[-1]) # center of the initial grating span
L_grating_est = xR_init[-1] - xL_init[0] # initial grating length estimate
x_left = wg_L + pad_left
x_right = slot_radius_min + L_grating_est + pad_right
sim_size_x = x_right + x_left
sim_size_z = z_top + z_bot
sim_center = (0.5 * (x_right - x_left), 0.0, 0.0)
sim_size_2d = (sim_size_x, 0.0, sim_size_z)
print("Initial grating scale:")
print(f" n_eff_wg = {n_eff_wg:.8f}")
print(f" period_len = {float(period_len):.6f} um")
print(f" slot_radius_min = {float(slot_radius_min):.6f} um")
print(f" N = {N}")
print()
print("Optimization parameterization:")
print(f" params length = {len(params_init)}")
print(f" trench variables = {N}")
print(f" gap variables = {N - 1}")
print()
print("Initial trench and gap values:")
print(f" w0 = {float(w0):.6f} um")
print(f" g0 = {float(g0):.6f} um")
print(f" w bounds = [{float(w_min):.3f}, {float(w_max):.3f}] um")
print(f" g bounds = [{float(g_min):.3f}, {float(g_max):.3f}] um")
print()
print("Initial grating span:")
print(f" slot span x = [{float(xL_init[0]):.3f}, {float(xR_init[-1]):.3f}] um")
print(f" grating length = {float(L_grating_est):.3f} um")
print(f" grating center = {float(x_gc_center):.3f} um")
print()
print("2D simulation box:")
print(f" sim_center = {sim_center}")
print(f" sim_size_2d = {sim_size_2d}")
Initial grating scale: n_eff_wg = 2.61381416 period_len = 0.305301 um slot_radius_min = 2.000000 um N = 25 Optimization parameterization: params length = 49 trench variables = 25 gap variables = 24 Initial trench and gap values: w0 = 0.152650 um g0 = 0.152650 um w bounds = [0.070, 1.500] um g bounds = [0.070, 1.500] um Initial grating span: slot span x = [2.000, 9.480] um grating length = 7.480 um grating center = 5.740 um 2D simulation box: sim_center = (np.float64(3.989936891834705), 0.0, 0.0) sim_size_2d = (np.float64(16.97987378366941), 0.0, 2.0)
Base 2D Structures, Boundaries, Grid, and Slot Builder¶
Here we build the base 2D simulation layout, including the suspended membrane, input waveguide, boundary conditions, and grid specification.
We also define the grating builder, which converts the projected trench and gap widths into fully etched air trenches through the membrane. This same builder is used to generate the initial grating and each updated geometry during the adjoint optimization.
membrane = td.Structure(
geometry=td.Box(
center=(0.0, 0.0, z_mem_center),
size=(td.inf, Ly, t_mem),
),
medium=device_medium,
)
waveguide = td.Structure(
geometry=td.Box(
center=(wg_center_x, 0.0, z_mem_center),
size=(wg_L, Ly, t_mem),
),
medium=device_medium,
)
pml = td.PML()
boundary_spec = td.BoundarySpec(
x=td.Boundary(plus=pml, minus=pml), # absorbs waves leaving the simulation in x
y=td.Boundary.periodic(), # represents the invariant 2D direction
z=td.Boundary(plus=pml, minus=pml), # absorbs upward and downward radiation
)
grid_spec = td.GridSpec.auto(
min_steps_per_wvl=20
) # automatic grid used for 2D simulations
def build_slots_from_wgaps(w, g):
"""
Build the fully etched radial air trenches from trench widths and gaps.
Returns the slot structures and the inner/outer trench radii.
"""
xL, xR = edges_from_wgaps(w, g)
slots = []
for inner_radius, outer_radius in zip(xL, xR):
inner_verts = inner_radius * unit_verts
outer_verts = outer_radius * unit_verts[::-1]
slot_vertices = anp.concatenate((inner_verts, outer_verts))
slots.append(
td.Structure(
geometry=td.PolySlab(
vertices=slot_vertices,
slab_bounds=(-t_mem / 2, t_mem / 2),
axis=2,
),
medium=air,
)
)
return slots, xL, xR
slots_init, xL_chk, xR_chk = build_slots_from_wgaps(w_init, g_init)
print("2D base structures:")
print(f" membrane size = (inf, {Ly:.4f}, {t_mem:.4f}) um")
print(
f" waveguide span = [{float(wg_left_end_x):.4f}, {float(wg_right_end_x):.4f}] um"
)
print(f" waveguide center = {float(wg_center_x):.4f} um")
print()
print("2D boundaries and grid:")
print(" x boundary = PML / PML")
print(" y boundary = periodic")
print(" z boundary = PML / PML")
print(" grid = auto, min_steps_per_wvl = 20")
print()
print("Initial etched trenches:")
print(f" number of slots = {len(slots_init)}")
print(f" first slot = [{float(xL_chk[0]):.6f}, {float(xR_chk[0]):.6f}] um")
print(f" last slot = [{float(xL_chk[-1]):.6f}, {float(xR_chk[-1]):.6f}] um")
2D base structures: membrane size = (inf, 0.3000, 0.1500) um waveguide span = [-4.0000, 0.0000] um waveguide center = -2.0000 um 2D boundaries and grid: x boundary = PML / PML y boundary = periodic z boundary = PML / PML grid = auto, min_steps_per_wvl = 20 Initial etched trenches: number of slots = 25 first slot = [2.000000, 2.152650] um last slot = [9.327223, 9.479874] um
2D Sources and Monitors¶
The 2D simulations use two source configurations. In the beam-source simulation, a Gaussian beam with a 1.5 µm waist radius is launched downward toward the grating, and a mode monitor measures the power coupled into the waveguide. In the mode-source simulation, the waveguide mode is launched toward the grating, and the same monitor measures back-reflection.
The mode-source simulation also records the upward near field above the grating. This field is later projected into angle space to evaluate how much power is radiated into the desired collection cone.
# Source pulse
freq0_2d = freqs_2d[idx_c_2d] # center frequency
freq_width_2d = np.max(freqs_2d) - np.min(
freqs_2d
) # bandwidth covering the 2D wavelength grid
beam_time = td.GaussianPulse(
freq0=freq0_2d,
fwidth=freq_width_2d,
)
# Beam source and waveguide mode source
# The beam is fixed during the optimization.
beam_center_x = float(
0.5 * (xL_init[0] + xR_init[-1])
) # x-center of the initial grating
beam_src = td.GaussianBeam(
size=(3.0 * beam_waist, 3.0 * beam_waist, 0.0),
center=(beam_center_x, 0.0, beam_center_z),
source_time=beam_time,
angle_theta=0.0,
direction="-",
waist_radius=beam_waist,
waist_distance=-beam_center_z,
pol_angle=np.pi / 2,
)
# The mode source launches the waveguide mode toward the grating.
mode_src = td.ModeSource(
size=(0.0, 3.0 * w_wg, 5.0 * t_mem),
center=(wg_right_end_x - 0.75, 0.0, z_mem_center),
source_time=beam_time,
mode_spec=td.ModeSpec(num_modes=1),
mode_index=0,
direction="+",
)
# Waveguide mode monitor
# In the beam-source simulation, this monitor measures coupling into the waveguide.
# In the mode-source simulation, it measures reflection back toward the input.
mode_mon = td.ModeMonitor(
center=(mode_x, 0.0, z_mem_center),
size=(0.0, Ly, 0.600),
freqs=freqs_2d,
mode_spec=td.ModeSpec(num_modes=1),
name="wg_mode",
)
# Field monitor for visualization
# This monitor is not part of the objective. It is used for plotting the center-wavelength field profile.
field_monitor_xz = td.FieldMonitor(
center=(sim_center[0], 0.0, sim_center[2]),
size=(sim_size_2d[0], 0.0, sim_size_2d[2]),
freqs=[freqs_2d[idx_c_2d]],
name="field_xz",
)
# Grating-centered near-field and angular projection monitors
grating_x_min_2d = float(xL_init[0]) # inner edge of the first trench
grating_x_max_2d = float(xR_init[-1]) # outer edge of the last trench
top_monitor_z_2d = beam_center_z # height of the upward near-field monitor
# Margins around the full grating aperture.
proj_x_margin_left_2d = 0.50 # margin before the first trench
proj_x_margin_right_2d = 0.50 # margin after the last trench
proj_x_min_2d = grating_x_min_2d - proj_x_margin_left_2d
proj_x_max_2d = grating_x_max_2d + proj_x_margin_right_2d
proj_x_center_2d = 0.5 * (proj_x_min_2d + proj_x_max_2d)
proj_x_size_2d = proj_x_max_2d - proj_x_min_2d
# The y-size must cover the full curved radial aperture.
proj_y_margin_2d = 1.0
x_for_proj_y_span_2d = max(
abs(proj_x_min_2d),
abs(proj_x_max_2d),
abs(grating_x_max_2d),
)
proj_y_size_2d = max(
float(Ly),
float(
2.0 * x_for_proj_y_span_2d * np.sin(slot_half_angle) + 2.0 * proj_y_margin_2d
),
)
proj_monitor_center_2d = (
proj_x_center_2d,
0.0,
top_monitor_z_2d,
)
proj_monitor_size_2d = (
proj_x_size_2d,
proj_y_size_2d,
0.0,
)
# The top-field monitor records the near field used for far-field projection.
top_field_extra_x_2d = 0.60
top_field_extra_y_2d = 0.60
top_field_monitor = td.FieldMonitor(
center=proj_monitor_center_2d,
size=(
proj_monitor_size_2d[0] + 2.0 * top_field_extra_x_2d,
proj_monitor_size_2d[1] + 2.0 * top_field_extra_y_2d,
0.0,
),
freqs=freqs_2d,
name="top_field",
colocate=False,
)
# Angular grid used to evaluate the upward radiation direction.
max_theta_deg_2d = 89
num_theta_2d = 2 * 2 * max_theta_deg_2d + 1
theta_array_2d = (
np.pi
/ 180
* np.linspace(
-max_theta_deg_2d,
max_theta_deg_2d,
num_theta_2d,
)
)
proj_monitor_2d = td.FieldProjectionAngleMonitor(
center=proj_monitor_center_2d,
size=proj_monitor_size_2d,
name="projection",
freqs=freqs_2d,
normal_dir="+",
proj_distance=10e3,
theta=theta_array_2d,
phi=0,
)
# Diagnostic flux monitors
# This upward flux monitor uses the same aperture as the projection monitor.
flux_monitor = td.FluxMonitor(
center=proj_monitor_center_2d,
size=proj_monitor_size_2d,
name="flux",
freqs=freqs_2d,
normal_dir="+",
)
# The flux box is diagnostic only. It is not used in the objective.
flux_box_x_margin_left_2d = 0.30
flux_box_x_margin_right_2d = 0.30
flux_box_x_min_2d = grating_x_min_2d - flux_box_x_margin_left_2d
flux_box_x_max_2d = grating_x_max_2d + flux_box_x_margin_right_2d
flux_box_x_center_2d = 0.5 * (flux_box_x_min_2d + flux_box_x_max_2d)
flux_box_x_size_2d = flux_box_x_max_2d - flux_box_x_min_2d
x_for_flux_y_span_2d = max(
abs(flux_box_x_min_2d),
abs(flux_box_x_max_2d),
)
flux_box_y_size_2d = max(
float(Ly),
float(
2.0 * x_for_flux_y_span_2d * np.sin(slot_half_angle) + 2.0 * proj_y_margin_2d
),
)
flux_box = td.FluxMonitor(
center=(flux_box_x_center_2d, 0.0, 0.0),
size=(flux_box_x_size_2d, flux_box_y_size_2d, 4.0 * t_mem),
name="flux_box",
freqs=freqs_2d,
exclude_surfaces=["x-"],
)
# Monitor groups
# Beam-source simulation: free-space beam coupling into the waveguide.
monitors_opt_beam = [
mode_mon,
field_monitor_xz,
]
# Mode-source simulation: waveguide reflection and upward radiation.
monitors_opt_mode = [
mode_mon,
proj_monitor_2d,
top_field_monitor,
field_monitor_xz,
]
# Extra diagnostic monitors can be added in optional validation runs.
monitors_diag = [
flux_monitor,
flux_box,
]
# Aperture checks
# The top-field monitor should share the projection center and be larger.
assert np.isclose(top_field_monitor.center[0], proj_monitor_2d.center[0])
assert np.isclose(top_field_monitor.center[1], proj_monitor_2d.center[1])
assert np.isclose(top_field_monitor.center[2], proj_monitor_2d.center[2])
assert top_field_monitor.size[0] > proj_monitor_2d.size[0]
assert top_field_monitor.size[1] > proj_monitor_2d.size[1]
print("2D source settings:")
print(f" beam source center = {beam_src.center}")
print(f" beam waist = {beam_waist:.3f} um")
print(f" center frequency = {beam_time.freq0:.4e} Hz")
print(f" source bandwidth = {beam_time.fwidth:.4e} Hz")
print()
print(f" mode source center = {mode_src.center}")
print(f" mode source direction = {mode_src.direction}")
print()
print("2D monitor aperture:")
print(
f" grating x range = [{grating_x_min_2d:.4f}, {grating_x_max_2d:.4f}] um"
)
print(f" projection x range = [{proj_x_min_2d:.4f}, {proj_x_max_2d:.4f}] um")
print(
f" flux box x range = [{flux_box_x_min_2d:.4f}, {flux_box_x_max_2d:.4f}] um"
)
print()
print(f" top field center = {top_field_monitor.center}")
print(f" top field size = {top_field_monitor.size}")
print(f" projection center = {proj_monitor_2d.center}")
print(f" projection size = {proj_monitor_2d.size}")
print(
f" theta range = [{theta_array_2d[0] * 180 / np.pi:.1f}, {theta_array_2d[-1] * 180 / np.pi:.1f}] deg"
)
print()
2D source settings: beam source center = (5.739936891834705, 0.0, 0.3) beam waist = 1.500 um center frequency = 3.7568e+14 Hz source bandwidth = 4.7263e+13 Hz mode source center = (-0.75, 0.0, 0.0) mode source direction = + 2D monitor aperture: grating x range = [2.0000, 9.4799] um projection x range = [1.5000, 9.9799] um flux box x range = [1.7000, 9.7799] um top field center = (5.739936891834705, 0.0, 0.3) top field size = (9.679873783669409, 10.02663572372539, 0.0) projection center = (5.739936891834705, 0.0, 0.3) projection size = (8.47987378366941, 8.82663572372539, 0.0) theta range = [-89.0, 89.0] deg
Build 2D Beam-Source and Mode-Source Simulations¶
Now we define the 2D simulation builder function using the simulation components defined earlier. During the optimization, it is called with the updated design parameters to reconstruct the grating geometry and build the corresponding 2D simulations for each iteration.
We also define the baseline simulations from the starting design parameters for visualization.
USE_EXTRA_MONITORS_2D = (
False # Optional diagnostic flux monitors. They are not used in the objective.
)
run_time_2d = 5e-12 # simulation run time
def build_sims_2d(params_u, use_extra_monitors=USE_EXTRA_MONITORS_2D):
"""
Build the two 2D simulations used by the objective.
Returns:
sim_beam: beam-source simulation for free-space-to-waveguide coupling
sim_mode: mode-source simulation for reflection and upward radiation
"""
w, g = params_to_wgaps(params_u)
slots, _xL, _xR = build_slots_from_wgaps(w, g)
structures = [
membrane,
waveguide,
*slots,
]
monitors_beam = list(monitors_opt_beam)
monitors_mode = list(monitors_opt_mode)
if use_extra_monitors:
monitors_beam += list(monitors_diag)
monitors_mode += list(monitors_diag)
common_sim_kwargs = {
"center": sim_center,
"size": sim_size_2d,
"grid_spec": grid_spec,
"boundary_spec": boundary_spec,
"structures": structures,
"medium": background,
"run_time": run_time_2d,
}
sim_beam = td.Simulation(
**common_sim_kwargs,
sources=[beam_src],
monitors=monitors_beam,
)
sim_mode = td.Simulation(
**common_sim_kwargs,
sources=[mode_src],
monitors=monitors_mode,
)
return sim_beam, sim_mode
sim_beam_base, sim_mode_base = build_sims_2d(
anp.array(params_init),
use_extra_monitors=True,
)
print("Built baseline 2D simulations:")
print(f" run_time_2d = {run_time_2d:.2e} s")
print()
print("Beam-source simulation:")
print(" source = beam_src")
print(f" monitors = {[m.name for m in sim_beam_base.monitors]}")
print()
print("Mode-source simulation:")
print(" source = mode_src")
print(f" monitors = {[m.name for m in sim_mode_base.monitors]}")
print()
Built baseline 2D simulations: run_time_2d = 5.00e-12 s Beam-source simulation: source = beam_src monitors = ['wg_mode', 'field_xz', 'flux', 'flux_box'] Mode-source simulation: source = mode_src monitors = ['wg_mode', 'projection', 'top_field', 'field_xz', 'flux', 'flux_box']
Plot the Initial 2D Simulations¶
Before running the optimization, we plot the initial beam-source and mode-source simulations to check the starting geometry, source placement, monitors, and simulation domain.
# This cell only visualizes the simulation layout.
# It does not run the FDTD simulation.
fig, axes = plt.subplots(1, 2, figsize=(14, 4), constrained_layout=True)
sim_beam_base.plot(y=0, ax=axes[0])
axes[0].set_title("2D beam-source simulation")
axes[0].set_xlabel("x (um)")
axes[0].set_ylabel("z (um)")
sim_mode_base.plot(y=0, ax=axes[1])
axes[1].set_title("2D mode-source simulation")
axes[1].set_xlabel("x (um)")
axes[1].set_ylabel("z (um)")
plt.show()
print("Initial 2D simulation layouts plotted.")
Initial 2D simulation layouts plotted.
2D Objective and Adjoint Optimization¶
In this section, we define the objective function used to guide the 2D grating optimization and use its adjoint gradient to update the design parameters controlling the trench and gap widths.
2D Far-Field Projection and FOM Extraction¶
We first extract the optical performance quantities used in the objective. Waveguide coupling and back-reflection are obtained from the mode amplitudes, while the field recorded above the grating is projected into angle space. This angular projection allows us to estimate the upward-radiated power, the collected power within the target angular range of ±15°, and the angular spill outside that range.
dtheta_2d = theta_array_2d[1] - theta_array_2d[0]
collection_angle_rad_2d = collection_angle_deg * np.pi / 180
def get_monitor_by_name(sim, name):
"""
Return a monitor object from a simulation by name.
This is used so that the projection uses the monitors from the
actual simulation object.
"""
for monitor in sim.monitors:
if monitor.name == name:
return monitor
raise KeyError(
f"Monitor {name!r} not found. Available monitors: {[m.name for m in sim.monitors]}"
)
def get_proj_fields_2d(sim_data, monitor_near, monitor_far):
"""
Project the near fields from the top-field monitor to angle space.
Returns the projected far-field data on the theta grid.
"""
projector = td.FieldProjector.from_near_field_monitors(
sim_data=sim_data,
near_monitors=[monitor_near],
normal_dirs=["+"],
pts_per_wavelength=14,
)
return projector.project_fields(monitor_far)
def figures_of_merit_2d(sim_beam_data, sim_mode_data, sim_mode):
"""
Extract the 2D figures of merit.
Returns reflection, coupling, projected angular power, angle diagnostics,
collected power, and total upward power.
"""
top_field_monitor_local = get_monitor_by_name(sim_mode, "top_field")
proj_monitor_2d_local = get_monitor_by_name(sim_mode, "projection")
# Back-reflection from the mode-source simulation.
reflectivity = (
anp.abs(sim_mode_data["wg_mode"].amps.sel(direction="-", mode_index=0).values)
** 2
)
# Coupling into the waveguide from the beam-source simulation.
coupling = (
anp.abs(sim_beam_data["wg_mode"].amps.sel(direction="-", mode_index=0).values)
** 2
)
# Upward radiation projected from near field to angle space.
projected_field_data = get_proj_fields_2d(
sim_mode_data,
top_field_monitor_local,
proj_monitor_2d_local,
)
power = (
projected_field_data.power.squeeze().values
* proj_monitor_2d_local.proj_distance
)
theta = projected_field_data.theta
# Total upward projected power at each wavelength.
upwards_power = dtheta_2d * anp.sum(power, axis=0)
# Power collected inside the angular cone.
collection_mask_2d = (-collection_angle_rad_2d <= theta) & (
theta <= collection_angle_rad_2d
)
collected_power = dtheta_2d * anp.sum(
power[collection_mask_2d, :],
axis=0,
)
# Angle diagnostics at each wavelength.
ave_angle = anp.sum(
theta.reshape((len(theta), 1)) * power * dtheta_2d,
axis=0,
)
stdev_angle = anp.sqrt(
anp.sum(
(theta.reshape((len(theta), 1)) - ave_angle.reshape((1, len(ave_angle))))
** 2
* power
* dtheta_2d,
axis=0,
)
)
peak_angle = theta[anp.argmax(power[:, idx_c_2d])]
return (
reflectivity,
coupling,
power,
peak_angle,
ave_angle,
stdev_angle,
collected_power,
upwards_power,
)
def summarize_2d_foms(foms):
"""
Convert the raw 2D FOM arrays into a compact summary dictionary.
Returns the center-wavelength values and target-band averages.
"""
(
reflectivity,
coupling,
_power,
peak_angle,
ave_angle,
stdev_angle,
collected_power,
upwards_power,
) = foms
return {
"center_wavelength_nm": float(lams_um_2d[idx_c_2d] * 1000),
"center_coupling": float(coupling[idx_c_2d]),
"band_mean_coupling": float(anp.mean(coupling[mask_T_band_2d])),
"center_reflectivity": float(reflectivity[idx_c_2d]),
"band_mean_reflectivity": float(anp.mean(reflectivity[mask_R_band_2d])),
"center_upwards_power": float(upwards_power[idx_c_2d]),
"center_collected_power": float(collected_power[idx_c_2d]),
"center_angular_spill": float(
upwards_power[idx_c_2d] - collected_power[idx_c_2d]
),
"peak_angle_deg": float(peak_angle * 180 / np.pi),
"average_angle_deg": float(ave_angle[idx_c_2d] * 180 / np.pi),
"stdev_angle_deg": float(stdev_angle[idx_c_2d] * 180 / np.pi),
}
def print_2d_fom_summary(summary):
"""Print the most important 2D figures of merit."""
print(f"2D FOM summary at {summary['center_wavelength_nm']:.1f} nm:")
print(f" center coupling = {100 * summary['center_coupling']:.3f}%")
print(f" T-band mean coupling = {100 * summary['band_mean_coupling']:.3f}%")
print(f" center reflection = {100 * summary['center_reflectivity']:.3f}%")
print(f" R-band mean reflection = {100 * summary['band_mean_reflectivity']:.3f}%")
print(f" upward power = {100 * summary['center_upwards_power']:.3f}%")
print(f" collected cone power = {100 * summary['center_collected_power']:.3f}%")
print(f" angular spill = {100 * summary['center_angular_spill']:.3f}%")
print(f" peak angle = {summary['peak_angle_deg']:.3f} deg")
print(f" average angle = {summary['average_angle_deg']:.3f} deg")
print(f" angle stdev = {summary['stdev_angle_deg']:.3f} deg")
print("2D FOM extraction is ready.")
print(f" collection half-angle = {collection_angle_deg:.1f} deg")
print(f" T-band wavelengths = {np.round(lams_um_2d[mask_T_band_2d] * 1000, 3)} nm")
print(f" R-band wavelengths = {np.round(lams_um_2d[mask_R_band_2d] * 1000, 3)} nm")
2D FOM extraction is ready. collection half-angle = 15.0 deg T-band wavelengths = [778. 788. 798. 808. 818.] nm R-band wavelengths = [778. 788. 798. 808. 818.] nm
2D Objective Function¶
Next, we define the scalar objective that is maximized during the 2D adjoint optimization. The objective is written as a weighted sum of several physical terms, where positive weights reward desired behavior and negative weights penalize undesired behavior, as follows:
A. The coupling terms reward power transfer from the free-space beam into the waveguide. We include:
- the harmonic-mean coupling over the T-band, which gives more weight to lower-coupling wavelength points and therefore helps flatten the coupling response across the target band,
- the mean coupling over the T-band to improve the overall band response,
- the center-wavelength coupling to keep the design-wavelength performance high.
B. The reflection terms penalize power reflected back into the waveguide. These include:
- the center-wavelength reflection,
- the mean reflection over the R-band,
- a smooth worst-case reflection term, which places a stronger penalty on the highest-reflection wavelength points in the band, helping flatten the reflection response.
C. The radiation terms control how the grating radiates power upward. These include:
- the collected upward power at the center wavelength, which rewards power radiated within the target angular range of ±15°,
- the angular spill, which penalizes upward power radiated outside the collection range,
- a smooth angular-moment term that penalizes radiation away from the normal direction.
Staged objective schedule
Rather than using one fixed set of weights throughout the optimization, we use a staged schedule. The same objective terms are kept, but their relative weights are adjusted as the design improves: the first stage focuses mainly on building broadband coupling, while the later stages place more weight on center-wavelength coupling and reducing reflection. The final stage also uses a smaller learning rate for finer refinement.
# Objective weight schedule
# The same objective structure is used throughout the 2D optimization,
# but the weights are changed in stages.
# Stage 1: broadband coupling search
WEIGHTS_2D_STAGE1 = {
"band_coupling_harmonic_mean": 5.0e7,
"band_coupling_mean": 1.0e6,
"center_coupling": 2.0e5,
"center_collected": 1.0e3,
"center_reflection": -5.0e4,
"band_mean_reflection": -3.0e4,
"band_worst_reflection": -8.0e4,
"angular_spill": -5.0e4,
"center_angle_moment": -1.0e3,
}
# Stage 2: reflection and radiation cleanup
WEIGHTS_2D_STAGE2 = {
"band_coupling_harmonic_mean": 5.0e7,
"band_coupling_mean": 1.0e5,
"center_coupling": 5.0e6,
"center_collected": 1.0e3,
"center_reflection": -5.0e5,
"band_mean_reflection": -5.0e4,
"band_worst_reflection": -5.0e5,
"angular_spill": -5.0e4,
"center_angle_moment": -1.0e3,
}
# Stage 3: final refinement
WEIGHTS_2D_STAGE3 = {
"band_coupling_harmonic_mean": 2.5e7,
"band_coupling_mean": 1.0e5,
"center_coupling": 2.5e7,
"center_collected": 1.0e3,
"center_reflection": -5.0e5,
"band_mean_reflection": -5.0e4,
"band_worst_reflection": -5.0e5,
"angular_spill": -5.0e4,
"center_angle_moment": -1.0e3,
}
# Automatic 2D optimization stage schedule
# Each stage has its own weights, learning rate, target band, and number
# of iterations. This lets the full 2D optimization run automatically.
STAGES_2D = [
{
"stage_id": 1,
"name": "stage1_build_coupling",
"n_iters": 310, # iterations 0 through 309
"learning_rate": 0.005,
"band_half_width_um": 0.025, # 50 nm total target band
"weights": WEIGHTS_2D_STAGE1,
},
{
"stage_id": 2,
"name": "stage2_cleanup",
"n_iters": 20, # iterations 310 through 329
"learning_rate": 0.005,
"band_half_width_um": 0.025, # 50 nm total target band
"weights": WEIGHTS_2D_STAGE2,
},
{
"stage_id": 3,
"name": "stage3_final_refinement",
"n_iters": 20, # iterations 330 through 349
"learning_rate": 0.0005,
"band_half_width_um": 0.025, # 50 nm total target band
"weights": WEIGHTS_2D_STAGE3,
},
]
def add_stage_bounds_2d(stages):
"""Add start and stop iteration numbers to each 2D stage."""
stages_with_bounds = []
start_iter = 0
for stage in stages:
stage = dict(stage)
stage["start_iter"] = start_iter
stage["stop_iter"] = start_iter + int(stage["n_iters"])
stages_with_bounds.append(stage)
start_iter = stage["stop_iter"]
return stages_with_bounds
STAGES_2D = add_stage_bounds_2d(STAGES_2D)
TOTAL_ITERS_2D = STAGES_2D[-1]["stop_iter"]
def get_stage_for_iter_2d(iter_index):
"""Return the active 2D stage for a given iteration number."""
for stage in STAGES_2D:
if stage["start_iter"] <= iter_index < stage["stop_iter"]:
return stage
raise ValueError(
f"Iteration {iter_index} is outside the 2D stage schedule. "
f"The last scheduled iteration is {TOTAL_ITERS_2D - 1}."
)
def set_stage_2d(stage, verbose=True):
"""Set the active 2D weights and target band for one stage."""
global WEIGHTS_2D
WEIGHTS_2D = dict(stage["weights"])
set_target_band_2d(stage["band_half_width_um"], verbose=False)
if verbose:
print("Active 2D optimization stage:")
print(f" stage id = {stage['stage_id']}")
print(f" name = {stage['name']}")
print(
f" iterations = {stage['start_iter']} to {stage['stop_iter'] - 1}"
)
print(f" learning rate = {stage['learning_rate']:.3e}")
print(f" band half-width = {1000 * stage['band_half_width_um']:.1f} nm")
print(
f" T-band wavelengths= {np.round(lams_um_2d[mask_T_band_2d] * 1000, 3)} nm"
)
print()
# Initialize the objective using Stage 1.
set_stage_2d(STAGES_2D[0])
# Constants used by the smooth objective terms
# Small value used to avoid division by zero in the harmonic mean.
T_HMEAN_EPS_2D = 1e-12
# Smooth maximum scale for the worst reflection term.
# Smaller values make the smooth maximum closer to a true maximum.
TAU_R_BAND_2D = 3.0e-2
# Number of wavelengths included in the coupling and reflection bands.
N_T_BAND_2D = float(np.sum(mask_T_band_2d))
N_R_BAND_2D = float(np.sum(mask_R_band_2d))
if N_T_BAND_2D < 1:
raise ValueError("mask_T_band_2d does not include any wavelength points.")
if N_R_BAND_2D < 1:
raise ValueError("mask_R_band_2d does not include any wavelength points.")
# Optional output cache
# When SAVE_2D_CACHE is True, the downloaded HDF5 files are saved locally
SAVE_2D_CACHE = False
DIR_2D_CACHE = Path("2d_optimization_cache")
if SAVE_2D_CACHE:
DIR_2D_CACHE.mkdir(parents=True, exist_ok=True)
sim_data_last_2d = [None]
# 2D objective function
def objective_terms_2d(foms):
"""
Compute the raw 2D objective terms from the FOM arrays.
Returns the unweighted terms before multiplying by WEIGHTS_2D.
"""
(
reflectivity,
coupling,
power,
_peak_angle,
_ave_angle,
_stdev_angle,
collected_power,
upwards_power,
) = foms
# Coupling values inside the target transmission band.
T_band = coupling[mask_T_band_2d]
# Reflection values inside the target reflection band.
R_band = reflectivity[mask_R_band_2d]
# Harmonic-mean coupling over the target band.
# This rewards broadband behavior and penalizes weak wavelengths strongly.
band_coupling_harmonic_mean = N_T_BAND_2D / anp.sum(1.0 / (T_band + T_HMEAN_EPS_2D))
# Mean coupling over the target band.
# This rewards overall band performance.
band_coupling_mean = anp.mean(T_band)
# Coupling at the center wavelength.
# This keeps the design wavelength performance high.
center_coupling = coupling[idx_c_2d]
# Power collected inside the target angular cone at the center wavelength.
# This rewards useful upward radiation near vertical.
center_collected = collected_power[idx_c_2d]
# Reflection at the center wavelength.
# This penalizes direct back-reflection into the input waveguide.
center_reflection = reflectivity[idx_c_2d]
# Mean reflection over the reflection band.
# This penalizes broadband reflection.
band_mean_reflection = anp.mean(R_band)
# Smooth worst-case reflection over the reflection band.
# This approximates max(R_band), but remains differentiable.
band_worst_reflection = TAU_R_BAND_2D * anp.log(
anp.mean(anp.exp(R_band / TAU_R_BAND_2D))
)
# Upward radiation outside the collection cone.
# This penalizes power that is radiated upward but not collected.
angular_spill = upwards_power[idx_c_2d] - collected_power[idx_c_2d]
# Smooth angular-spread penalty at the center wavelength.
theta_rad = anp.array(theta_array_2d)
P_center = power[:, idx_c_2d]
theta_accept_rad = collection_angle_deg * anp.pi / 180.0
angle_weight = (theta_rad / theta_accept_rad) ** 2
center_angle_moment = anp.sum(P_center * angle_weight) / (anp.sum(P_center) + 1e-12)
return {
"band_coupling_harmonic_mean": band_coupling_harmonic_mean,
"band_coupling_mean": band_coupling_mean,
"center_coupling": center_coupling,
"center_collected": center_collected,
"center_reflection": center_reflection,
"band_mean_reflection": band_mean_reflection,
"band_worst_reflection": band_worst_reflection,
"angular_spill": angular_spill,
"center_angle_moment": center_angle_moment,
}
def weighted_objective_2d(raw_terms):
"""
Convert raw objective terms into the scalar objective.
Returns:
objective_value: scalar value maximized by the optimizer
weighted_terms: each raw term multiplied by its weight
"""
weighted_terms = {key: WEIGHTS_2D[key] * raw_terms[key] for key in WEIGHTS_2D}
objective_value = sum(weighted_terms.values())
return objective_value, weighted_terms
def objective_2d(
params_u,
task_name="gc_2d_tutorial",
verbose=False,
return_raw_terms_only=False,
):
"""
Run the two 2D simulations and evaluate the objective.
This is the function differentiated by the adjoint optimizer.
"""
# Build the beam-source and mode-source simulations for the current design.
sim_beam, sim_mode = build_sims_2d(
params_u,
use_extra_monitors=False,
)
# Local paths for saving the latest simulation results.
path_beam = DIR_2D_CACHE / f"{task_name}_beam.hdf5" if SAVE_2D_CACHE else None
path_mode = DIR_2D_CACHE / f"{task_name}_mode.hdf5" if SAVE_2D_CACHE else None
# Beam-source simulation:
# measures coupling from the free-space beam into the waveguide.
sim_beam_data = web.run(
sim_beam,
task_name=f"{task_name}_beam",
path=str(path_beam) if path_beam is not None else None,
verbose=verbose,
)
# Mode-source simulation:
# measures reflection and upward projected radiation.
sim_mode_data = web.run(
sim_mode,
task_name=f"{task_name}_mode",
path=str(path_mode) if path_mode is not None else None,
verbose=verbose,
)
# Store the latest simulation data for plotting and debugging.
sim_data_last_2d[0] = (
sim_beam_data,
sim_mode_data,
sim_beam,
sim_mode,
)
# Extract coupling, reflection, projected power, and angular quantities.
foms = figures_of_merit_2d(
sim_beam_data,
sim_mode_data,
sim_mode,
)
# Convert FOM arrays into raw objective terms.
raw_terms = objective_terms_2d(foms)
if return_raw_terms_only:
return raw_terms, foms
# Multiply each term by its weight and sum them.
objective_value, weighted_terms = weighted_objective_2d(raw_terms)
return objective_value, (foms, raw_terms, weighted_terms)
# This wrapper returns both the objective value and its gradient with respect
# to the grating design variables.
val_grad_2d = value_and_grad(objective_2d, has_aux=True)
print("2D objective function is ready.")
Active 2D optimization stage: stage id = 1 name = stage1_build_coupling iterations = 0 to 309 learning rate = 5.000e-03 band half-width = 25.0 nm T-band wavelengths= [778. 788. 798. 808. 818.] nm 2D objective function is ready.
Optional 2D Baseline Check¶
Before starting the 2D optimization, we can optionally run the initial grating design and extract the same figures of merit used later in the objective. This provides a baseline for the unoptimized structure and confirms that the simulation setup, monitors, and FOM extraction functions are working correctly.
The initial design is only a simple starting point based on an estimated grating period and fill factor, so its coupling is expected to be very low and its back-reflection high.
# Optional 2D baseline check
RUN_BASELINE_2D = True # set to False to skip the baseline check
if RUN_BASELINE_2D:
_, aux0_2d = objective_2d(
anp.array(params_init),
task_name="baseline_2d",
verbose=False,
)
foms0_2d, raw_terms0_2d, _ = aux0_2d
summary0_2d = summarize_2d_foms(foms0_2d)
print_2d_fom_summary(summary0_2d)
print()
print("2D objective terms:")
for key in WEIGHTS_2D:
print(f" {key:26s} raw = {float(raw_terms0_2d[key]): .6e} ")
else:
print("Skipped 2D baseline check.")
2D FOM summary at 798.0 nm: center coupling = 0.001% T-band mean coupling = 0.001% center reflection = 30.899% R-band mean reflection = 25.853% upward power = 34.218% collected cone power = 1.971% angular spill = 32.246% peak angle = -40.500 deg average angle = -10.989 deg angle stdev = 18.145 deg 2D objective terms: band_coupling_harmonic_mean raw = 9.724169e-06 band_coupling_mean raw = 1.007622e-05 center_coupling raw = 8.204467e-06 center_collected raw = 1.971387e-02 center_reflection raw = 3.089913e-01 band_mean_reflection raw = 2.585251e-01 band_worst_reflection raw = 2.915487e-01 angular_spill raw = 3.224642e-01 center_angle_moment raw = 6.876853e+00
2D Live Optimization Plot Helpers¶
We define the helper functions used to visualize the 2D optimization while it is running. The live plot tracks the objective value, coupling, reflection, and upward radiation pattern after each saved iteration. It helps check that the optimizer is improving the grating in the expected direction.
# 2D live optimization plot helpers
def _history_array_2d(history, key):
"""Return a numpy array from a history list."""
if key not in history or len(history[key]) == 0:
return np.array([])
return np.array(history[key])
def _center_and_band_from_history_2d(history, key, band_mask):
"""Return center-wavelength and band-mean traces from a spectral history array."""
arr = _history_array_2d(history, key)
if arr.size == 0:
return np.array([]), np.array([])
center = arr[:, idx_c_2d]
band_mean = np.mean(arr[:, band_mask], axis=1)
return center, band_mean
def _latest_farfield_2d(history):
"""Return theta in degrees and the latest center-wavelength radiation pattern."""
power_hist = _history_array_2d(history, "power")
if power_hist.size == 0:
return None, None
latest_power = np.array(power_hist[-1], dtype=float)
if latest_power.ndim != 2:
return None, None
theta_deg = np.array(theta_array_2d, dtype=float) * 180 / np.pi
power_center = latest_power[:, idx_c_2d]
return theta_deg, power_center
def make_live_optimization_figure_2d():
"""Create the live 2D optimization figure."""
fig = make_subplots(
rows=3,
cols=2,
specs=[
[{"type": "xy"}, {"type": "polar", "rowspan": 3}],
[{"type": "xy"}, None],
[{"type": "xy"}, None],
],
column_widths=[0.55, 0.45],
row_heights=[0.34, 0.33, 0.33],
subplot_titles=[
"Objective",
"Radiated power at center wavelength",
"Coupling",
"Reflection",
],
)
fig.update_layout(
width=1150,
height=800,
showlegend=True,
title="2D adjoint optimization live progress",
)
fig.update_xaxes(title_text="Iteration", row=1, col=1)
fig.update_yaxes(title_text="Objective", row=1, col=1)
fig.update_xaxes(title_text="Iteration", row=2, col=1)
fig.update_yaxes(title_text="Coupling (%)", row=2, col=1)
fig.update_xaxes(title_text="Iteration", row=3, col=1)
fig.update_yaxes(title_text="Reflection (%)", row=3, col=1)
fig.update_polars(
radialaxis_title="Power",
angularaxis={
"rotation": 90,
"direction": "counterclockwise",
},
row=1,
col=2,
)
return fig
def update_live_optimization_figure_2d(fig, history):
"""Update the live 2D optimization figure from the current history."""
fig.data = []
values = _history_array_2d(history, "values")
n = len(values)
if n == 0:
return fig
iters = np.arange(n)
# Objective history.
fig.add_trace(
go.Scatter(
x=iters,
y=values,
mode="lines+markers",
name="Objective",
),
row=1,
col=1,
)
# Coupling history.
coupling_center, coupling_band = _center_and_band_from_history_2d(
history,
"coupling",
mask_T_band_2d,
)
if len(coupling_center) > 0:
fig.add_trace(
go.Scatter(
x=iters,
y=100 * coupling_center,
mode="lines+markers",
name="Center coupling",
),
row=2,
col=1,
)
fig.add_trace(
go.Scatter(
x=iters,
y=100 * coupling_band,
mode="lines+markers",
name="T-band mean coupling",
),
row=2,
col=1,
)
# Reflection history.
reflection_center, reflection_band = _center_and_band_from_history_2d(
history,
"reflectivity",
mask_R_band_2d,
)
if len(reflection_center) > 0:
fig.add_trace(
go.Scatter(
x=iters,
y=100 * reflection_center,
mode="lines+markers",
name="Center reflection",
),
row=3,
col=1,
)
fig.add_trace(
go.Scatter(
x=iters,
y=100 * reflection_band,
mode="lines+markers",
name="R-band mean reflection",
),
row=3,
col=1,
)
# Latest center-wavelength angular radiation pattern.
theta_deg, power_center = _latest_farfield_2d(history)
if theta_deg is not None:
fig.add_trace(
go.Scatterpolar(
theta=theta_deg,
r=power_center,
mode="lines",
name="Radiated power at center λ",
),
row=1,
col=2,
)
return fig
def display_live_optimization_figure_2d(fig, history):
"""Refresh and display the live 2D optimization figure."""
update_live_optimization_figure_2d(fig, history)
clear_output(wait=True)
display(fig)
fig_live_2d = make_live_optimization_figure_2d()
print("2D live optimization plot helpers are ready.")
2D live optimization plot helpers are ready.
Run the 2D Adjoint Optimization¶
Finally, we run the staged 2D adjoint optimization.
At each iteration, the active stage determines the objective weights, learning rate, and target wavelength band used for that part of the optimization. The beam-source and mode-source simulations are evaluated, the scalar objective and its adjoint gradient are computed, and the design parameters are updated using the Adam optimizer.
After each iteration, the main figures of merit, objective terms, gradients, current parameters, and active stage settings are saved to the history .pkl file. The live plots are also updated so the optimization progress can be monitored while the run is in progress. If a saved optimization history already exists, the loop loads it and resumes from the last saved iteration; otherwise, it starts from the initial design parameters.
(Each iteration costs about 0.125 FlexCredits and takes about 3 minutes.)
# Run 2D adjoint optimization
# If True, the notebook runs the 2D optimization using the staged schedule.
# If a saved history exists, the optimization resumes from it; otherwise,
# a new optimization starts from the initial design parameters.
RUN_2D_OPTIMIZATION = True
# Output path for the 2D optimization history.
HISTORY_2D_PATH = Path("gc_2d_optimization_history.pkl")
def to_numpy_2d(x):
"""Convert arrays and scalar objects to pickle-friendly values."""
if hasattr(x, "_value"):
return to_numpy_2d(x._value)
if isinstance(x, dict):
return {k: to_numpy_2d(v) for k, v in x.items()}
if isinstance(x, (list, tuple)):
return type(x)(to_numpy_2d(v) for v in x)
if (
hasattr(x, "values")
and not callable(x.values)
and not isinstance(x, (str, bytes))
):
return to_numpy_2d(x.values)
arr = np.asarray(x)
if arr.shape == ():
return arr.item()
return np.array(arr, dtype=float)
def stage_schedule_metadata_2d():
"""Return a pickle-friendly copy of the 2D stage schedule."""
return [
{
"stage_id": int(stage["stage_id"]),
"name": str(stage["name"]),
"n_iters": int(stage["n_iters"]),
"start_iter": int(stage["start_iter"]),
"stop_iter": int(stage["stop_iter"]),
"learning_rate": float(stage["learning_rate"]),
"band_half_width_um": float(stage["band_half_width_um"]),
"weights": dict(stage["weights"]),
}
for stage in STAGES_2D
]
def make_empty_history_2d():
"""Create a new 2D optimization history."""
return {
"metadata": {
"lambda0_um": float(lambda0_um),
"wavelengths_nm": list(np.round(lams_um_2d * 1000, 6)),
"stage_schedule_2d": stage_schedule_metadata_2d(),
},
"values": [],
"stage_id": [],
"stage_name": [],
"learning_rate": [],
"band_half_width_um": [],
"weights": [],
"params": [],
"params_current": [],
"gradients": [],
"grad_norm": [],
"coupling": [],
"reflectivity": [],
"power": [],
"peak_angle": [],
"ave_angle": [],
"stdev_angle": [],
"collected_power": [],
"upwards_power": [],
"raw_terms": [],
"weighted_terms": [],
"summary": [],
"params_current_2d": None,
"opt_state_2d": None,
}
def load_history_2d(path):
"""Load a saved 2D history file."""
with open(path, "rb") as f:
history = pickle.load(f)
return history
td.config.logging.level = "ERROR"
if RUN_2D_OPTIMIZATION:
# Start or resume the 2D optimization
if HISTORY_2D_PATH.exists():
history_2d = load_history_2d(HISTORY_2D_PATH)
params_current_2d = np.array(history_2d["params_current_2d"], dtype=float)
print("Loaded existing 2D history and will continue from it.")
print(f" history path = {HISTORY_2D_PATH}")
print(f" saved iterations = {len(history_2d['values'])}")
else:
history_2d = make_empty_history_2d()
params_current_2d = np.array(params_init, dtype=float)
history_2d["params_current_2d"] = params_current_2d
print("Starting a fresh 2D optimization.")
print(f" history path = {HISTORY_2D_PATH}")
start_iter_2d = len(history_2d["values"])
stop_iter_2d = TOTAL_ITERS_2D
optimizer_2d = None
opt_state_2d = history_2d.get("opt_state_2d", None)
print(f" history path = {HISTORY_2D_PATH}")
print(f" total scheduled iterations = {TOTAL_ITERS_2D}")
print()
print("2D stage schedule:")
for stage in STAGES_2D:
print(
f" Stage {stage['stage_id']}: "
f"{stage['start_iter']} to {stage['stop_iter'] - 1}, "
f"lr={stage['learning_rate']:.3e}, "
f"band={1000 * stage['band_half_width_um']:.1f} nm half-width"
)
print()
# Live plot is always shown for the tutorial run.
fig_live_2d = make_live_optimization_figure_2d()
display_live_optimization_figure_2d(fig_live_2d, history_2d)
for iter_2d in range(start_iter_2d, stop_iter_2d):
stage_2d = get_stage_for_iter_2d(iter_2d)
# Update the active weights, learning rate, and target band
# when a new stage starts.
# The Adam state is kept continuous between stages.
if (iter_2d == start_iter_2d) or (iter_2d == stage_2d["start_iter"]):
set_stage_2d(stage_2d, verbose=False)
optimizer_2d = optax.adam(learning_rate=stage_2d["learning_rate"])
# The Adam state is kept continuous between stages.
if opt_state_2d is None:
opt_state_2d = optimizer_2d.init(params_current_2d)
print()
print("-" * 80)
print(f"Starting 2D {stage_2d['name']}")
print(f" stage id = {stage_2d['stage_id']}")
print(
f" iterations = {stage_2d['start_iter']} to {stage_2d['stop_iter'] - 1}"
)
print(f" learning rate = {stage_2d['learning_rate']:.3e}")
print(f" band half-width = {1000 * stage_2d['band_half_width_um']:.1f} nm")
print(
f" T-band = {np.round(lams_um_2d[mask_T_band_2d] * 1000, 3)} nm"
)
print("-" * 80)
print()
print("=" * 80)
print(f"2D iteration {iter_2d}")
# Save the exact parameter vector evaluated in this iteration.
params_eval_2d = np.array(params_current_2d, dtype=float).copy()
# Evaluate objective and gradient.
(obj_2d, grad_2d), aux_2d = val_grad_2d(
anp.array(params_eval_2d),
task_name=f"opt2d_stage{stage_2d['stage_id']}_iter_{iter_2d:04d}",
verbose=False,
)
foms_2d, raw_terms_2d, weighted_terms_2d = aux_2d
obj_2d = float(to_numpy_2d(obj_2d))
grad_2d = np.array(to_numpy_2d(grad_2d), dtype=float)
grad_norm_2d = float(np.linalg.norm(grad_2d))
foms_2d = tuple(to_numpy_2d(x) for x in foms_2d)
raw_terms_2d = to_numpy_2d(raw_terms_2d)
weighted_terms_2d = to_numpy_2d(weighted_terms_2d)
# Optax minimizes by default, so use -grad to maximize the objective.
updates_2d, opt_state_2d = optimizer_2d.update(
-grad_2d,
opt_state_2d,
params_current_2d,
)
params_current_2d = optax.apply_updates(
params_current_2d,
updates_2d,
)
params_current_2d = np.array(params_current_2d, dtype=float)
(
reflectivity_2d,
coupling_2d,
power_2d,
peak_angle_2d,
ave_angle_2d,
stdev_angle_2d,
collected_power_2d,
upwards_power_2d,
) = foms_2d
summary_2d = summarize_2d_foms(foms_2d)
summary_2d = to_numpy_2d(summary_2d)
# Save evaluated design and FOMs.
history_2d["values"].append(obj_2d)
history_2d["stage_id"].append(int(stage_2d["stage_id"]))
history_2d["stage_name"].append(str(stage_2d["name"]))
history_2d["learning_rate"].append(float(stage_2d["learning_rate"]))
history_2d["band_half_width_um"].append(float(stage_2d["band_half_width_um"]))
history_2d["weights"].append(dict(stage_2d["weights"]))
history_2d["params"].append(params_eval_2d)
history_2d["params_current"].append(params_current_2d)
history_2d["gradients"].append(grad_2d)
history_2d["grad_norm"].append(grad_norm_2d)
history_2d["coupling"].append(coupling_2d)
history_2d["reflectivity"].append(reflectivity_2d)
history_2d["power"].append(power_2d)
history_2d["peak_angle"].append(peak_angle_2d)
history_2d["ave_angle"].append(ave_angle_2d)
history_2d["stdev_angle"].append(stdev_angle_2d)
history_2d["collected_power"].append(collected_power_2d)
history_2d["upwards_power"].append(upwards_power_2d)
history_2d["raw_terms"].append(raw_terms_2d)
history_2d["weighted_terms"].append(weighted_terms_2d)
history_2d["summary"].append(summary_2d)
# Save continuation state.
history_2d["params_current_2d"] = params_current_2d
history_2d["opt_state_2d"] = opt_state_2d
# Always save the history after each iteration.
with open(HISTORY_2D_PATH, "wb") as f:
pickle.dump(history_2d, f)
display_live_optimization_figure_2d(fig_live_2d, history_2d)
print(f"Completed 2D iteration {iter_2d}")
print(f" stage = {stage_2d['stage_id']} ({stage_2d['name']})")
print(f" objective = {obj_2d:.6e}")
print(f" grad norm = {grad_norm_2d:.6e}")
print(f" center coupling = {100 * summary_2d['center_coupling']:.4f}%")
print(
f" T-band mean coupling = {100 * summary_2d['band_mean_coupling']:.4f}%"
)
print(
f" center reflection = {100 * summary_2d['center_reflectivity']:.4f}%"
)
print(
f" R-band mean reflection = {100 * summary_2d['band_mean_reflectivity']:.4f}%"
)
print(
f" upward power = {100 * summary_2d['center_upwards_power']:.4f}%"
)
print(
f" collected cone power = {100 * summary_2d['center_collected_power']:.4f}%"
)
print(
f" angular spill = {100 * summary_2d['center_angular_spill']:.4f}%"
)
print(f" peak angle = {summary_2d['peak_angle_deg']:.3f} deg")
print()
print("2D optimization finished.")
print(f" total saved iterations = {len(history_2d['values'])}")
print(f" history saved to = {HISTORY_2D_PATH}")
# Print the final saved iteration.
final_iter_2d = len(history_2d["values"]) - 1
summary_2d = history_2d["summary"][-1]
print()
print(f"Final saved iteration {final_iter_2d}")
print(
f" stage = {history_2d['stage_id'][-1]} ({history_2d['stage_name'][-1]})"
)
print(f" objective = {history_2d['values'][-1]:.6e}")
print(f" grad norm = {history_2d['grad_norm'][-1]:.6e}")
print(f" center coupling = {100 * summary_2d['center_coupling']:.4f}%")
print(f" T-band mean coupling = {100 * summary_2d['band_mean_coupling']:.4f}%")
print(f" center reflection = {100 * summary_2d['center_reflectivity']:.4f}%")
print(
f" R-band mean reflection = {100 * summary_2d['band_mean_reflectivity']:.4f}%"
)
print(f" upward power = {100 * summary_2d['center_upwards_power']:.4f}%")
print(
f" collected cone power = {100 * summary_2d['center_collected_power']:.4f}%"
)
print(f" angular spill = {100 * summary_2d['center_angular_spill']:.4f}%")
print(f" peak angle = {summary_2d['peak_angle_deg']:.3f} deg")
else:
print("2D optimization skipped.")
if HISTORY_2D_PATH.exists():
history_2d = load_history_2d(HISTORY_2D_PATH)
print("Loaded saved 2D history.")
print(f" history path = {HISTORY_2D_PATH}")
print(f" saved iterations = {len(history_2d['values'])}")
else:
history_2d = make_empty_history_2d()
print("No saved 2D history was found.")
2D optimization finished. total saved iterations = 350 history saved to = gc_2d_optimization_history.pkl Final saved iteration 349 stage = 3 (stage3_final_refinement) objective = 1.105830e+07 grad norm = 1.346244e+06 center coupling = 23.2395% T-band mean coupling = 21.3485% center reflection = 0.1470% R-band mean reflection = 5.1416% upward power = 49.0554% collected cone power = 29.4071% angular spill = 19.6482% peak angle = -1.000 deg
Select and Inspect the 2D Design¶
After completing the 2D optimization, we can select any saved iteration for further inspection and use it as the starting geometry for the 3D model. Here, we select the final iteration (349), which shows good optical performance, with relatively high coupling, low reflection, and near-vertical radiation.
We then inspect its coupling, reflection, upward radiation, and far-field response.
SELECT_2D_ITER = 349 # None = best objective, -1 = latest, or use an integer
# Load 2D history
if HISTORY_2D_PATH.exists():
with open(HISTORY_2D_PATH, "rb") as f:
history_2d = pickle.load(f)
print(f"Loaded 2D history from: {HISTORY_2D_PATH}")
print(f" saved iterations = {len(history_2d['values'])}")
else:
raise FileNotFoundError(
f"No 2D history file found at {HISTORY_2D_PATH}. "
"Run the 2D optimization cell first."
)
# Check available complete entries
required_keys_2d = [
"values",
"params",
"coupling",
"reflectivity",
"power",
]
n_complete_2d = min(len(history_2d[key]) for key in required_keys_2d)
if n_complete_2d == 0:
raise ValueError("No complete 2D optimization history found.")
# Select iteration
values_2d = np.array(history_2d["values"][:n_complete_2d], dtype=float)
best_iter_2d = int(np.argmax(values_2d))
if SELECT_2D_ITER is None:
selected_iter_2d = best_iter_2d
elif int(SELECT_2D_ITER) == -1:
selected_iter_2d = n_complete_2d - 1
else:
selected_iter_2d = int(SELECT_2D_ITER)
if selected_iter_2d < 0 or selected_iter_2d >= n_complete_2d:
raise ValueError(
f"selected_iter_2d={selected_iter_2d} is outside the available range "
f"0 ... {n_complete_2d - 1}."
)
# Extract selected design
params_selected_2d = np.array(history_2d["params"][selected_iter_2d], dtype=float)
w_selected_2d, g_selected_2d = params_to_wgaps(anp.array(params_selected_2d))
w_selected_2d = np.array(w_selected_2d, dtype=float)
g_selected_2d = np.array(g_selected_2d, dtype=float)
xL_selected_2d, xR_selected_2d = edges_from_wgaps(
anp.array(w_selected_2d),
anp.array(g_selected_2d),
)
xL_selected_2d = np.array(xL_selected_2d, dtype=float)
xR_selected_2d = np.array(xR_selected_2d, dtype=float)
# Extract selected spectra and far field
coupling_selected_2d = np.array(history_2d["coupling"][selected_iter_2d], dtype=float)
reflectivity_selected_2d = np.array(
history_2d["reflectivity"][selected_iter_2d], dtype=float
)
power_selected_2d = np.array(history_2d["power"][selected_iter_2d], dtype=float)
if coupling_selected_2d.shape[0] != len(lams_um_2d):
raise ValueError(
"The selected history does not match the current wavelength grid.\n"
f" history wavelengths = {coupling_selected_2d.shape[0]}\n"
f" current wavelengths = {len(lams_um_2d)}"
)
# Fix possible transposed far-field map.
if power_selected_2d.shape == (len(lams_um_2d), len(theta_array_2d)):
power_selected_2d = power_selected_2d.T
if power_selected_2d.shape != (len(theta_array_2d), len(lams_um_2d)):
raise ValueError(
f"Unexpected power_selected_2d shape {power_selected_2d.shape}; "
f"expected {(len(theta_array_2d), len(lams_um_2d))}."
)
has_collected_2d = (
"collected_power" in history_2d
and len(history_2d["collected_power"]) > selected_iter_2d
)
has_upwards_2d = (
"upwards_power" in history_2d
and len(history_2d["upwards_power"]) > selected_iter_2d
)
if has_collected_2d:
collected_selected_2d = np.array(
history_2d["collected_power"][selected_iter_2d],
dtype=float,
)
if has_upwards_2d:
upwards_selected_2d = np.array(
history_2d["upwards_power"][selected_iter_2d],
dtype=float,
)
# Build selected FOM summary
if len(history_2d.get("summary", [])) > selected_iter_2d:
summary_selected_2d = history_2d["summary"][selected_iter_2d]
else:
foms_selected_2d = (
reflectivity_selected_2d,
coupling_selected_2d,
power_selected_2d,
history_2d["peak_angle"][selected_iter_2d],
np.array(history_2d["ave_angle"][selected_iter_2d], dtype=float),
np.array(history_2d["stdev_angle"][selected_iter_2d], dtype=float),
collected_selected_2d if has_collected_2d else np.zeros_like(lams_um_2d),
upwards_selected_2d if has_upwards_2d else np.zeros_like(lams_um_2d),
)
summary_selected_2d = summarize_2d_foms(foms_selected_2d)
# Plot coupling and reflection spectra
lams_nm_2d = lams_um_2d * 1000
fig, axes = plt.subplots(1, 2, figsize=(12, 4), constrained_layout=True)
axes[0].plot(lams_nm_2d, 100 * coupling_selected_2d, "o-", label="Coupling")
axes[0].axvline(lambda0_um * 1000, linestyle="--", label="center wavelength")
axes[0].axvspan(
lams_nm_2d[mask_T_band_2d][0],
lams_nm_2d[mask_T_band_2d][-1],
alpha=0.15,
label="T-band",
)
axes[0].set_xlabel("Wavelength (nm)")
axes[0].set_ylabel("Coupling (%)")
axes[0].set_title("Beam-source coupling spectrum")
axes[0].grid(True, alpha=0.3)
axes[0].legend()
axes[1].plot(lams_nm_2d, 100 * reflectivity_selected_2d, "o-", label="Reflection")
axes[1].axvline(lambda0_um * 1000, linestyle="--", label="center wavelength")
axes[1].axvspan(
lams_nm_2d[mask_R_band_2d][0],
lams_nm_2d[mask_R_band_2d][-1],
alpha=0.15,
label="R-band",
)
axes[1].set_xlabel("Wavelength (nm)")
axes[1].set_ylabel("Reflection (%)")
axes[1].set_title("Mode-source reflection spectrum")
axes[1].grid(True, alpha=0.3)
axes[1].legend()
fig.suptitle(f"2D spectra at iteration {selected_iter_2d}", fontsize=14)
plt.show()
# Plot upward and collected power spectra
if has_collected_2d or has_upwards_2d:
plt.figure(figsize=(7, 4))
if has_upwards_2d:
plt.plot(lams_nm_2d, 100 * upwards_selected_2d, "o-", label="Upward power")
if has_collected_2d:
plt.plot(
lams_nm_2d,
100 * collected_selected_2d,
"o-",
label=f"Collected power ±{collection_angle_deg:.0f}°",
)
plt.axvline(lambda0_um * 1000, linestyle="--", label="center wavelength")
plt.xlabel("Wavelength (nm)")
plt.ylabel("Power (%)")
plt.title(f"2D upward and collected power at iteration {selected_iter_2d}")
plt.grid(True, alpha=0.3)
plt.legend()
plt.tight_layout()
plt.show()
# Plot angle-resolved far-field map
theta_deg_2d = theta_array_2d * 180 / np.pi
plt.figure(figsize=(8, 5))
plt.pcolormesh(
lams_nm_2d,
theta_deg_2d,
100 * power_selected_2d,
shading="auto",
)
plt.colorbar(label="Radiated power (%)")
plt.axvline(lambda0_um * 1000, linestyle="--", color="white", linewidth=1.2)
plt.axhline(0, linestyle="-", color="white", linewidth=1.0)
plt.axhline(collection_angle_deg, linestyle="--", color="white", linewidth=0.9)
plt.axhline(-collection_angle_deg, linestyle="--", color="white", linewidth=0.9)
plt.xlabel("Wavelength (nm)")
plt.ylabel("Angle θ (deg)")
plt.title(f"2D angle-resolved radiation map at iteration {selected_iter_2d}")
plt.tight_layout()
plt.show()
# Plot center-wavelength 2D far field
# This is the 1D angular far-field profile at the design wavelength.
# Positive angle points toward +x, negative angle points toward -x.
theta_deg_2d = theta_array_2d * 180 / np.pi
power_center_selected_2d = power_selected_2d[:, idx_c_2d]
fig, ax = plt.subplots(1, 1, figsize=(10, 4.5))
ax.plot(
theta_deg_2d,
power_center_selected_2d,
linewidth=1.8,
label="Projected power",
)
ax.axvline(
0.0,
linestyle=":",
linewidth=1.0,
label="vertical",
)
ax.axvline(
collection_angle_deg,
linestyle="--",
linewidth=1.2,
label=f"+{collection_angle_deg:.0f}° collection edge",
)
ax.axvline(
-collection_angle_deg,
linestyle="--",
linewidth=1.2,
label=f"-{collection_angle_deg:.0f}° collection edge",
)
ax.set_title(
f"2D far field at {lams_nm_2d[idx_c_2d]:.1f} nm — iteration {selected_iter_2d}"
)
ax.set_xlabel(r"$\theta$ (deg), signed")
ax.set_ylabel("2D projected power")
ax.grid(True, alpha=0.3)
ax.legend()
plt.tight_layout()
plt.show()
# Print selected-design summary
print("2D design selection:")
print(f" selected iter = {selected_iter_2d}")
print(f" selected objective = {values_2d[selected_iter_2d]:.6e}")
print()
print_2d_fom_summary(summary_selected_2d)
print()
print("Selected 2D geometry:")
print(f" number of trenches = {len(w_selected_2d)}")
print(f" min trench width = {1000 * np.min(w_selected_2d):.2f} nm")
print(f" min gap width = {1000 * np.min(g_selected_2d):.2f} nm")
print(
f" grating x range = [{xL_selected_2d[0]:.4f}, {xR_selected_2d[-1]:.4f}] um"
)
Loaded 2D history from: gc_2d_optimization_history.pkl saved iterations = 350
2D design selection: selected iter = 349 selected objective = 1.105830e+07 2D FOM summary at 798.0 nm: center coupling = 23.239% T-band mean coupling = 21.348% center reflection = 0.147% R-band mean reflection = 5.142% upward power = 49.055% collected cone power = 29.407% angular spill = 19.648% peak angle = -1.000 deg average angle = -3.978 deg angle stdev = 19.636 deg Selected 2D geometry: number of trenches = 25 min trench width = 77.74 nm min gap width = 79.70 nm grating x range = [2.0000, 9.0014] um
3D Model Construction and Validation¶
After selecting the 2D design, we use its trench and gap sequence to build a 3D suspended grating coupler. The 3D model includes effects that are not captured in the 2D approximation, such as the finite grating aperture, taper geometry, waveguide width, and transverse radiation pattern. For this reason, the first 3D validation is used to evaluate how much of the 2D performance carries over before doing any 3D placement sweep or adjoint optimization.
3D Wavelength Grid and Simulation Constants¶
We start by defining the wavelength grid and simulation settings used for the 3D validation. We also define the 3D far-field angular grid, boundary conditions, symmetry settings, and sizing parameters used by the 3D geometry and simulation builders.
# 3D wavelength grid
# For 3D, the target-band half-width h sets the wavelength spacing.
# The five wavelength points are:
# lambda0 + [-2h, -h, 0, +h, +2h]
# The target band includes the central three points:
# lambda0 + [-h, 0, +h]
# The two outer points are kept as diagnostic wavelengths.
DEFAULT_TARGET_HALF_WIDTH_3D_UM = 0.0125 # 12.5 nm
def set_active_wavelength_grid_3d(target_half_width_um, verbose=True):
"""
Set the active 3D wavelength grid and objective-band masks.
If target_half_width_um = h, the five wavelength points are:
lambda0 + [-2h, -h, 0, +h, +2h]
The objective target band includes:
lambda0 + [-h, 0, +h]
"""
global target_half_width_3d_um
global offset_indices_3d, wavelength_offsets_3d_um
global lams_um_3d, lams_nm_3d, freqs_3d, idx_c_3d
global target_band_mask_3d
global mask_T_band_3d, mask_R_band_3d
global mask_outside_T_band_3d
target_half_width_3d_um = float(target_half_width_um)
offset_indices_3d = np.array([-2, -1, 0, 1, 2], dtype=float)
wavelength_offsets_3d_um = target_half_width_3d_um * offset_indices_3d
lams_um_3d = lambda0_um + wavelength_offsets_3d_um
lams_nm_3d = lams_um_3d * 1000
freqs_3d = td.C_0 / lams_um_3d
idx_c_3d = int(np.argmin(np.abs(lams_um_3d - lambda0_um)))
# The central three wavelength points are used in the objective band.
target_band_mask_3d = np.abs(offset_indices_3d) <= 1
mask_T_band_3d = target_band_mask_3d.copy()
mask_R_band_3d = target_band_mask_3d.copy()
mask_outside_T_band_3d = ~mask_T_band_3d
if verbose:
print("3D wavelength grid:")
print(f" target half-width = {1000 * target_half_width_3d_um:.1f} nm")
print(
f" wavelength offsets = {np.round(wavelength_offsets_3d_um * 1000, 3)} nm"
)
print(f" all wavelengths = {np.round(lams_nm_3d, 3)} nm")
print(
f" T-band wavelengths = {np.round(lams_nm_3d[mask_T_band_3d], 3)} nm"
)
print(
f" R-band wavelengths = {np.round(lams_nm_3d[mask_R_band_3d], 3)} nm"
)
print(
f" diagnostic wavelengths = {np.round(lams_nm_3d[mask_outside_T_band_3d], 3)} nm"
)
print(f" center index = {idx_c_3d}")
print(f" center wavelength = {lams_nm_3d[idx_c_3d]:.3f} nm")
print()
# Initialize the default 3D grid used by validation and sweep.
set_active_wavelength_grid_3d(
DEFAULT_TARGET_HALF_WIDTH_3D_UM,
verbose=False,
)
# 3D far-field angular grid
max_theta_deg_3d = 89
num_theta_3d = 2 * 2 * max_theta_deg_3d + 1
theta_array_3d = (
np.pi
/ 180
* np.linspace(
0,
max_theta_deg_3d,
num_theta_3d,
)
)
num_phi_3d = 181
phi_array_3d = np.linspace(0, 2 * np.pi, num_phi_3d)
# 3D grid, boundaries, symmetry, and run time
min_steps_per_wvl_3d = 10
grid_spec_3d = td.GridSpec.auto(
wavelength=lambda0_um,
min_steps_per_wvl=min_steps_per_wvl_3d,
)
boundary_spec_3d = td.BoundarySpec.all_sides(
boundary=td.PML(),
)
symmetry_3d = (0, -1, 0) # mirror symmetry across y = 0
run_time_3d = run_time_2d
# 3D geometry sizing
pml_spacing_3d = 0.5
taper_margin_angle_3d = np.deg2rad(2.0)
taper_half_angle_3d = slot_half_angle + taper_margin_angle_3d
max_dist_shift_3d = 12.0
taper_tail_clearance_3d = pad_right
max_taper_end_x_3d = float(
slot_radius_min + max_dist_shift_3d + L_grating_est + taper_tail_clearance_3d
)
top_monitor_x_margin_3d = 2.0
top_monitor_y_margin_3d = 0.5
sim_x_min_3d = -3.0
def get_taper_half_width_3d(taper_end_x):
"""Return the taper half-width at the taper end."""
return float(
0.5 * w_wg
+ max(float(taper_end_x) - float(x_apex), 0.0) * np.tan(taper_half_angle_3d)
)
y_margin_3d = 1.0
beam_half_size_3d = 0.5 * 3.0 * beam_waist
def get_device_y_span_3d(taper_end_x):
"""
Return the needed 3D device y-span.
It covers both the taper width and the Gaussian beam source width.
"""
taper_half_width = get_taper_half_width_3d(taper_end_x)
y_half_needed = (
max(
taper_half_width,
beam_half_size_3d,
)
+ y_margin_3d
)
return float(2.0 * y_half_needed)
device_y_span_3d = get_device_y_span_3d(max_taper_end_x_3d)
print("3D wavelength grid:")
print(f" wavelength offsets = {np.round(wavelength_offsets_3d_um * 1000, 3)} nm")
print(f" all wavelengths = {np.round(lams_um_3d * 1000, 3)} nm")
print(
f" T-band wavelengths = {np.round(lams_um_3d[mask_T_band_3d] * 1000, 3)} nm"
)
print(
f" R-band wavelengths = {np.round(lams_um_3d[mask_R_band_3d] * 1000, 3)} nm"
)
print(
f" diagnostic wavelengths = {np.round(lams_um_3d[mask_outside_T_band_3d] * 1000, 3)} nm"
)
print(f" center wavelength = {lams_um_3d[idx_c_3d] * 1000:.3f} nm")
print()
print("3D angular grid:")
print(
f" theta range = {theta_array_3d[0] * 180 / np.pi:.1f} to {theta_array_3d[-1] * 180 / np.pi:.1f} deg"
)
print(f" num theta = {len(theta_array_3d)}")
print(f" num phi = {len(phi_array_3d)}")
print()
print("3D simulation settings:")
print(f" min_steps_per_wvl = {min_steps_per_wvl_3d}")
print(f" symmetry = {symmetry_3d}")
print(f" run time = {run_time_3d:.2e} s")
print()
print("3D geometry sizing:")
print(f" taper half-angle = {taper_half_angle_3d * 180 / np.pi:.3f} deg")
print(f" max dist shift = {max_dist_shift_3d:.3f} um")
print(f" device y-span = {device_y_span_3d:.3f} um")
print(f" sim x-min = {sim_x_min_3d:.3f} um")
3D wavelength grid: wavelength offsets = [-25. -12.5 0. 12.5 25. ] nm all wavelengths = [773. 785.5 798. 810.5 823. ] nm T-band wavelengths = [785.5 798. 810.5] nm R-band wavelengths = [785.5 798. 810.5] nm diagnostic wavelengths = [773. 823.] nm center wavelength = 798.000 nm 3D angular grid: theta range = 0.0 to 89.0 deg num theta = 357 num phi = 181 3D simulation settings: min_steps_per_wvl = 10 symmetry = (0, -1, 0) run time = 5.00e-12 s 3D geometry sizing: taper half-angle = 22.000 deg max dist shift = 12.000 um device y-span = 22.081 um sim x-min = -3.000 um
Build the 3D Grating from the Selected 2D Design¶
Here, we convert the selected 2D trench and gap sequence into a 3D suspended grating. The trench and gap widths define the radial slot edges. The parameter dist_shift controls the grating position along the waveguide axis, while apex_x controls the curvature of the grating arcs.
The function make_two_sims_3d() builds the two 3D simulations used later in the workflow.
For the first 3D validation, we keep apex_x and dist_shift equal to zero. At this stage, the goal is only to construct the 3D version of the selected 2D design and check its initial 3D performance. The grating placement is adjusted later in the 3D placement sweep.
# 3D geometry builders and simulation builder
# 3D placement controls
# The first trench physical position is controlled by dist_shift.
# dist_shift moves the physical grating and the beam center along x.
# apex_x moves the curvature center of the grating arcs.
DEFAULT_DIST_SHIFT_3D = 0.0
DEFAULT_APEX_X_3D = 0.0
# Clearance between the curved trench ends and taper sidewalls.
TRENCH_TAPER_CLEARANCE_3D = 0.30
def _current_params_for_3d(params_u=None):
"""Return selected 2D parameters unless a parameter vector is provided."""
if params_u is not None:
return params_u
if "params_selected_2d" not in globals():
raise ValueError(
"params_selected_2d is not defined. Run the 2D design-selection cell first."
)
return params_selected_2d
def get_slot_rmin_3d(apex_x=DEFAULT_APEX_X_3D, dist_shift=DEFAULT_DIST_SHIFT_3D):
"""
Return the first trench radius relative to the grating curvature apex.
The physical first-trench position is:
x_first = apex_x + slot_rmin
= slot_radius_min + dist_shift
"""
return slot_radius_min + dist_shift - apex_x
def get_last_trench_x_3d(
apex_x=DEFAULT_APEX_X_3D,
dist_shift=DEFAULT_DIST_SHIFT_3D,
params_u=None,
):
"""Return the physical x-position of the last trench outer edge."""
params_local = _current_params_for_3d(params_u)
w_local, g_local = params_to_wgaps(anp.array(params_local))
slot_rmin_local = get_slot_rmin_3d(
apex_x=apex_x,
dist_shift=dist_shift,
)
_, xR_local = edges_from_wgaps(
w_local,
g_local,
slot_rmin=slot_rmin_local,
)
return float(apex_x + xR_local[-1])
def get_taper_end_x_3d(
apex_x=DEFAULT_APEX_X_3D,
dist_shift=DEFAULT_DIST_SHIFT_3D,
params_u=None,
):
"""Return the physical x-position where the taper ends."""
return float(
get_last_trench_x_3d(
apex_x=apex_x,
dist_shift=dist_shift,
params_u=params_u,
)
+ taper_tail_clearance_3d
)
def make_sim_box_3d(
apex_x=DEFAULT_APEX_X_3D,
dist_shift=DEFAULT_DIST_SHIFT_3D,
params_u=None,
):
"""Build a 3D simulation box sized to the selected grating."""
taper_end_x_local = get_taper_end_x_3d(
apex_x=apex_x,
dist_shift=dist_shift,
params_u=params_u,
)
device_y_span_local = get_device_y_span_3d(taper_end_x_local)
return td.Box.from_bounds(
rmin=(
sim_x_min_3d,
-0.5 * device_y_span_local - pml_spacing_3d,
z_mem_bot - z_bot / 2 - pml_spacing_3d,
),
rmax=(
taper_end_x_local,
0.5 * device_y_span_local + pml_spacing_3d,
z_mem_top + z_top / 2 + pml_spacing_3d,
),
)
def make_top_monitor_geometry_3d(
sim_box_local,
apex_x=DEFAULT_APEX_X_3D,
dist_shift=DEFAULT_DIST_SHIFT_3D,
params_u=None,
):
"""Return the top monitor center and size for 3D upward radiation."""
params_local = _current_params_for_3d(params_u)
w_local, g_local = params_to_wgaps(anp.array(params_local))
slot_rmin_local = get_slot_rmin_3d(
apex_x=apex_x,
dist_shift=dist_shift,
)
xL_local, xR_local = edges_from_wgaps(
w_local,
g_local,
slot_rmin=slot_rmin_local,
)
# xL and xR are radii relative to apex_x.
xL0_phys = float(apex_x + xL_local[0])
xR_last_phys = float(apex_x + xR_local[-1])
grating_center_x = 0.5 * (xL0_phys + xR_last_phys)
grating_span_x = xR_last_phys - xL0_phys
monitor_x_size = grating_span_x + 2.0 * top_monitor_x_margin_3d
x_min_allowed = sim_box_local.bounds[0][0] + pml_spacing_3d
x_max_allowed = sim_box_local.bounds[1][0] - pml_spacing_3d
monitor_x_min = max(grating_center_x - 0.5 * monitor_x_size, x_min_allowed)
monitor_x_max = min(grating_center_x + 0.5 * monitor_x_size, x_max_allowed)
monitor_x_center = 0.5 * (monitor_x_min + monitor_x_max)
monitor_x_size = monitor_x_max - monitor_x_min
taper_end_x_local = get_taper_end_x_3d(
apex_x=apex_x,
dist_shift=dist_shift,
params_u=params_local,
)
taper_half_width_local = get_taper_half_width_3d(taper_end_x_local)
monitor_y_size = 2.0 * (taper_half_width_local + top_monitor_y_margin_3d)
y_min_allowed = sim_box_local.bounds[0][1] + pml_spacing_3d
y_max_allowed = sim_box_local.bounds[1][1] - pml_spacing_3d
monitor_y_min = max(-0.5 * monitor_y_size, y_min_allowed)
monitor_y_max = min(0.5 * monitor_y_size, y_max_allowed)
monitor_y_center = 0.5 * (monitor_y_min + monitor_y_max)
monitor_y_size = monitor_y_max - monitor_y_min
top_monitor_center_local = (
monitor_x_center,
monitor_y_center,
beam_center_z,
)
top_monitor_size_local = (
monitor_x_size,
monitor_y_size,
0.0,
)
return top_monitor_center_local, top_monitor_size_local
def make_waveguide_struct_3d():
"""Build the straight input waveguide."""
return td.Structure(
geometry=td.Box(
center=(wg_center_x, 0.0, z_mem_center),
size=(wg_L, w_wg, t_mem),
),
medium=device_medium,
background_medium=air,
name="waveguide",
)
def make_taper_struct_3d(
apex_x=DEFAULT_APEX_X_3D,
dist_shift=DEFAULT_DIST_SHIFT_3D,
params_u=None,
):
"""Build the flared taper connecting the waveguide to the grating."""
taper_end_x_local = get_taper_end_x_3d(
apex_x=apex_x,
dist_shift=dist_shift,
params_u=params_u,
)
taper_half_width_local = get_taper_half_width_3d(taper_end_x_local)
taper_vertices = np.array(
[
[x_apex, -0.5 * w_wg],
[taper_end_x_local, -taper_half_width_local],
[taper_end_x_local, taper_half_width_local],
[x_apex, 0.5 * w_wg],
],
dtype=float,
)
return td.Structure(
geometry=td.PolySlab(
vertices=taper_vertices,
slab_bounds=(-t_mem / 2, t_mem / 2),
axis=2,
),
medium=device_medium,
background_medium=air,
name="taper",
)
def get_clearance_slot_unit_verts_3d(
apex_x,
radius,
taper_end_x_local,
clearance_um=TRENCH_TAPER_CLEARANCE_3D,
):
"""
Return radius-dependent unit vertices for one trench edge.
The trench is clipped inside the taper sidewall so a clearance remains.
"""
radius = float(radius)
clearance_um = float(clearance_um)
if radius <= 0:
raise ValueError(f"Invalid trench radius: {radius}")
a = 0.5 * w_wg
taper_half_width_end = get_taper_half_width_3d(taper_end_x_local)
m = (taper_half_width_end - a) / (taper_end_x_local - x_apex)
b = a - m * x_apex
b_clear = b - clearance_um * np.sqrt(1.0 + m**2)
A = 1.0 + m**2
B = -2.0 * apex_x + 2.0 * m * b_clear
C = apex_x**2 + b_clear**2 - radius**2
disc = B**2 - 4.0 * A * C
if disc < 0:
raise ValueError(
"No circle/cleared-taper intersection found. "
f"radius={radius:.4f}, clearance={clearance_um:.4f}, "
f"disc={disc:.4e}. Try reducing TRENCH_TAPER_CLEARANCE_3D."
)
sqrt_disc = np.sqrt(disc)
roots = np.array(
[
(-B + sqrt_disc) / (2.0 * A),
(-B - sqrt_disc) / (2.0 * A),
],
dtype=float,
)
valid_roots = roots[(roots >= x_apex - 1e-9) & (roots <= taper_end_x_local + 1e-9)]
if len(valid_roots) == 0:
x_int = float(np.max(roots))
else:
x_int = float(np.max(valid_roots))
y_int = float(m * x_int + b_clear)
theta_max = np.arctan2(y_int, x_int - apex_x)
if theta_max <= 0:
raise ValueError(
f"Computed theta_max <= 0: theta_max={theta_max:.6f} rad, "
f"radius={radius:.4f}, x_int={x_int:.4f}, y_int={y_int:.4f}. "
"Try reducing TRENCH_TAPER_CLEARANCE_3D or checking apex/dist shift."
)
theta_local = np.linspace(-theta_max, theta_max, len(unit_verts))
return np.column_stack(
[
np.cos(theta_local),
np.sin(theta_local),
]
)
def build_slot_group_3d(
w,
g,
apex_x=DEFAULT_APEX_X_3D,
dist_shift=DEFAULT_DIST_SHIFT_3D,
params_u=None,
clearance_um=TRENCH_TAPER_CLEARANCE_3D,
):
"""Build the 3D fully etched grating trench group."""
slot_rmin_local = get_slot_rmin_3d(
apex_x=apex_x,
dist_shift=dist_shift,
)
xL, xR = edges_from_wgaps(
w,
g,
slot_rmin=slot_rmin_local,
)
taper_end_x_local = get_taper_end_x_3d(
apex_x=apex_x,
dist_shift=dist_shift,
params_u=params_u,
)
slot_geometries = []
for inner_radius, outer_radius in zip(xL, xR):
inner_radius = float(inner_radius)
outer_radius = float(outer_radius)
inner_unit = get_clearance_slot_unit_verts_3d(
apex_x=apex_x,
radius=inner_radius,
taper_end_x_local=taper_end_x_local,
clearance_um=clearance_um,
)
outer_unit = get_clearance_slot_unit_verts_3d(
apex_x=apex_x,
radius=outer_radius,
taper_end_x_local=taper_end_x_local,
clearance_um=clearance_um,
)
inner_verts = np.column_stack(
[
apex_x + inner_radius * inner_unit[:, 0],
inner_radius * inner_unit[:, 1],
]
)
outer_verts = np.column_stack(
[
apex_x + outer_radius * outer_unit[::-1, 0],
outer_radius * outer_unit[::-1, 1],
]
)
slot_vertices = np.concatenate((inner_verts, outer_verts), axis=0)
slot_geometries.append(
td.PolySlab(
vertices=slot_vertices,
slab_bounds=(-t_mem / 2, t_mem / 2),
axis=2,
)
)
slot_group = td.GeometryGroup(geometries=slot_geometries)
slot_struct = td.Structure(
geometry=slot_group,
medium=air,
background_medium=device_medium,
name="grating_etch",
priority=4,
)
return slot_struct, xL, xR
def make_two_sims_3d(
params_u=None,
use_field_monitors=False,
dist_shift=DEFAULT_DIST_SHIFT_3D,
apex_x=DEFAULT_APEX_X_3D,
clearance_um=TRENCH_TAPER_CLEARANCE_3D,
):
"""Build the 3D mode-source and beam-source simulations."""
params_local = _current_params_for_3d(params_u)
# dist_shift moves the physical grating and the beam together.
shifted_beam_center_x = beam_center_x + dist_shift
w, g = params_to_wgaps(anp.array(params_local))
slot_struct_3d, _xL, _xR = build_slot_group_3d(
w,
g,
apex_x=apex_x,
dist_shift=dist_shift,
params_u=params_local,
clearance_um=clearance_um,
)
sim_box_local = make_sim_box_3d(
apex_x=apex_x,
dist_shift=dist_shift,
params_u=params_local,
)
top_monitor_center_local, top_monitor_size_local = make_top_monitor_geometry_3d(
sim_box_local,
apex_x=apex_x,
dist_shift=dist_shift,
params_u=params_local,
)
structures_3d = [
make_taper_struct_3d(
apex_x=apex_x,
dist_shift=dist_shift,
params_u=params_local,
),
make_waveguide_struct_3d(),
slot_struct_3d,
]
beam_src_3d = td.GaussianBeam(
size=(3.0 * beam_waist, 3.0 * beam_waist, 0.0),
center=(float(shifted_beam_center_x), 0.0, beam_center_z),
source_time=beam_time,
angle_theta=0.0,
direction="-",
waist_radius=beam_waist,
waist_distance=-beam_center_z,
pol_angle=np.pi / 2,
)
mode_mon_3d = td.ModeMonitor(
center=(mode_x, 0.0, z_mem_center),
size=(0.0, 3.0 * w_wg, 5.0 * t_mem),
freqs=freqs_3d,
mode_spec=td.ModeSpec(num_modes=1),
name="wg_mode",
)
top_field_monitor_3d = td.FieldMonitor(
center=top_monitor_center_local,
size=top_monitor_size_local,
freqs=freqs_3d,
name="top_field",
colocate=False,
)
proj_monitor_3d = td.FieldProjectionAngleMonitor(
center=top_monitor_center_local,
size=top_monitor_size_local,
name="projection",
freqs=freqs_3d,
normal_dir="+",
proj_distance=10e3,
theta=theta_array_3d,
phi=phi_array_3d,
)
flux_monitor_3d = td.FluxMonitor(
center=top_monitor_center_local,
size=top_monitor_size_local,
name="flux",
freqs=freqs_3d,
normal_dir="+",
)
flux_box_3d = td.FluxMonitor(
center=(top_monitor_center_local[0], 0.0, 0.0),
size=(top_monitor_size_local[0], top_monitor_size_local[1], 4.0 * t_mem),
name="flux_box",
freqs=freqs_3d,
exclude_surfaces=["x-"],
)
device_y_span_local = sim_box_local.size[1] - 2.0 * pml_spacing_3d
field_monitor_xy_3d = td.FieldMonitor(
center=(sim_box_local.center[0], 0.0, z_mem_center),
size=(sim_box_local.size[0], device_y_span_local, 0.0),
freqs=[freqs_3d[idx_c_3d]],
name="field_xy",
)
field_monitor_xz_3d = td.FieldMonitor(
center=sim_box_local.center,
size=(sim_box_local.size[0], 0.0, sim_box_local.size[2]),
freqs=[freqs_3d[idx_c_3d]],
name="field_xz",
)
monitors_mode_3d = [
mode_mon_3d,
top_field_monitor_3d,
proj_monitor_3d,
flux_monitor_3d,
flux_box_3d,
]
monitors_beam_3d = [
mode_mon_3d,
]
if use_field_monitors:
monitors_mode_3d += [field_monitor_xy_3d, field_monitor_xz_3d]
monitors_beam_3d += [field_monitor_xy_3d, field_monitor_xz_3d]
sim_mode_3d = td.Simulation(
center=sim_box_local.center,
size=sim_box_local.size,
grid_spec=grid_spec_3d,
boundary_spec=boundary_spec_3d,
structures=structures_3d,
medium=background,
sources=[mode_src],
monitors=monitors_mode_3d,
run_time=run_time_3d,
symmetry=symmetry_3d,
)
sim_beam_3d = td.Simulation(
center=sim_box_local.center,
size=sim_box_local.size,
grid_spec=grid_spec_3d,
boundary_spec=boundary_spec_3d,
structures=structures_3d,
medium=background,
sources=[beam_src_3d],
monitors=monitors_beam_3d,
run_time=run_time_3d,
symmetry=symmetry_3d,
)
return sim_mode_3d, sim_beam_3d
# Dry-run build check
sim_mode_3d_check, sim_beam_3d_check = make_two_sims_3d(
params_u=params_selected_2d,
use_field_monitors=True,
dist_shift=DEFAULT_DIST_SHIFT_3D,
apex_x=DEFAULT_APEX_X_3D,
clearance_um=TRENCH_TAPER_CLEARANCE_3D,
)
print("3D geometry builders are ready.")
print()
print("Default 3D build:")
print(f" apex_x = {DEFAULT_APEX_X_3D:.4f} um")
print(f" dist_shift = {DEFAULT_DIST_SHIFT_3D:.4f} um")
print(f" trench/taper clearance = {TRENCH_TAPER_CLEARANCE_3D:.4f} um")
print(
f" slot_rmin = {get_slot_rmin_3d(DEFAULT_APEX_X_3D, DEFAULT_DIST_SHIFT_3D):.4f} um"
)
print(
f" last trench x = {get_last_trench_x_3d(DEFAULT_APEX_X_3D, DEFAULT_DIST_SHIFT_3D, params_selected_2d):.4f} um"
)
print(
f" taper end x = {get_taper_end_x_3d(DEFAULT_APEX_X_3D, DEFAULT_DIST_SHIFT_3D, params_selected_2d):.4f} um"
)
print(f" mode sim size = {sim_mode_3d_check.size}")
print(f" beam sim size = {sim_beam_3d_check.size}")
print(f" number of structures = {len(sim_mode_3d_check.structures)}")
print()
print("3D mode-source simulation:")
print(f" source = {sim_mode_3d_check.sources[0].__class__.__name__}")
print(f" monitors = {[m.name for m in sim_mode_3d_check.monitors]}")
print()
print("3D beam-source simulation:")
print(f" source = {sim_beam_3d_check.sources[0].__class__.__name__}")
print(f" monitors = {[m.name for m in sim_beam_3d_check.monitors]}")
3D geometry builders are ready. Default 3D build: apex_x = 0.0000 um dist_shift = 0.0000 um trench/taper clearance = 0.3000 um slot_rmin = 2.0000 um last trench x = 9.0014 um taper end x = 12.0014 um mode sim size = (15.001370751796882, 12.997737059393867, 2.15) beam sim size = (15.001370751796882, 12.997737059393867, 2.15) number of structures = 3 3D mode-source simulation: source = ModeSource monitors = ['wg_mode', 'top_field', 'projection', 'flux', 'flux_box', 'field_xy', 'field_xz'] 3D beam-source simulation: source = GaussianBeam monitors = ['wg_mode', 'field_xy', 'field_xz']
Plot the 3D Build¶
Before running the 3D validation, we first plot the generated 3D simulations. This checks that the selected 2D grating was converted correctly, that the taper and trenches are in the expected positions, and that the sources and monitors are placed correctly.
# This cell only visualizes the 3D simulation layout.
# It does not run the simulation.
fig, axes = plt.subplots(1, 2, figsize=(14, 5), constrained_layout=True)
# Top view through the membrane plane.
sim_mode_3d_check.plot(z=z_mem_center, ax=axes[0])
axes[0].set_title("3D mode-source simulation: top view")
axes[0].set_xlabel("x (um)")
axes[0].set_ylabel("y (um)")
# Side view through the center of the device.
sim_mode_3d_check.plot(y=0.0, ax=axes[1])
axes[1].set_title("3D mode-source simulation: side view")
axes[1].set_xlabel("x (um)")
axes[1].set_ylabel("z (um)")
plt.show()
fig, axes = plt.subplots(1, 2, figsize=(14, 5), constrained_layout=True)
# Top view for the beam-source simulation.
sim_beam_3d_check.plot(z=z_mem_center, ax=axes[0])
axes[0].set_title("3D beam-source simulation: top view")
axes[0].set_xlabel("x (um)")
axes[0].set_ylabel("y (um)")
# Side view for the beam-source simulation.
sim_beam_3d_check.plot(y=0.0, ax=axes[1])
axes[1].set_title("3D beam-source simulation: side view")
axes[1].set_xlabel("x (um)")
axes[1].set_ylabel("z (um)")
plt.show()
print("3D layout check:")
print(f" mode-source sim size = {sim_mode_3d_check.size}")
print(f" beam-source sim size = {sim_beam_3d_check.size}")
3D layout check: mode-source sim size = (15.001370751796882, 12.997737059393867, 2.15) beam-source sim size = (15.001370751796882, 12.997737059393867, 2.15)
3D Figures of Merit¶
We use the same main figures of merit as in the 2D workflow so that the 2D and 3D results can be compared directly: coupling into the waveguide, back-reflection, upward-radiated power, collected power, angular spill, and the main radiation direction.
The difference is that these quantities are now extracted from the full 3D simulations. In particular, the far-field projection gives the full angular radiation pattern above the grating, including transverse spreading that is not captured in the 2D model.
# 3D FOM extraction
def _get_monitor_by_name_3d(sim, name):
"""Return monitor object from a 3D simulation by name."""
for mon in sim.monitors:
if mon.name == name:
return mon
raise KeyError(
f"Monitor {name!r} not found. Available monitors: {[m.name for m in sim.monitors]}"
)
def figures_of_merit_3d(sim_mode_3d_data=None, sim_beam_3d_data=None, sim_mode_3d=None):
"""
Extract the 3D figures of merit.
Mode-source simulation:
wg_mode backward amplitude -> reflection
projection monitor power -> upward radiation and collected power
Beam-source simulation:
wg_mode backward amplitude -> beam-to-waveguide coupling
"""
reflectivity = None
coupling = None
power = None
peak_angle = None
collected_power = None
upwards_power = None
if sim_mode_3d_data is not None:
# Mode-source reflection.
reflectivity = (
anp.abs(
sim_mode_3d_data["wg_mode"]
.amps.sel(
direction="-",
mode_index=0,
)
.values
)
** 2
)
# Use the projection monitor result saved by the server-side simulation.
proj_power = sim_mode_3d_data["projection"].power.squeeze()
if sim_mode_3d is not None:
proj_monitor = _get_monitor_by_name_3d(sim_mode_3d, "projection")
proj_distance = proj_monitor.proj_distance
else:
proj_distance = 10e3
power = proj_power * proj_distance**2
# Peak theta for each wavelength.
peak_angle = power.theta[power.argmax(dim=["theta", "phi"])["theta"]]
# Collected upward power inside the collection cone.
theta_max_deg = collection_angle_deg
theta_mask = power.theta <= theta_max_deg * np.pi / 180
collected_power = power.isel(theta=theta_mask) * np.sin(
power.isel(theta=theta_mask).theta
)
collected_power = collected_power.integrate(coord=("theta", "phi")).values
# Total upward projected power.
upwards_power = (
(power * np.sin(power.theta)).integrate(coord=("theta", "phi")).values
)
if sim_beam_3d_data is not None:
# Beam-source coupling into the waveguide mode.
coupling = (
anp.abs(
sim_beam_3d_data["wg_mode"]
.amps.sel(
direction="-",
mode_index=0,
)
.values
)
** 2
)
return (
reflectivity,
coupling,
power,
peak_angle,
collected_power,
upwards_power,
)
def summarize_3d_foms(foms_3d):
"""Convert raw 3D FOM arrays into a compact scalar summary."""
(
reflectivity,
coupling,
_power,
peak_angle,
collected_power,
upwards_power,
) = foms_3d
peak_angle_arr = np.asarray(peak_angle)
if peak_angle_arr.ndim == 0:
peak_angle_center_rad = float(peak_angle_arr)
else:
peak_angle_center_rad = float(peak_angle_arr.reshape(-1)[idx_c_3d])
return {
"center_wavelength_nm": float(lams_um_3d[idx_c_3d] * 1000),
"center_coupling": float(coupling[idx_c_3d]),
"band_mean_coupling": float(np.mean(coupling[mask_T_band_3d])),
"center_reflectivity": float(reflectivity[idx_c_3d]),
"band_mean_reflectivity": float(np.mean(reflectivity[mask_R_band_3d])),
"center_upwards_power": float(upwards_power[idx_c_3d]),
"center_collected_power": float(collected_power[idx_c_3d]),
"center_angular_spill": float(
upwards_power[idx_c_3d] - collected_power[idx_c_3d]
),
"peak_angle_deg": float(peak_angle_center_rad * 180 / np.pi),
}
def print_3d_fom_summary(summary):
"""Print the main 3D figures of merit."""
print(f"3D FOM summary at {summary['center_wavelength_nm']:.0f} nm:")
print(f" center coupling = {100 * summary['center_coupling']:.3f}%")
print(f" T-band mean coupling = {100 * summary['band_mean_coupling']:.3f}%")
print(f" center reflection = {100 * summary['center_reflectivity']:.3f}%")
print(f" R-band mean reflection = {100 * summary['band_mean_reflectivity']:.3f}%")
print(f" upward power = {100 * summary['center_upwards_power']:.3f}%")
print(
f" collected power (15° cone) = {100 * summary['center_collected_power']:.3f}%"
)
print(f" angular spill = {100 * summary['center_angular_spill']:.3f}%")
print(f" peak angle = {summary['peak_angle_deg']:.3f} deg")
print("3D FOM extraction is ready.")
3D FOM extraction is ready.
Validate the Selected 2D Design in 3D¶
Now we run the first 3D validation of the selected 2D design and extract the baseline 3D performance.
# Use the default 3D wavelength grid for validation.
set_active_wavelength_grid_3d(
DEFAULT_TARGET_HALF_WIDTH_3D_UM,
verbose=False,
)
VALIDATION_APEX_X_3D = DEFAULT_APEX_X_3D
VALIDATION_DIST_SHIFT_3D = DEFAULT_DIST_SHIFT_3D
TASK_NAME_3D_VALIDATION = (
(
f"3d_validation_iter_{selected_iter_2d:04d}"
f"_apex_{VALIDATION_APEX_X_3D:+.3f}"
f"_shift_{VALIDATION_DIST_SHIFT_3D:+.3f}"
)
.replace("+", "p")
.replace("-", "m")
.replace(".", "p")
)
# Build the two 3D validation simulations
sim_mode_3d_validation, sim_beam_3d_validation = make_two_sims_3d(
params_u=params_selected_2d,
use_field_monitors=True,
dist_shift=VALIDATION_DIST_SHIFT_3D,
apex_x=VALIDATION_APEX_X_3D,
clearance_um=TRENCH_TAPER_CLEARANCE_3D,
)
print("3D validation setup:")
print(f" selected 2D iteration = {selected_iter_2d}")
print(f" apex_x = {VALIDATION_APEX_X_3D:+.4f} um")
print(f" dist_shift = {VALIDATION_DIST_SHIFT_3D:+.4f} um")
print(f" task name = {TASK_NAME_3D_VALIDATION}")
print(f" wavelengths = {np.round(lams_um_3d * 1000, 3)} nm")
print(f" T-band wavelengths = {np.round(lams_um_3d[mask_T_band_3d] * 1000, 3)} nm")
print(f" R-band wavelengths = {np.round(lams_um_3d[mask_R_band_3d] * 1000, 3)} nm")
print()
# Run the 3D mode-source simulation
print("Running 3D mode-source simulation...")
sim_mode_3d_validation_data = web.run(
sim_mode_3d_validation,
task_name=f"{TASK_NAME_3D_VALIDATION}_mode",
verbose=False,
)
# Run the 3D beam-source simulation
print()
print("Running 3D beam-source simulation...")
sim_beam_3d_validation_data = web.run(
sim_beam_3d_validation,
task_name=f"{TASK_NAME_3D_VALIDATION}_beam",
verbose=False,
)
# Compute 3D figures of merit
foms_3d_validation = figures_of_merit_3d(
sim_mode_3d_validation_data,
sim_beam_3d_validation_data,
sim_mode_3d_validation,
)
summary_3d_validation = summarize_3d_foms(foms_3d_validation)
print()
print_3d_fom_summary(summary_3d_validation)
3D validation setup: selected 2D iteration = 349 apex_x = +0.0000 um dist_shift = +0.0000 um task name = 3d_validation_iter_0349_apex_p0p000_shift_p0p000 wavelengths = [773. 785.5 798. 810.5 823. ] nm T-band wavelengths = [785.5 798. 810.5] nm R-band wavelengths = [785.5 798. 810.5] nm Running 3D mode-source simulation... Running 3D beam-source simulation... 3D FOM summary at 798 nm: center coupling = 9.923% T-band mean coupling = 7.914% center reflection = 12.200% R-band mean reflection = 17.418% upward power = 40.662% collected power (15° cone) = 13.568% angular spill = 27.093% peak angle = 6.500 deg
Plot the 3D Validation Results¶
Here we plot the results from the initial 3D validation. As we can see, there is a clear drop in performance compared with the 2D result, with lower coupling and higher reflection. This is expected when moving from the simplified 2D model to the full 3D structure.
However, the design still keeps enough useful coupling to start from. The following 3D optimization steps therefore aim to recover the lost performance while optimizing the actual 3D structure.
# Plot 3D validation results
if "foms_3d_validation" not in globals():
raise ValueError("foms_3d_validation not found. Run the 3D validation cell first.")
(
reflectivity_3d_validation,
coupling_3d_validation,
power_3d_validation,
_,
collected_power_3d_validation,
upwards_power_3d_validation,
) = foms_3d_validation
reflectivity_3d_validation_np = np.array(reflectivity_3d_validation, dtype=float)
coupling_3d_validation_np = np.array(coupling_3d_validation, dtype=float)
collected_power_3d_validation_np = np.array(collected_power_3d_validation, dtype=float)
upwards_power_3d_validation_np = np.array(upwards_power_3d_validation, dtype=float)
lams_nm_3d = lams_um_3d * 1000
# Coupling and reflection spectra
fig, axes = plt.subplots(1, 2, figsize=(12, 4), constrained_layout=True)
axes[0].plot(
lams_nm_3d,
100 * coupling_3d_validation_np,
"o-",
label="3D coupling",
)
axes[0].axvline(
lambda0_um * 1000,
linestyle="--",
label="center wavelength",
)
axes[0].axvspan(
lams_nm_3d[mask_T_band_3d][0],
lams_nm_3d[mask_T_band_3d][-1],
alpha=0.15,
label="T-band",
)
axes[0].set_xlabel("Wavelength (nm)")
axes[0].set_ylabel("Coupling (%)")
axes[0].set_title("3D beam-source coupling")
axes[0].grid(True, alpha=0.3)
axes[0].legend()
axes[1].plot(
lams_nm_3d,
100 * reflectivity_3d_validation_np,
"o-",
label="3D reflection",
)
axes[1].axvline(
lambda0_um * 1000,
linestyle="--",
label="center wavelength",
)
axes[1].axvspan(
lams_nm_3d[mask_R_band_3d][0],
lams_nm_3d[mask_R_band_3d][-1],
alpha=0.15,
label="R-band",
)
axes[1].set_xlabel("Wavelength (nm)")
axes[1].set_ylabel("Reflection (%)")
axes[1].set_title("3D mode-source reflection")
axes[1].grid(True, alpha=0.3)
axes[1].legend()
fig.suptitle(
f"3D validation spectra from selected 2D iteration {selected_iter_2d}",
fontsize=14,
)
plt.show()
# Upward and collected power spectra
plt.figure(figsize=(7, 4))
plt.plot(
lams_nm_3d,
100 * upwards_power_3d_validation_np,
"o-",
label="Upward power",
)
plt.plot(
lams_nm_3d,
100 * collected_power_3d_validation_np,
"o-",
label=f"Collected power within {collection_angle_deg:.0f}°",
)
plt.axvline(
lambda0_um * 1000,
linestyle="--",
label="center wavelength",
)
plt.xlabel("Wavelength (nm)")
plt.ylabel("Power (%)")
plt.title("3D upward and collected radiation")
plt.grid(True, alpha=0.3)
plt.legend()
plt.tight_layout()
plt.show()
# 3D far-field polar power distribution
# The projection monitor returns power(theta, phi, wavelength).
# Here we plot the center-wavelength angular power distribution as a
# normalized polar heat map.
if hasattr(power_3d_validation, "dims"):
power_da_3d = power_3d_validation
# Select the center wavelength.
power_center_3d = power_da_3d.sel(
f=freqs_3d[idx_c_3d],
method="nearest",
)
theta_vals_rad_3d = np.array(power_center_3d.theta.values, dtype=float)
phi_vals_rad_3d = np.array(power_center_3d.phi.values, dtype=float)
power_center_3d_np = np.array(
power_center_3d.transpose("theta", "phi").values,
dtype=float,
)
# Normalize the far-field map to its peak value.
max_power_3d = np.nanmax(power_center_3d_np)
if max_power_3d <= 0:
raise ValueError(
"Cannot normalize 3D far field because the maximum power is zero."
)
power_center_3d_norm = power_center_3d_np / max_power_3d
# We plot phi as the angular coordinate and theta as the radial coordinate.
phi_grid_3d, theta_grid_3d = np.meshgrid(
phi_vals_rad_3d,
theta_vals_rad_3d,
)
fig = plt.figure(figsize=(7, 6))
ax = fig.add_subplot(111, projection="polar")
pcm = ax.pcolormesh(
phi_grid_3d,
theta_grid_3d * 180 / np.pi,
100 * power_center_3d_norm,
shading="auto",
vmin=0,
vmax=100,
)
cbar = fig.colorbar(
pcm,
ax=ax,
pad=0.10,
shrink=0.65,
)
cbar.set_label("Normalized power (%)")
# Draw the collection cone as a circle at theta = collection_angle_deg.
phi_ring_3d = np.linspace(0, 2 * np.pi, 361)
ax.plot(
phi_ring_3d,
collection_angle_deg * np.ones_like(phi_ring_3d),
linestyle="--",
linewidth=1.2,
label=f"{collection_angle_deg:.0f}° collection cone",
)
ax.set_theta_zero_location("E")
ax.set_theta_direction(1)
ax.set_rlim(0, theta_vals_rad_3d[-1] * 180 / np.pi)
ax.set_rlabel_position(135)
ax.set_title(f"3D normalized far-field power at {lams_nm_3d[idx_c_3d]:.1f} nm")
ax.legend(loc="upper right", bbox_to_anchor=(1.30, 1.08))
plt.tight_layout()
plt.show()
# Peak direction in theta/phi.
peak_index_3d = np.unravel_index(
np.argmax(power_center_3d_np),
power_center_3d_np.shape,
)
peak_theta_3d = theta_vals_rad_3d[peak_index_3d[0]] * 180 / np.pi
else:
print(
"Skipping 3D far-field polar plot because power_3d_validation "
"is not an xarray DataArray."
)
# Printed summary
summary_3d_validation = summarize_3d_foms(foms_3d_validation)
print_3d_fom_summary(summary_3d_validation)
if hasattr(power_3d_validation, "dims"):
print()
print("3D center-wavelength far field:")
print(f" wavelength = {lams_nm_3d[idx_c_3d]:.2f} nm")
print(f" peak theta = {peak_theta_3d:.3f} deg")
print(f" collection range = 0 to {collection_angle_deg:.1f} deg")
3D FOM summary at 798 nm: center coupling = 9.923% T-band mean coupling = 7.914% center reflection = 12.200% R-band mean reflection = 17.418% upward power = 40.662% collected power (15° cone) = 13.568% angular spill = 27.093% peak angle = 6.500 deg 3D center-wavelength far field: wavelength = 798.00 nm peak theta = 6.500 deg collection range = 0 to 15.0 deg
3D Placement Sweep¶
Before starting the full 3D adjoint optimization, we perform a small sweep over two placement parameters: the grating apex position and the distance shift between the taper and the grating region. The trench sequence is kept fixed during this sweep, while the grating placement and curvature are varied.
The goal here is to improve the initial grating placement, recover some of the performance lost in the 2D-to-3D transition, and choose a better starting point for the 3D optimization.
We start by choosing a reasonable set of apex_x and dist_shift values to test.
Each placement case is evaluated with the mode-source and beam-source simulations. The figures of merit are then extracted for each case and collected into a table so the different placements can be compared.
RUN_3D_SWEEP = True # set True to submit the sweep simulations
# Use the default 3D wavelength grid for the placement sweep.
set_active_wavelength_grid_3d(
DEFAULT_TARGET_HALF_WIDTH_3D_UM,
verbose=False,
)
# Sweep the radial-grating curvature center along x.
# More negative apex_x values move the center of curvature farther back
# toward the input waveguide, changing how the curved trenches meet the taper.
APEX_X_VALUES_3D = np.array([-2.0, -1.0, 0.0])
# Sweep the physical grating position along x.
# Positive dist_shift moves the grating, together with the beam center,
# farther away from the input waveguide.
DIST_SHIFT_VALUES_3D = np.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0])
USE_FIELD_MONITORS_3D_SWEEP = (
False # optional: set True to use field monitors for each sweep case
)
def make_3d_sweep_task_name(apex_x, dist_shift):
"""Create a short path-safe task name for a 3D sweep case."""
ax_tag = f"{apex_x:+.3f}".replace("+", "p").replace("-", "m").replace(".", "p")
ds_tag = f"{dist_shift:+.3f}".replace("+", "p").replace("-", "m").replace(".", "p")
return f"3d_sweep_i{selected_iter_2d:04d}_ax{ax_tag}_ds{ds_tag}"
sweep_results_3d = []
sweep_rows_3d = []
if RUN_3D_SWEEP:
total_cases_3d = len(APEX_X_VALUES_3D) * len(DIST_SHIFT_VALUES_3D)
case_count_3d = 0
for apex_x_3d in APEX_X_VALUES_3D:
for dist_shift_3d in DIST_SHIFT_VALUES_3D:
case_count_3d += 1
apex_x_3d = float(apex_x_3d)
dist_shift_3d = float(dist_shift_3d)
task_name_3d = make_3d_sweep_task_name(
apex_x=apex_x_3d,
dist_shift=dist_shift_3d,
)
print()
print("=" * 72)
print(f"3D sweep case {case_count_3d} / {total_cases_3d}")
print(f" apex_x = {apex_x_3d:+.4f} um")
print(f" dist_shift = {dist_shift_3d:+.4f} um")
print(f" task name = {task_name_3d}")
print("=" * 72)
# Build this 3D placement case.
sim_mode_3d_sweep, sim_beam_3d_sweep = make_two_sims_3d(
params_u=params_selected_2d,
use_field_monitors=USE_FIELD_MONITORS_3D_SWEEP,
dist_shift=dist_shift_3d,
apex_x=apex_x_3d,
clearance_um=TRENCH_TAPER_CLEARANCE_3D,
)
# Run mode-source simulation.
print("Running mode-source simulation...")
sim_mode_3d_sweep_data = web.run(
sim_mode_3d_sweep,
task_name=f"{task_name_3d}_mode",
verbose=False,
)
# Run beam-source simulation.
print()
print("Running beam-source simulation...")
sim_beam_3d_sweep_data = web.run(
sim_beam_3d_sweep,
task_name=f"{task_name_3d}_beam",
verbose=False,
)
# Extract FOMs.
foms_3d_sweep = figures_of_merit_3d(
sim_mode_3d_data=sim_mode_3d_sweep_data,
sim_beam_3d_data=sim_beam_3d_sweep_data,
sim_mode_3d=sim_mode_3d_sweep,
)
summary_3d_sweep = summarize_3d_foms(foms_3d_sweep)
print()
print_3d_fom_summary(summary_3d_sweep)
row_3d = {
"case": case_count_3d,
"apex_x_um": apex_x_3d,
"dist_shift_um": dist_shift_3d,
"center_coupling_percent": 100 * summary_3d_sweep["center_coupling"],
"T_band_mean_coupling_percent": 100
* summary_3d_sweep["band_mean_coupling"],
"center_reflection_percent": 100
* summary_3d_sweep["center_reflectivity"],
"R_band_mean_reflection_percent": 100
* summary_3d_sweep["band_mean_reflectivity"],
"upward_power_percent": 100 * summary_3d_sweep["center_upwards_power"],
"collected_power_percent": 100
* summary_3d_sweep["center_collected_power"],
"angular_spill_percent": 100 * summary_3d_sweep["center_angular_spill"],
"peak_angle_deg": summary_3d_sweep["peak_angle_deg"],
}
sweep_rows_3d.append(row_3d)
sweep_results_3d.append(
{
"case": case_count_3d,
"apex_x_um": apex_x_3d,
"dist_shift_um": dist_shift_3d,
"task_name": task_name_3d,
"sim_mode": sim_mode_3d_sweep,
"sim_beam": sim_beam_3d_sweep,
"foms": foms_3d_sweep,
"summary": summary_3d_sweep,
"row": row_3d,
}
)
sweep_table_3d = pd.DataFrame(sweep_rows_3d)
print()
print("3D sweep complete.")
display(sweep_table_3d)
else:
print("3D sweep skipped.")
print("Set RUN_3D_SWEEP = True to run the apex_x / dist_shift sweep.")
print()
print("Planned sweep values:")
print(f" apex_x values = {APEX_X_VALUES_3D} um")
print(f" dist_shift values = {DIST_SHIFT_VALUES_3D} um")
======================================================================== 3D sweep case 1 / 18 apex_x = -2.0000 um dist_shift = +0.0000 um task name = 3d_sweep_i0349_axm2p000_dsp0p000 ======================================================================== Running mode-source simulation... Running beam-source simulation... 3D FOM summary at 798 nm: center coupling = 7.264% T-band mean coupling = 5.508% center reflection = 5.908% R-band mean reflection = 12.313% upward power = 40.060% collected power (15° cone) = 10.172% angular spill = 29.888% peak angle = 7.750 deg ======================================================================== 3D sweep case 2 / 18 apex_x = -2.0000 um dist_shift = +1.0000 um task name = 3d_sweep_i0349_axm2p000_dsp1p000 ======================================================================== Running mode-source simulation... Running beam-source simulation... 3D FOM summary at 798 nm: center coupling = 5.051% T-band mean coupling = 7.793% center reflection = 9.875% R-band mean reflection = 14.297% upward power = 36.940% collected power (15° cone) = 8.481% angular spill = 28.459% peak angle = 8.500 deg ======================================================================== 3D sweep case 3 / 18 apex_x = -2.0000 um dist_shift = +2.0000 um task name = 3d_sweep_i0349_axm2p000_dsp2p000 ======================================================================== Running mode-source simulation... Running beam-source simulation... 3D FOM summary at 798 nm: center coupling = 10.478% T-band mean coupling = 8.754% center reflection = 16.812% R-band mean reflection = 22.802% upward power = 38.340% collected power (15° cone) = 14.938% angular spill = 23.402% peak angle = 6.750 deg ======================================================================== 3D sweep case 4 / 18 apex_x = -2.0000 um dist_shift = +3.0000 um task name = 3d_sweep_i0349_axm2p000_dsp3p000 ======================================================================== Running mode-source simulation... Running beam-source simulation... 3D FOM summary at 798 nm: center coupling = 9.389% T-band mean coupling = 9.413% center reflection = 24.493% R-band mean reflection = 24.468% upward power = 35.939% collected power (15° cone) = 14.232% angular spill = 21.707% peak angle = 7.500 deg ======================================================================== 3D sweep case 5 / 18 apex_x = -2.0000 um dist_shift = +4.0000 um task name = 3d_sweep_i0349_axm2p000_dsp4p000 ======================================================================== Running mode-source simulation... Running beam-source simulation... 3D FOM summary at 798 nm: center coupling = 6.887% T-band mean coupling = 8.560% center reflection = 32.682% R-band mean reflection = 22.150% upward power = 31.904% collected power (15° cone) = 12.655% angular spill = 19.249% peak angle = 8.000 deg ======================================================================== 3D sweep case 6 / 18 apex_x = -2.0000 um dist_shift = +5.0000 um task name = 3d_sweep_i0349_axm2p000_dsp5p000 ======================================================================== Running mode-source simulation... Running beam-source simulation... 3D FOM summary at 798 nm: center coupling = 6.749% T-band mean coupling = 8.055% center reflection = 31.825% R-band mean reflection = 25.887% upward power = 32.433% collected power (15° cone) = 13.181% angular spill = 19.253% peak angle = 7.750 deg ======================================================================== 3D sweep case 7 / 18 apex_x = -1.0000 um dist_shift = +0.0000 um task name = 3d_sweep_i0349_axm1p000_dsp0p000 ======================================================================== Running mode-source simulation... Running beam-source simulation... 3D FOM summary at 798 nm: center coupling = 8.867% T-band mean coupling = 7.470% center reflection = 10.627% R-band mean reflection = 17.207% upward power = 41.208% collected power (15° cone) = 12.271% angular spill = 28.937% peak angle = 7.000 deg ======================================================================== 3D sweep case 8 / 18 apex_x = -1.0000 um dist_shift = +1.0000 um task name = 3d_sweep_i0349_axm1p000_dsp1p000 ======================================================================== Running mode-source simulation... Running beam-source simulation... 3D FOM summary at 798 nm: center coupling = 6.081% T-band mean coupling = 8.520% center reflection = 16.418% R-band mean reflection = 16.339% upward power = 35.413% collected power (15° cone) = 9.264% angular spill = 26.148% peak angle = 8.500 deg ======================================================================== 3D sweep case 9 / 18 apex_x = -1.0000 um dist_shift = +2.0000 um task name = 3d_sweep_i0349_axm1p000_dsp2p000 ======================================================================== Running mode-source simulation... Running beam-source simulation... 3D FOM summary at 798 nm: center coupling = 9.258% T-band mean coupling = 9.329% center reflection = 26.130% R-band mean reflection = 26.208% upward power = 35.207% collected power (15° cone) = 13.607% angular spill = 21.600% peak angle = 7.500 deg ======================================================================== 3D sweep case 10 / 18 apex_x = -1.0000 um dist_shift = +3.0000 um task name = 3d_sweep_i0349_axm1p000_dsp3p000 ======================================================================== Running mode-source simulation... Running beam-source simulation... 3D FOM summary at 798 nm: center coupling = 9.677% T-band mean coupling = 9.330% center reflection = 22.234% R-band mean reflection = 25.714% upward power = 36.622% collected power (15° cone) = 14.456% angular spill = 22.166% peak angle = 7.000 deg ======================================================================== 3D sweep case 11 / 18 apex_x = -1.0000 um dist_shift = +4.0000 um task name = 3d_sweep_i0349_axm1p000_dsp4p000 ======================================================================== Running mode-source simulation... Running beam-source simulation... 3D FOM summary at 798 nm: center coupling = 9.589% T-band mean coupling = 9.154% center reflection = 23.285% R-band mean reflection = 24.891% upward power = 36.316% collected power (15° cone) = 15.017% angular spill = 21.300% peak angle = 7.250 deg ======================================================================== 3D sweep case 12 / 18 apex_x = -1.0000 um dist_shift = +5.0000 um task name = 3d_sweep_i0349_axm1p000_dsp5p000 ======================================================================== Running mode-source simulation... Running beam-source simulation... 3D FOM summary at 798 nm: center coupling = 9.743% T-band mean coupling = 8.684% center reflection = 22.745% R-band mean reflection = 22.520% upward power = 36.693% collected power (15° cone) = 15.830% angular spill = 20.863% peak angle = 7.000 deg ======================================================================== 3D sweep case 13 / 18 apex_x = +0.0000 um dist_shift = +0.0000 um task name = 3d_sweep_i0349_axp0p000_dsp0p000 ======================================================================== Running mode-source simulation... Running beam-source simulation... 3D FOM summary at 798 nm: center coupling = 9.923% T-band mean coupling = 7.914% center reflection = 12.200% R-band mean reflection = 17.418% upward power = 40.662% collected power (15° cone) = 13.568% angular spill = 27.093% peak angle = 6.500 deg ======================================================================== 3D sweep case 14 / 18 apex_x = +0.0000 um dist_shift = +1.0000 um task name = 3d_sweep_i0349_axp0p000_dsp1p000 ======================================================================== Running mode-source simulation... Running beam-source simulation... 3D FOM summary at 798 nm: center coupling = 8.805% T-band mean coupling = 8.089% center reflection = 14.925% R-band mean reflection = 18.550% upward power = 38.932% collected power (15° cone) = 12.137% angular spill = 26.794% peak angle = 6.750 deg ======================================================================== 3D sweep case 15 / 18 apex_x = +0.0000 um dist_shift = +2.0000 um task name = 3d_sweep_i0349_axp0p000_dsp2p000 ======================================================================== Running mode-source simulation... Running beam-source simulation... 3D FOM summary at 798 nm: center coupling = 9.871% T-band mean coupling = 8.528% center reflection = 18.021% R-band mean reflection = 17.597% upward power = 38.203% collected power (15° cone) = 13.858% angular spill = 24.345% peak angle = 6.750 deg ======================================================================== 3D sweep case 16 / 18 apex_x = +0.0000 um dist_shift = +3.0000 um task name = 3d_sweep_i0349_axp0p000_dsp3p000 ======================================================================== Running mode-source simulation... Running beam-source simulation... 3D FOM summary at 798 nm: center coupling = 9.008% T-band mean coupling = 8.696% center reflection = 18.060% R-band mean reflection = 18.493% upward power = 36.951% collected power (15° cone) = 13.947% angular spill = 23.004% peak angle = 6.750 deg ======================================================================== 3D sweep case 17 / 18 apex_x = +0.0000 um dist_shift = +4.0000 um task name = 3d_sweep_i0349_axp0p000_dsp4p000 ======================================================================== Running mode-source simulation... Running beam-source simulation... 3D FOM summary at 798 nm: center coupling = 7.736% T-band mean coupling = 8.842% center reflection = 19.644% R-band mean reflection = 17.694% upward power = 35.197% collected power (15° cone) = 13.223% angular spill = 21.974% peak angle = 7.250 deg ======================================================================== 3D sweep case 18 / 18 apex_x = +0.0000 um dist_shift = +5.0000 um task name = 3d_sweep_i0349_axp0p000_dsp5p000 ======================================================================== Running mode-source simulation... Running beam-source simulation... 3D FOM summary at 798 nm: center coupling = 7.568% T-band mean coupling = 8.402% center reflection = 20.315% R-band mean reflection = 13.214% upward power = 34.325% collected power (15° cone) = 13.004% angular spill = 21.321% peak angle = 7.250 deg 3D sweep complete.
| case | apex_x_um | dist_shift_um | center_coupling_percent | T_band_mean_coupling_percent | center_reflection_percent | R_band_mean_reflection_percent | upward_power_percent | collected_power_percent | angular_spill_percent | peak_angle_deg | |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 1 | -2.0 | 0.0 | 7.264474 | 5.507684 | 5.907963 | 12.312919 | 40.060412 | 10.172049 | 29.888363 | 7.75 |
| 1 | 2 | -2.0 | 1.0 | 5.050510 | 7.793138 | 9.875228 | 14.296568 | 36.940266 | 8.480860 | 28.459406 | 8.50 |
| 2 | 3 | -2.0 | 2.0 | 10.478479 | 8.753970 | 16.812368 | 22.801847 | 38.339669 | 14.937739 | 23.401931 | 6.75 |
| 3 | 4 | -2.0 | 3.0 | 9.389430 | 9.413425 | 24.493047 | 24.468430 | 35.938922 | 14.232322 | 21.706600 | 7.50 |
| 4 | 5 | -2.0 | 4.0 | 6.886843 | 8.560387 | 32.682334 | 22.149768 | 31.903616 | 12.655103 | 19.248513 | 8.00 |
| 5 | 6 | -2.0 | 5.0 | 6.749242 | 8.055424 | 31.824823 | 25.887089 | 32.433308 | 13.180797 | 19.252511 | 7.75 |
| 6 | 7 | -1.0 | 0.0 | 8.866545 | 7.469753 | 10.626749 | 17.206803 | 41.208470 | 12.271290 | 28.937180 | 7.00 |
| 7 | 8 | -1.0 | 1.0 | 6.080564 | 8.520009 | 16.417643 | 16.339438 | 35.412804 | 9.264372 | 26.148432 | 8.50 |
| 8 | 9 | -1.0 | 2.0 | 9.257661 | 9.329244 | 26.130221 | 26.208332 | 35.206742 | 13.606561 | 21.600180 | 7.50 |
| 9 | 10 | -1.0 | 3.0 | 9.676796 | 9.329916 | 22.234411 | 25.713523 | 36.621691 | 14.455643 | 22.166048 | 7.00 |
| 10 | 11 | -1.0 | 4.0 | 9.588906 | 9.154226 | 23.285239 | 24.890796 | 36.316312 | 15.016613 | 21.299699 | 7.25 |
| 11 | 12 | -1.0 | 5.0 | 9.743429 | 8.684196 | 22.744882 | 22.519894 | 36.693372 | 15.830480 | 20.862892 | 7.00 |
| 12 | 13 | 0.0 | 0.0 | 9.923005 | 7.913633 | 12.199564 | 17.417782 | 40.661582 | 13.568418 | 27.093164 | 6.50 |
| 13 | 14 | 0.0 | 1.0 | 8.805013 | 8.088596 | 14.925445 | 18.550056 | 38.931541 | 12.137340 | 26.794201 | 6.75 |
| 14 | 15 | 0.0 | 2.0 | 9.871143 | 8.527933 | 18.021432 | 17.596893 | 38.202869 | 13.858056 | 24.344812 | 6.75 |
| 15 | 16 | 0.0 | 3.0 | 9.007686 | 8.696349 | 18.059732 | 18.493068 | 36.950859 | 13.946586 | 23.004273 | 6.75 |
| 16 | 17 | 0.0 | 4.0 | 7.736038 | 8.841879 | 19.643997 | 17.694346 | 35.196600 | 13.222544 | 21.974056 | 7.25 |
| 17 | 18 | 0.0 | 5.0 | 7.567934 | 8.402031 | 20.315247 | 13.213792 | 34.325337 | 13.003886 | 21.321451 | 7.25 |
Select the 3D Placement¶
After inspecting the 3D sweep results, we choose apex_x = -2.0 µm and dist_shift = 2.0 µm as a balanced starting point for the 3D adjoint optimization. This case gives the highest coupling among the sweep cases, while still keeping the back-reflection reasonable and the peak radiation angle close to normal incidence.
# Choose the 3D placement settings to carry forward.
SELECTED_APEX_X_3D = -2.0
SELECTED_DIST_SHIFT_3D = 2.0
selected_apex_x_3d = float(SELECTED_APEX_X_3D)
selected_dist_shift_3d = float(SELECTED_DIST_SHIFT_3D)
# If a sweep table exists, show the matching row
if "sweep_table_3d" in globals() and len(sweep_table_3d) > 0:
sweep_match_3d = sweep_table_3d[
np.isclose(sweep_table_3d["apex_x_um"], selected_apex_x_3d)
& np.isclose(sweep_table_3d["dist_shift_um"], selected_dist_shift_3d)
]
if len(sweep_match_3d) == 0:
print("Selected placement was not found in sweep_table_3d.")
print("The selected values will still be used in later cells.")
print()
print("Available sweep cases:")
display(sweep_table_3d)
else:
print("Selected 3D sweep case:")
display(sweep_match_3d)
else:
print("Using the selected apex_x and dist_shift values directly.")
# Build the selected 3D simulations for a final layout check
sim_mode_3d_selected, _ = make_two_sims_3d(
params_u=params_selected_2d,
use_field_monitors=True,
dist_shift=selected_dist_shift_3d,
apex_x=selected_apex_x_3d,
clearance_um=TRENCH_TAPER_CLEARANCE_3D,
)
print()
print("Selected 3D placement:")
print(f" selected 2D iteration = {selected_iter_2d}")
print(f" apex_x = {selected_apex_x_3d:+.4f} um")
print(f" dist_shift = {selected_dist_shift_3d:+.4f} um")
print(
f" slot_rmin = {get_slot_rmin_3d(selected_apex_x_3d, selected_dist_shift_3d):.4f} um"
)
print(
f" last trench x = {get_last_trench_x_3d(selected_apex_x_3d, selected_dist_shift_3d, params_selected_2d):.4f} um"
)
print(
f" taper end x = {get_taper_end_x_3d(selected_apex_x_3d, selected_dist_shift_3d, params_selected_2d):.4f} um"
)
print(f" 3D sim size = {sim_mode_3d_selected.size}")
Selected 3D sweep case:
| case | apex_x_um | dist_shift_um | center_coupling_percent | T_band_mean_coupling_percent | center_reflection_percent | R_band_mean_reflection_percent | upward_power_percent | collected_power_percent | angular_spill_percent | peak_angle_deg | |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 2 | 3 | -2.0 | 2.0 | 10.478479 | 8.75397 | 16.812368 | 22.801847 | 38.339669 | 14.937739 | 23.401931 | 6.75 |
Selected 3D placement: selected 2D iteration = 349 apex_x = -2.0000 um dist_shift = +2.0000 um slot_rmin = 6.0000 um last trench x = 11.0014 um taper end x = 14.0014 um 3D sim size = (17.001370751796877, 14.613841962734487, 2.15)
3D Adjoint Optimization¶
Now that we have a better 3D starting point from the placement sweep, we can start the full 3D adjoint optimization. The grating placement is kept fixed, while the trench and gap widths are optimized directly in 3D.
Here the main goal is to recover more of the performance that was lost when moving from 2D to 3D.
Build Adjoint-Compatible 3D Simulations¶
To start, we define the geometry helpers and simulation builder used in the 3D adjoint optimization.
The helper functions convert the current trench and gap parameters into the curved 3D grating geometry. The main builder then uses this geometry to construct the two simulations needed for the objective: the mode-source and beam-source simulations.
# 3D adjoint starting point
# The 3D adjoint optimization starts from the selected 2D grating design
# and the selected 3D placement.
params_start_3d_adj = np.array(params_selected_2d, dtype=float).copy()
params_3d_adj = params_start_3d_adj.copy()
ADJ_APEX_X_3D = float(selected_apex_x_3d)
ADJ_DIST_SHIFT_3D = float(selected_dist_shift_3d)
# 3D adjoint source time
# The adjoint simulations reuse the same source pulse as the 3D validation.
# The monitors use the active 3D wavelength grid.
beam_time_3d_adj = beam_time
mode_src_3d_adj = mode_src
freq0_3d_adj = float(beam_time_3d_adj.freq0)
fwidth_3d_adj = float(beam_time_3d_adj.fwidth)
# Helper for non-optimized scalar quantities
def _detach_float_3d(x):
"""
Convert a scalar to a Python float for non-optimized sizing.
This is used for quantities such as the simulation box, taper end,
monitor size, and fixed angular sampling. The optimized trench vertices
are kept differentiable so the adjoint gradient can flow through them.
"""
try:
return float(x._value)
except AttributeError:
return float(x)
# Curved-grating geometry helpers
def get_slot_rmin_3d_adj(apex_x_local, dist_shift_local=0.0):
"""
Return the first trench radius relative to the curvature center.
The physical first trench position is controlled by dist_shift:
x_first = apex_x + slot_rmin
= slot_radius_min + dist_shift
"""
return float(slot_radius_min + dist_shift_local - apex_x_local)
def get_slot_half_angle_3d_adj(apex_x_local, radius_local):
"""
Return the trench half-angle for a radius measured from the curvature center.
"""
angle_arg = float(
np.clip(
apex_x_local * np.sin(slot_half_angle) / radius_local,
-0.999999,
0.999999,
)
)
return float(slot_half_angle + np.arcsin(angle_arg))
def get_slot_unit_verts_3d_adj(apex_x_local, radius_local):
"""
Return unit-circle vertices for a trench edge.
The angular samples are fixed numbers. The optimized radii are applied
later so the trench vertices remain differentiable.
"""
slot_half_angle_local = get_slot_half_angle_3d_adj(
apex_x_local,
radius_local,
)
slot_angles_local = np.linspace(
-slot_half_angle_local,
slot_half_angle_local,
num_slot_angles,
)
return np.array(
[[np.cos(angle), np.sin(angle)] for angle in slot_angles_local],
dtype=float,
)
def get_last_trench_x_3d_adj(apex_x_local, dist_shift_local=0.0, params_u=None):
"""
Return the physical x-position of the last trench outer edge.
This value is used only for non-optimized sizing, so the last radius is
detached before converting to a Python float.
"""
params_local = _current_params_for_3d(params_u)
w_local, g_local = params_to_wgaps(anp.array(params_local))
slot_rmin_local = get_slot_rmin_3d_adj(
apex_x_local,
dist_shift_local=dist_shift_local,
)
_, xR_local = edges_from_wgaps(
w_local,
g_local,
slot_rmin=slot_rmin_local,
)
return float(apex_x_local + _detach_float_3d(xR_local[-1]))
def get_taper_end_x_3d_adj(apex_x_local, dist_shift_local=0.0, params_u=None):
"""
Return the physical x-position where the taper ends.
"""
return float(
get_last_trench_x_3d_adj(
apex_x_local,
dist_shift_local=dist_shift_local,
params_u=params_u,
)
+ taper_tail_clearance_3d
)
def make_taper_struct_3d_adj(apex_x_local, dist_shift_local=0.0, params_u=None):
"""
Build the 3D taper structure.
"""
taper_end_x_local = get_taper_end_x_3d_adj(
apex_x_local,
dist_shift_local=dist_shift_local,
params_u=params_u,
)
taper_half_width_local = get_taper_half_width_3d(taper_end_x_local)
taper_vertices = np.array(
[
[x_apex, -0.5 * w_wg],
[taper_end_x_local, -taper_half_width_local],
[taper_end_x_local, taper_half_width_local],
[x_apex, 0.5 * w_wg],
],
dtype=float,
)
return td.Structure(
geometry=td.PolySlab(
vertices=taper_vertices,
slab_bounds=(-t_mem / 2, t_mem / 2),
axis=2,
),
medium=device_medium,
background_medium=air,
name="taper",
)
def make_sim_box_3d_adj(apex_x_local, dist_shift_local=0.0, params_u=None):
"""
Build the 3D simulation box for the adjoint run.
"""
taper_end_x_local = get_taper_end_x_3d_adj(
apex_x_local,
dist_shift_local=dist_shift_local,
params_u=params_u,
)
device_y_span_local = get_device_y_span_3d(taper_end_x_local)
return td.Box.from_bounds(
rmin=(
sim_x_min_3d,
-0.5 * device_y_span_local - pml_spacing_3d,
z_mem_bot - z_bot / 2 - pml_spacing_3d,
),
rmax=(
taper_end_x_local,
0.5 * device_y_span_local + pml_spacing_3d,
z_mem_top + z_top / 2 + pml_spacing_3d,
),
)
def make_top_monitor_geometry_3d_adj(
sim_box_local,
apex_x_local,
dist_shift_local=0.0,
params_u=None,
):
"""
Build the top monitor geometry used for local far-field projection.
"""
params_local = _current_params_for_3d(params_u)
w_local, g_local = params_to_wgaps(anp.array(params_local))
slot_rmin_local = get_slot_rmin_3d_adj(
apex_x_local,
dist_shift_local=dist_shift_local,
)
xL_local, xR_local = edges_from_wgaps(
w_local,
g_local,
slot_rmin=slot_rmin_local,
)
xL0_phys = float(apex_x_local + _detach_float_3d(xL_local[0]))
xR_last_phys = float(apex_x_local + _detach_float_3d(xR_local[-1]))
grating_center_x = 0.5 * (xL0_phys + xR_last_phys)
grating_span_x = xR_last_phys - xL0_phys
monitor_x_size = grating_span_x + 2.0 * top_monitor_x_margin_3d
x_min_allowed = sim_box_local.bounds[0][0] + pml_spacing_3d
x_max_allowed = sim_box_local.bounds[1][0] - pml_spacing_3d
monitor_x_min = max(grating_center_x - 0.5 * monitor_x_size, x_min_allowed)
monitor_x_max = min(grating_center_x + 0.5 * monitor_x_size, x_max_allowed)
monitor_x_center = 0.5 * (monitor_x_min + monitor_x_max)
monitor_x_size = monitor_x_max - monitor_x_min
taper_end_x_local = get_taper_end_x_3d_adj(
apex_x_local,
dist_shift_local=dist_shift_local,
params_u=params_local,
)
taper_half_width_local = get_taper_half_width_3d(taper_end_x_local)
monitor_y_size = 2.0 * (taper_half_width_local + top_monitor_y_margin_3d)
y_min_allowed = sim_box_local.bounds[0][1] + pml_spacing_3d
y_max_allowed = sim_box_local.bounds[1][1] - pml_spacing_3d
monitor_y_min = max(-0.5 * monitor_y_size, y_min_allowed)
monitor_y_max = min(0.5 * monitor_y_size, y_max_allowed)
monitor_y_center = 0.5 * (monitor_y_min + monitor_y_max)
monitor_y_size = monitor_y_max - monitor_y_min
top_monitor_center_local = (
monitor_x_center,
monitor_y_center,
beam_center_z,
)
top_monitor_size_local = (
monitor_x_size,
monitor_y_size,
0.0,
)
return top_monitor_center_local, top_monitor_size_local
# 3D trench builders
def build_slot_group_3d_adj_plot(w, g, apex_x_local, dist_shift_local=0.0):
"""
Build a grouped grating structure for plotting.
This uses the same clearance-aware trench shape as the 3D validation
and placement sweep, so the adjoint starting geometry matches the
selected sweep case.
"""
slot_rmin_local = get_slot_rmin_3d_adj(
apex_x_local,
dist_shift_local=dist_shift_local,
)
xL, xR = edges_from_wgaps(
w,
g,
slot_rmin=slot_rmin_local,
)
taper_end_x_local = float(
apex_x_local + _detach_float_3d(xR[-1]) + taper_tail_clearance_3d
)
slot_geometries = []
for r_in, r_out in zip(xL, xR):
r_in_float = _detach_float_3d(r_in)
r_out_float = _detach_float_3d(r_out)
inner_unit = get_clearance_slot_unit_verts_3d(
apex_x=apex_x_local,
radius=r_in_float,
taper_end_x_local=taper_end_x_local,
clearance_um=TRENCH_TAPER_CLEARANCE_3D,
)
outer_unit = get_clearance_slot_unit_verts_3d(
apex_x=apex_x_local,
radius=r_out_float,
taper_end_x_local=taper_end_x_local,
clearance_um=TRENCH_TAPER_CLEARANCE_3D,
)
inner_verts = np.column_stack(
[
apex_x_local + r_in_float * inner_unit[:, 0],
r_in_float * inner_unit[:, 1],
]
)
outer_verts = np.column_stack(
[
apex_x_local + r_out_float * outer_unit[::-1, 0],
r_out_float * outer_unit[::-1, 1],
]
)
slot_vertices = np.concatenate([inner_verts, outer_verts], axis=0)
slot_geometries.append(
td.PolySlab(
vertices=slot_vertices,
slab_bounds=(-t_mem / 2, t_mem / 2),
axis=2,
)
)
return td.Structure(
geometry=td.GeometryGroup(geometries=slot_geometries),
medium=air,
background_medium=device_medium,
name="grating_etch",
priority=4,
)
def build_slot_group_struct_3d_adj(w, g, apex_x_local, dist_shift_local=0.0):
"""Single differentiable grating structure (matches the sweep build)."""
slot_rmin_local = get_slot_rmin_3d_adj(
apex_x_local, dist_shift_local=dist_shift_local
)
xL, xR = edges_from_wgaps(w, g, slot_rmin=slot_rmin_local)
taper_end_x_local = float(
apex_x_local + _detach_float_3d(xR[-1]) + taper_tail_clearance_3d
)
slot_geometries = []
for r_in, r_out in zip(xL, xR):
r_in_f, r_out_f = _detach_float_3d(r_in), _detach_float_3d(r_out)
inner_unit = get_clearance_slot_unit_verts_3d(
apex_x=apex_x_local,
radius=r_in_f,
taper_end_x_local=taper_end_x_local,
clearance_um=TRENCH_TAPER_CLEARANCE_3D,
)
outer_unit = get_clearance_slot_unit_verts_3d(
apex_x=apex_x_local,
radius=r_out_f,
taper_end_x_local=taper_end_x_local,
clearance_um=TRENCH_TAPER_CLEARANCE_3D,
)
inner_x = apex_x_local + r_in * inner_unit[:, 0] # r_in traced
inner_y = r_in * inner_unit[:, 1]
outer_x = apex_x_local + r_out * outer_unit[::-1, 0]
outer_y = r_out * outer_unit[::-1, 1]
verts = anp.concatenate(
[
anp.stack([inner_x, inner_y], axis=1),
anp.stack([outer_x, outer_y], axis=1),
],
axis=0,
)
slot_geometries.append(
td.PolySlab(vertices=verts, slab_bounds=(-t_mem / 2, t_mem / 2), axis=2)
)
return td.Structure(
geometry=td.GeometryGroup(geometries=slot_geometries),
medium=air,
background_medium=device_medium,
name="grating_etch",
priority=4,
)
# 3D adjoint source and monitors
def make_beam_source_3d_adj(dist_shift_local=0.0):
"""
Build the 3D Gaussian beam source for adjoint simulations.
"""
shifted_beam_center_x = beam_center_x + dist_shift_local
return td.GaussianBeam(
size=(3.0 * beam_waist, 3.0 * beam_waist, 0.0),
center=(float(shifted_beam_center_x), 0.0, beam_center_z),
source_time=beam_time_3d_adj,
angle_theta=0.0,
direction="-",
waist_radius=beam_waist,
waist_distance=-beam_center_z,
pol_angle=np.pi / 2,
)
def make_monitors_3d_adj(
sim_box_local,
top_center,
top_size,
use_field_monitors=False,
):
"""
Build monitors for the 3D adjoint simulations.
Mode-source simulation:
wg_mode + top_field + projection target
Beam-source simulation:
wg_mode
"""
mode_monitor_adj = td.ModeMonitor(
center=(mode_x, 0.0, z_mem_center),
size=(0.0, 3.0 * w_wg, 5.0 * t_mem),
freqs=freqs_3d,
mode_spec=td.ModeSpec(num_modes=1),
name="wg_mode",
)
top_field_adj = td.FieldMonitor(
center=top_center,
size=top_size,
freqs=[freqs_3d[idx_c_3d]],
name="top_field",
colocate=False,
)
projection_adj = td.FieldProjectionAngleMonitor(
center=top_center,
size=top_size,
name="projection",
freqs=[freqs_3d[idx_c_3d]],
normal_dir="+",
proj_distance=10e3,
theta=theta_array_3d,
phi=phi_array_3d,
)
monitors_mode = [
mode_monitor_adj,
top_field_adj,
projection_adj,
]
monitors_beam = [
mode_monitor_adj,
]
if use_field_monitors:
device_y_span_local = sim_box_local.size[1] - 2.0 * pml_spacing_3d
field_xy_adj = td.FieldMonitor(
center=(sim_box_local.center[0], 0.0, z_mem_center + 0.074),
size=(sim_box_local.size[0], device_y_span_local, 0.0),
freqs=[freqs_3d[idx_c_3d]],
name="field_xy",
)
field_xz_adj = td.FieldMonitor(
center=sim_box_local.center,
size=(sim_box_local.size[0], 0.0, sim_box_local.size[2]),
freqs=[freqs_3d[idx_c_3d]],
name="field_xz",
)
monitors_mode += [field_xy_adj, field_xz_adj]
monitors_beam += [field_xy_adj, field_xz_adj]
return monitors_mode, monitors_beam
# Main 3D adjoint simulation builder
def make_two_sims_3d_adj(
params_u=None,
use_field_monitors=False,
adjoint_compatible=True,
):
"""
Build the mode-source and beam-source simulations for 3D adjoint optimization.
The trench vertices remain differentiable when adjoint_compatible=True.
Non-optimized quantities such as the simulation box, taper extent, and
monitor sizes are detached from the gradient trace.
"""
params_local = _current_params_for_3d(params_u)
w_local, g_local = params_to_wgaps(anp.array(params_local))
if adjoint_compatible:
slot_struct = build_slot_group_struct_3d_adj(
w_local,
g_local,
apex_x_local=ADJ_APEX_X_3D,
dist_shift_local=ADJ_DIST_SHIFT_3D,
)
else:
slot_struct = build_slot_group_3d_adj_plot(
w_local,
g_local,
apex_x_local=ADJ_APEX_X_3D,
dist_shift_local=ADJ_DIST_SHIFT_3D,
)
structures = [
make_taper_struct_3d_adj(
apex_x_local=ADJ_APEX_X_3D,
dist_shift_local=ADJ_DIST_SHIFT_3D,
params_u=params_local,
),
make_waveguide_struct_3d(),
slot_struct,
]
sim_box_local = make_sim_box_3d_adj(
apex_x_local=ADJ_APEX_X_3D,
dist_shift_local=ADJ_DIST_SHIFT_3D,
params_u=params_local,
)
top_center, top_size = make_top_monitor_geometry_3d_adj(
sim_box_local,
apex_x_local=ADJ_APEX_X_3D,
dist_shift_local=ADJ_DIST_SHIFT_3D,
params_u=params_local,
)
monitors_mode, monitors_beam = make_monitors_3d_adj(
sim_box_local,
top_center,
top_size,
use_field_monitors=use_field_monitors,
)
common_sim_kwargs = {
"center": sim_box_local.center,
"size": sim_box_local.size,
"grid_spec": grid_spec_3d,
"boundary_spec": boundary_spec_3d,
"structures": structures,
"medium": background,
"run_time": run_time_3d,
"symmetry": symmetry_3d,
}
sim_mode_3d_adj = td.Simulation(
**common_sim_kwargs,
sources=[mode_src_3d_adj],
monitors=monitors_mode,
)
sim_beam_3d_adj = td.Simulation(
**common_sim_kwargs,
sources=[make_beam_source_3d_adj(dist_shift_local=ADJ_DIST_SHIFT_3D)],
monitors=monitors_beam,
)
return sim_mode_3d_adj, sim_beam_3d_adj
# Dry-run build check
# Test the adjoint-compatible simulation builder without running FDTD.
sim_mode_3d_adj_check, sim_beam_3d_adj_check = make_two_sims_3d_adj(
params_u=params_3d_adj,
use_field_monitors=True,
adjoint_compatible=True,
)
print("3D adjoint simulation builder is ready.")
print()
print("3D adjoint starting point:")
print(f" selected 2D iteration = {selected_iter_2d}")
print(f" apex_x = {ADJ_APEX_X_3D:+.4f} um")
print(f" dist_shift = {ADJ_DIST_SHIFT_3D:+.4f} um")
print()
print("3D adjoint source:")
print(f" center wavelength = {lams_um_3d[idx_c_3d] * 1000:.3f} nm")
print(f" freq0 = {freq0_3d_adj:.4e} Hz")
print(f" fwidth = {fwidth_3d_adj:.4e} Hz")
print()
print("Dry-run simulation check:")
print(f" mode sim size = {sim_mode_3d_adj_check.size}")
print(f" beam sim size = {sim_beam_3d_adj_check.size}")
print(f" mode monitors = {[m.name for m in sim_mode_3d_adj_check.monitors]}")
print(f" beam monitors = {[m.name for m in sim_beam_3d_adj_check.monitors]}")
print(f" mode structures = {len(sim_mode_3d_adj_check.structures)}")
print(f" beam structures = {len(sim_beam_3d_adj_check.structures)}")
3D adjoint simulation builder is ready. 3D adjoint starting point: selected 2D iteration = 349 apex_x = -2.0000 um dist_shift = +2.0000 um 3D adjoint source: center wavelength = 798.000 nm freq0 = 3.7568e+14 Hz fwidth = 4.7263e+13 Hz Dry-run simulation check: mode sim size = (17.001370751796877, 14.613841962734487, 2.15) beam sim size = (17.001370751796877, 14.613841962734487, 2.15) mode monitors = ['wg_mode', 'top_field', 'projection', 'field_xy', 'field_xz'] beam monitors = ['wg_mode', 'field_xy', 'field_xz'] mode structures = 3 beam structures = 3
3D Adjoint Objective¶
For the 3D optimization, we use the same main objective terms as in the 2D optimization, but now they are calculated directly from the full 3D simulations.
We again use a staged schedule. The optimization starts by focusing more on improving the coupling over the target band. Then, the target band is gradually narrowed from ±10 nm to ±5 nm and finally ±2.5 nm, while more weight is placed on the center-wavelength coupling, reflection, and radiation direction. The learning rate is also reduced in the later stages for finer refinement.
# 3D adjoint FOM extraction and objective
# 3D adjoint objective weight schedule
# Stage 1: focus more on band coupling
WEIGHTS_3D_STAGE1 = {
"band_coupling": 80.0,
"band_coupling_mean": 8.0,
"center_coupling": 25.0,
"center_collected": 1.0,
"center_reflection": -3.0,
"R_band_mean_reflection": -6.0,
"R_band_worst_reflection": -18.0,
"angular_spill": -2.0,
"center_angle_moment": -0.3,
}
# Stage 2: shift more weight toward center coupling and reflection
WEIGHTS_3D_STAGE2 = {
"band_coupling": 30.0,
"band_coupling_mean": 5.0,
"center_coupling": 100.0,
"center_collected": 1.0,
"center_reflection": -25.0,
"R_band_mean_reflection": -3.0,
"R_band_worst_reflection": -8.0,
"angular_spill": -2.0,
"center_angle_moment": -1.0,
}
# Stage 3: focus strongly on center coupling, reflection, and radiation direction
WEIGHTS_3D_STAGE3 = {
"band_coupling": 8.0,
"band_coupling_mean": 1.0,
"center_coupling": 160.0,
"center_collected": 1.0,
"center_reflection": -40.0,
"R_band_mean_reflection": -1.0,
"R_band_worst_reflection": -3.0,
"angular_spill": -2.0,
"center_angle_moment": -2.0,
}
# Stage 4: final refinement with stronger reflection and angle control
WEIGHTS_3D_STAGE4 = {
"band_coupling": 30.0,
"band_coupling_mean": 1.0,
"center_coupling": 160.0,
"center_collected": 1.0,
"center_reflection": -60.0,
"R_band_mean_reflection": -1.0,
"R_band_worst_reflection": -3.0,
"angular_spill": -2.0,
"center_angle_moment": -3.0,
}
# 3D staged optimization schedule
# Each stage changes the objective weights, learning rate, and target band.
# Stage 1:
# target band = 798 ± 10 nm = [788, 798, 808] nm
# Stage 2:
# target band = 798 ± 5 nm = [793, 798, 803] nm
# Stage 3:
# target band = 798 ± 2.5 nm = [795.5, 798, 800.5] nm
# Stage 4:
# target band = 798 ± 2.5 nm = [795.5, 798, 800.5] nm
STAGES_3D_ADJ = [
{
"stage_id": 1,
"name": "stage1_3d",
"n_iters": 5, # iterations 0 through 4
"learning_rate": 0.005,
"target_half_width_um": 0.010,
"weights": WEIGHTS_3D_STAGE1,
},
{
"stage_id": 2,
"name": "stage2_3d",
"n_iters": 10, # iterations 5 through 14
"learning_rate": 0.0025,
"target_half_width_um": 0.005,
"weights": WEIGHTS_3D_STAGE2,
},
{
"stage_id": 3,
"name": "stage3_3d",
"n_iters": 40, # iterations 15 through 54
"learning_rate": 0.001,
"target_half_width_um": 0.0025,
"weights": WEIGHTS_3D_STAGE3,
},
{
"stage_id": 4,
"name": "stage4_3d",
"n_iters": 10, # iterations 55 through 64
"learning_rate": 0.001,
"target_half_width_um": 0.0025,
"weights": WEIGHTS_3D_STAGE4,
},
]
def add_stage_bounds_3d_adj(stages):
"""Add start/stop iteration numbers to each 3D adjoint stage."""
stages_with_bounds = []
start_iter = 0
for stage in stages:
stage = dict(stage)
stage["start_iter"] = start_iter
stage["stop_iter"] = start_iter + int(stage["n_iters"])
stages_with_bounds.append(stage)
start_iter = stage["stop_iter"]
return stages_with_bounds
STAGES_3D_ADJ = add_stage_bounds_3d_adj(STAGES_3D_ADJ)
TOTAL_ITERS_3D_ADJ = STAGES_3D_ADJ[-1]["stop_iter"]
def get_stage_for_iter_3d_adj(iter_index):
"""Return the active 3D adjoint stage for a saved iteration index."""
for stage in STAGES_3D_ADJ:
if stage["start_iter"] <= iter_index < stage["stop_iter"]:
return stage
raise ValueError(
f"3D adjoint iteration {iter_index} is outside the staged schedule "
f"0 ... {TOTAL_ITERS_3D_ADJ - 1}."
)
def set_stage_3d_adj(stage, verbose=True):
"""Set the active 3D adjoint weights, learning rate, and wavelength grid."""
global WEIGHTS_3D
global learning_rate_3d_adj
WEIGHTS_3D = dict(stage["weights"])
learning_rate_3d_adj = float(stage["learning_rate"])
set_active_wavelength_grid_3d(
stage["target_half_width_um"],
verbose=verbose,
)
# Initialize the objective with the first 3D stage.
set_stage_3d_adj(
STAGES_3D_ADJ[0],
verbose=False,
)
# Constants used by the smooth objective terms
# Collection half-angle used for the upward collected-power term.
MAX_COLLECTION_ANGLE_3D_DEG = collection_angle_deg
# Smooth maximum scale for the worst reflection term.
# Smaller values make the smooth maximum closer to a true maximum.
SMOOTH_MAX_TAU_REFLECT_3D = 0.03
# Small value used to avoid division by zero.
EPS_3D_OBJ = 1e-12
def _smooth_max_3d(x, tau=0.03):
"""Smooth approximation to max(x), used for worst-band reflection."""
x = anp.array(x)
x0 = anp.max(x)
return x0 + tau * anp.log(anp.mean(anp.exp((x - x0) / tau)) + EPS_3D_OBJ)
def _harmonic_mean_3d(x, eps=1e-12):
"""Harmonic mean used to reward the weakest wavelength in the band."""
x = anp.array(x)
return x.size / anp.sum(1.0 / (x + eps))
def _get_monitor_3d_by_name(sim, name):
"""Return a monitor object by name."""
for mon in sim.monitors:
if mon.name == name:
return mon
raise KeyError(
f"Monitor {name!r} not found. Available monitors: {[m.name for m in sim.monitors]}"
)
def get_proj_fields_3d_local(sim_mode_data, sim_mode_3d):
"""
Local 3D far-field projection from the top_field monitor.
"""
top_field_monitor_3d = _get_monitor_3d_by_name(sim_mode_3d, "top_field")
proj_monitor_3d = _get_monitor_3d_by_name(sim_mode_3d, "projection")
projector_3d = td.FieldProjector.from_near_field_monitors(
sim_data=sim_mode_data,
near_monitors=[top_field_monitor_3d],
normal_dirs=["+"],
pts_per_wavelength=14,
)
return projector_3d.project_fields(proj_monitor_3d)
def _local_projected_power_3d_center(sim_mode_data, sim_mode_3d):
"""
Return center-wavelength projected far-field power.
Returns:
power_center(theta, phi)
theta
phi
"""
proj_3d = get_proj_fields_3d_local(sim_mode_data, sim_mode_3d)
proj_monitor_3d = _get_monitor_3d_by_name(sim_mode_3d, "projection")
power_da = proj_3d.power.squeeze(drop=True)
if not all(dim in power_da.dims for dim in ("theta", "phi")):
raise ValueError(
f"Unexpected projected power dims: {power_da.dims}. "
"Expected theta and phi dimensions."
)
# The 3D adjoint objective uses the center-wavelength angular projection.
if "f" in power_da.dims:
if power_da.sizes["f"] == len(freqs_3d):
power_da = power_da.isel(f=idx_c_3d)
else:
power_da = power_da.isel(f=0)
power_da = power_da.transpose("theta", "phi")
power_center = power_da.values * (proj_monitor_3d.proj_distance**2)
theta = anp.array(power_da.coords["theta"].values)
phi = anp.array(power_da.coords["phi"].values)
return power_center, theta, phi
def figures_of_merit_3d_adj(
sim_mode_3d,
sim_beam_3d,
sim_mode_data=None,
sim_beam_data=None,
):
"""
Extract 3D FOMs for the adjoint objective.
Mode-source simulation:
reflection from wg_mode
upward/collected radiation from local projection of top_field
Beam-source simulation:
coupling from wg_mode
"""
reflectivity = None
coupling = None
power = None
peak_angle = None
collected_power = None
upwards_power = None
center_angle_moment = None
if sim_mode_data is not None:
reflectivity = (
anp.abs(
sim_mode_data["wg_mode"]
.amps.sel(
direction="-",
mode_index=0,
)
.values
)
** 2
)
power_center, theta, phi = _local_projected_power_3d_center(
sim_mode_data,
sim_mode_3d,
)
dtheta_3d = float(theta[1] - theta[0])
dphi_3d = float(phi[1] - phi[0])
theta_col_max = MAX_COLLECTION_ANGLE_3D_DEG * anp.pi / 180.0
sin_theta = anp.sin(theta).reshape((-1, 1))
collection_mask_3d = (0.0 <= theta) & (theta <= theta_col_max)
upwards_center = dtheta_3d * dphi_3d * anp.sum(power_center * sin_theta)
collected_center = (
dtheta_3d
* dphi_3d
* anp.sum(
power_center[collection_mask_3d, :] * sin_theta[collection_mask_3d, :]
)
)
# Smooth off-normal radiation penalty.
theta_weight = (theta.reshape((-1, 1)) / theta_col_max) ** 2
center_angle_moment = (
dtheta_3d
* dphi_3d
* anp.sum(power_center * sin_theta * theta_weight)
/ (upwards_center + EPS_3D_OBJ)
)
# Store center-wavelength radiation terms as wavelength-shaped arrays.
one_hot_center = anp.array(
[1.0 if i == idx_c_3d else 0.0 for i in range(len(freqs_3d))]
)
upwards_power = one_hot_center * upwards_center
collected_power = one_hot_center * collected_center
# Keep center far field for diagnostic plotting/printing.
power = (power_center, theta, phi)
peak_angle = None
if sim_beam_data is not None:
coupling = (
anp.abs(
sim_beam_data["wg_mode"]
.amps.sel(
direction="-",
mode_index=0,
)
.values
)
** 2
)
return (
reflectivity,
coupling,
power,
peak_angle,
collected_power,
upwards_power,
center_angle_moment,
)
def objective_terms_3d_adj(
coupling,
reflectivity,
collected_power,
upwards_power,
center_angle_moment,
):
"""Raw scalar terms used in the 3D adjoint objective."""
T_band = coupling[mask_T_band_3d]
R_band = reflectivity[mask_R_band_3d]
band_coupling = _harmonic_mean_3d(T_band, eps=EPS_3D_OBJ)
band_coupling_mean = anp.mean(T_band)
center_coupling = coupling[idx_c_3d]
center_collected = collected_power[idx_c_3d]
center_reflection = reflectivity[idx_c_3d]
R_band_mean_reflection = anp.mean(R_band)
R_band_worst_reflection = _smooth_max_3d(
R_band,
tau=SMOOTH_MAX_TAU_REFLECT_3D,
)
angular_spill = upwards_power[idx_c_3d] - collected_power[idx_c_3d]
return {
"band_coupling": band_coupling,
"band_coupling_mean": band_coupling_mean,
"center_coupling": center_coupling,
"center_collected": center_collected,
"center_reflection": center_reflection,
"R_band_mean_reflection": R_band_mean_reflection,
"R_band_worst_reflection": R_band_worst_reflection,
"angular_spill": angular_spill,
"center_angle_moment": center_angle_moment,
}
def objective_value_3d_adj_from_terms(raw_terms):
"""Weighted 3D objective value."""
weighted_terms = {}
obj = 0.0
for name, weight in WEIGHTS_3D.items():
weighted_terms[name] = weight * raw_terms[name]
obj = obj + weighted_terms[name]
return obj, weighted_terms
def objective_3d_adj(params_u, task_name="adj3d"):
"""
Differentiable 3D adjoint objective.
Builds:
mode-source simulation -> reflection + upward radiation
beam-source simulation -> coupling
"""
sim_mode_3d, sim_beam_3d = make_two_sims_3d_adj(
params_u=params_u,
use_field_monitors=False,
adjoint_compatible=True,
)
sim_mode_data = web.run(
sim_mode_3d,
task_name=f"{task_name}_mode",
verbose=False,
)
sim_beam_data = web.run(
sim_beam_3d,
task_name=f"{task_name}_beam",
verbose=False,
)
(
reflectivity,
coupling,
power,
peak_angle,
collected_power,
upwards_power,
center_angle_moment,
) = figures_of_merit_3d_adj(
sim_mode_3d=sim_mode_3d,
sim_beam_3d=sim_beam_3d,
sim_mode_data=sim_mode_data,
sim_beam_data=sim_beam_data,
)
raw_terms = objective_terms_3d_adj(
coupling=coupling,
reflectivity=reflectivity,
collected_power=collected_power,
upwards_power=upwards_power,
center_angle_moment=center_angle_moment,
)
obj, weighted_terms = objective_value_3d_adj_from_terms(raw_terms)
aux = [
reflectivity,
coupling,
power,
peak_angle,
collected_power,
upwards_power,
raw_terms,
weighted_terms,
]
return obj, aux
val_grad_3d_adj = value_and_grad(objective_3d_adj, has_aux=True)
print("3D adjoint FOM/objective helpers are ready.")
3D adjoint FOM/objective helpers are ready.
3D Adjoint Live Plot¶
Here we define the live plot used to track the 3D optimization progress, including the objective, coupling, reflection, and radiation terms.
# adjoint live plot helpers
def make_live_optimization_figure_3d_adj():
"""Create an empty live plot for 3D adjoint optimization progress."""
fig = make_subplots(
rows=2,
cols=2,
specs=[
[{"type": "xy"}, {"type": "xy"}],
[{"type": "xy"}, {"type": "xy"}],
],
subplot_titles=[
"Objective",
"Coupling",
"Reflection",
"Radiation terms",
],
)
fig.update_layout(
width=1150,
height=750,
showlegend=True,
title="3D adjoint optimization live progress",
)
fig.update_xaxes(title_text="Iteration", row=1, col=1)
fig.update_yaxes(title_text="Objective", row=1, col=1)
fig.update_xaxes(title_text="Iteration", row=1, col=2)
fig.update_yaxes(title_text="Coupling (%)", row=1, col=2)
fig.update_xaxes(title_text="Iteration", row=2, col=1)
fig.update_yaxes(title_text="Reflection (%)", row=2, col=1)
fig.update_xaxes(title_text="Iteration", row=2, col=2)
fig.update_yaxes(title_text="Power (%)", row=2, col=2)
return fig
def update_live_optimization_figure_3d_adj(fig, history):
"""Update the 3D adjoint live plot from the saved history."""
n = min(
len(history.get("values", [])),
len(history.get("coupling", [])),
len(history.get("reflectivity", [])),
len(history.get("collected_power", [])),
len(history.get("upwards_power", [])),
)
if n == 0:
clear_output(wait=True)
display(fig)
return fig
iters = np.arange(n)
values = np.array(history["values"][:n], dtype=float)
coupling = np.array(history["coupling"][:n], dtype=float)
reflectivity = np.array(history["reflectivity"][:n], dtype=float)
collected_power = np.array(history["collected_power"][:n], dtype=float)
upwards_power = np.array(history["upwards_power"][:n], dtype=float)
angular_spill = upwards_power - collected_power
center_coupling = coupling[:, idx_c_3d]
band_coupling = np.mean(coupling[:, mask_T_band_3d], axis=1)
center_reflection = reflectivity[:, idx_c_3d]
band_reflection = np.mean(reflectivity[:, mask_R_band_3d], axis=1)
center_collected = collected_power[:, idx_c_3d]
center_upwards = upwards_power[:, idx_c_3d]
center_spill = angular_spill[:, idx_c_3d]
fig.data = ()
# Objective
fig.add_trace(
go.Scatter(
x=iters,
y=values,
mode="lines+markers",
name="Objective",
),
row=1,
col=1,
)
# Coupling
fig.add_trace(
go.Scatter(
x=iters,
y=100 * center_coupling,
mode="lines+markers",
name="Center coupling",
),
row=1,
col=2,
)
fig.add_trace(
go.Scatter(
x=iters,
y=100 * band_coupling,
mode="lines+markers",
name="T-band mean coupling",
),
row=1,
col=2,
)
# Reflection
fig.add_trace(
go.Scatter(
x=iters,
y=100 * center_reflection,
mode="lines+markers",
name="Center reflection",
),
row=2,
col=1,
)
fig.add_trace(
go.Scatter(
x=iters,
y=100 * band_reflection,
mode="lines+markers",
name="R-band mean reflection",
),
row=2,
col=1,
)
# Radiation terms
fig.add_trace(
go.Scatter(
x=iters,
y=100 * center_collected,
mode="lines+markers",
name=f"Collected ±{collection_angle_deg:.0f}°",
),
row=2,
col=2,
)
fig.add_trace(
go.Scatter(
x=iters,
y=100 * center_upwards,
mode="lines+markers",
name="Upward power",
),
row=2,
col=2,
)
fig.add_trace(
go.Scatter(
x=iters,
y=100 * center_spill,
mode="lines+markers",
name="Angular spill",
),
row=2,
col=2,
)
clear_output(wait=True)
display(fig)
return fig
fig_live_3d_adj = make_live_optimization_figure_3d_adj()
print("3D adjoint live plot helpers are ready.")
3D adjoint live plot helpers are ready.
Run the 3D Adjoint Optimization¶
Finally, we run the staged 3D adjoint optimization. At each iteration, the 3D simulations are run to evaluate the objective and its adjoint gradient, and the grating parameters are then updated. The coupling and reflection spectra, upward-radiation results, objective terms, gradients, and current grating parameters are saved to the history .pkl file.
(Each iteration costs about 1 FlexCredit and takes about 9 minutes.)
# Run 3D adjoint optimization loop
RUN_3D_ADJ_OPTIMIZATION = True
# 3D adjoint history path
def make_um_tag_3d(value):
"""Make a short path-safe tag for a value in microns."""
return f"{float(value):+.3f}".replace("+", "p").replace("-", "m").replace(".", "p")
tag_3d_adj = (
f"iter{selected_iter_2d:04d}"
f"_ax{make_um_tag_3d(selected_apex_x_3d)}"
f"_ds{make_um_tag_3d(selected_dist_shift_3d)}"
)
HISTORY_3D_ADJ_PATH = Path(f"gc_3d_adj_optimization_history_{tag_3d_adj}.pkl")
# Save/load helpers
def to_numpy_tree_3d(obj):
"""Convert autograd/xarray/optax objects into NumPy/Python objects."""
if hasattr(obj, "_value"):
return to_numpy_tree_3d(obj._value)
if isinstance(obj, dict):
return {key: to_numpy_tree_3d(val) for key, val in obj.items()}
if isinstance(obj, list):
return [to_numpy_tree_3d(val) for val in obj]
if isinstance(obj, tuple):
values = [to_numpy_tree_3d(val) for val in obj]
if hasattr(obj, "_fields"):
return type(obj)(*values)
return tuple(values)
if isinstance(obj, np.ndarray):
if obj.dtype == object:
return np.array(
[to_numpy_tree_3d(val) for val in obj.tolist()],
dtype=object,
)
return np.array(obj)
if (
hasattr(obj, "values")
and not callable(obj.values)
and not isinstance(obj, (str, bytes))
):
return to_numpy_tree_3d(obj.values)
if isinstance(obj, (str, bytes, int, float, bool, type(None))):
return obj
if np.isscalar(obj):
return obj.item() if hasattr(obj, "item") else obj
try:
arr = np.asarray(obj)
except (TypeError, ValueError):
return repr(obj)
if arr.shape == ():
return arr.item()
if arr.dtype == object:
return np.array(
[to_numpy_tree_3d(val) for val in arr.tolist()],
dtype=object,
)
return np.array(arr)
def stage_schedule_metadata_3d_adj():
"""Return a save-friendly copy of the 3D adjoint stage schedule."""
return [
{
"stage_id": int(stage["stage_id"]),
"name": str(stage["name"]),
"learning_rate": float(stage["learning_rate"]),
"target_half_width_um": float(stage["target_half_width_um"]),
"weights": dict(stage["weights"]),
}
for stage in STAGES_3D_ADJ
]
def make_empty_history_3d_adj():
"""Create a fresh 3D adjoint optimization history."""
return {
"metadata": {
"lambda0_um": float(lambda0_um),
"selected_2d_iter": int(selected_iter_2d),
"apex_x_um": float(selected_apex_x_3d),
"dist_shift_um": float(selected_dist_shift_3d),
"stage_schedule_3d_adj": stage_schedule_metadata_3d_adj(),
"history_tag": tag_3d_adj,
},
"values": [],
"params": [],
"params_eval": [],
"params_current": np.array(params_selected_2d, dtype=float).copy(),
"gradients": [],
"grad_norm": [],
"reflectivity": [],
"coupling": [],
"power": [],
"peak_angle": [],
"collected_power": [],
"upwards_power": [],
"raw_terms": [],
"weighted_terms": [],
"summary": [],
"stage_id": [],
"stage_name": [],
"learning_rate": [],
"target_half_width_um": [],
"wavelengths_nm": [],
"weights": [],
"opt_state_3d_adj": None,
}
def ensure_history_keys_3d_adj(history):
"""Add any missing history keys."""
empty = make_empty_history_3d_adj()
for key, val in empty.items():
if key not in history:
history[key] = val
if "metadata" not in history or history["metadata"] is None:
history["metadata"] = {}
history["metadata"].update(
{
"lambda0_um": float(lambda0_um),
"selected_2d_iter": int(selected_iter_2d),
"apex_x_um": float(selected_apex_x_3d),
"dist_shift_um": float(selected_dist_shift_3d),
"stage_schedule_3d_adj": stage_schedule_metadata_3d_adj(),
"history_tag": tag_3d_adj,
}
)
return history
def save_history_3d_adj(history):
"""Save the 3D adjoint optimization history."""
with open(HISTORY_3D_ADJ_PATH, "wb") as f:
pickle.dump(to_numpy_tree_3d(history), f)
def load_history_3d_adj(path):
"""Load a saved 3D adjoint optimization history."""
with open(path, "rb") as f:
return pickle.load(f)
def get_current_params_from_history_3d_adj(history):
"""Return the latest updated 3D adjoint parameter vector."""
params_current = history.get("params_current", None)
if params_current is not None:
arr = np.array(params_current, dtype=float)
if arr.size > 0:
if arr.ndim == 1:
return arr.copy()
return arr[-1].copy()
if len(history.get("params", [])) > 0:
return np.array(history["params"][-1], dtype=float).copy()
return np.array(params_selected_2d, dtype=float).copy()
def peak_angles_from_power_3d(power_data):
"""
Extract the peak radiation direction from the center-wavelength 3D power map.
Returns:
theta_deg : polar angle away from +z
phi_deg : azimuth angle in the x-y plane
signed_x_angle_deg : signed angle projected onto the x-z plane
"""
if power_data is None:
return None
power_center, theta, phi = power_data
power_center = np.array(power_center, dtype=float)
theta = np.array(theta, dtype=float)
phi = np.array(phi, dtype=float)
if power_center.size == 0:
return None
i_theta, i_phi = np.unravel_index(
np.nanargmax(power_center),
power_center.shape,
)
theta_peak = float(theta[i_theta])
phi_peak = float(phi[i_phi])
signed_x_angle = np.arctan(np.tan(theta_peak) * np.cos(phi_peak))
return {
"theta_deg": theta_peak * 180.0 / np.pi,
"phi_deg": phi_peak * 180.0 / np.pi,
"signed_x_angle_deg": signed_x_angle * 180.0 / np.pi,
}
# Iteration summary helpers
def summarize_3d_adj_iteration_to_dict(
value,
reflectivity,
coupling,
collected_power,
upwards_power,
grad_norm,
peak_angle_diag=None,
):
"""Create a compact summary dictionary for one 3D adjoint iteration."""
angular_spill = upwards_power - collected_power
summary = {
"objective": float(value),
"grad_norm": float(grad_norm),
"center_coupling": float(coupling[idx_c_3d]),
"band_mean_coupling": float(np.mean(coupling[mask_T_band_3d])),
"center_reflectivity": float(reflectivity[idx_c_3d]),
"band_mean_reflectivity": float(np.mean(reflectivity[mask_R_band_3d])),
"center_collected_power": float(collected_power[idx_c_3d]),
"center_upwards_power": float(upwards_power[idx_c_3d]),
"center_angular_spill": float(angular_spill[idx_c_3d]),
"peak_theta_deg": np.nan,
"peak_phi_deg": np.nan,
"peak_signed_x_angle_deg": np.nan,
}
if peak_angle_diag is not None:
summary["peak_theta_deg"] = float(peak_angle_diag["theta_deg"])
summary["peak_phi_deg"] = float(peak_angle_diag["phi_deg"])
summary["peak_signed_x_angle_deg"] = float(
peak_angle_diag["signed_x_angle_deg"]
)
return summary
def print_3d_adj_iteration_summary(iter_idx, summary):
"""Print one compact 3D adjoint iteration summary."""
print(f"3D adjoint iteration {iter_idx}")
print(f" objective = {summary['objective']:.6e}")
print(f" grad norm = {summary['grad_norm']:.6e}")
print(f" center coupling = {100 * summary['center_coupling']:.4f}%")
print(f" T-band mean coupling = {100 * summary['band_mean_coupling']:.4f}%")
print(f" center reflection = {100 * summary['center_reflectivity']:.4f}%")
print(f" R-band mean reflection = {100 * summary['band_mean_reflectivity']:.4f}%")
print(f" center collected = {100 * summary['center_collected_power']:.4f}%")
print(f" upward power = {100 * summary['center_upwards_power']:.4f}%")
print(f" angular spill = {100 * summary['center_angular_spill']:.4f}%")
if not np.isnan(summary["peak_theta_deg"]):
print(" peak radiation direction:")
print(f" theta = {summary['peak_theta_deg']:.3f} deg")
print(f" phi = {summary['peak_phi_deg']:.3f} deg")
print(f" signed x-z angle = {summary['peak_signed_x_angle_deg']:.3f} deg")
# Load or initialize history
if HISTORY_3D_ADJ_PATH.exists():
history_3d_adj = load_history_3d_adj(HISTORY_3D_ADJ_PATH)
history_3d_adj = ensure_history_keys_3d_adj(history_3d_adj)
params_3d_adj = get_current_params_from_history_3d_adj(history_3d_adj)
print(f"Loaded 3D adjoint history from: {HISTORY_3D_ADJ_PATH}")
else:
history_3d_adj = make_empty_history_3d_adj()
params_3d_adj = np.array(params_selected_2d, dtype=float).copy()
print("Started a new 3D adjoint history.")
start_iter_3d_adj = len(history_3d_adj["values"])
stop_iter_3d_adj = TOTAL_ITERS_3D_ADJ
if start_iter_3d_adj < stop_iter_3d_adj:
stage_3d_adj = get_stage_for_iter_3d_adj(start_iter_3d_adj)
else:
stage_3d_adj = STAGES_3D_ADJ[-1]
set_stage_3d_adj(
stage_3d_adj,
verbose=False,
)
optimizer_3d_adj = optax.adam(learning_rate=learning_rate_3d_adj)
# The Adam state is kept continuous between stages.
if history_3d_adj.get("opt_state_3d_adj", None) is not None:
opt_state_3d_adj = history_3d_adj["opt_state_3d_adj"]
print("Loaded Adam state from 3D adjoint history.")
else:
opt_state_3d_adj = optimizer_3d_adj.init(params_3d_adj)
print("Adam state initialized from current 3D parameters.")
print()
print("3D adjoint setup:")
print(f" history path = {HISTORY_3D_ADJ_PATH}")
print(f" saved iterations = {len(history_3d_adj['values'])}")
print(f" selected 2D iteration = {selected_iter_2d}")
print(f" apex_x = {selected_apex_x_3d:+.4f} um")
print(f" dist_shift = {selected_dist_shift_3d:+.4f} um")
print(f" learning rate = {learning_rate_3d_adj}")
print(f" run optimization = {RUN_3D_ADJ_OPTIMIZATION}")
print()
# Prepare live plot
if "make_live_optimization_figure_3d_adj" not in globals():
raise NameError(
"make_live_optimization_figure_3d_adj is not defined. "
"Run the 3D live-plot helper cell first."
)
if "update_live_optimization_figure_3d_adj" not in globals():
raise NameError(
"update_live_optimization_figure_3d_adj is not defined. "
"Run the 3D live-plot helper cell first."
)
fig_live_3d_adj = make_live_optimization_figure_3d_adj()
# Show the current optimization history before the next 3D iteration starts.
update_live_optimization_figure_3d_adj(
fig_live_3d_adj,
history_3d_adj,
)
# Run optimization loop
if RUN_3D_ADJ_OPTIMIZATION:
run_is_complete_3d_adj = start_iter_3d_adj >= stop_iter_3d_adj
if run_is_complete_3d_adj:
print("3D adjoint optimization is already complete.")
print(f" saved iterations = {start_iter_3d_adj}")
print()
for iter_idx_3d_adj in range(start_iter_3d_adj, stop_iter_3d_adj):
stage_3d_adj = get_stage_for_iter_3d_adj(iter_idx_3d_adj)
if (
iter_idx_3d_adj == start_iter_3d_adj
or iter_idx_3d_adj == stage_3d_adj["start_iter"]
):
set_stage_3d_adj(stage_3d_adj, verbose=True)
optimizer_3d_adj = optax.adam(learning_rate=learning_rate_3d_adj)
# The Adam state is kept continuous between stages.
if opt_state_3d_adj is None:
opt_state_3d_adj = optimizer_3d_adj.init(params_3d_adj)
print(
f"Starting 3D adjoint {stage_3d_adj['name']} "
f"(stage {stage_3d_adj['stage_id']})"
)
print(
f" iteration range = "
f"{stage_3d_adj['start_iter']} ... "
f"{stage_3d_adj['stop_iter'] - 1}"
)
print(f" learning rate = {learning_rate_3d_adj}")
print(
f" target half-width = "
f"{1000 * stage_3d_adj['target_half_width_um']:.1f} nm"
)
print()
params_eval_3d_adj = np.array(params_3d_adj, dtype=float).copy()
task_name_3d_adj = (
f"adj3d_s{stage_3d_adj['stage_id']}_{tag_3d_adj}_it{iter_idx_3d_adj:04d}"
)
print("=" * 80)
print(f"Running {task_name_3d_adj}")
# With has_aux=True, this returns:
# (value, gradient), aux
(value_3d_adj, grad_3d_adj), aux_3d_adj = val_grad_3d_adj(
anp.array(params_eval_3d_adj),
task_name=task_name_3d_adj,
)
(
reflectivity_3d_adj,
coupling_3d_adj,
power_3d_adj,
_,
collected_power_3d_adj,
upwards_power_3d_adj,
raw_terms_3d_adj,
weighted_terms_3d_adj,
) = [to_numpy_tree_3d(item) for item in aux_3d_adj]
value_3d_adj = float(to_numpy_tree_3d(value_3d_adj))
grad_3d_adj = np.array(to_numpy_tree_3d(grad_3d_adj), dtype=float)
reflectivity_3d_adj = np.array(reflectivity_3d_adj, dtype=float)
coupling_3d_adj = np.array(coupling_3d_adj, dtype=float)
collected_power_3d_adj = np.array(collected_power_3d_adj, dtype=float)
upwards_power_3d_adj = np.array(upwards_power_3d_adj, dtype=float)
grad_norm_3d_adj = float(np.linalg.norm(grad_3d_adj))
peak_angle_diag_3d_adj = peak_angles_from_power_3d(power_3d_adj)
summary_iter_3d_adj = summarize_3d_adj_iteration_to_dict(
value=value_3d_adj,
reflectivity=reflectivity_3d_adj,
coupling=coupling_3d_adj,
collected_power=collected_power_3d_adj,
upwards_power=upwards_power_3d_adj,
grad_norm=grad_norm_3d_adj,
peak_angle_diag=peak_angle_diag_3d_adj,
)
# Store evaluated state before the optimizer update.
history_3d_adj["values"].append(value_3d_adj)
history_3d_adj["params"].append(params_eval_3d_adj)
history_3d_adj["params_eval"].append(params_eval_3d_adj)
history_3d_adj["gradients"].append(grad_3d_adj)
history_3d_adj["grad_norm"].append(grad_norm_3d_adj)
history_3d_adj["reflectivity"].append(reflectivity_3d_adj)
history_3d_adj["coupling"].append(coupling_3d_adj)
history_3d_adj["collected_power"].append(collected_power_3d_adj)
history_3d_adj["upwards_power"].append(upwards_power_3d_adj)
history_3d_adj["power"].append(power_3d_adj)
history_3d_adj["peak_angle"].append(peak_angle_diag_3d_adj)
history_3d_adj["raw_terms"].append(raw_terms_3d_adj)
history_3d_adj["weighted_terms"].append(weighted_terms_3d_adj)
history_3d_adj["summary"].append(summary_iter_3d_adj)
history_3d_adj["stage_id"].append(int(stage_3d_adj["stage_id"]))
history_3d_adj["stage_name"].append(str(stage_3d_adj["name"]))
history_3d_adj["learning_rate"].append(float(stage_3d_adj["learning_rate"]))
history_3d_adj["target_half_width_um"].append(
float(stage_3d_adj["target_half_width_um"])
)
history_3d_adj["wavelengths_nm"].append(np.array(lams_nm_3d, dtype=float))
history_3d_adj["weights"].append(dict(stage_3d_adj["weights"]))
# Maximize the objective by applying Adam to the negative gradient.
updates_3d_adj, opt_state_3d_adj = optimizer_3d_adj.update(
-grad_3d_adj,
opt_state_3d_adj,
params_eval_3d_adj,
)
params_3d_adj = optax.apply_updates(
params_eval_3d_adj,
updates_3d_adj,
)
history_3d_adj["params_current"] = np.array(
params_3d_adj,
dtype=float,
).copy()
history_3d_adj["opt_state_3d_adj"] = opt_state_3d_adj
# Save after every iteration.
save_history_3d_adj(history_3d_adj)
# Update live plot after every saved iteration.
# This clears the Tidy3D verbose output from the completed iteration.
update_live_optimization_figure_3d_adj(
fig_live_3d_adj,
history_3d_adj,
)
print_3d_adj_iteration_summary(
iter_idx_3d_adj,
summary_iter_3d_adj,
)
print(f"Saved 3D adjoint history to: {HISTORY_3D_ADJ_PATH}")
print()
if not run_is_complete_3d_adj:
save_history_3d_adj(history_3d_adj)
print("3D adjoint optimization finished.")
print(f" total saved iterations = {len(history_3d_adj['values'])}")
print(f" history path = {HISTORY_3D_ADJ_PATH}")
# Print the latest saved iteration directly from history.
if len(history_3d_adj["values"]) > 0:
final_iter_3d_adj = len(history_3d_adj["values"]) - 1
summary_3d_adj = history_3d_adj["summary"][-1]
print()
print(f"Final saved iteration {final_iter_3d_adj}")
print(f" history file = {HISTORY_3D_ADJ_PATH.name}")
print(
f" stage = {history_3d_adj['stage_id'][-1]} ({history_3d_adj['stage_name'][-1]})"
)
print(f" objective = {history_3d_adj['values'][-1]:.6e}")
print(f" grad norm = {history_3d_adj['grad_norm'][-1]:.6e}")
print(
f" center coupling = {100 * summary_3d_adj['center_coupling']:.4f}%"
)
print(
f" T-band mean coupling = {100 * summary_3d_adj['band_mean_coupling']:.4f}%"
)
print(
f" center reflection = {100 * summary_3d_adj['center_reflectivity']:.4f}%"
)
print(
f" R-band mean reflection = {100 * summary_3d_adj['band_mean_reflectivity']:.4f}%"
)
print(
f" upward power = {100 * summary_3d_adj['center_upwards_power']:.4f}%"
)
print(
f" collected cone power = {100 * summary_3d_adj['center_collected_power']:.4f}%"
)
print(
f" angular spill = {100 * summary_3d_adj['center_angular_spill']:.4f}%"
)
if not np.isnan(summary_3d_adj["peak_theta_deg"]):
print(
f" peak theta = {summary_3d_adj['peak_theta_deg']:.3f} deg"
)
print(
f" peak phi = {summary_3d_adj['peak_phi_deg']:.3f} deg"
)
print(
f" signed x-z angle = {summary_3d_adj['peak_signed_x_angle_deg']:.3f} deg"
)
else:
print("3D adjoint optimization skipped.")
print("Set RUN_3D_ADJ_OPTIMIZATION = True to run.")
3D adjoint optimization is already complete. saved iterations = 65 Final saved iteration 64 history file = gc_3d_adj_optimization_history_iter0349_axm2p000_dsp2p000.pkl stage = 4 (stage4_3d) objective = 2.708651e+01 grad norm = 7.056228e+01 center coupling = 20.8802% T-band mean coupling = 19.4620% center reflection = 0.1091% R-band mean reflection = 1.7228% upward power = 46.7384% collected cone power = 28.0242% angular spill = 18.7143% peak theta = 5.500 deg peak phi = 180.000 deg signed x-z angle = -5.500 deg
Final Inspection and Export¶
After completing the 3D adjoint optimization, we inspect the saved history and select the final iteration (64), which shows good overall optical performance. At this point, the coupling efficiency has nearly recovered the optimized 2D result, reaching 20.88% compared with 23.24% in 2D, while maintaining very low back-reflection (0.11%) and near-vertical radiation (peak angle of 5.5°). This gives us a final design with efficient, low-reflection, near-vertical free-space coupling.
We then plot its spectra, radiation pattern, and field profiles before exporting the design as an etch-opening GDS mask.
# Final inspection of selected 3D adjoint design
SELECT_3D_ADJ_ITER = 64
FINAL_VALIDATION_HALF_WIDTH_NM = (
25.0 # half-width of the band we want to inspect in the final validation
)
FINAL_VALIDATION_NUM_WL = 101 # number of wavelengths in the final validation band
FINAL_TARGET_HALF_WIDTH_NM = 2.5 # half-width of the target band from optimization
# Selected optimized design
if "history_3d_adj" not in globals() or len(history_3d_adj.get("values", [])) == 0:
raise ValueError(
"3D adjoint history is empty. Run the 3D adjoint optimization first."
)
if SELECT_3D_ADJ_ITER < 0 or SELECT_3D_ADJ_ITER >= len(history_3d_adj["values"]):
raise IndexError(
f"Selected iteration must be between 0 and {len(history_3d_adj['values']) - 1}."
)
iter_final_3d = int(SELECT_3D_ADJ_ITER)
params_final_3d = np.array(
history_3d_adj["params_eval"][iter_final_3d], dtype=float
).copy()
objective_final_3d = float(history_3d_adj["values"][iter_final_3d])
# Dense validation wavelength grid
lambda0_nm = lambda0_um * 1000.0
lams_final_nm = np.linspace(
lambda0_nm - FINAL_VALIDATION_HALF_WIDTH_NM,
lambda0_nm + FINAL_VALIDATION_HALF_WIDTH_NM,
FINAL_VALIDATION_NUM_WL,
)
lams_final_um = lams_final_nm / 1000.0
freqs_final_3d = td.C_0 / lams_final_um
idx_c_final_3d = int(np.argmin(np.abs(lams_final_nm - lambda0_nm)))
freq_c_final_3d = freqs_final_3d[idx_c_final_3d]
print("Final 3D validation:")
print(f" selected iteration = {iter_final_3d}")
print(f" wavelength range = {lams_final_nm[0]:.1f} to {lams_final_nm[-1]:.1f} nm")
print(f" wavelength points = {len(lams_final_nm)}")
print(f" wavelength spacing = {lams_final_nm[1] - lams_final_nm[0]:.3f} nm")
# Build final validation simulations
# The mode monitors use all 101 wavelengths.
# The top-field, far-field, xy-field, and xz-field monitors use 798 nm only.
freqs_3d_saved = freqs_3d.copy()
idx_c_3d_saved = idx_c_3d
try:
freqs_3d = freqs_final_3d
idx_c_3d = idx_c_final_3d
sim_mode_final_3d, sim_beam_final_3d = make_two_sims_3d_adj(
params_u=params_final_3d,
use_field_monitors=True,
adjoint_compatible=True,
)
finally:
freqs_3d = freqs_3d_saved
idx_c_3d = idx_c_3d_saved
task_tag_final_3d = f"final3d_iter{iter_final_3d:04d}"
print()
print("Running final mode-source and beam-source simulations...")
sim_mode_final_3d_data = web.run(
sim_mode_final_3d,
task_name=f"{task_tag_final_3d}_mode",
verbose=False,
)
sim_beam_final_3d_data = web.run(
sim_beam_final_3d,
task_name=f"{task_tag_final_3d}_beam",
verbose=False,
)
# Extract dense coupling and reflection spectra
def extract_mode_power_spectrum_3d(sim_data, direction="-"):
amp = sim_data["wg_mode"].amps.sel(direction=direction, mode_index=0)
freqs = np.asarray(amp.f.values, dtype=float)
power = np.abs(np.asarray(amp.values)) ** 2
lams_nm = td.C_0 / freqs * 1000.0
order = np.argsort(lams_nm)
return lams_nm[order], power[order]
lams_coupling_nm, coupling_final_3d = extract_mode_power_spectrum_3d(
sim_beam_final_3d_data
)
lams_reflection_nm, reflection_final_3d = extract_mode_power_spectrum_3d(
sim_mode_final_3d_data
)
if not np.allclose(lams_coupling_nm, lams_reflection_nm, atol=1e-9, rtol=0.0):
raise ValueError("Beam-source and mode-source wavelength grids do not match.")
lams_plot_final_nm = lams_coupling_nm
idx_c_plot_final_3d = int(np.argmin(np.abs(lams_plot_final_nm - lambda0_nm)))
target_mask_final_3d = (
np.abs(lams_plot_final_nm - lambda0_nm) <= FINAL_TARGET_HALF_WIDTH_NM + 1e-12
)
# Coupling and reflection spectra
fig, axes = plt.subplots(1, 2, figsize=(12, 4), constrained_layout=True)
axes[0].plot(
lams_plot_final_nm, 100 * coupling_final_3d, linewidth=1.8, label="Coupling"
)
axes[0].axvline(lambda0_nm, linestyle="--", label="center wavelength")
axes[0].axvspan(
lambda0_nm - FINAL_TARGET_HALF_WIDTH_NM,
lambda0_nm + FINAL_TARGET_HALF_WIDTH_NM,
alpha=0.15,
label=f"target band (±{FINAL_TARGET_HALF_WIDTH_NM:g} nm)",
)
axes[0].set_xlabel("Wavelength (nm)")
axes[0].set_ylabel("Coupling (%)")
axes[0].set_title("Beam-source coupling")
axes[0].grid(True, alpha=0.3)
axes[0].legend(loc="upper left", fontsize=10)
axes[1].plot(
lams_plot_final_nm, 100 * reflection_final_3d, linewidth=1.8, label="Reflection"
)
axes[1].axvline(lambda0_nm, linestyle="--", label="center wavelength")
axes[1].axvspan(
lambda0_nm - FINAL_TARGET_HALF_WIDTH_NM,
lambda0_nm + FINAL_TARGET_HALF_WIDTH_NM,
alpha=0.15,
label=f"target band (±{FINAL_TARGET_HALF_WIDTH_NM:g} nm)",
)
axes[1].set_xlabel("Wavelength (nm)")
axes[1].set_ylabel("Reflection (%)")
axes[1].set_title("Mode-source reflection")
axes[1].grid(True, alpha=0.3)
axes[1].legend(loc="upper left", fontsize=10)
fig.suptitle(f"Final 3D validation — iteration {iter_final_3d}", fontsize=14)
plt.show()
# Center-wavelength field plots
for monitor_name in ["field_xy", "field_xz"]:
fig, axes = plt.subplots(1, 2, figsize=(12, 4.5), constrained_layout=True)
sim_mode_final_3d_data.plot_field(
monitor_name, "Ey", "real", f=freq_c_final_3d, ax=axes[0]
)
axes[0].set_title(f"Mode source: Re{{Ey}}, {monitor_name}")
sim_beam_final_3d_data.plot_field(
monitor_name, "Ey", "real", f=freq_c_final_3d, ax=axes[1]
)
axes[1].set_title(f"Beam source: Re{{Ey}}, {monitor_name}")
fig.suptitle(
f"3D field at {lambda0_nm:.1f} nm — iteration {iter_final_3d}", fontsize=14
)
plt.show()
# Center-wavelength 3D far field
power_final_3d, theta_final_3d, phi_final_3d = _local_projected_power_3d_center(
sim_mode_final_3d_data,
sim_mode_final_3d,
)
power_final_3d = np.asarray(power_final_3d, dtype=float)
theta_final_3d = np.asarray(theta_final_3d, dtype=float)
phi_final_3d = np.asarray(phi_final_3d, dtype=float)
max_power_final_3d = np.nanmax(power_final_3d)
if not np.isfinite(max_power_final_3d) or max_power_final_3d <= 0:
raise ValueError(
"Cannot normalize the far-field plot because its maximum power is not positive."
)
power_final_norm_3d = power_final_3d / max_power_final_3d
phi_grid_final_3d, theta_grid_final_3d = np.meshgrid(phi_final_3d, theta_final_3d)
fig = plt.figure(figsize=(7, 6))
ax = fig.add_subplot(111, projection="polar")
pcm = ax.pcolormesh(
phi_grid_final_3d,
theta_grid_final_3d * 180 / np.pi,
100 * power_final_norm_3d,
shading="auto",
vmin=0,
vmax=100,
)
cbar = plt.colorbar(pcm, ax=ax, pad=0.10, shrink=0.8)
cbar.set_label("Normalized power (%)")
phi_ring = np.linspace(0, 2 * np.pi, 361)
ax.plot(
phi_ring,
collection_angle_deg * np.ones_like(phi_ring),
linestyle="--",
linewidth=1.2,
label=f"{collection_angle_deg:.0f}° collection cone",
)
ax.set_theta_zero_location("E")
ax.set_theta_direction(1)
ax.set_rlim(0, theta_final_3d[-1] * 180 / np.pi)
ax.set_rlabel_position(135)
ax.set_title(f"Final 3D far-field at {lambda0_nm:.1f} nm")
ax.legend(loc="upper right", bbox_to_anchor=(1.35, 1.10))
plt.tight_layout()
plt.show()
# Center-wavelength radiation metrics
dtheta = float(theta_final_3d[1] - theta_final_3d[0])
dphi = float(phi_final_3d[1] - phi_final_3d[0])
sin_theta = np.sin(theta_final_3d).reshape((-1, 1))
theta_collection_max = collection_angle_deg * np.pi / 180.0
collection_mask = (theta_final_3d >= 0.0) & (theta_final_3d <= theta_collection_max)
upward_final_3d = dtheta * dphi * np.sum(power_final_3d * sin_theta)
collected_final_3d = (
dtheta
* dphi
* np.sum(power_final_3d[collection_mask, :] * sin_theta[collection_mask, :])
)
spill_final_3d = upward_final_3d - collected_final_3d
# Peak radiation direction
peak_idx = np.unravel_index(np.nanargmax(power_final_3d), power_final_3d.shape)
peak_theta_rad = theta_final_3d[peak_idx[0]]
peak_phi_rad = phi_final_3d[peak_idx[1]]
peak_theta_deg = peak_theta_rad * 180 / np.pi
peak_phi_deg = peak_phi_rad * 180 / np.pi
signed_xz_angle_deg = (
np.arctan(np.tan(peak_theta_rad) * np.cos(peak_phi_rad)) * 180 / np.pi
)
# Final summary
print()
print("Final 3D design summary:")
print(f" iteration = {iter_final_3d}")
print(f" saved objective = {objective_final_3d:.6e}")
print(f" center coupling = {100 * coupling_final_3d[idx_c_plot_final_3d]:.4f}%")
print(
f" target-band coupling = {100 * np.mean(coupling_final_3d[target_mask_final_3d]):.4f}%"
)
print(
f" center reflection = {100 * reflection_final_3d[idx_c_plot_final_3d]:.4f}%"
)
print(
f" target-band reflection = {100 * np.mean(reflection_final_3d[target_mask_final_3d]):.4f}%"
)
print(f" upward power = {100 * upward_final_3d:.4f}%")
print(f" collected power = {100 * collected_final_3d:.4f}%")
print(f" angular spill = {100 * spill_final_3d:.4f}%")
print(f" peak theta = {peak_theta_deg:.3f} deg")
print(f" peak phi = {peak_phi_deg:.3f} deg")
print(f" signed x-z angle = {signed_xz_angle_deg:.3f} deg")
Final 3D validation: selected iteration = 64 wavelength range = 773.0 to 823.0 nm wavelength points = 101 wavelength spacing = 0.500 nm Running final mode-source and beam-source simulations...
Final 3D design summary: iteration = 64 saved objective = 2.708651e+01 center coupling = 20.8802% target-band coupling = 19.9553% center reflection = 0.1091% target-band reflection = 1.1506% upward power = 46.7384% collected power = 28.0242% angular spill = 18.7143% peak theta = 5.500 deg peak phi = 180.000 deg signed x-z angle = -5.500 deg
Export Final 3D Design to GDS¶
Finally, we export the selected optimized 3D design as a GDS etch-opening mask. The mask includes the optimized curved grating trenches and the side etch openings that define the waveguide and taper sidewalls, while the white space remains as suspended material.
We also save a CSV file containing the trench widths, radii, gaps, and placement parameters for reference.
# Export final 3D design to GDS as an etch-opening mask
# GDS layer settings
# Mask convention:
# layer 1 = regions written by e-beam / etched openings
# white space = remaining material, including the waveguide, taper,
# grating gaps, and supporting tethers.
LAYER_ETCH = 1
# Side trench width around the waveguide and taper.
# These etched trenches define the waveguide and taper sidewalls.
SIDE_TRENCH_WIDTH_UM = 1.0
# The taper side trenches extend slightly beyond the last grating trench.
TAPER_SIDE_END_AFTER_LAST_TRENCH_UM = 0.5
# The taper side trenches are interrupted at these relative positions.
# The unetched gaps remain as material tethers supporting the membrane.
TAPER_TETHER_CENTER_FRACTIONS = [0.33, 0.66]
TAPER_TETHER_WIDTH_UM = 0.45
# GDS coordinates are written in microns with 1 nm precision.
GDS_UNIT = 1e-6
GDS_PRECISION = 1e-9
# Use the final design selected and validated in the previous cell
if "iter_final_3d" not in globals() or "params_final_3d" not in globals():
raise ValueError("Run the final 3D validation cell before exporting the GDS.")
export_iter_3d = int(iter_final_3d)
params_export_3d = np.array(params_final_3d, dtype=float).copy()
# Use the same grating placement used during the 3D adjoint optimization.
export_apex_x_3d = float(ADJ_APEX_X_3D)
export_dist_shift_3d = float(ADJ_DIST_SHIFT_3D)
# Curved grating trench polygons
def gds_trench_polygons_from_params(params_u, apex_x_local, dist_shift_local):
"""Return the optimized curved grating trenches as GDS polygons."""
w_local, g_local = params_to_wgaps(anp.array(params_u))
# Radius of the first trench relative to the curvature center.
slot_rmin_local = get_slot_rmin_3d_adj(
apex_x_local,
dist_shift_local=dist_shift_local,
)
# Inner and outer radii of all optimized trench openings.
xL_local, xR_local = edges_from_wgaps(
w_local,
g_local,
slot_rmin=slot_rmin_local,
)
trench_polygons = []
for r_in, r_out in zip(xL_local, xR_local):
r_in = float(r_in)
r_out = float(r_out)
# Unit-circle vertices describing the inner and outer curved edges.
inner_unit = get_slot_unit_verts_3d_adj(apex_x_local, r_in)
outer_unit = get_slot_unit_verts_3d_adj(apex_x_local, r_out)
inner_verts = np.column_stack(
(
apex_x_local + r_in * inner_unit[:, 0],
r_in * inner_unit[:, 1],
)
)
# Reverse the outer edge so the complete polygon is ordered correctly.
outer_verts = np.column_stack(
(
apex_x_local + r_out * outer_unit[::-1, 0],
r_out * outer_unit[::-1, 1],
)
)
trench_polygons.append(np.concatenate((inner_verts, outer_verts), axis=0))
return (
trench_polygons,
np.array(xL_local, dtype=float),
np.array(xR_local, dtype=float),
np.array(w_local, dtype=float),
np.array(g_local, dtype=float),
)
# Side trench helpers
def offset_line_polygon(p0, p1, width_um, side):
"""
Build a constant-width trench along one device sidewall.
p0 and p1 define the inner edge of the etched trench.
The trench is offset outward from the suspended device.
"""
p0 = np.array(p0, dtype=float)
p1 = np.array(p1, dtype=float)
tangent = p1 - p0
length = np.linalg.norm(tangent)
if length <= 0:
raise ValueError("Cannot offset a zero-length sidewall segment.")
tangent /= length
if side == "top":
normal = np.array([-tangent[1], tangent[0]])
if normal[1] < 0:
normal = -normal
elif side == "bottom":
normal = np.array([tangent[1], -tangent[0]])
if normal[1] > 0:
normal = -normal
else:
raise ValueError("side must be 'top' or 'bottom'.")
q0 = p0 + width_um * normal
q1 = p1 + width_um * normal
return np.array([p0, p1, q1, q0], dtype=float)
def make_x_segments_with_gaps(x_start, x_end, gap_centers, gap_width):
"""
Split a side trench into etched segments while leaving specified
intervals unetched. These unetched intervals form material tethers.
"""
if x_end <= x_start:
return []
gaps = []
for xc in gap_centers:
g0 = max(x_start, xc - 0.5 * gap_width)
g1 = min(x_end, xc + 0.5 * gap_width)
if g1 > g0:
gaps.append((g0, g1))
gaps = sorted(gaps)
segments = []
current = x_start
for g0, g1 in gaps:
if g0 > current:
segments.append((current, g0))
current = max(current, g1)
if current < x_end:
segments.append((current, x_end))
return segments
# Waveguide and taper side trenches
def gds_waveguide_and_taper_side_trenches(params_u, apex_x_local, dist_shift_local):
"""
Return the side etch openings that define the waveguide and taper.
The straight waveguide has continuous side trenches. The taper side
trenches are segmented so the unetched gaps remain as membrane tethers.
"""
taper_end_x_full = get_taper_end_x_3d_adj(
apex_x_local=apex_x_local,
dist_shift_local=dist_shift_local,
params_u=params_u,
)
taper_half_width_full = get_taper_half_width_3d(taper_end_x_full)
# Find the physical x-position of the final grating trench.
w_local, g_local = params_to_wgaps(anp.array(params_u))
slot_rmin_local = get_slot_rmin_3d_adj(
apex_x_local,
dist_shift_local=dist_shift_local,
)
_, xR_local = edges_from_wgaps(
w_local,
g_local,
slot_rmin=slot_rmin_local,
)
last_trench_x = float(apex_x_local + np.array(xR_local, dtype=float)[-1])
# Stop the side trenches shortly after the last grating trench,
# but never extend them beyond the physical taper end.
taper_side_end_x = min(
float(taper_end_x_full),
float(last_trench_x + TAPER_SIDE_END_AFTER_LAST_TRENCH_UM),
)
if taper_side_end_x <= x_apex:
raise ValueError(
f"Invalid taper side trench end x = {taper_side_end_x:.4f} um."
)
# Linear taper half-width from the waveguide edge to the taper end.
taper_slope = (float(taper_half_width_full) - 0.5 * w_wg) / (
float(taper_end_x_full) - x_apex
)
def taper_half_width_at_x(x):
return 0.5 * w_wg + taper_slope * (x - x_apex)
# Straight waveguide side trenches
# Their inner edges lie exactly at y = +/- w_wg / 2.
x_wg_left = wg_center_x - 0.5 * wg_L
x_wg_right = x_apex
wg_top_trench = np.array(
[
[x_wg_left, 0.5 * w_wg],
[x_wg_right, 0.5 * w_wg],
[x_wg_right, 0.5 * w_wg + SIDE_TRENCH_WIDTH_UM],
[x_wg_left, 0.5 * w_wg + SIDE_TRENCH_WIDTH_UM],
],
dtype=float,
)
wg_bottom_trench = np.array(
[
[x_wg_left, -0.5 * w_wg - SIDE_TRENCH_WIDTH_UM],
[x_wg_right, -0.5 * w_wg - SIDE_TRENCH_WIDTH_UM],
[x_wg_right, -0.5 * w_wg],
[x_wg_left, -0.5 * w_wg],
],
dtype=float,
)
side_trench_polys = [
wg_top_trench,
wg_bottom_trench,
]
# Taper side trenches and membrane tethers
# Place the tether gaps at fixed fractions along the taper side trench.
tether_centers_x = [
x_apex + frac * (taper_side_end_x - x_apex)
for frac in TAPER_TETHER_CENTER_FRACTIONS
]
taper_segments = make_x_segments_with_gaps(
x_start=x_apex,
x_end=taper_side_end_x,
gap_centers=tether_centers_x,
gap_width=TAPER_TETHER_WIDTH_UM,
)
# Build the top and bottom etched side trenches for each remaining segment.
for x0, x1 in taper_segments:
y0_top = taper_half_width_at_x(x0)
y1_top = taper_half_width_at_x(x1)
y0_bottom = -taper_half_width_at_x(x0)
y1_bottom = -taper_half_width_at_x(x1)
side_trench_polys.append(
offset_line_polygon(
(x0, y0_top),
(x1, y1_top),
SIDE_TRENCH_WIDTH_UM,
side="top",
)
)
side_trench_polys.append(
offset_line_polygon(
(x0, y0_bottom),
(x1, y1_bottom),
SIDE_TRENCH_WIDTH_UM,
side="bottom",
)
)
return (
side_trench_polys,
taper_side_end_x,
last_trench_x,
)
# Build the etch-opening polygons
(
trench_polys_gds,
xL_export,
xR_export,
w_export,
g_export,
) = gds_trench_polygons_from_params(
params_export_3d,
apex_x_local=export_apex_x_3d,
dist_shift_local=export_dist_shift_3d,
)
(
side_trench_polys_gds,
taper_side_end_x_export,
last_trench_x_export,
) = gds_waveguide_and_taper_side_trenches(
params_export_3d,
apex_x_local=export_apex_x_3d,
dist_shift_local=export_dist_shift_3d,
)
# Create output file names
export_tag = (
f"iter{export_iter_3d:04d}"
f"_ax{make_um_tag_3d(export_apex_x_3d)}"
f"_ds{make_um_tag_3d(export_dist_shift_3d)}"
)
gds_path = Path(f"gc_etchmask_{export_tag}.gds")
csv_path = Path(f"gc_etchmask_{export_tag}_geometry_nm.csv")
# Create and write the GDS
lib = gdstk.Library(
unit=GDS_UNIT,
precision=GDS_PRECISION,
)
cell = lib.new_cell("GC_ETCH_MASK")
# Add the waveguide and taper side etch openings.
for poly in side_trench_polys_gds:
cell.add(
gdstk.Polygon(
poly,
layer=LAYER_ETCH,
)
)
# Add the optimized curved grating trench openings.
for poly in trench_polys_gds:
cell.add(
gdstk.Polygon(
poly,
layer=LAYER_ETCH,
)
)
lib.write_gds(str(gds_path))
# Save optimized grating geometry as a CSV file
# Each row corresponds to one grating trench. The gap column gives the
# material spacing following that trench; the final trench has no next gap.
gap_after_nm = np.full(len(w_export), np.nan)
n_gaps_to_store = min(
len(g_export),
len(w_export) - 1,
)
if n_gaps_to_store > 0:
gap_after_nm[:n_gaps_to_store] = 1000.0 * g_export[:n_gaps_to_store]
geometry_export_table = pd.DataFrame(
{
"trench_index": np.arange(len(w_export)),
"inner_radius_nm": 1000.0 * xL_export,
"trench_width_nm": 1000.0 * w_export,
"outer_radius_nm": 1000.0 * xR_export,
"gap_after_nm": gap_after_nm,
"apex_x_um": export_apex_x_3d,
"dist_shift_um": export_dist_shift_3d,
"side_trench_width_um": SIDE_TRENCH_WIDTH_UM,
"taper_side_end_x_um": taper_side_end_x_export,
"last_trench_x_um": last_trench_x_export,
}
)
geometry_export_table.to_csv(
csv_path,
index=False,
)
# Preview the exported GDS
# Re-open the saved file and plot the etch polygons as a quick check.
lib_check = gdstk.read_gds(str(gds_path))
top_cells = lib_check.top_level()
if len(top_cells) == 0:
raise RuntimeError("No top-level cells found in exported GDS.")
cell_check = top_cells[0]
fig, ax = plt.subplots(figsize=(10, 6))
for poly in cell_check.polygons:
if poly.layer != LAYER_ETCH:
continue
pts = np.array(poly.points)
ax.fill(
pts[:, 0],
pts[:, 1],
alpha=0.35,
edgecolor="k",
linewidth=0.5,
)
ax.set_aspect("equal")
ax.set_xlabel("x (µm)")
ax.set_ylabel("y (µm)")
ax.set_title("Exported GDS etch mask")
ax.grid(alpha=0.25)
plt.show()
# Export summary
print("GDS etch-mask export complete.")
print(f" selected 3D adj iter = {export_iter_3d}")
print(f" GDS file = {gds_path}")
print(f" geometry CSV = {csv_path}")
print()
print("GDS convention:")
print(f" layer {LAYER_ETCH}: etched openings written by e-beam")
print(" white space: remaining suspended material")
print()
print("Device geometry:")
print(f" apex x = {export_apex_x_3d:.3f} µm")
print(f" distance shift = {export_dist_shift_3d:.3f} µm")
print(f" side trench width = {SIDE_TRENCH_WIDTH_UM:.3f} µm")
print(f" tether gap width = {TAPER_TETHER_WIDTH_UM:.3f} µm")
print(f" taper side end x = {taper_side_end_x_export:.4f} µm")
print(f" last grating trench x = {last_trench_x_export:.4f} µm")
print()
print("Grating geometry:")
print(f" number of trenches = {len(w_export)}")
print(f" min trench width = {1000.0 * np.min(w_export):.3f} nm")
print(f" max trench width = {1000.0 * np.max(w_export):.3f} nm")
print(f" min gap = {1000.0 * np.min(g_export):.3f} nm")
print(f" max gap = {1000.0 * np.max(g_export):.3f} nm")
display(
geometry_export_table[
[
"trench_index",
"inner_radius_nm",
"trench_width_nm",
"gap_after_nm",
]
]
)
GDS etch-mask export complete. selected 3D adj iter = 64 GDS file = gc_etchmask_iter0064_axm2p000_dsp2p000.gds geometry CSV = gc_etchmask_iter0064_axm2p000_dsp2p000_geometry_nm.csv GDS convention: layer 1: etched openings written by e-beam white space: remaining suspended material Device geometry: apex x = -2.000 µm distance shift = 2.000 µm side trench width = 1.000 µm tether gap width = 0.450 µm taper side end x = 11.4856 µm last grating trench x = 10.9856 µm Grating geometry: number of trenches = 25 min trench width = 76.676 nm max trench width = 433.355 nm min gap = 77.925 nm max gap = 207.953 nm
| trench_index | inner_radius_nm | trench_width_nm | gap_after_nm | |
|---|---|---|---|---|
| 0 | 0 | 6000.000000 | 90.330011 | 158.370019 |
| 1 | 1 | 6248.700031 | 91.489936 | 135.330851 |
| 2 | 2 | 6475.520817 | 92.666183 | 143.866811 |
| 3 | 3 | 6712.053811 | 102.986324 | 143.504330 |
| 4 | 4 | 6958.544465 | 97.921413 | 143.558426 |
| 5 | 5 | 7200.024304 | 105.695195 | 134.481960 |
| 6 | 6 | 7440.201459 | 100.428300 | 151.017378 |
| 7 | 7 | 7691.647137 | 100.830447 | 124.187289 |
| 8 | 8 | 7916.664873 | 81.280542 | 160.327099 |
| 9 | 9 | 8158.272513 | 189.254170 | 172.253431 |
| 10 | 10 | 8519.780115 | 197.366896 | 170.734913 |
| 11 | 11 | 8887.881924 | 76.675556 | 77.925268 |
| 12 | 12 | 9042.482748 | 84.720014 | 161.886800 |
| 13 | 13 | 9289.089563 | 375.332618 | 151.572312 |
| 14 | 14 | 9815.994493 | 433.354537 | 92.625778 |
| 15 | 15 | 10341.974808 | 125.223390 | 207.952991 |
| 16 | 16 | 10675.151189 | 136.446947 | 133.235071 |
| 17 | 17 | 10944.833207 | 119.959337 | 108.872047 |
| 18 | 18 | 11173.664591 | 144.982289 | 116.343407 |
| 19 | 19 | 11434.990287 | 137.189444 | 181.768821 |
| 20 | 20 | 11753.948553 | 199.174560 | 192.548427 |
| 21 | 21 | 12145.671540 | 137.464639 | 123.680299 |
| 22 | 22 | 12406.816478 | 119.007983 | 118.829784 |
| 23 | 23 | 12644.654245 | 105.626966 | 115.660921 |
| 24 | 24 | 12865.942132 | 119.620162 | NaN |