8×8 Thermo-Optic Beneš Switch

A Beneš network [1] connects inputs to outputs through stages of two-by-two switches. It is rearrangeably non-blocking: every permutation of inputs to outputs can be realized by some setting of the switches. In silicon photonics each 2×2 switch is usually a Mach–Zehnder interferometer (MZI) tuned by heaters [2].
In this example we lay out a complete 8×8 thermo-optic Beneš switch and simulate the laid-out chip as a circuit. The chip has:
- 5 stages of 4 MZIs (20 MZIs, 40 heaters)
- 16 waveguide crossings in the shuffles between stages
- 16 grating couplers on a 127 µm fiber-array pitch
- 41 bond pads (one per heater plus a shared ground)
The simulation is post-layout: every waveguide, bend, crossing and grating coupler enters the S matrix with its drawn length. Switch states are applied as per-reference model updates, so all 20 MZIs share one cell and nothing is rebuilt between simulations.
The notebook follows these steps:
- Check the PDK building blocks: directional coupler, heater, crossing and grating coupler.
- Build one thermo-optic MZI switch and switch it with a temperature update.
- Route a permutation through the abstract Beneš network.
- Lay out the full chip, step by step.
- Simulate the chip: set the switch states, route permutations and sweep the wavelength.
We use SiPhoPDK, a demonstration PDK for PhotonForge: a synthetic O-band (1310 nm) silicon-on-insulator process whose components all carry analytic or measured models, so everything runs locally. Install it with pip install siphopdk-forge. SiPhoPDK is not a foundry PDK and must not be used for a tape-out.
import itertoolsimport mathimport warnings
import matplotlib.pyplot as pltimport numpy as npimport photonforge as pfimport siphopdk as spimport tidy3d as tdfrom photonforge.live_viewer import LiveViewerfrom siphopdk import _calibration as cal
viewer = LiveViewer()LiveViewer started at http://127.0.0.1:65376. Call its 'stop()' method to free the port.We load the technology and use the local mode solver for the waveguide models.
tech = sp.siphopdk()pf.config.default_technology = techpf.config.use_local_mode_solver = True
wavelength_0 = pf.C_0 / cal.REF_FREQUENCY # design wavelength, 1.31 µmf0 = [cal.REF_FREQUENCY] # single-frequency simulationswavelengths = np.linspace(1.29, 1.33, 41)frequencies = pf.C_0 / wavelengthsprint(f"Design wavelength: {wavelength_0 * 1e3:.0f} nm")Design wavelength: 1310 nmEvery waveguide with bends on the chip is drawn by route_wire, which passes a Manhattan path to route. A waypoint at the middle of each inner segment, with that segment’s direction, makes the route turn exactly at the given corners. The route gets one AnalyticWaveguideModel with the PDK’s strip-waveguide constants. The model measures the drawn length with route_length and adds the PDK bend loss once per corner.
wire_spec = tech.ports["SI_STRIP_O"]
def heading(a, b): """Direction of the Manhattan segment from a to b, in degrees.""" return round(math.degrees(math.atan2(b[1] - a[1], b[0] - a[0])) / 90) * 90 % 360
def route_wire(vertices, name, radius=10.0): """Strip waveguide along a Manhattan path, with ports P0 at the first vertex and P1 at the last.""" v = [tuple(map(float, p)) for p in vertices] waypoints = [ ((v[k][0] + v[k + 1][0]) / 2, (v[k][1] + v[k + 1][1]) / 2, heading(v[k], v[k + 1])) for k in range(1, len(v) - 2) ] model = pf.AnalyticWaveguideModel( n_eff=cal.N_EFF_STRIP, n_group=cal.N_GROUP_STRIP, propagation_loss=cal.LOSS_STRIP, extra_loss=cal.LOSS_BEND_90 * (len(v) - 2), reference_frequency=cal.REF_FREQUENCY, ) return pf.parametric.route( port1=pf.Port(v[0], (heading(v[0], v[1]) + 180) % 360, wire_spec), port2=pf.Port(v[-1], heading(v[-2], v[-1]), wire_spec), waypoints=waypoints, radius=radius, bend_kwargs={"euler_fraction": 0.2}, model=model, technology=tech, name=name, )Building blocks
Section titled “Building blocks”Directional coupler
Section titled “Directional coupler”The 2×2 splitter of each MZI is the PDK directional coupler, designed for a 50:50 split at 1310 nm.
dc = sp.directional_coupler(technology=tech)viewer(dc)Its analytic model splits the power equally, with 0.1 dB excess loss:
s_dc = dc.s_matrix(frequencies, show_progress=False)k0 = len(wavelengths) // 2 # index of 1310 nmbar, cross = (abs(s_dc["P0@0", f"{p}@0"][k0]) ** 2 for p in ("P2", "P3"))print(f"P0 -> P2: {bar:.3f}, P0 -> P3: {cross:.3f}, excess loss {-10 * np.log10(bar + cross):.2f} dB")P0 -> P2: 0.489, P0 -> P3: 0.489, excess loss 0.10 dBThermal phase shifter
Section titled “Thermal phase shifter”Each MZI arm has a 300 µm TiN heater over the waveguide.
heater_length = 300.0heater = sp.thermal_phase_shifter(length=heater_length, heater_width=2.0, technology=tech)viewer(heater)The heater’s model, AnalyticWaveguideModel, has a temperature parameter and adds to the effective index. A π phase shift therefore needs
T0 = 293.0 # ambient temperature (K)dT_pi = wavelength_0 / (2 * heater_length * cal.DN_DT)print(f"dn/dT = {cal.DN_DT:.2e} /K -> ΔT_π = {dT_pi:.2f} K on a {heater_length:.0f} µm heater")dn/dT = 1.86e-04 /K -> ΔT_π = 11.74 K on a 300 µm heaterWe can check this by updating the model’s temperature and reading the phase of the transmitted light:
heater_model = heater.active_modeltemperatures = np.linspace(0, 2 * dT_pi, 41)phase = []for dT in temperatures: heater_model.update(temperature=T0 + dT) s = heater.s_matrix(f0, show_progress=False) phase.append(np.angle(s["P0@0", "P1@0"][0]))heater_model.update(temperature=T0) # back to ambientphase = np.unwrap(phase)phase = abs(phase - phase[0])
fig, ax = plt.subplots(figsize=(5, 3.2), tight_layout=True)ax.plot(temperatures, phase / np.pi)ax.axvline(dT_pi, color="gray", ls="--", lw=1)ax.set(xlabel="ΔT (K)", ylabel="Added phase (π rad)", title="Heater phase at 1310 nm")ax.grid(alpha=0.3)
There is one subtlety. The model adds a fixed amount to the phase, so the thermal phase it produces is the same at every wavelength. Physically the phase is , which gets smaller at longer wavelengths:
for wl in (1.29, 1.31, 1.33): phi = [] for dT in (0, dT_pi): heater_model.update(temperature=T0 + dT) s = heater.s_matrix([pf.C_0 / wl], show_progress=False) phi.append(np.angle(s["P0@0", "P1@0"][0])) heater_model.update(temperature=T0) model_phase = abs(np.angle(np.exp(1j * (phi[0] - phi[1])))) print(f"{wl * 1e3:.0f} nm: model {model_phase / np.pi:.3f} π, physical {wavelength_0 / wl:.3f} π")1290 nm: model 1.000 π, physical 1.016 π1310 nm: model 1.000 π, physical 1.000 π1330 nm: model 1.000 π, physical 0.985 πAt a single wavelength this does not matter. For spectra we restore the physical behavior by solving one frequency at a time and scaling the heater’s temperature step by (see solve below).
Crossing and grating coupler
Section titled “Crossing and grating coupler”The shuffles between stages need waveguide crossings, and the chip couples to fibers through grating couplers. Both come with models from the PDK.
crossing = sp.crossing(technology=tech)gc = sp.grating_coupler(technology=tech)
s_x = crossing.s_matrix(f0, show_progress=False)s_gc = gc.s_matrix(f0, show_progress=False)db = lambda s, a, b: 10 * np.log10(abs(s[a, b][0]) ** 2)print(f"crossing: through {db(s_x, 'P0@0', 'P2@0'):.2f} dB, crosstalk {db(s_x, 'P0@0', 'P1@0'):.1f} dB")print(f"grating coupler: fiber -> waveguide {db(s_gc, 'FIBER@0', 'P0@0'):.2f} dB at 1310 nm")viewer(crossing)crossing: through -0.13 dB, crosstalk -40.0 dBgrating coupler: fiber -> waveguide -1.30 dB at 1310 nmThe grating coupler couples a fiber above the chip into the waveguide at port P0:
viewer(gc)Thermo-optic MZI switch
Section titled “Thermo-optic MZI switch”The switch cell joins two directional couplers with two heated arms:
- With both heaters off, the arms are balanced and the MZI is in the cross state: the upper input goes to the lower output.
- Heating one arm by puts the MZI in the bar state: the upper input goes to the upper output.
Cell geometry
Section titled “Cell geometry”The cell spans two lanes of the switch fabric, 127 µm apart. Its inputs and outputs sit d = 12 µm above or below the lane rows, so the shuffle waveguides between stages have room to bend in and out. The middle stage of the network uses a variant whose outputs both sit on the lower rows.
lane_pitch = 127.0 # lane pitch = fiber-array pitchdc_length, dc_pitch = 45.0, 8.6 # coupler length and port pitchfan = 30.0 # fan-in / fan-out regionarm_y = dc_pitch / 2 + 20.0 # arm offset from the cell axisx_in = fan + dc_length # first coupler output planex_heater = x_in + 25.0 # heater startx_dc2 = x_in + 50.0 + heater_length # second coupler input planecell_width = x_dc2 + dc_length + fanx_signal, x_ground = x_heater + 2.0, x_heater + heater_length - 2.0 # heater contactsx_rail = x_dc2 - 6.0 # ground railvia = sp.via_stack(size=2.0, technology=tech)Cell function
Section titled “Cell function”thermal_mzi builds the cell in four parts:
- Fan-in and couplers. Two
route_wirewaveguides bring the inputs together at the first coupler. - Heated arms. Each arm gets a heater reference. The upper arm (A) is added first, so it is heater reference 0, and the lower arm (B) is reference 1. We use these indices later to select a heater.
- Fan-out. The outputs spread back out to the lane rows of the next stage.
- Electrical connections. A via stack on each heater’s signal end leads to an M2 terminal (
AorB). The ground end connects through an M2 strap to a rail that runs the height of the column.
A CircuitModel makes the cell simulable as a whole.
def thermal_mzi(name="Thermal MZI", middle=False, d=12.0): c = pf.Component(name, technology=tech) wire = lambda vertices, tag: c.add_reference(route_wire(vertices, f"{name}_{tag}")) a, h = dc_pitch / 2, lane_pitch / 2 y_in = (h - d, -h - d) y_out = y_in if middle else (h + d, -h + d)
# 1. fan-in, couplers fan_0 = wire([(0, y_in[0]), (15, y_in[0]), (15, a), (fan, a)], "fin0") fan_1 = wire([(0, y_in[1]), (15, y_in[1]), (15, -a), (fan, -a)], "fin1") c.add_reference(pf.Reference(dc, (fan, -a))) c.add_reference(pf.Reference(dc, (x_dc2, -a)))
# 2. heated arms: reference 0 is the upper arm (A), reference 1 the lower (B) for sign, arm in ((1, "A"), (-1, "B")): y = sign * arm_y x_end = x_heater + heater_length wire([(x_in, sign * a), (x_in + 12, sign * a), (x_in + 12, y), (x_heater, y)], f"{arm}_in") c.add_reference(pf.Reference(heater, (x_heater, y))) wire([(x_end, y), (x_end + 13, y), (x_end + 13, sign * a), (x_dc2, sign * a)], f"{arm}_out")
# 3. fan-out x_out = x_dc2 + dc_length fout_0 = wire([(x_out, a), (x_out + 15, a), (x_out + 15, y_out[0]), (cell_width, y_out[0])], "fout0") fout_1 = wire([(x_out, -a), (x_out + 15, -a), (x_out + 15, y_out[1]), (cell_width, y_out[1])], "fout1") c.add_port(fan_0["P0"], "I0") c.add_port(fan_1["P0"], "I1") c.add_port(fout_0["P1"], "O0") c.add_port(fout_1["P1"], "O1")
# 4. electrical: signal via -> M2 terminal, ground via -> M2 strap -> column rail for sign in (1, -1): y = sign * arm_y c.add_reference(pf.Reference(via, (x_signal, y))) c.add_reference(pf.Reference(via, (x_ground, y))) c.add("M2", pf.Rectangle(corner1=(x_ground - 1.5, y - 1.5), corner2=(x_rail + 2.0, y + 1.5))) c.add("M2", pf.Rectangle(corner1=(x_rail - 2.0, -lane_pitch - 0.5), corner2=(x_rail + 2.0, lane_pitch + 0.5))) c.add_terminal( { "A": pf.Terminal("M2", pf.Rectangle(center=(x_signal, arm_y), size=(3.0, 3.0))), "B": pf.Terminal("M2", pf.Rectangle(center=(x_signal, -arm_y), size=(3.0, 3.0))), } ) c.add_model(pf.CircuitModel(), "Circuit") return c
mzi = thermal_mzi()viewer(mzi)Switching the MZI
Section titled “Switching the MZI”Both arms use the same heater component, so updating heater_model directly would heat both. Instead, we pass reference-based updates through the circuit model’s updates argument. An update path names a component and, in brackets, an index among the references to it, here f"{heater.name}[0]" for arm A. The update overrides the model’s temperature for that reference only:
hot_arm_a = {f"{heater.name}[0]": {"model_updates": {"temperature": T0 + dT_pi}}}
for label, updates in (("heaters off", {}), ("arm A at ΔT_π", hot_arm_a)): s = mzi.s_matrix(f0, show_progress=False, model_kwargs={"updates": updates}) print(f"{label}:") for i in ("I0", "I1"): powers = " ".join(f"{i} → {o}: {abs(s[f'{i}@0', f'{o}@0'][0]) ** 2:.3f}" for o in ("O0", "O1")) print(f" {powers}")heaters off: I0 → O0: 0.000 I0 → O1: 0.915 I1 → O0: 0.913 I1 → O1: 0.000arm A at ΔT_π: I0 → O0: 0.915 I0 → O1: 0.000 I1 → O0: 0.000 I1 → O1: 0.915About 0.4 dB of the power does not reach an output. That is the loss of the two couplers, the heaters, and the cell’s wires and bends.
Sweeping the temperature of arm A gives the switching curve, with the cross state at and the bar state at :
temperatures = np.linspace(0, 2 * dT_pi, 81)transmission = np.zeros((temperatures.size, 2))for i, dT in enumerate(temperatures): updates = {f"{heater.name}[0]": {"model_updates": {"temperature": T0 + dT}}} s = mzi.s_matrix(f0, show_progress=False, model_kwargs={"updates": updates}) transmission[i] = [abs(s["I0@0", "O0@0"][0]) ** 2, abs(s["I0@0", "O1@0"][0]) ** 2]
fig, ax = plt.subplots(figsize=(6, 3.5), tight_layout=True)ax.plot(temperatures, transmission, label=["I0 → O0 (bar)", "I0 → O1 (cross)"])ax.axvline(dT_pi, color="gray", ls="--", lw=1)ax.set(xlabel="ΔT on arm A (K)", ylabel="Transmission", title="MZI switching curve at 1310 nm")ax.legend()ax.grid(alpha=0.3)
The Beneš network
Section titled “The Beneš network”Before laying out the chip, we look at the network it implements:
- Lanes are numbered 0–7 from the top.
- Switch is row of stage and takes lanes and .
- Four fixed permutations, the shuffles, join consecutive stages. Each maps an output lane of one stage to an input lane of the next.
The network is its own mirror image about the middle stage, and the layout will be too.
The recursive construction [1] gives the shuffles. A block of size is a column of switches, two blocks of size , and another column of switches. After the first column, the upper output of switch goes to input of the upper sub-block and the lower output goes to input of the lower sub-block. Before the last column, the opposite mapping brings the sub-block outputs back together. A block of size 2 is a single switch.
benes_perms writes these mappings into the shuffle lists, block by block:
def n_stages(N): """Number of switch stages, 2 log2(N) - 1.""" n = int(round(math.log2(N))) assert 2**n == N and N >= 2, "N must be a power of 2" return 2 * n - 1
def benes_perms(N): """The inter-stage shuffles: perms[s][l] is the input lane of stage s + 1 fed by output lane l of stage s.""" perms = [list(range(N)) for _ in range(n_stages(N) - 1)]
def build(lo, M, s0): # block of size M on lanes lo..lo+M-1, first column at stage s0 if M == 2: return half = M // 2 last = s0 + 2 * int(math.log2(M)) - 2 # stage of the block's last column for i in range(half): # after the first column: split into the two sub-blocks perms[s0][lo + 2 * i] = lo + i perms[s0][lo + 2 * i + 1] = lo + half + i for j in range(half): # before the last column: merge them back perms[last - 1][lo + j] = lo + 2 * j perms[last - 1][lo + half + j] = lo + 2 * j + 1 build(lo, half, s0 + 1) build(lo + half, half, s0 + 1)
build(0, N, 0) return permsN = 8S = n_stages(N)perms = benes_perms(N)print(f"{S} stages × {N // 2} switches = {S * N // 2} MZIs")for k, p in enumerate(perms): print(f"shuffle {k}: output lane -> next input lane {p}")5 stages × 4 switches = 20 MZIsshuffle 0: output lane -> next input lane [0, 4, 1, 5, 2, 6, 3, 7]shuffle 1: output lane -> next input lane [0, 2, 1, 3, 4, 6, 5, 7]shuffle 2: output lane -> next input lane [0, 2, 1, 3, 4, 6, 5, 7]shuffle 3: output lane -> next input lane [0, 2, 4, 6, 1, 3, 5, 7]The looping algorithm [1] finds the switch states for any target permutation. At each level of the recursion it decides which inputs go through the upper sub-block and which through the lower one:
- The two inputs of a first-column switch must go to different sub-blocks.
- The two inputs whose destinations share a last-column switch must also go to different sub-blocks.
Starting from an unassigned input, the algorithm sends it to the upper sub-block, sends its switch partner to the lower one, then follows the second rule to the next input. Repeating this until the loop closes satisfies both rules. The sub-block assignments fix the first and last columns, and the two sub-blocks are routed the same way.
trace_states follows light through the abstract network, so we can check the result. Here bar sends lane and cross sends lane .
def route_permutation(N, target): """Looping algorithm: switch states {(s, r): "bar" | "cross"} that send input i to output target[i].""" states = {}
def route(lo, M, s0, perm): # perm: block input j -> block output perm[j] if M == 2: states[(s0, lo // 2)] = "bar" if perm[0] == 0 else "cross" return half = M // 2 last = s0 + 2 * int(math.log2(M)) - 2 inv = [0] * M for j, o in enumerate(perm): inv[o] = j side = [None] * M # 0 = upper sub-block, 1 = lower for start in range(M): j = start while side[j] is None: side[j] = 0 partner = j ^ 1 # shares the first-column switch: other side side[partner] = 1 j = inv[perm[partner] ^ 1] # shares the partner's last-column switch: upper side upper, lower = [0] * half, [0] * half for j in range(M): (upper if side[j] == 0 else lower)[j // 2] = perm[j] // 2 for k in range(half): states[(s0, lo // 2 + k)] = "bar" if side[2 * k] == 0 else "cross" states[(last, lo // 2 + k)] = "bar" if side[inv[2 * k]] == 0 else "cross" route(lo, half, s0 + 1, upper) route(lo + half, half, s0 + 1, lower)
route(0, N, 0, list(target)) return states
def trace_states(N, states): """Output lane reached by each input under the given switch states.""" perms, S = benes_perms(N), n_stages(N) outputs = [] for lane in range(N): for s in range(S): r, k = lane // 2, lane % 2 lane = 2 * r + (k if states[(s, r)] == "bar" else 1 - k) if s < S - 1: lane = perms[s][lane] outputs.append(lane) return outputsTo see the result, plot_benes draws the network with each input’s light path in its own color:
def plot_benes(states, title=""): """Abstract network: switches as boxes, light paths colored by input.""" colors = plt.cm.tab10(np.arange(N)) fig, ax = plt.subplots(figsize=(10, 4.2), tight_layout=True) for s in range(S): for r in range(N // 2): ax.add_patch(plt.Rectangle((3 * s - 0.5, 2 * r - 0.3), 1, 1.6, fc="0.93", ec="0.4")) ax.text(3 * s, 2 * r - 0.45, states[(s, r)][0].upper(), ha="center", va="bottom", fontsize=8, color="0.3") for i in range(N): lane, xs, ys = i, [-1.5], [i] for s in range(S): r, k = lane // 2, lane % 2 out = 2 * r + (k if states[(s, r)] == "bar" else 1 - k) xs += [3 * s - 0.5, 3 * s + 0.5] ys += [lane, out] lane = perms[s][out] if s < S - 1 else out xs.append(3 * (S - 1) + 2) ys.append(lane) ax.plot(xs, ys, color=colors[i], lw=2) ax.text(-1.7, i, f"IN{i + 1}", ha="right", va="center", fontsize=8) ax.text(3 * (S - 1) + 2.2, lane, f"OUT{lane + 1}", ha="left", va="center", fontsize=8) ax.set_ylim(N - 0.4, -1.0) ax.set_xlim(-3, 3 * (S - 1) + 3.5) ax.axis("off") ax.set_title(title)We pick a target permutation, route it, and check it in the abstract network. We will simulate the same permutation on the chip later.
target = [2, 7, 0, 5, 1, 6, 3, 4] # IN(i+1) -> OUT(target[i]+1)states = route_permutation(N, target)assert trace_states(N, states) == targetplot_benes(states, f"Switch states for permutation {[t + 1 for t in target]} (B = bar, C = cross)")
Chip layout
Section titled “Chip layout”We now build the full chip, one step at a time:
- Floorplan. Five MZI columns separated by shuffle regions.
- MZIs. Stages 0–2 use the MZI cell directly; the middle stage, 2, uses the variant with both outputs on the lower rows. Stages 3–4 are the same cells rotated 180° and mirrored, so the right half of the chip is the left half reflected.
- Grating couplers. The inputs (IN1–IN8) face left and the outputs (OUT1–OUT8) face right, on the 127 µm pitch.
- Shuffles. Each inter-stage permutation is routed on Manhattan tracks. Wherever two tracks cross, the wires are cut and a PDK crossing is inserted: 6 + 2 + 2 + 6 = 16 crossings.
- Heater pads. Each heater’s signal end gets its own M2 trace to a bond pad above or below the network (40 pads).
- Ground. The column ground rails join an M1 bus along each edge, which leads to a single ground pad.
- Ports and model. The chip’s ports are the grating couplers’
FIBERports, so the simulated loss is fiber-to-fiber. The chip gets aCircuitModel.
Floorplan
Section titled “Floorplan”The layout parameters and the coordinate helpers come first. wx converts an x coordinate inside an MZI cell to chip coordinates, taking the mirroring of stages 3–4 into account.
bend_radius = 10.0d = 12.0 # MZI port rows sit d above / below the lane rowsshuffle_first, shuffle_pitch = 30.0, 20.0 # first shuffle track from the stage plane, track pitchhalf_cross = 6.0 # half length of the crossing cellgc_lead = 60.0 # straight lead between a grating coupler and its stagepad_size, pad_step, pad_rows = 70.0, 50.0, 90.0 # pad, slot step, distance between the 2 pad rowstrace_width, trace_pitch, jog_step = 3.0, 6.0, 6.0x_window = 8.0 # first trace window (cell-local), left of the couplersx_gnd, bus_width = 20.0, 8.0 # ground pad column, ground bus width
H, mid = N // 2, S // 2 # switches per stage, middle stageshuffle_width = 2 * shuffle_first + shuffle_pitch * (N - 1)col_x = [gc_lead + k * (cell_width + shuffle_width) for k in range(S)] # left edge of each stagex_end = col_x[-1] + cell_widthx_axis = col_x[mid] + cell_width / 2 # mirror axislane_y = lambda l: (N - 1 - l) * lane_pitchrow_y = [lane_y(2 * r) - lane_pitch / 2 for r in range(H)]mirrored = lambda s: s > midwx = lambda s, x: col_x[s] + cell_width - x if mirrored(s) else col_x[s] + x # cell x -> chip xin_dy = lambda s: d if mirrored(s) else -d # input port offset from the lane rowout_dy = lambda s: -d if s >= mid else d # output port offset from the lane rowWe also need a small helper: metal_route draws a Manhattan metal trace with a terminal at each end.
def metal_route(name, layer, pts, width): route = pf.Component(name, technology=tech) for p, q in zip(pts, pts[1:]): route.add(layer, pf.Rectangle( corner1=(min(p[0], q[0]) - width / 2, min(p[1], q[1]) - width / 2), corner2=(max(p[0], q[0]) + width / 2, max(p[1], q[1]) + width / 2), )) route.add_terminal({ "T1": pf.Terminal(layer, pf.Rectangle(center=pts[0], size=(width, width))), "T2": pf.Terminal(layer, pf.Rectangle(center=pts[-1], size=(width, width))), }) return routeAll 20 MZIs are references to two cells: tbenes_mzi_h300 for the outer stages and tbenes_mzi_h300_mid for the middle one. While placing them we record mzi_index[(s, r)] = (cell name, k), where k is the position of that switch among the references to its cell. The circuit-model update paths will need exactly this pair to reach one switch.
mzi_cells = {"outer": thermal_mzi("tbenes_mzi_h300"), "middle": thermal_mzi("tbenes_mzi_h300_mid", middle=True)}chip = pf.Component("benes_8x8_thermal", technology=tech)
mzis, mzi_index, count = {}, {}, {"outer": 0, "middle": 0}for s in range(S): kind = "middle" if s == mid else "outer" for r in range(H): if mirrored(s): ref = pf.Reference(mzi_cells[kind], (col_x[s] + cell_width, row_y[r]), rotation=180, x_reflection=True) else: ref = pf.Reference(mzi_cells[kind], (col_x[s], row_y[r])) mzis[(s, r)] = chip.add_reference(ref) mzi_index[(s, r)] = (mzi_cells[kind].name, count[kind]) count[kind] += 1viewer(chip)Grating couplers
Section titled “Grating couplers”Each grating coupler connects to its stage through a straight lead.
gcs_in, gcs_out = [], []for l in range(N): for gcs, x_gc, x_lead, y, rotation in ( (gcs_in, col_x[0] - gc_lead, col_x[0] - gc_lead, lane_y(l) + in_dy(0), 180), (gcs_out, x_end + gc_lead, x_end, lane_y(l) + out_dy(S - 1), 0), ): g = chip.add_reference(pf.Reference(gc, (0, 0), rotation=rotation)) g.translate((x_gc - float(g["P0"].center[0]), y - float(g["P0"].center[1]))) gcs.append(g) chip.add_reference(pf.Reference(sp.straight(length=gc_lead, technology=tech), (x_lead, y)))viewer(chip)Shuffles and crossings
Section titled “Shuffles and crossings”Each shuffle wire runs horizontally from its source lane to its own vertical track, then vertically to the destination lane, then horizontally into the next stage. The track order is:
- Wires going up, topmost first.
- Wires going down, bottommost first.
- Wires that stay on their lane.
plan_shuffle places the tracks in that order and finds every point where one wire’s vertical crosses another wire’s horizontal. It checks that each crossing sits on a straight section, clear of the bends. place_wire then cuts each wire around its crossings and draws the pieces: straight waveguides for single segments and route_wire cells for pieces with bends.
def arc_length(v, p): """Distance along the path v to the point p on it.""" s = 0.0 for a, b in zip(v, v[1:]): if min(a[0], b[0]) - 1e-9 <= p[0] <= max(a[0], b[0]) + 1e-9 and min(a[1], b[1]) - 1e-9 <= p[1] <= max(a[1], b[1]) + 1e-9: return s + abs(p[0] - a[0]) + abs(p[1] - a[1]) s += abs(b[0] - a[0]) + abs(b[1] - a[1])
def point_at(v, s): """Point at distance s along the path v.""" for a, b in zip(v, v[1:]): seg = abs(b[0] - a[0]) + abs(b[1] - a[1]) if s <= seg + 1e-9: t = s / seg return (a[0] + t * (b[0] - a[0]), a[1] + t * (b[1] - a[1])) s -= seg
def plan_shuffle(perm, x0, ys, yd): """Wires for one shuffle starting at x0; ys / yd give the source / destination y of a lane.""" up = sorted((a for a, b in enumerate(perm) if a != b and yd(b) > ys(a)), key=lambda a: -ys(a)) down = sorted((a for a, b in enumerate(perm) if a != b and yd(b) <= ys(a)), key=ys) jog = [a for a, b in enumerate(perm) if a == b] track = {a: x0 + shuffle_first + shuffle_pitch * k for k, a in enumerate(up + down + jog)} wires = [[(x0, ys(a)), (track[a], ys(a)), (track[a], yd(b)), (x0 + shuffle_width, yd(b))] for a, b in enumerate(perm)] crossings, cuts = [], [[] for _ in wires] for i, j in itertools.combinations(range(N), 2): for v, h in ((wires[i], wires[j]), (wires[j], wires[i])): (xv, y0), (_, y1) = v[1], v[2] for (xa, yh), (xb, _) in (h[:2], h[2:]): if min(xa, xb) < xv < max(xa, xb) and min(y0, y1) < yh < max(y0, y1): crossings.append((xv, yh)) cuts[i].append(arc_length(wires[i], (xv, yh))) cuts[j].append(arc_length(wires[j], (xv, yh))) for v, c in zip(wires, cuts): # crossings must sit on straight sections, clear of the bends corners = [arc_length(v, v[1]), arc_length(v, v[2])] assert all(abs(s - k) > half_cross + bend_radius for s in c for k in corners) return [dict(vertices=v, cuts=sorted(c)) for v, c in zip(wires, cuts)], crossings
def place_wire(v, cuts, tag): """Draw the wire v, leaving a gap of one crossing cell at each cut.""" total = arc_length(v, v[-1]) bounds = [0.0] + [s for c in cuts for s in (c - half_cross, c + half_cross)] + [total] for k in range(0, len(bounds), 2): sa, sb = bounds[k], bounds[k + 1] pts = [point_at(v, sa)] pts += [p for p in v[1:-1] if sa + 1e-9 < arc_length(v, p) < sb - 1e-9] pts.append(point_at(v, sb)) if len(pts) == 2: angle = round(math.degrees(math.atan2(pts[1][1] - pts[0][1], pts[1][0] - pts[0][0])) / 90) * 90 length = pf.snap_to_grid(abs(pts[1][0] - pts[0][0]) + abs(pts[1][1] - pts[0][1])) chip.add_reference(pf.Reference(sp.straight(length=length, technology=tech), pts[0], rotation=angle)) else: chip.add_reference(route_wire(pts, f"{tag}_{k // 2}", radius=bend_radius))We plan the two shuffles of the left half and mirror them about the chip axis for the right half.
xings, plans = [], []x_center = 2 * x_axisfor s in range(S - 1): if s < mid: wires, crossings = plan_shuffle( perms[s], col_x[s] + cell_width, lambda l: lane_y(l) + out_dy(s), lambda l: lane_y(l) + in_dy(s + 1) ) plans.append((wires, crossings)) else: # right half: mirror image of the left half left_wires, left_crossings = plans[S - 2 - s] crossings = [(x_center - x, y) for x, y in left_crossings] wires = [] for w in left_wires: total = arc_length(w["vertices"], w["vertices"][-1]) wires.append(dict(vertices=[(x_center - x, y) for x, y in w["vertices"][::-1]], cuts=sorted(total - c for c in w["cuts"]))) for x, y in crossings: xings.append(chip.add_reference(pf.Reference(crossing, (x, y)))) for k, w in enumerate(wires): place_wire(w["vertices"], w["cuts"], f"shuffle{s}_wire{k}")print(f"{len(xings)} crossings")viewer(chip)16 crossingsHeater pads
Section titled “Heater pads”Each of the 40 heater signal terminals is routed to its own pad: the upper two rows of switches go to pads above the network, and the lower two rows to pads below. Each trace has three parts:
- A horizontal run out of the MZI to its own vertical window, a column of x positions spaced
trace_pitchapart left of the couplers. - A vertical run up or down to a jog level, a horizontal track above or below the network.
- A horizontal run along the jog level to its pad’s x position, then up or down into the pad.
assign_pad_slots spreads the pad slots out from the chip axis on two staggered rows. It gives each trace a jog level so that no two traces on the same side cross.
def assign_pad_slots(candidates): """Set the pad position and jog level of each trace on one side; returns the number of levels used.""" lst = sorted(candidates, key=lambda c: c["xw"]) half = len(lst) // 2 for j, c in enumerate(lst): # pad slots spread out from the chip axis, alternating inner / outer row m = (half - 1 - j) if j < half else (j - half) c["xp"] = x_axis + (-1 if j < half else 1) * pad_step * (m + 1) c["outer"] = m % 2 == 0 c["move"] = c["xp"] - c["xw"] levels_used = level_mid = 0 for group in ("mid", "rest"): # the middle stage takes the lowest levels sub = [c for c in lst if (c["s"] == mid) == (group == "mid")] right = [c for c in sub if c["move"] > 1e-6] left = [c for c in sub if c["move"] < -1e-6] for c in sub: c["level"] = 0 for i in range(len(right) - 1, -1, -1): # a trace must clear every trace it passes over c = right[i] c["level"] = 1 + max([e["level"] for e in right[i + 1:] if e["xw"] < c["xp"] + trace_width + 1.5] or [-1]) for i in range(len(left)): c = left[i] c["level"] = 1 + max([e["level"] for e in left[:i] if e["xw"] > c["xp"] - trace_width - 1.5] or [-1]) top = max([c["level"] + 1 for c in sub] or [0]) if group == "mid": level_mid = top else: for c in sub: c["level"] += level_mid top += level_mid levels_used = max(levels_used, top) return levels_used
candidates = {"top": [], "bot": []}for s in range(S): for side in ("top", "bot"): up = side == "top" for r in range(0, H // 2) if up else range(H // 2, H): f = (H // 2 - 1 - r) if up else (r - H // 2) # 0 = row farthest from that edge pair = [(2 * f, "B"), (2 * f + 1, "A")] if up else [(2 * f, "A"), (2 * f + 1, "B")] for k, arm in pair: candidates[side].append(dict(s=s, r=r, arm=arm, xw=wx(s, x_window + trace_pitch * k)))levels_used = max(assign_pad_slots(candidates[side]) for side in candidates)With the slots assigned, we draw the traces and pads. The jog band and the two pad rows sit just outside the ground rails at the top and bottom of the network.
pad = sp.bond_pad(pad_size=pad_size, technology=tech)y_top_rail = row_y[0] + lane_pitch + 0.5y_bot_rail = row_y[-1] - lane_pitch - 0.5band = jog_step * levels_usedjog0_top, jog0_bot = y_top_rail + 25.0, y_bot_rail - 25.0pad_in_top = jog0_top + band + 20.0 + pad_size / 2 + 2.5pad_in_bot = jog0_bot - band - 20.0 - pad_size / 2 - 2.5pad_out_top, pad_out_bot = pad_in_top + pad_rows, pad_in_bot - pad_rows
pads = []for side in ("top", "bot"): up = side == "top" for c in candidates[side]: y_arm = row_y[c["r"]] + (arm_y if c["arm"] == "A" else -arm_y) jog_y = jog0_top + jog_step * c["level"] if up else jog0_bot - jog_step * c["level"] pad_y = (pad_out_top if c["outer"] else pad_in_top) if up else (pad_out_bot if c["outer"] else pad_in_bot) pts = [(wx(c["s"], x_signal), y_arm), (c["xw"], y_arm), (c["xw"], jog_y), (c["xp"], jog_y), (c["xp"], pad_y)] pts = [p for i, p in enumerate(pts) if i == 0 or abs(p[0] - pts[i - 1][0]) + abs(p[1] - pts[i - 1][1]) > 1e-9] chip.add_reference(metal_route(f"trace_s{c['s']}r{c['r']}{c['arm']}", "M2", pts, trace_width)) pads.append(chip.add_reference(pf.Reference(pad, (c["xp"], pad_y))))viewer(chip)Ground
Section titled “Ground”The ground rail of every column ends in a via to an M1 bus along the top and bottom edges of the network. The rails already join the two buses into one net, so only the top bus rises to a ground pad.
for side, y_rail, sign, pad_y in (("top", y_top_rail, -1, pad_in_top), ("bot", y_bot_rail, 1, None)): xs = [wx(s, x_rail) for s in range(S)] y_bus = y_rail + sign * 2.0 for x in xs: chip.add_reference(pf.Reference(via, (x, y_bus))) pts = [(max(xs), y_bus), (x_gnd if pad_y else min(xs), y_bus)] + ([(x_gnd, pad_y)] if pad_y else []) chip.add_reference(metal_route(f"ground_bus_{side}", "M1", pts, bus_width)) if pad_y: pads.append(chip.add_reference(pf.Reference(pad, (x_gnd, pad_y))))viewer(chip)Ports and circuit model
Section titled “Ports and circuit model”Finally we add the fiber ports and the circuit model and draw a floorplan outline. The info dictionary collects what the simulation cells need, chiefly mzi_index.
for k, g in enumerate(gcs_in): chip.add_port(g["FIBER"], f"IN{k + 1}")for k, g in enumerate(gcs_out): chip.add_port(g["FIBER"], f"OUT{k + 1}")chip.add_model(pf.CircuitModel(), "Circuit")(x0, y0), (x1, y1) = chip.bounds()chip.add("FLOORPLAN", pf.Rectangle((float(x0) - 20, float(y0) - 20), (float(x1) + 20, float(y1) + 20)))
info = dict(mzis=mzis, mzi_index=mzi_index, xings=xings, pads=pads, die=(float(x1 - x0) + 40, float(y1 - y0) + 40))print(f"die {info['die'][0] / 1e3:.2f} × {info['die'][1] / 1e3:.2f} mm, {len(mzis)} MZIs, " f"{len(xings)} crossings, {len(pads)} pads")print("ports:", sorted(chip.ports))viewer(chip)die 3.55 × 1.62 mm, 20 MZIs, 16 crossings, 41 padsports: ['IN1', 'IN2', 'IN3', 'IN4', 'IN5', 'IN6', 'IN7', 'IN8', 'OUT1', 'OUT2', 'OUT3', 'OUT4', 'OUT5', 'OUT6', 'OUT7', 'OUT8']As a check, the MZI cell on the chip behaves exactly like the one we simulated on its own:
chip_mzi = mzis[(0, 0)].components_a = mzi.s_matrix(f0, show_progress=False)s_b = chip_mzi.s_matrix(f0, show_progress=False)diff = max(abs(s_a[k][0] - s_b[k][0]) for k in s_a.elements)print(f"chip MZI cell: {chip_mzi.name}; max |ΔS| against the notebook cell = {diff:.1e}")chip MZI cell: tbenes_mzi_h300; max |ΔS| against the notebook cell = 0.0e+00Setting the switch states
Section titled “Setting the switch states”To heat arm A of switch , we tell the circuit model which heater reference to update. An update path walks down the layout hierarchy, starting at the chip. Each level is a component name with an index in brackets, and the index picks one reference among the references to that component at that level, counted in the order they were added:
mzi_cell_name[k]/heater_name[0]-
mzi_cell_name[k]: picks the MZI.kis the switch’s position among the references to its cell, recorded inmzi_indexwhen we placed the MZIs:stage cell for rows 0–3 0 tbenes_mzi_h3000, 1, 2, 3 1 tbenes_mzi_h3004, 5, 6, 7 2 tbenes_mzi_h300_mid0, 1, 2, 3 3 tbenes_mzi_h3008, 9, 10, 11 4 tbenes_mzi_h30012, 13, 14, 15 -
heater_name[0]: picks the heater inside that MZI. Index 0 is arm A (upper), the first heater added inthermal_mzi, and index 1 is arm B (lower).
The update replaces that one heater’s temperature while the circuit model computes that reference. All the other heaters, including the other 39 references to the same heater cell, stay at ambient.
Names in a path match whole component names, so tbenes_mzi_h300 does not also select tbenes_mzi_h300_mid. Only the characters *, ? and \ have a special meaning and would need escaping; none of our cell names contain them.
heater_updates turns a dictionary of switch states into circuit-model updates, heating arm A of every switch in the bar state:
def heater_updates(states, dt_scale=1.0): """Circuit-model updates that heat arm A of every switch in the bar state.""" updates = {} for key, state in states.items(): if state == "bar": cell, k = mzi_index[key] updates[f"{cell}[{k}]/{heater.name}[0]"] = { "model_updates": {"temperature": T0 + dT_pi * dt_scale} } return updates
heater_updates({(3, 1): "bar"}){'tbenes_mzi_h300[9]/tps_l300p0[0]': {'model_updates': {'temperature': 304.7383512544803}}}Solving the chip
Section titled “Solving the chip”solve computes the 8×8 fiber-to-fiber power matrix P[f, i, o] from IN(i+1) to OUT(o+1). It runs one frequency at a time so it can scale the heater step by , which restores the physical thermal phase discussed above.
def solve(states, frequencies): """Power transmission P[f, i, o] from IN(i+1) to OUT(o+1).""" P = np.zeros((len(frequencies), N, N)) for j, f in enumerate(frequencies): updates = heater_updates(states, dt_scale=f / cal.REF_FREQUENCY) s = chip.s_matrix([f], show_progress=False, model_kwargs={"updates": updates}) for i in range(N): for o in range(N): P[j, i, o] = abs(s[f"IN{i + 1}@0", f"OUT{o + 1}@0"][0]) ** 2 return PTwo helpers analyze the results:
metricschecks that every input reaches its target. It returns the insertion loss of each routed path and the worst crosstalk: the strongest unwanted signal at an output, relative to the wanted one.plot_matrixdraws the power matrix in dB, with the target cells outlined.
def metrics(P, target): """Routing check, insertion loss of each routed path (dB) and worst crosstalk at the outputs (dB).""" il = np.array([-10 * np.log10(P[i, target[i]]) for i in range(N)]) xt = max( 10 * np.log10(max(P[i, o] for i in range(N) if target[i] != o) / P[target.index(o), o]) for o in range(N) ) routed = all(int(np.argmax(P[i])) == target[i] for i in range(N)) return routed, il, xt
def plot_matrix(P, target, title): P_db = 10 * np.log10(np.maximum(P, 1e-12)) fig, ax = plt.subplots(figsize=(6, 5), tight_layout=True) im = ax.imshow(P_db, vmin=-60, vmax=0, cmap="viridis") for i in range(N): ax.add_patch(plt.Rectangle((target[i] - 0.5, i - 0.5), 1, 1, fill=False, ec="white", lw=1.5)) for o in range(N): color = "white" if P_db[i, o] < -30 else "black" ax.text(o, i, f"{P_db[i, o]:.0f}", ha="center", va="center", fontsize=7, color=color) ax.set_xticks(range(N), [f"OUT{o + 1}" for o in range(N)], rotation=45) ax.set_yticks(range(N), [f"IN{i + 1}" for i in range(N)]) ax.set_title(title, fontsize=10) fig.colorbar(im, ax=ax, label="Transmission (dB)")Simulating the chip
Section titled “Simulating the chip”All heaters off
Section titled “All heaters off”With every switch in the cross state, the routing simulated on the layout must equal the abstract network’s:
all_cross = {key: "cross" for key in mzi_index}P = solve(all_cross, f0)[0]simulated = [int(np.argmax(P[i])) for i in range(N)]expected = trace_states(N, all_cross)print("simulated:", [o + 1 for o in simulated])print("abstract: ", [o + 1 for o in expected])plot_matrix(P, simulated, "All heaters off (every switch in cross)")simulated: [5, 6, 7, 8, 1, 2, 3, 4]abstract: [5, 6, 7, 8, 1, 2, 3, 4]
Routing a permutation
Section titled “Routing a permutation”Now the permutation we routed in the abstract network. The looping algorithm set the switch states, and heater_updates turns them into heater temperatures:
P = solve(states, f0)[0]routed, il, xt = metrics(P, target)n_bar = sum(v == "bar" for v in states.values())print(f"{n_bar} of 20 switches in bar; routed correctly: {routed}")print(f"insertion loss {il.min():.2f}–{il.max():.2f} dB, worst crosstalk {xt:.1f} dB")plot_matrix(P, target, f"Permutation {[t + 1 for t in target]} at 1310 nm")13 of 20 switches in bar; routed correctly: Trueinsertion loss 4.96–5.86 dB, worst crosstalk -33.5 dB
The insertion loss differs between paths because a path passes through between 0 and 8 crossings in the shuffles. The rest of the loss is the same on every path:
- two grating couplers: 2 × 1.3 dB
- ten directional couplers: 10 × 0.1 dB
- the drawn waveguide length and bends
Random permutations
Section titled “Random permutations”Because the network is rearrangeably non-blocking, every permutation can be routed. We check a set of random ones on the layout:
rng = np.random.default_rng(7)rows = []for _ in range(8): t = [int(v) for v in rng.permutation(N)] P = solve(route_permutation(N, t), f0)[0] routed, il, xt = metrics(P, t) rows.append((routed, il.min(), il.max(), xt)) print(f"{[v + 1 for v in t]}: routed {routed}, IL {il.min():.2f}–{il.max():.2f} dB, crosstalk {xt:.1f} dB")print(f"{sum(r[0] for r in rows)}/{len(rows)} routed; worst crosstalk {max(r[3] for r in rows):.1f} dB")[1, 7, 8, 3, 5, 6, 2, 4]: routed True, IL 4.80–5.72 dB, crosstalk -38.6 dB[8, 4, 7, 3, 1, 5, 2, 6]: routed True, IL 5.25–5.60 dB, crosstalk -34.0 dB[4, 5, 6, 3, 1, 8, 2, 7]: routed True, IL 4.97–6.02 dB, crosstalk -33.9 dB[7, 5, 8, 4, 6, 2, 3, 1]: routed True, IL 5.26–5.60 dB, crosstalk -38.7 dB[1, 7, 6, 5, 2, 8, 3, 4]: routed True, IL 4.80–5.85 dB, crosstalk -34.0 dB[8, 1, 2, 3, 5, 7, 4, 6]: routed True, IL 4.97–5.72 dB, crosstalk -36.6 dB[6, 3, 8, 7, 4, 5, 1, 2]: routed True, IL 5.25–5.57 dB, crosstalk -38.6 dB[7, 6, 2, 4, 1, 3, 8, 5]: routed True, IL 4.83–5.73 dB, crosstalk -34.3 dB8/8 routed; worst crosstalk -33.9 dBWavelength response
Section titled “Wavelength response”Finally we sweep the wavelength for the reversal permutation (IN1→OUT8, …, IN8→OUT1), with the heaters set for 1310 nm. Each wavelength is a separate circuit solve, so we use a coarse sweep. Two effects show up:
- The routed signals roll off away from 1310 nm because of the grating couplers’ bandwidth.
- The crosstalk rises because the heated arms drift away from π, so the switches in the bar state leak.
reverse = list(range(N))[::-1]reverse_states = route_permutation(N, reverse)sweep_wavelengths = np.linspace(1.29, 1.33, 11)P = solve(reverse_states, pf.C_0 / sweep_wavelengths)
crosstalk = [metrics(P[j], reverse)[2] for j in range(len(sweep_wavelengths))]fig, ax = plt.subplots(figsize=(7, 4), tight_layout=True)for i in range(N): ax.plot(sweep_wavelengths * 1e3, 10 * np.log10(P[:, i, reverse[i]]), lw=1.2, label=f"IN{i + 1} → OUT{reverse[i] + 1}")ax.plot(sweep_wavelengths * 1e3, crosstalk, "k--", label="worst crosstalk")ax.set(xlabel="Wavelength (nm)", ylabel="Transmission / crosstalk (dB)", title="Reversal permutation, heaters set for 1310 nm")ax.legend(fontsize=7, ncol=3)ax.grid(alpha=0.3)
Summary
Section titled “Summary”- One MZI cell with two heated arms, reused 20 times, makes the full 8×8 Beneš fabric. The switch state is a heater temperature applied per reference through the circuit model’s
updates, so the layout is never rebuilt between simulations. - Update paths such as
tbenes_mzi_h300[9]/tps_l300p0[0]walk the hierarchy as name–index pairs. Recordingmzi_indexwhile placing the MZIs gives the index of each switch, so each update reaches exactly one heater. - The laid-out chip routes every permutation we tried, with about 5–6 dB fiber-to-fiber loss and crosstalk below −33 dB at 1310 nm.
Not modeled
Section titled “Not modeled”The circuit uses the PDK’s ideal devices: the MZI arms are perfectly balanced and the couplers split exactly 50:50, so no per-switch bias calibration is needed. These effects are left out:
- Thermal crosstalk between neighboring heaters.
- Heater power and the IR drop on the shared ground return. Up to 20 heaters run at once through one ground pad, so a tape-out would need wider rails and more ground pads.
- The wavelength dependence of the coupler split, which makes the band-edge crosstalk above optimistic.
Any of these can be added by replacing the corresponding PDK model. For example, a fitted coupler model or a temperature map from a Tidy3D HEAT simulation can be passed through the same updates mechanism.
References
Section titled “References”- V. E. Beneš, “Optimal rearrangeable multistage connecting networks,” Bell System Technical Journal 43, 1641–1656 (1964).
- M. Ghanaatian, A. Shafiee, M. Nikdast, SPIE Photonics West (2025), author copy.