1×8 MMI power splitter: particle swarm optimization versus adjoint inverse design#
inverse design
This notebook is inspired by the work Y. Yao, et al., "Compact and Low-Insertion-Loss 1×N Power Splitter in Silicon Photonics," J. Lightwave Technol. 39, 6253-6259 (2021) DOI: 10.1109/JLT.2021.3098346. The device is a 1×8 multimode interference (MMI) power splitter on a 220 nm silicon-on-insulator (SOI) platform. Its input and output tapers are made of 10 segments of equal length, and the widths at the segment boundaries are the design
variables. The paper optimizes these widths with a particle swarm optimization (PSO) driven by 3D FDTD simulations.
We reproduce the PSO of the paper and then optimize the same device with the adjoint method (inverse design), which also adjusts the length and the width of the MMI body. Both optimizations use the same FDTD simulation, the same starting point and the same number of iterations, so that the two methods can be compared on cost and on the quality of the result.
The device uses 220 nm SOI, 10 segments of 1 µm, an input width of 0.45 µm, widths bounded in [0.45, 1.20] µm and 8 outputs, at 1550 nm with the TE0 mode. The output tapers are centered at the N-fold self-imaging positions, \(y_q = (9/2 - q)\,W_\text{MMI}/8\), for the output ports \(q = 1, \dots, 8\).
The PSO is run with the Design plugin of Tidy3D. For another PSO example, see the particle swarm optimization of a polarization beam splitter. If you are new to adjoint optimization, start with the tutorial on automatic differentiation in Tidy3D and the inverse design lectures.

[1]:
import os
import time
import autograd.numpy as anp
from autograd.tracer import getval
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tidy3d as td
import tidy3d.web as web
import tidy3d.plugins.design as tdd
from tidy3d.plugins.autograd import adam, optimize
Device and Simulation#
The input taper starts as a 0.45 µm wide waveguide, changes width over 10 segments of 1 µm and ends at the MMI body. The eight output tapers are copies of the input taper rotated by 180 degrees. The widths \(w_{11}\) to \(w_{19}\) at the segment boundaries are the design variables, and \(w_{10} = 0.45\) µm is fixed. The width varies linearly inside each segment, and the last segment keeps the width \(w_{19}\). The tapers are built as PolySlab objects. The simulation uses a uniform \(\text{SiO}_2\) background (no substrate), a TE0 mode source, one ModeMonitor per output port, 10 grid points per wavelength and a symmetry plane at \(z = 0\).
The geometry functions accept both NumPy arrays and autograd arrays, so the same make_sim serves the PSO and the inverse design.
[2]:
# device (Yao et al. 2021, Sec. II and Table I)
N_OUT = 8
L_MMI0, W_MMI0 = 27.7, 11.35 # µm
SEG_LEN = 1.0 # µm, segment length
N_SEG = 10 # segments per taper
L_TAPER = N_SEG * SEG_LEN
W_IN = 0.45 # µm, first segment (input waveguide width), fixed
W_MIN, W_MAX = 0.45, 1.20 # µm, bounds of the free widths w11..w19
H_SI = 0.22 # µm
W_TABLE1 = np.array([0.45, 0.52, 0.68, 0.83, 0.85, 1.12, 0.87, 0.92, 0.91, 1.20]) # paper, 1x8
# materials
N_SI, N_SIO2 = 3.48, 1.444
SI = td.Medium(permittivity=N_SI**2, name="Si")
SIO2 = td.Medium(permittivity=N_SIO2**2, name="SiO2")
# simulation
LDA0 = 1.55
FREQ0 = td.C_0 / LDA0
SPW = 10 # grid points per wavelength
RUN_TIME = 5e-12
L_IN = 100.0 # access waveguides extended into the PML
X_MIN, X_SRC = -1.0, -0.5
Z_MIN, Z_MAX = -H_SI / 2 - 2.0, H_SI / 2 + 2.0 # uniform SiO2 cladding, 2 µm above and below the Si
Y_PAD = 2.0
SYMMETRY = (0, 0, 1) # TE0: Ey even at z = 0
MODE_SPEC = td.ModeSpec(num_modes=1, target_neff=N_SI)
K_OUT = np.arange(N_OUT)[::-1] - (N_OUT - 1) / 2 # +3.5 ... -3.5 (O1 at the top)
FOLDER = "mmi1x8_pso_vs_invdes"
[3]:
def y_out(W_mmi, anp=np):
"""Centers of the output tapers: N-fold self-imaging positions ((N + 1)/2 - q) * W_MMI / N, q = 1..N."""
return anp.array(K_OUT) * (W_mmi / N_OUT)
def taper_vertices(widths, anp=np):
"""Input taper + access waveguide, narrow end at x <= 0, wide end at x = L_TAPER."""
hw = anp.concatenate([widths[:1], widths, widths[-1:]]) / 2
xs = np.concatenate([[-L_IN], np.arange(N_SEG + 1) * SEG_LEN])
top = anp.stack([anp.array(xs), hw], axis=-1)
bot = anp.stack([anp.array(xs[::-1]), -hw[::-1]], axis=-1)
return anp.concatenate([top, bot], axis=0)
def taper_out_vertices(widths, y_center, L_mmi, anp=np):
"""Output taper: the input taper rotated by 180 degrees and placed at the MMI end."""
v = taper_vertices(widths, anp)
return anp.stack([(L_TAPER + L_mmi) + L_TAPER - v[:, 0], y_center - v[:, 1]], axis=-1)
def structures(widths, L_mmi, W_mmi, anp=np):
slab = (-H_SI / 2, H_SI / 2)
out = [td.Structure(geometry=td.PolySlab(vertices=taper_vertices(widths, anp), axis=2,
slab_bounds=slab), medium=SI),
td.Structure(geometry=td.Box.from_bounds(rmin=(L_TAPER, -W_mmi / 2, -H_SI / 2),
rmax=(L_TAPER + L_mmi, W_mmi / 2, H_SI / 2)),
medium=SI)]
yo = y_out(W_mmi, anp)
for i in range(N_OUT):
out.append(td.Structure(geometry=td.PolySlab(
vertices=taper_out_vertices(widths, yo[i], L_mmi, anp), axis=2, slab_bounds=slab),
medium=SI))
return out
def make_sim(widths, L_mmi=L_MMI0, W_mmi=W_MMI0, anp=np, field=False):
"""widths: the 10 segment widths w10..w19 (w10 = W_IN). Works with numpy or autograd arrays."""
L_val, W_val = float(getval(L_mmi)), float(getval(W_mmi))
X_MAX = L_TAPER + L_val + L_TAPER + 1.0
X_MON = X_MAX - 0.5
port = W_val / N_OUT
yo = np.asarray(y_out(W_val), dtype=float)
source = td.ModeSource(center=(X_SRC, 0, 0), size=(0, port, port),
source_time=td.GaussianPulse(freq0=FREQ0, fwidth=FREQ0 / 10),
direction="+", mode_spec=MODE_SPEC, mode_index=0)
monitors = [td.ModeMonitor(center=(X_MON, float(yc), 0), size=(0, port, port), freqs=[FREQ0],
mode_spec=MODE_SPEC, name=f"O{i + 1}") for i, yc in enumerate(yo)]
if field:
monitors += [td.FieldMonitor(center=(0, 0, 0), size=(td.inf, td.inf, 0), freqs=[FREQ0],
name="field_xy"),
td.FieldMonitor(center=(X_MON, 0, 0), size=(0, td.inf, td.inf), freqs=[FREQ0],
name="field_yz")]
return td.Simulation(
center=((X_MIN + X_MAX) / 2, 0, (Z_MIN + Z_MAX) / 2),
size=(X_MAX - X_MIN, W_val + Y_PAD, Z_MAX - Z_MIN),
grid_spec=td.GridSpec.auto(min_steps_per_wvl=SPW, wavelength=LDA0),
structures=structures(widths, L_mmi, W_mmi, anp),
sources=[source], monitors=monitors, run_time=RUN_TIME,
boundary_spec=td.BoundarySpec.all_sides(boundary=td.PML()),
medium=SIO2, symmetry=SYMMETRY)
def port_powers(sim_data):
return np.array([float(np.sum(np.abs(sim_data[f"O{i + 1}"].amps.sel(
mode_index=0, direction="+", f=FREQ0).values) ** 2)) for i in range(N_OUT)])
def fom(P):
"""Paper Eq. (1): FoM = sum(P_q) / sum((P_q - 1/N)^2)."""
P = np.asarray(P)
return float(P.sum() / np.sum((P - 1 / N_OUT) ** 2))
We plot the simulation with the widths of Table I of the paper, in the \(xy\) plane at \(z = 0\) and in the \(yz\) plane of the output monitors, and estimate the cost of one simulation.
[4]:
sim0 = make_sim(W_TABLE1, field=True)
fig, axs = plt.subplots(1, 2, figsize=(14, 3.5))
sim0.plot(z=0, ax=axs[0])
axs[0].set_aspect("auto")
sim0.plot(x=L_TAPER + L_MMI0 + L_TAPER + 0.5, ax=axs[1])
plt.show()
print("cost of one simulation (FlexCredit):",
web.estimate_cost(web.upload(sim0, task_name="mmi1x8_estimate", folder_name=FOLDER, verbose=False), verbose=False))
cost of one simulation (FlexCredit): 0.2966706872592254
Particle Swarm Optimization#
This is the method of the paper, run with the MethodParticleSwarm of the Tidy3D Design plugin, with the paper’s hyperparameters: 30 particles, inertia \(w = 1\), cognitive and social coefficients \(c_1 = c_2 = 2\), and widths bounded in [0.45, 1.20] µm. The objective is the paper’s figure of merit (Eq. 1),
where \(P_q\) is the TE0 power in output port \(q\). The numerator is the transmitted power and the denominator is the squared deviation from an equal split, so the FoM grows as the split becomes uniform and lossless.
Particles that leave the bounds are clipped to them (bh_strategy="nearest"), the velocity is limited to ±0.02 µm per iteration (velocity_clamp), and the initial positions and velocities are set explicitly (init_pos, init_velocity).
Each iteration runs the 30 simulations as one Batch. Every evaluation is appended to a CSV file, and pso_pre returns the stored value when a position has already been evaluated. The optimization is deterministic for a given seed, so a rerun replays the stored iterations without any simulation and only runs the missing ones; with the files saved with this notebook, the cell below
runs no simulation.
[5]:
N_PARTICLES, N_ITER = 30, 55
SEED = 1
DIM = N_SEG - 1
PSO_DIR = "assets/mmi1x8_pso"
PSO_CSV = os.path.join(PSO_DIR, "evaluations.csv")
os.makedirs(PSO_DIR, exist_ok=True)
WCOLS = [f"w1{k + 1}" for k in range(DIM)]
np.random.seed(SEED)
X0 = np.random.uniform(W_MIN, W_MAX, (N_PARTICLES, DIM)) # initial swarm; X0[0] is also the inverse design start
V0 = np.random.uniform(0, 1, (N_PARTICLES, DIM))
cache = {} # position -> FoM, for the iterations stored completely in the CSV
if os.path.exists(PSO_CSV):
stored = pd.read_csv(PSO_CSV).drop_duplicates(["iter", "particle"], keep="first")
complete = stored.groupby("iter").particle.count() == N_PARTICLES
for _, r in stored[stored["iter"].isin(complete[complete].index)].iterrows():
cache[tuple(np.round(r[WCOLS].to_numpy(float), 8))] = float(r.FoM)
print("stored evaluations:", len(cache), f"({len(cache) // N_PARTICLES} complete iterations)")
state_pso = {"n_eval": 0, "pending": []}
def pso_pre(**w):
pos = tuple(np.round([w[c] for c in WCOLS], 8))
state_pso["n_eval"] += 1
if pos in cache:
return cache[pos]
state_pso["pending"].append((state_pso["n_eval"] - 1, pos))
return make_sim(np.concatenate([[W_IN], pos]))
def pso_post(x):
if isinstance(x, float):
return x
P = port_powers(x)
idx, pos = state_pso["pending"].pop(0)
row = {"time": time.time(), "iter": idx // N_PARTICLES, "particle": idx % N_PARTICLES, "FoM": fom(P),
"sumP": float(P.sum()), "w10": W_IN, **dict(zip(WCOLS, pos))}
pd.DataFrame([row]).to_csv(PSO_CSV, mode="a", header=not os.path.exists(PSO_CSV), index=False)
cache[pos] = row["FoM"]
return row["FoM"]
stored evaluations: 1650 (55 complete iterations)
[6]:
method = tdd.MethodParticleSwarm(
n_particles=N_PARTICLES, n_iter=N_ITER, cognitive_coeff=2.0, social_coeff=2.0, weight=1.0, seed=SEED,
init_pos=X0, init_velocity=V0, bh_strategy="nearest", velocity_clamp=(-0.02, 0.02))
design_space = tdd.DesignSpace(
method=method, parameters=[tdd.ParameterFloat(name=c, span=(W_MIN, W_MAX)) for c in WCOLS],
task_name="mmi1x8_pso", folder_name=FOLDER, path_dir=PSO_DIR)
n_stored = len(cache)
t0 = time.time()
design_space.run(pso_pre, pso_post, verbose=False)
print(f"evaluations: {state_pso['n_eval']} | replayed from file: {n_stored} | simulated now: {len(cache) - n_stored} "
f"| wall time: {(time.time() - t0) / 60:.1f} min")
evaluations: 1650 | replayed from file: 1650 | simulated now: 0 | wall time: 0.0 min
[7]:
d = pd.read_csv(PSO_CSV).drop_duplicates(["iter", "particle"], keep="first")
d = d[d["iter"] < N_ITER].sort_values(["iter", "particle"])
per_iter = d.groupby("iter").FoM.max()
ibest = d.FoM.idxmax()
w_pso = d.loc[ibest, [f"w1{k}" for k in range(N_SEG)]].to_numpy(float)
fig, ax = plt.subplots(figsize=(7, 4.5))
ax.plot(per_iter.index + 1, per_iter.values, ".", color="0.75", label="best of iteration")
ax.plot(per_iter.index + 1, per_iter.cummax().values, "r-", lw=2, label="best so far")
ax.set_xlabel("iteration")
ax.set_ylabel("FoM (Eq. 1)")
ax.legend()
ax.grid(alpha=0.3)
plt.show()
print("PSO best FoM:", round(float(d.FoM[ibest]), 1), "at iteration", int(d["iter"][ibest]) + 1,
"| simulations:", len(d))
print("PSO widths w10..w19 (µm):", np.round(w_pso, 3))
PSO best FoM: 19212.5 at iteration 55 | simulations: 1650
PSO widths w10..w19 (µm): [0.45 0.746 0.994 0.937 0.949 0.953 0.911 0.861 0.878 1.2 ]
[8]:
sd_pso = web.run(make_sim(w_pso, field=True), task_name="mmi1x8_pso_best", folder_name=FOLDER, verbose=False)
P_pso = port_powers(sd_pso)
ports = [f"O{i + 1}" for i in range(N_OUT)]
display(pd.DataFrame({**dict(zip(ports, np.round(P_pso, 5))),
"insertion loss (dB)": round(-10 * np.log10(P_pso.sum()), 4),
"uniformity (dB)": round(-10 * np.log10(P_pso.min() / P_pso.max()), 4),
"FoM (Eq. 1)": round(fom(P_pso), 1)}, index=["PSO"]))
fig, axs = plt.subplots(1, 2, figsize=(14, 3.4))
sd_pso.plot_field("field_xy", "E", val="abs^2", f=FREQ0, ax=axs[0])
axs[0].set_aspect("auto")
sd_pso.plot_field("field_yz", "E", val="abs^2", f=FREQ0, ax=axs[1])
plt.show()
| O1 | O2 | O3 | O4 | O5 | O6 | O7 | O8 | insertion loss (dB) | uniformity (dB) | FoM (Eq. 1) | |
|---|---|---|---|---|---|---|---|---|---|---|---|
| PSO | 0.12145 | 0.12299 | 0.12281 | 0.12297 | 0.12297 | 0.12281 | 0.12299 | 0.12145 | 0.0857 | 0.0546 | 19212.4 |
Adjoint Inverse Design#
The second method optimizes the same device with gradients. Tidy3D computes the gradient of the objective with respect to all design parameters from one forward and one adjoint simulation, whatever the number of parameters. Here the parameters are the nine free widths plus \(L_\text{MMI}\) and \(W_\text{MMI}\), which are left free so that the MMI body and the position of the output tapers can adjust together with the taper profile. The widths are mapped to [0.45, 1.20] µm through a hyperbolic tangent, and the parameters are updated with Adam (learning rate 0.1) through the optimize function of the autograd plugin.
Objective. The paper’s FoM is not a good objective for a gradient method. It is a ratio whose denominator goes to zero at the solution, so the FoM and its gradient grow without bound as the split becomes uniform. Instead, we use the squared deviation from an equal split,
which is bounded, has zero gradient at the solution and keeps the meaning of the denominator of the FoM. The transmitted power \(\sum_q P_q\) does not appear explicitly, but since each \(P_q\) is pushed toward \(1/N\), maximizing \(J\) also drives \(\sum_q P_q\) toward 1. The FoM of Eq. 1 is still computed at every step for comparison with the PSO.
The starting point is the first particle of the PSO swarm, with \(L_\text{MMI} = 27.7\) µm and \(W_\text{MMI} = 11.35\) µm.
[9]:
NUM_STEPS, LEARNING_RATE = 55, 0.1
def params_from_widths(widths):
t = (np.asarray(widths) - W_MIN) / (W_MAX - W_MIN)
return np.arctanh(np.clip(2 * t - 1, -1 + 1e-12, 1 - 1e-12)) / np.pi
def unpack(params):
t = (anp.tanh(np.pi * anp.array(params[:DIM])) + 1.0) / 2.0
widths = anp.concatenate([anp.array([W_IN]), W_MIN + t * (W_MAX - W_MIN)])
return widths, params[DIM], params[DIM + 1]
params0 = np.concatenate([params_from_widths(X0[0]), [L_MMI0, W_MMI0]])
print("starting widths w11..w19 (µm):", np.round(X0[0], 4))
state = {"step": 0}
rows = []
def objective(params):
widths, L_mmi, W_mmi = unpack(params)
sd = web.run(make_sim(widths, L_mmi, W_mmi, anp=anp), task_name=f"mmi1x8_id_step{state['step']:03d}",
folder_name=FOLDER, verbose=False)
P = anp.stack([anp.sum(abs(sd[f"O{i + 1}"].amps.sel(mode_index=0, direction="+", f=FREQ0).values) ** 2)
for i in range(N_OUT)])
state["P"] = np.array([float(getval(p)) for p in P])
return -anp.sum((P - 1 / N_OUT) ** 2)
def record_step(params, grad, opt_state, step, objective_val):
w = np.array(unpack(params)[0])
rows.append({"time": time.time(), "step": step, "J": float(objective_val),
"FoM": fom(state["P"]), "sumP": float(state["P"].sum()),
"grad_norm": float(np.linalg.norm(grad)), "L_MMI": float(params[DIM]),
"W_MMI": float(params[DIM + 1]), **{f"w1{k}": float(w[k]) for k in range(N_SEG)},
**{f"P{q + 1}": float(state["P"][q]) for q in range(N_OUT)}})
state["step"] = step + 1
print(f"step {step + 1}/{NUM_STEPS}: J {float(objective_val):.3e} | FoM {fom(state['P']):.0f} | "
f"|grad| {np.linalg.norm(grad):.3g} | L_MMI {float(params[DIM]):.3f} | "
f"W_MMI {float(params[DIM + 1]):.3f}", flush=True)
starting widths w11..w19 (µm): [0.7628 0.9902 0.4501 0.6767 0.5601 0.5193 0.5897 0.7092 0.7476]
[10]:
t0 = time.time()
optimize(objective, params0=params0, optimizer=adam(learning_rate=LEARNING_RATE), num_steps=NUM_STEPS,
callback=record_step, direction="max")
print(f"inverse design wall time: {(time.time() - t0) / 3600:.2f} h")
08:57:38 UTC WARNING: Simulation final field decay value of 0.000164 is greater
than the simulation shutoff threshold of 1e-05. Consider running
the simulation again with a larger 'run_time' duration for more
accurate results. step 1/55: J -1.162e-02 | FoM 63 | |grad| 0.09 | L_MMI 27.700 | W_MMI 11.35009:01:56 UTC WARNING: Simulation final field decay value of 3.24e-05 is greater
than the simulation shutoff threshold of 1e-05. Consider running
the simulation again with a larger 'run_time' duration for more
accurate results. step 2/55: J -5.192e-03 | FoM 155 | |grad| 0.0415 | L_MMI 27.600 | W_MMI 11.450step 3/55: J -5.088e-03 | FoM 163 | |grad| 0.0678 | L_MMI 27.539 | W_MMI 11.518step 4/55: J -2.331e-03 | FoM 371 | |grad| 0.03 | L_MMI 27.475 | W_MMI 11.498step 5/55: J -2.213e-03 | FoM 392 | |grad| 0.0287 | L_MMI 27.428 | W_MMI 11.465step 6/55: J -1.280e-03 | FoM 703 | |grad| 0.0183 | L_MMI 27.397 | W_MMI 11.427step 7/55: J -1.004e-03 | FoM 908 | |grad| 0.00817 | L_MMI 27.377 | W_MMI 11.386step 8/55: J -6.077e-04 | FoM 1539 | |grad| 0.00343 | L_MMI 27.365 | W_MMI 11.348step 9/55: J -7.577e-04 | FoM 1230 | |grad| 0.0107 | L_MMI 27.355 | W_MMI 11.314step 10/55: J -7.019e-04 | FoM 1337 | |grad| 0.0108 | L_MMI 27.350 | W_MMI 11.287step 11/55: J -4.483e-04 | FoM 2118 | |grad| 0.00537 | L_MMI 27.349 | W_MMI 11.268step 12/55: J -4.110e-04 | FoM 2316 | |grad| 0.00437 | L_MMI 27.349 | W_MMI 11.251step 13/55: J -4.183e-04 | FoM 2273 | |grad| 0.00687 | L_MMI 27.350 | W_MMI 11.237step 14/55: J -4.060e-04 | FoM 2336 | |grad| 0.00694 | L_MMI 27.349 | W_MMI 11.226step 15/55: J -3.017e-04 | FoM 3161 | |grad| 0.00404 | L_MMI 27.347 | W_MMI 11.217step 16/55: J -2.618e-04 | FoM 3651 | |grad| 0.0028 | L_MMI 27.343 | W_MMI 11.210step 17/55: J -2.305e-04 | FoM 4162 | |grad| 0.0019 | L_MMI 27.339 | W_MMI 11.206step 18/55: J -2.666e-04 | FoM 3597 | |grad| 0.00172 | L_MMI 27.334 | W_MMI 11.202step 19/55: J -2.831e-04 | FoM 3382 | |grad| 0.00154 | L_MMI 27.329 | W_MMI 11.200step 20/55: J -2.857e-04 | FoM 3353 | |grad| 0.00164 | L_MMI 27.322 | W_MMI 11.198step 21/55: J -2.658e-04 | FoM 3611 | |grad| 0.00159 | L_MMI 27.315 | W_MMI 11.197step 22/55: J -2.363e-04 | FoM 4072 | |grad| 0.00158 | L_MMI 27.308 | W_MMI 11.196step 23/55: J -2.327e-04 | FoM 4139 | |grad| 0.00181 | L_MMI 27.301 | W_MMI 11.197step 24/55: J -2.326e-04 | FoM 4141 | |grad| 0.00201 | L_MMI 27.294 | W_MMI 11.198step 25/55: J -2.224e-04 | FoM 4333 | |grad| 0.00216 | L_MMI 27.288 | W_MMI 11.201step 26/55: J -2.108e-04 | FoM 4577 | |grad| 0.00211 | L_MMI 27.282 | W_MMI 11.205step 27/55: J -1.956e-04 | FoM 4941 | |grad| 0.0019 | L_MMI 27.277 | W_MMI 11.209step 28/55: J -1.687e-04 | FoM 5741 | |grad| 0.00167 | L_MMI 27.272 | W_MMI 11.215step 29/55: J -1.503e-04 | FoM 6453 | |grad| 0.00148 | L_MMI 27.268 | W_MMI 11.221step 30/55: J -1.543e-04 | FoM 6284 | |grad| 0.00139 | L_MMI 27.264 | W_MMI 11.227step 31/55: J -1.476e-04 | FoM 6566 | |grad| 0.00121 | L_MMI 27.259 | W_MMI 11.234step 32/55: J -1.395e-04 | FoM 6945 | |grad| 0.000734 | L_MMI 27.254 | W_MMI 11.241step 33/55: J -1.377e-04 | FoM 7028 | |grad| 0.000496 | L_MMI 27.249 | W_MMI 11.248step 34/55: J -1.412e-04 | FoM 6847 | |grad| 0.000756 | L_MMI 27.245 | W_MMI 11.254step 35/55: J -1.465e-04 | FoM 6592 | |grad| 0.00101 | L_MMI 27.240 | W_MMI 11.259step 36/55: J -1.502e-04 | FoM 6428 | |grad| 0.00114 | L_MMI 27.236 | W_MMI 11.263step 37/55: J -1.494e-04 | FoM 6463 | |grad| 0.00118 | L_MMI 27.233 | W_MMI 11.266step 38/55: J -1.452e-04 | FoM 6657 | |grad| 0.00116 | L_MMI 27.230 | W_MMI 11.269step 39/55: J -1.360e-04 | FoM 7115 | |grad| 0.00109 | L_MMI 27.228 | W_MMI 11.270step 40/55: J -1.274e-04 | FoM 7607 | |grad| 0.000963 | L_MMI 27.227 | W_MMI 11.270step 41/55: J -1.240e-04 | FoM 7829 | |grad| 0.000832 | L_MMI 27.225 | W_MMI 11.270step 42/55: J -1.246e-04 | FoM 7794 | |grad| 0.000802 | L_MMI 27.225 | W_MMI 11.269step 43/55: J -1.261e-04 | FoM 7703 | |grad| 0.000801 | L_MMI 27.224 | W_MMI 11.267step 44/55: J -1.277e-04 | FoM 7609 | |grad| 0.000741 | L_MMI 27.224 | W_MMI 11.265step 45/55: J -1.254e-04 | FoM 7751 | |grad| 0.000623 | L_MMI 27.223 | W_MMI 11.264step 46/55: J -1.205e-04 | FoM 8070 | |grad| 0.000506 | L_MMI 27.223 | W_MMI 11.262step 47/55: J -1.168e-04 | FoM 8323 | |grad| 0.000424 | L_MMI 27.223 | W_MMI 11.260step 48/55: J -1.127e-04 | FoM 8624 | |grad| 0.000385 | L_MMI 27.223 | W_MMI 11.258step 49/55: J -1.099e-04 | FoM 8848 | |grad| 0.000388 | L_MMI 27.223 | W_MMI 11.256step 50/55: J -1.104e-04 | FoM 8803 | |grad| 0.000396 | L_MMI 27.223 | W_MMI 11.253step 51/55: J -1.117e-04 | FoM 8692 | |grad| 0.000349 | L_MMI 27.222 | W_MMI 11.251step 52/55: J -1.112e-04 | FoM 8738 | |grad| 0.000286 | L_MMI 27.222 | W_MMI 11.249step 53/55: J -1.089e-04 | FoM 8924 | |grad| 0.000216 | L_MMI 27.222 | W_MMI 11.248
step 54/55: J -1.036e-04 | FoM 9389 | |grad| 0.000208 | L_MMI 27.222 | W_MMI 11.246
step 55/55: J -1.006e-04 | FoM 9675 | |grad| 0.000305 | L_MMI 27.222 | W_MMI 11.245
inverse design wall time: 2.63 h
[11]:
h = pd.DataFrame(rows)
jbest = h.J.idxmax()
w_id = h.loc[jbest, [f"w1{k}" for k in range(N_SEG)]].to_numpy(float)
L_id, W_id = float(h.L_MMI[jbest]), float(h.W_MMI[jbest])
fig, axs = plt.subplots(1, 2, figsize=(13, 4.2))
axs[0].plot(np.arange(len(h)) + 1, -h.J, "r.-")
axs[0].set_yscale("log")
axs[0].set_xlabel("step")
axs[0].set_ylabel(r"$-J = \sum_q (P_q - 1/N)^2$")
axs[0].grid(alpha=0.3, which="both")
axs[1].plot(np.arange(len(h)) + 1, h.L_MMI, "b.-")
axs[1].set_ylabel("L_MMI (µm)", color="b")
ax2 = axs[1].twinx()
ax2.plot(np.arange(len(h)) + 1, h.W_MMI, "g.-")
ax2.set_ylabel("W_MMI (µm)", color="g")
axs[1].set_xlabel("step")
axs[1].grid(alpha=0.3)
plt.show()
print("inverse design best J:", f"{float(h.J[jbest]):.3e}", "at step", int(jbest) + 1, "| simulations:", 2 * len(h))
print("widths w10..w19 (µm):", np.round(w_id, 3), "| L_MMI:", round(L_id, 3), "| W_MMI:", round(W_id, 3))
inverse design best J: -1.006e-04 at step 55 | simulations: 110
widths w10..w19 (µm): [0.45 1.051 1.165 0.643 1.136 1.13 0.834 1.188 1.196 1.198] | L_MMI: 27.222 | W_MMI: 11.245
[12]:
sd_id = web.run(make_sim(w_id, L_id, W_id, field=True), task_name="mmi1x8_id_best", folder_name=FOLDER, verbose=False)
P_id = h.loc[jbest, [f"P{q + 1}" for q in range(N_OUT)]].to_numpy(float)
display(pd.DataFrame({**dict(zip(ports, np.round(P_id, 5))),
"insertion loss (dB)": round(-10 * np.log10(P_id.sum()), 4),
"uniformity (dB)": round(-10 * np.log10(P_id.min() / P_id.max()), 4),
"FoM (Eq. 1)": round(fom(P_id), 1)}, index=["inverse design"]))
fig, axs = plt.subplots(1, 2, figsize=(14, 3.4))
sd_id.plot_field("field_xy", "E", val="abs^2", f=FREQ0, ax=axs[0])
axs[0].set_aspect("auto")
sd_id.plot_field("field_yz", "E", val="abs^2", f=FREQ0, ax=axs[1])
plt.show()
| O1 | O2 | O3 | O4 | O5 | O6 | O7 | O8 | insertion loss (dB) | uniformity (dB) | FoM (Eq. 1) | |
|---|---|---|---|---|---|---|---|---|---|---|---|
| inverse design | 0.12121 | 0.12057 | 0.1212 | 0.12364 | 0.12364 | 0.1212 | 0.12057 | 0.12121 | 0.1178 | 0.109 | 9674.6 |
Comparison#
It is interesting to note that both methods converge in a similar way during the first iterations. The inverse design is much cheaper, since each step costs only 2 simulations (one forward and one adjoint), but because it follows the gradient from the starting point, it can get trapped in a local minimum. The PSO is more expensive, with 30 simulations per iteration, but since its particles are spread over the design space, it can find other minima.
[13]:
p0 = d[(d["iter"] == 0) & (d.particle == 0)].iloc[0]
pso_F = np.concatenate([[p0.FoM], per_iter.cummax().values])
pso_J = np.concatenate([[-p0.sumP / p0.FoM], (-d.sumP / d.FoM).groupby(d["iter"]).max().cummax().values])
x_pso, x_id = np.arange(len(pso_F)), np.arange(len(h))
fig, ax = plt.subplots(figsize=(7, 4.5))
ax.plot(x_pso, pso_F, "r-", lw=2, label="PSO (best so far)")
ax.plot(x_id, h.FoM, "b.-", label="inverse design")
ax.set_xlabel("iteration")
ax.set_ylabel("FoM (Eq. 1)")
ax.legend()
ax.grid(alpha=0.3)
plt.show()
fig, ax = plt.subplots(figsize=(7, 4.5))
ax.plot(x_pso, -pso_J, "r-", lw=2, label="PSO (best so far)")
ax.plot(x_id, -h.J, "b.-", label="inverse design")
ax.set_yscale("log")
ax.set_xlabel("iteration")
ax.set_ylabel(r"$-J = \sum_q (P_q - 1/N)^2$")
ax.legend()
ax.grid(alpha=0.3, which="both")
plt.show()
[14]:
summary = pd.DataFrame({
"PSO": {"iterations": N_ITER, "simulations": int(len(d)), "FoM (Eq. 1)": round(fom(P_pso), 1),
"-J": f"{np.sum((P_pso - 1 / N_OUT) ** 2):.2e}",
"insertion loss (dB)": round(-10 * np.log10(P_pso.sum()), 4),
"uniformity (dB)": round(-10 * np.log10(P_pso.min() / P_pso.max()), 4),
"L_MMI (µm)": L_MMI0, "W_MMI (µm)": W_MMI0},
"inverse design": {"iterations": len(h), "simulations": int(2 * len(h)), "FoM (Eq. 1)": round(fom(P_id), 1),
"-J": f"{np.sum((P_id - 1 / N_OUT) ** 2):.2e}",
"insertion loss (dB)": round(-10 * np.log10(P_id.sum()), 4),
"uniformity (dB)": round(-10 * np.log10(P_id.min() / P_id.max()), 4),
"L_MMI (µm)": round(L_id, 3), "W_MMI (µm)": round(W_id, 3)}})
summary
| PSO | inverse design | |
|---|---|---|
| iterations | 55 | 55 |
| simulations | 1650 | 110 |
| FoM (Eq. 1) | 19212.4 | 9674.6 |
| -J | 5.10e-05 | 1.01e-04 |
| insertion loss (dB) | 0.0857 | 0.1178 |
| uniformity (dB) | 0.0546 | 0.109 |
| L_MMI (µm) | 27.7 | 27.222 |
| W_MMI (µm) | 11.35 | 11.245 |