TIDY3D
LEARNING CENTER

Topology optimization of silicon nanocavities for field confinement

Two-dimensional semiconductors such as monolayer WSe2 host tightly bound excitons with large oscillator strengths, but their atomic thickness leaves very little volume for interaction with free-space light. Placing the monolayer on a nanophotonic cavity that squeezes the optical field into a small hotspot right beneath it is one way to boost this light-matter coupling. Plasmonic gap antennas achieve extreme confinement but suffer from ohmic loss, while conventional dielectric cavities such as photonic crystals and microrings are low-loss but limited to diffraction-scale mode volumes.

Topology optimization bridges the two. By treating every pixel of the design region as a free parameter, it can find freeform dielectric geometries that concentrate light into deep-subwavelength regions with negligible absorption compared to metals. Matthiessen et al. use this approach to design 2D-periodic arrays of silicon nanocavities on a sapphire substrate, covered with an hBN-encapsulated WSe2 monolayer. The optimized cavities converge to a bowtie-like feature at the center of each unit cell, producing a near-field hotspot with transverse size of only 30–40 nm directly under the monolayer. The authors report a field amplitude enhancement exceeding 50× under realistic material losses, an approximately tenfold raw photoluminescence enhancement over off-cavity regions, and more directional emission toward the collection optics compared to WSe2 on flat silicon.

In this notebook, we reproduce this design workflow with Tidy3D’s autograd plugin and validate the resulting cavity:

  1. Setup. One unit cell of the array, with period \(P = 2\lambda\) at the WSe2 emission energy (1.65 eV, \(\lambda \approx 751\) nm) and a Si layer of thickness \(\lambda / (2 n_\mathrm{Si})\) on sapphire, covered by the WSe2 monolayer and a 13.4 nm hBN layer. The Si layer is the design region, described by a pixelated density that interpolates between air and dispersive, lossy silicon.
  2. Optimization. Under x-polarized plane-wave illumination at normal incidence, we maximize the intensity enhancement \(|E_x / E_\mathrm{inc}|^2\) at the center of the cavity, on the Si top surface where the monolayer sits. Mirror symmetry, a conic filter and a projection with gradually increasing sharpness steer the design toward a binary, fabricable structure, and a narrow central slit is fixed to air to open a gap at the hotspot.
  3. Validation. We map the field enhancement of the optimized cavity under plane-wave illumination, and compare the cavity with a flat Si film in terms of the absorption spectra (with the flat film checked against an exact transfer-matrix result) and the near fields and far-field directivity of an x-oriented dipole emitter placed at the hotspot in a finite supercell of the array.

References

  1. O. Matthiessen et al., “Topology-optimized dielectric cavities for enhanced excitonic light emission from WSe2,” Light: Science & Applications 15:387 (2026). DOI:10.1038/s41377-026-02436-w
  2. P. G. Zotev et al., “Van der Waals Materials for Applications in Nanophotonics,” Laser & Photonics Reviews 17, 2200957 (2023). DOI:10.1002/lpor.202200957

Schematic of the topology-optimized Si nanocavity array on sapphire, covered by WSe2 and hBN

Simulation Setup

We first define the materials, the design and optimization hyperparameters, and a base simulation of one periodic unit cell, then connect the design parameters to a Tidy3D structure and the figure of merit.

from pathlib import Path

import autograd.numpy as np
import matplotlib.pyplot as plt
import tidy3d as td
from autograd import grad_and_aux
from autograd.tracer import getval
from tidy3d import web
from tidy3d.plugins.autograd import adam, apply_updates
from tidy3d.plugins.autograd.invdes import ConicFilter, tanh_projection
from tidy3d.plugins.dispersion import FastDispersionFitter

td.config.logging.level = "ERROR"
td.config.adjoint.local_gradient = True
td.config.adjoint.parallel_run = True
print(f"Tidy3D version: {td.__version__}")

SIM_DIR = Path("./data")
FOLDER_NAME = "Si_nanocavity"
Tidy3D version: 2.13.0

Materials

We target the WSe2 exciton emission at 1.65 eV over a 1.5–1.9 eV band, using lossy crystalline Si (Palik), a non-dispersive sapphire substrate, and the 2D WSe2 monolayer model from the material library. hBN is uniaxial and transparent in this range, so its ordinary (in-plane) and extraordinary (out-of-plane) indices from Zotev et al. are fitted with pole-residue models and combined into an anisotropic medium.

We also build non-dispersive copies of Si, hBN and WSe2 that match the dispersive models exactly at 1.65 eV, and use them wherever only that frequency matters:

  • Optimization runs. The figure of merit is evaluated only at 1.65 eV, so the hBN and WSe2 layers use the non-dispersive copies. The Si design region keeps the dispersive model, since the density interpolates its pole-residue terms.
  • Dipole runs. The 5 × 5 supercell has PML on all sides and its layers cross the side PML. A dispersive, lossy medium inside a standard PML can diverge, and the emission analysis is evaluated only at 1.65 eV, so the whole stack, including the Si cavity, is non-dispersive.

The broadband plane-wave validation runs use the dispersive models throughout.

# Photon energies (eV).
energy_list = np.linspace(1.5, 1.9, 81)
energy_target = 1.65

freqs = energy_list / (2 * np.pi * td.HBAR)
wvls = td.C_0 / freqs
f_target = energy_target / (2 * np.pi * td.HBAR)
wvl_target = td.C_0 / f_target

f0 = (freqs[0] + freqs[-1]) / 2
fwidth = 0.67 * (freqs[-1] - freqs[0])

# Dispersive models.
n_sapphire = 1.767
sapphire = td.Medium.from_nk(n=n_sapphire, k=0, freq=f_target, name="Al2O3")
si = td.material_library["cSi"]["Palik_Lossy"]
wse2 = td.material_library["WSe2"]["Li2014"]

hBN_o, hBN_e = (
    FastDispersionFitter.from_file(f"./assets/Zotev-{axis}.txt", skiprows=1).fit(
        min_num_poles=2, tolerance_rms=1e-4
    )[0]
    for axis in "oe"
)
hBN = td.AnisotropicMedium(xx=hBN_o, yy=hBN_o, zz=hBN_e)


# Non-dispersive copies, exact at f_target.
def non_dispersive(medium, **kwargs):
    return td.Medium.from_nk(
        *medium.nk_model(frequency=f_target), freq=f_target, **kwargs
    )


si_nd = non_dispersive(si, name="cSi @ 1.65 eV")
hBN_nd = td.AnisotropicMedium(
    xx=non_dispersive(hBN_o), yy=non_dispersive(hBN_o), zz=non_dispersive(hBN_e)
)
# WSe2: an equivalent 1 nm slab at f_target, folded back into a sheet.
wse2_nd = td.Medium2D.from_medium(
    non_dispersive(wse2.to_anisotropic_medium(axis=2, thickness=1e-3).xx),
    thickness=1e-3,
)
Best weighted RMS error: 5.55e-07 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100% 0:00:00

Best weighted RMS error: 6.99e-07 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100% 0:00:00

Design and Optimization Hyperparameters

The unit cell is discretized into N_DESIGN × N_DESIGN pixels, smoothed by a conic filter of radius R_BLUR (µm), and binarized by a projection of sharpness \(\beta\). Over N_STEP Adam iterations with learning rate LR, \(\beta\) rises geometrically from BETA_INIT to BETA_MAX during the first N_STEP_RAMP steps and then stays at BETA_MAX. SUPERCELL sets the number of unit cells in the dipole emission runs.

N_DESIGN = 200  # pixels per side of the unit cell
R_BLUR = 0.05  # conic filter radius (µm)

BETA_INIT = 1
BETA_MAX = 500
N_STEP_RAMP = 16  # steps of the beta ramp

LR = 0.9e-2
N_STEP = 30

SUPERCELL = (5, 5)  # odd, so the dipole cell sits at the origin

Geometry and Layer Stack

One unit cell of period \(P = 2\lambda\) holds a Si layer of thickness \(\lambda/(2n_\mathrm{Si})\) on sapphire, capped by the WSe2 monolayer and a 13.4 nm hBN layer (the AFM-measured thickness of one of the paper’s flakes). The WSe2 is modeled as a zero-thickness sheet 0.3 nm above the Si surface, and the figure-of-merit point and the dipole sit on it. The domain extends one wavelength (in sapphire) into the substrate, which keeps the PML clear of the dipole’s evanescent field, and half a wavelength above the hBN.

P = 2 * wvl_target
PIXEL_SIZE = P / N_DESIGN
n_si = si.nk_model(frequency=f_target)[0]
print(
    f"Min. design pixels per wavelength in Si: {(wvls / n_si / PIXEL_SIZE).min():.1f}"
)

# Layer thicknesses (µm).
t_si = wvl_target / (2 * n_si)
t_hbn = 0.0134
t_sub = 430.0

# Vertical positions (µm).
wvl_sub_max = (wvls / n_sapphire).max()
z_surface = t_si  # Si top surface
z_wse2 = z_surface + 0.3e-3  # WSe2 sheet, FOM point and dipole
z_top = t_si + t_hbn  # top of the hBN
z_min = -wvl_sub_max
z_max = z_top + wvls.max() / 2
z_src = z_top + wvls.max() / 10
z_flux_up = z_top + wvls.max() / 5
z_flux_down = -wvl_sub_max / 5
z_flux_net = (z_src + z_top) / 2
z_interfaces = [0, z_surface, z_wse2, z_top]


def slab(z_lo, z_hi, medium, name):
    return td.Structure(
        geometry=td.Box.from_bounds(
            rmin=(-td.inf, -td.inf, z_lo), rmax=(td.inf, td.inf, z_hi)
        ),
        medium=medium,
        name=name,
    )


substrate = slab(-t_sub, 0, sapphire, "sapphire substrate")
layer_hbn = slab(z_surface, z_top, hBN, "hBN layer")
layer_wse2 = slab(z_wse2, z_wse2, wse2, "WSe2 layer")
si_layer = slab(0, t_si, si, "Si layer")  # flat-film reference

base_structures = [substrate, layer_hbn, layer_wse2]
base_structures_nd = [
    substrate,
    layer_hbn.updated_copy(medium=hBN_nd),
    layer_wse2.updated_copy(medium=wse2_nd),
]
Min. design pixels per wavelength in Si: 23.3

Sources, Monitors and Base Simulation

An x-polarized plane wave illuminates the unit cell from above, with periodic boundaries in x and y and PML in z. A point monitor at the cavity center records the field for the figure of merit. Field cuts, flux planes and a far-field projection monitor are added for validation. The same source time drives an x-oriented dipole at the hotspot in the emission runs.

The x and y grids match the design pixels. The z grid is automatic, refined across the hBN layer by a LayerRefinementSpec and snapped to the source, monitor and hotspot planes, so a grid point lies on the WSe2 sheet. The sheet’s 0.3 nm offset above the Si surface is needed because placing a 2D medium directly on top of a custom medium (here, the Si design region) raises an error.

plane_wave = td.PlaneWave(
    source_time=td.GaussianPulse(freq0=f0, fwidth=fwidth),
    center=(0, 0, z_src),
    size=(td.inf, td.inf, 0),
    direction="-",
    pol_angle=0,
)
dipole = td.PointDipole(
    center=(0, 0, z_wse2), source_time=plane_wave.source_time, polarization="Ex"
)

# FOM point monitor.
mnt_point = td.FieldMonitor(
    center=(0, 0, z_wse2),
    size=(0, 0, 0),
    freqs=[f_target],
    name="field",
    fields=["Ex"],
)

field_monitors = [
    td.FieldMonitor(center=(0, 0, z_surface), size=size, freqs=freqs, name=name)
    for name, size in [
        ("field_xy", (td.inf, td.inf, 0)),
        ("field_xz", (td.inf, 0, td.inf)),
        ("field_yz", (0, td.inf, td.inf)),
    ]
]

flux_up = td.FluxMonitor(
    center=(0, 0, z_flux_up),
    size=(td.inf, td.inf, 0),
    freqs=freqs,
    name="flux_up",
    normal_dir="+",
)
flux_down = flux_up.updated_copy(
    center=(0, 0, z_flux_down), normal_dir="-", name="flux_down"
)
# Net flux P_inj - R. The injected power P_inj = flux_net + flux_up is not exactly 1 W.
flux_net = flux_up.updated_copy(
    center=(0, 0, z_flux_net), normal_dir="-", name="flux_net"
)

angle_mnt = td.FieldProjectionAngleMonitor(
    center=plane_wave.center,
    size=plane_wave.size,
    name="angle",
    normal_dir="+",
    freqs=[f_target],
    custom_origin=(0, 0, z_wse2),
    proj_distance=wvl_target * 10000,
    theta=np.linspace(0, 90, 91) * np.pi / 180,
    phi=np.linspace(0, 360, 721) * np.pi / 180,
)


def gridspec_with_refinement(min_steps_per_wvl=20, min_steps_along_axis=3):
    return td.GridSpec(
        grid_x=td.UniformGrid(dl=PIXEL_SIZE),
        grid_y=td.UniformGrid(dl=PIXEL_SIZE),
        grid_z=td.AutoGrid(min_steps_per_wvl=min_steps_per_wvl),
        wavelength=wvls.min(),
        snapping_points=[
            (0, 0, z) for z in (z_src, z_flux_up, z_flux_down, z_flux_net, z_wse2)
        ],
        layer_refinement_specs=[
            td.LayerRefinementSpec.from_structures(
                structures=[layer_hbn],
                axis=2,
                min_steps_along_axis=min_steps_along_axis,
            )
        ],
    )


sim_base = td.Simulation(
    size=(P, P, z_max - z_min),
    center=(0, 0, (z_max + z_min) / 2),
    grid_spec=gridspec_with_refinement(),
    structures=base_structures,
    sources=[plane_wave],
    monitors=[*field_monitors, mnt_point, flux_up, flux_down],
    run_time=td.RunTimeSpec(quality_factor=20, source_factor=200),
    shutoff=1e-6,
    boundary_spec=td.BoundarySpec(
        x=td.Boundary.periodic(), y=td.Boundary.periodic(), z=td.Boundary.pml()
    ),
    # x-polarized normal incidence.
    symmetry=(-1, 1, 0),
)

# Stack and grid at x = 0: close-up, then a wider view.
for xlim, ylim in [((-0.02, 0.02), (0.09, 0.125)), ((0, 0.2), (0.05, 0.35))]:
    fig, ax = plt.subplots()
    sim_base.plot(x=0, ax=ax)
    sim_base.plot_grid(x=0, ax=ax)
    ax.set(xlim=xlim, ylim=ylim)

sim_base.plot_3d()

Design Parameters to Structure

The latent parameters are mirror-symmetrized in x and y, smoothed with a conic filter of radius R_BLUR (ConicFilter), and projected toward 0 or 1 (tanh_projection). The filter uses periodic ("wrap") padding, so features that cross the unit-cell boundary are smoothed consistently with the neighboring cells of the array. A central slit of 2 × 4 pixels (about 15 nm along x by 30 nm along y) is then forced to air by multiplying the density with a constant mask (CENTER_MASK). The slit is narrow along the x polarization, so it opens a gap across which the field is concentrated at the hotspot.

get_density returns this masked density and is used everywhere the design is turned into a structure or plotted. The density interpolates the pole-residue permittivity of Si with air in a CustomPoleResidue medium. For more on a periodic design region with a density-based pole-residue model, see the metasurface color router example.

# Pixel centers of one unit cell.
x_design = np.linspace(-P / 2 + PIXEL_SIZE / 2, P / 2 - PIXEL_SIZE / 2, N_DESIGN)


def preprocess(arr, beta=BETA_INIT, eta=0.5, radius=R_BLUR):
    # Mirror symmetry in x and y, then filter with periodic padding (the design
    # region is one period of the array) and project.
    arr = (arr + arr[:, ::-1]) / 2
    arr = (arr + arr[::-1]) / 2
    conic_filter = ConicFilter.from_radius_dl(
        radius=radius, dl=PIXEL_SIZE, padding="wrap"
    )
    return tanh_projection(conic_filter(arr), beta=beta, eta=eta)


# Constant mask that zeroes the central pixels of each unit cell.
_c = N_DESIGN // 2
CENTER_MASK = np.ones((N_DESIGN, N_DESIGN, 1))
CENTER_MASK[_c - 1 : _c + 1, _c - 2 : _c + 2] = 0.0


def get_density(params, beta=BETA_INIT):
    # Projected density with the central pixels forced to air.
    return preprocess(params, beta=beta) * CENTER_MASK[..., 0]


def get_design_structure(params, beta=BETA_INIT, repeat=(1, 1)):
    # eps(density) = 1 + density * (eps_Si - 1) at every frequency, tiled `repeat` times.
    density = get_density(params, beta=beta)[..., None]
    density = np.tile(density, (*repeat, 1))
    coords = {
        dim: np.linspace(
            -P * n / 2 + PIXEL_SIZE / 2, P * n / 2 - PIXEL_SIZE / 2, N_DESIGN * n
        )
        for dim, n in zip("xy", repeat)
    } | {"z": [t_si / 2]}
    eps_inf = td.SpatialDataArray(1 + (si.eps_inf - 1) * density, coords=coords)
    poles = [
        (
            td.SpatialDataArray(a * np.ones_like(density), coords=coords),
            td.SpatialDataArray(c * density, coords=coords),
        )
        for a, c in si.poles
    ]
    return td.Structure(
        geometry=td.Box(center=(0, 0, t_si / 2), size=(td.inf, td.inf, t_si)),
        medium=td.CustomPoleResidue(eps_inf=eps_inf, poles=poles),
    )

Simulation Builders

make_sim builds either the plane-wave unit-cell simulation used for optimization and absorption (“fwd”), or a supercell excited by the x-dipole at the hotspot (“bwd”) for emission analysis. The supercell has PML on all sides and uses the non-dispersive hBN and WSe2; the validation runs below also replace its design region with non-dispersive Si PolySlabs. Its monitors are single-frequency and stop just short of the side PML, which Tidy3D adds outside the simulation box. A closed flux box around the stack records the total power leaving it, including the part guided sideways along the layers.

def supercell_monitors(repeat=SUPERCELL):
    # Single-frequency monitors stopping just short of the x/y PML.
    l_in = P * repeat[0] - 2 * PIXEL_SIZE
    field_cuts = [
        m.updated_copy(
            size=tuple(l_in if s == td.inf else s for s in m.size[:2]) + (m.size[2],),
            freqs=[f_target],
        )
        for m in field_monitors
    ]
    flux_planes = [
        m.updated_copy(size=(l_in, l_in, 0), freqs=[f_target])
        for m in (flux_up, flux_down)
    ]
    # Closed box: total power = up + down + sides.
    flux_box = td.FluxMonitor(
        center=(0, 0, (z_flux_up + z_flux_down) / 2),
        size=(l_in, l_in, z_flux_up - z_flux_down),
        freqs=[f_target],
        name="flux_box",
    )
    return [
        *field_cuts,
        *flux_planes,
        flux_box,
        angle_mnt.updated_copy(size=(l_in, l_in, 0)),
    ]


def make_sim(params, beta=BETA_INIT, validation=False, sim_type="fwd"):
    # "fwd": plane wave on a periodic unit cell. "bwd": x-dipole in a PML-bounded supercell.
    # hBN/WSe2 are non-dispersive except in "fwd" validation runs. Without `validation`, only
    # the FOM monitor is kept.
    if sim_type == "fwd":
        repeat = (1, 1)
        sources = [plane_wave]
        monitors = [*field_monitors, flux_up, flux_down, flux_net, mnt_point]
        boundary_spec = sim_base.boundary_spec
        structures = base_structures if validation else base_structures_nd
    elif sim_type == "bwd":
        repeat = SUPERCELL
        sources = [dipole]
        monitors = supercell_monitors(repeat)
        boundary_spec = td.BoundarySpec(
            x=td.Boundary.pml(num_layers=30),
            y=td.Boundary.pml(num_layers=30),
            z=td.Boundary.pml(),
        )
        structures = base_structures_nd
    else:
        raise ValueError(f"sim_type must be 'fwd' or 'bwd', got {sim_type!r}.")

    lx, ly, lz = sim_base.size
    return sim_base.updated_copy(
        size=(lx * repeat[0], ly * repeat[1], lz),
        sources=sources,
        structures=[
            *structures,
            get_design_structure(params, beta=beta, repeat=repeat),
        ],
        monitors=monitors if validation else [mnt_point],
        boundary_spec=boundary_spec,
    )

Grid Check: Flat Si/WSe2/hBN Film vs Transfer Matrix

Before optimizing, we check that the z grid resolves the thin layers. The flat Si film under the same hBN/WSe2 stack is a 1D problem, so its reflectance \(R\), transmittance \(T\), and absorbance \(A = 1 - R - T\) can be computed exactly with a transfer matrix (TMM). The WSe2 sheet enters it as a boundary condition with sheet conductivity \(\sigma\).

We run the flat film with 1, 3 (the setting used by sim_base) and 10 z cells across the 13.4 nm hBN layer (min_steps_along_axis of the layer refinement) and compare each with TMM. The 10-cell grid is expensive to use in every optimization step, while the 3-cell grid already agrees well with TMM, so sim_base uses 3 cells.

# Incident field of a 1 W plane wave over the unit cell.
E_INC = np.sqrt(2 * td.ETA_0) / P


def incident_power(sim_data):
    return sim_data["flux_net"].flux + sim_data["flux_up"].flux


def incident_field(sim_data, f=f_target):
    return E_INC * np.sqrt(incident_power(sim_data).sel(f=f, method="nearest").item())


def rta_spectra(sim_data):
    p_inj = incident_power(sim_data)
    return {
        "R": sim_data["flux_up"].flux / p_inj,
        "T": sim_data["flux_down"].flux / p_inj,
        "A": (sim_data["flux_net"].flux - sim_data["flux_down"].flux) / p_inj,
    }


def tmm_flat_stack(freq):
    # Indices are conjugated: Tidy3D uses exp(-i w t), the textbook matrices exp(+i w t).
    k0 = 2 * np.pi * freq / td.C_0
    n_hbn = np.conj(np.sqrt(hBN.xx.eps_model(freq)))
    n_si_f = np.conj(np.sqrt(si.eps_model(freq)))
    sheet = np.array([[1, 0], [np.conj(wse2.sigma_model(freq)) * td.ETA_0, 1]])

    def layer(n, d):
        phi = k0 * n * d
        return np.array(
            [[np.cos(phi), 1j * np.sin(phi) / n], [1j * n * np.sin(phi), np.cos(phi)]]
        )

    # (E, eta0 * H) for a unit transmitted field.
    b, c = layer(n_hbn, t_hbn) @ sheet @ layer(n_si_f, t_si) @ np.array([1, n_sapphire])
    r, t = (b - c) / (b + c), 2 / (b + c)
    return abs(r) ** 2, n_sapphire * abs(t) ** 2


tmm_r, tmm_t = np.array([tmm_flat_stack(f) for f in freqs]).T
tmm = {"R": tmm_r, "T": tmm_t, "A": 1 - tmm_r - tmm_t}

# Flat Si film; the design layer from make_sim is replaced.
sim_flat = make_sim(np.zeros((N_DESIGN, N_DESIGN)), validation=True).updated_copy(
    structures=[*base_structures, si_layer],
    monitors=[flux_up, flux_down, flux_net, mnt_point],
)

HBN_STEPS = [1, 3, 10]  # sim_base uses 3
grid_sims = {
    f"hbn_{n}": sim_flat.updated_copy(
        grid_spec=gridspec_with_refinement(min_steps_along_axis=n)
    )
    for n in HBN_STEPS
}
grid_data = web.run_async(
    simulations=grid_sims,
    path_dir=SIM_DIR / "grid_check",
    folder_name=FOLDER_NAME,
    verbose=False,
)
grid_spectra = {n: rta_spectra(grid_data[f"hbn_{n}"]) for n in HBN_STEPS}

fig, ax = plt.subplots()
for color, key in zip(["C0", "C1", "C2"], ("R", "T", "A")):
    for n, ls in zip(HBN_STEPS, [":", "-.", "-"]):
        ax.plot(
            energy_list,
            grid_spectra[n][key],
            color=color,
            ls=ls,
            label=f"{key}, {n} cells",
        )
    ax.plot(energy_list, tmm[key], "k--", lw=1, label="TMM" if key == "A" else None)
ax.axvline(energy_target, color="k", ls=":", lw=1)
ax.set(xlabel="Energy (eV)", ylabel="R, T, A", xlim=energy_list[[0, -1]], ylim=(0, 1))
ax.legend(ncols=2, fontsize="small");

Optimization

Objective Function

The figure of merit is the intensity enhancement \(|E_x / E_\mathrm{inc}|^2\) at the cavity center on the Si top surface, as in the paper, where \(E_\mathrm{inc}\) is the field of a 1 W plane wave spread over the unit cell (E_INC). grad_and_aux returns its gradient with respect to the design parameters (via the adjoint method) together with the FOM and enhancement for logging.

def field_enhancement(sim_data):
    # Normalized to the nominal 1 W.
    Ex = sim_data["field"].Ex.squeeze().data
    return np.abs(Ex / E_INC)


def param2fom(params, beta=BETA_INIT, step=0):
    sim = make_sim(params, beta=beta)
    sim_data = web.run(
        simulation=sim,
        path=SIM_DIR / f"step_{step}.hdf5",
        folder_name=FOLDER_NAME,
        task_name=f"step{step}",
        verbose=False,
    )
    enhancement = field_enhancement(sim_data)
    fom = enhancement**2
    return fom, [getval(fom).item(), getval(enhancement).item()]


grad_aux_p2f = grad_and_aux(param2fom)

Iteration

Starting from a uniform gray design, we run gradient ascent with Adam. The projection strength \(\beta\) rises geometrically over the first N_STEP_RAMP steps, so the design gradually becomes binary, and is then held at BETA_MAX for the remaining steps. The parameters, gradients, FOM, enhancement and \(\beta\) of every step are saved to opt_history.npz.

history_path = SIM_DIR / "opt_history.npz"

beta_schedule = np.concat(
    [
        np.geomspace(BETA_INIT, BETA_MAX, N_STEP_RAMP),
        np.full(N_STEP - N_STEP_RAMP, BETA_MAX),
    ]
)

params = np.full((N_DESIGN, N_DESIGN), 0.5)  # uniform gray start
optimizer = adam(learning_rate=LR, beta1=0.8, beta2=0.95)
opt_state = optimizer.init(params)
opt_history = {key: [] for key in ("params", "grad", "fom", "enhancement", "beta")}

print(f"{'STEP':<5}{'BETA':>10}{'FOM':>12}{'Enhance.':>12}{'max|grad|':>12}")
print("-" * 51)
for step, beta in enumerate(beta_schedule):
    grad, [fom, enhancement] = grad_aux_p2f(params, beta=beta, step=step)
    for key, value in zip(
        opt_history, (params.copy(), grad.copy(), fom, enhancement, float(beta))
    ):
        opt_history[key].append(value)
    print(
        f"{step:<5}{beta:>10.2f}{fom:>12.3f}{enhancement:>12.3f}{np.abs(grad).max():>12.2e}"
    )

    # Gradient ascent, with parameters kept in [0, 1].
    updates, opt_state = optimizer.update(-grad, opt_state, params)
    params = np.clip(apply_updates(params, updates), 0, 1)

np.savez(history_path, **opt_history)
STEP       BETA         FOM    Enhance.   max|grad|
---------------------------------------------------
0          1.00       0.577       0.760    3.11e-02
1          1.51       0.813       0.902    5.05e-02
2          2.29       1.132       1.064    8.59e-02
3          3.47       2.405       1.551    2.54e-01
4          5.24      13.093       3.618    1.64e+00
5          7.94      13.124       3.623    2.76e+00
6         12.01      48.449       6.961    1.11e+01
7         18.18      26.730       5.170    7.14e+00
8         27.51      32.335       5.686    6.80e+00
9         41.63      66.065       8.128    2.30e+01
10        63.00      87.546       9.357    2.92e+01
11        95.33      88.369       9.400    6.06e+01
12       144.27      95.627       9.779    1.32e+02
13       218.33     177.615      13.327    1.43e+02
14       330.40     195.977      13.999    1.11e+03
15       500.00     304.236      17.442    3.37e+02
16       500.00     472.870      21.746    2.34e+02
17       500.00     451.986      21.260    1.22e+02
18       500.00     543.892      23.321    1.26e+02
19       500.00     603.414      24.564    8.47e+02
20       500.00     648.409      25.464    1.19e+02
21       500.00     658.248      25.656    5.92e+02
22       500.00     702.492      26.505    5.25e+02
23       500.00     676.248      26.005    2.33e+02
24       500.00     749.034      27.368    4.47e+01
25       500.00     739.735      27.198    2.85e+02
26       500.00     777.977      27.892    2.91e+02
27       500.00     788.423      28.079    1.39e+02
28       500.00     814.879      28.546    2.19e+01
29       500.00     819.044      28.619    7.61e+01

Results and Analysis

Optimization Results

The FOM can jump between steps at high \(\beta\), so instead of the last iterate we take the best design among the steps at \(\beta = \beta_\mathrm{max}\) (shaded), where the projected density is nearly binary.

betas = np.asarray(opt_history["beta"])
foms = np.asarray(opt_history["fom"])
at_beta_max = np.flatnonzero(betas == BETA_MAX)
opt_idx = int(at_beta_max[np.argmax(foms[at_beta_max])])
params_opt = opt_history["params"][opt_idx]
beta_opt = betas[opt_idx]
density_opt = get_density(params_opt, beta=beta_opt)
print(f"Selected step {opt_idx}: beta = {beta_opt:.0f}, FOM = {foms[opt_idx]:.1f}")

fig, ax = plt.subplots()
ax.semilogy(foms, ".-")
ax.axvspan(at_beta_max[0] - 0.5, len(foms) - 0.5, color="0.9", zorder=0)
ax.plot(opt_idx, foms[opt_idx], "r*", ms=12, label="selected")
ax.set(
    xlabel="Iteration", ylabel="FOM $|E_x / E_{inc}|^2$", title="Optimization history"
)
ax.legend();
Selected step 29: beta = 500, FOM = 819.0

Conversion to PolySlabs

design_to_polyslabs converts the masked density of a design into binary PolySlab structures with Structure.list_from_dataarray, which traces the density contour halfway between its minimum and maximum. The density is first padded by one pixel on each side with its periodic continuation, so that features crossing the unit-cell boundary reach the cell edge. repeat tiles the density for the supercell. The vertices of each contour are then Gaussian-smoothed over smooth_sigma neighboring vertices to remove the staircase left by the pixel grid. smooth_sigma counts vertices rather than a length, and values much above 1 start to widen the bowtie gap. The contour is returned as Si structures for the solid regions and air structures for the holes inside them, and their vertices can be exported to a GDS layout for fabrication.

Below, the latent parameters and the masked density of the selected design are shown with the extracted contours (red). The density converges to a bowtie-like feature at the cavity center, with the forced air slit between its two tips (zoom).

def design_to_polyslabs(params, beta, medium, repeat=(1, 1), smooth_sigma=1.0):
    """Binarize the projected density into Si (`medium`) and air PolySlab structures."""
    # Pad with the periodic continuation so that the contour reaches the cell edges.
    density = np.pad(np.tile(get_density(params, beta=beta), repeat), 1, mode="wrap")
    coords = {
        dim: (np.arange(n) - (n - 1) / 2) * PIXEL_SIZE
        for dim, n in zip("xy", density.shape)
    } | {"z": [t_si / 2]}
    return td.Structure.list_from_dataarray(
        data=td.SpatialDataArray(density[..., None], coords=coords),
        slab_bounds=(0, t_si),
        foreground_medium=medium,
        background_medium=td.Medium(),
        name_prefix="Si cavity",
        smooth_sigma=smooth_sigma,
    )


def plot_density(data, ax, polyslabs=(), lim=P / 2):
    ax.pcolormesh(
        x_design, x_design, data.T, shading="auto", cmap="gray_r", vmin=0, vmax=1
    )
    for structure in polyslabs:
        xy = np.vstack([structure.geometry.vertices, structure.geometry.vertices[:1]])
        ax.plot(xy[:, 0], xy[:, 1], "r", lw=1.5)
    ax.set(aspect="equal", xlim=(-lim, lim), ylim=(-lim, lim), xlabel="x (µm)")


polyslabs_opt = design_to_polyslabs(params_opt, beta_opt, medium=si)

fig, ax = plt.subplots(1, 3, figsize=(12, 4), layout="constrained")
plot_density(params_opt, ax[0])
plot_density(density_opt, ax[1], polyslabs_opt)
plot_density(density_opt, ax[2], polyslabs_opt, lim=0.1)
ax[1].indicate_inset_zoom(ax[2], edgecolor="g", lw=3)
ax[0].set(title="Design parameters", ylabel="y (µm)")
ax[1].set(title="Density with PolySlab contours", yticklabels=[])
ax[2].set(title="Center zoom", yticklabels=[]);

Define and Run Validation Simulations

Each plane-wave simulation of the cavity is run twice: with the custom-medium design region built by make_sim (“opt”) and with that region converted to PolySlabs by design_to_polyslabs (“poly”). We compare them against a flat Si film of the same thickness (“ref”), and also run the cavity without the WSe2/hBN stack (“cavityonly”). The dipole runs use only the PolySlab design, built from the non-dispersive materials so that nothing dispersive enters the side PML. All simulations run as one batch.

sims = {}
for sim_type in ("fwd", "bwd"):
    base, si_medium = (
        (base_structures, si) if sim_type == "fwd" else (base_structures_nd, si_nd)
    )
    sim_opt = make_sim(params_opt, beta=beta_opt, validation=True, sim_type=sim_type)
    repeat = (1, 1) if sim_type == "fwd" else SUPERCELL
    design_polyslabs = design_to_polyslabs(params_opt, beta_opt, si_medium, repeat)
    if sim_type == "fwd":
        # No dispersive custom medium in the dipole supercell's PML.
        sims["opt_fwd"] = sim_opt
    sims[f"poly_{sim_type}"] = sim_opt.updated_copy(
        structures=[*base, *design_polyslabs]
    )
    sims[f"ref_{sim_type}"] = sim_opt.updated_copy(
        structures=[*base, si_layer.updated_copy(medium=si_medium)]
    )

# Cavity without hBN and WSe2.
sims["opt_cavityonly_fwd"] = sims["opt_fwd"].updated_copy(
    structures=[substrate, sims["opt_fwd"].structures[-1]]
)
sims["poly_cavityonly_fwd"] = sims["poly_fwd"].updated_copy(
    structures=[substrate, *polyslabs_opt]
)

LABELS = {
    "opt_fwd": "Cavity",
    "poly_fwd": "Cavity (PolySlab)",
    "opt_cavityonly_fwd": "Cavity w/o WSe2/hBN",
    "poly_cavityonly_fwd": "Cavity w/o WSe2/hBN (PolySlab)",
    "ref_fwd": "Flat Si",
    "poly_bwd": "Cavity (PolySlab)",
    "ref_bwd": "Flat Si",
}
result_dir = SIM_DIR / "result"
batch_data = web.run_async(
    simulations=sims, path_dir=result_dir, folder_name=FOLDER_NAME
)
Uploading data for 7 tasks ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100% 0:00:08

14:29:13 UTC Started working on Batch containing 7 tasks.                       
14:29:26 UTC Maximum FlexCredit cost: 12.464 for the whole batch.               
             Use 'Batch.real_cost()' to get the billed FlexCredit cost after    
             completion.                                                        
14:38:11 UTC Batch complete.                                                    
opt_fwd             → success ━━━━━━━━━━━━━━━━━━━━━━━━━ 100% 0:08:42
poly_fwd            → success ━━━━━━━━━━━━━━━━━━━━━━━━━ 100% 0:03:36
ref_fwd             → success ━━━━━━━━━━━━━━━━━━━━━━━━━ 100% 0:00:10
poly_bwd            → success ━━━━━━━━━━━━━━━━━━━━━━━━━ 100% 0:01:44
ref_bwd             → success ━━━━━━━━━━━━━━━━━━━━━━━━━ 100% 0:00:48
opt_cavityonly_f... → success ━━━━━━━━━━━━━━━━━━━━━━━━━ 100% 0:05:47
poly_cavityonly_... → success ━━━━━━━━━━━━━━━━━━━━━━━━━ 100% 0:03:10

Field Enhancement under Plane-Wave Illumination

The field enhancement \(|E| / E_\mathrm{inc}\) of the cavity at 1.65 eV, normalized to the power actually injected by the plane wave, is plotted on the xy plane at the Si surface and on the xz and yz cuts through the cavity center, with the structure outline (xy) and the layer interfaces (xz, yz) dashed.

def in_plane_dims(field_data):
    normal_axis = field_data.monitor.size.index(0)
    return [d for i, d in enumerate("xyz") if i != normal_axis]


def plot_map(data, ax, label, cmap, interfaces_color, extend="neither", **kwargs):
    h, v = data.dims
    im = ax.pcolormesh(data[h], data[v], data.T, cmap=cmap, shading="auto", **kwargs)
    plt.colorbar(im, cax=ax.inset_axes([1.03, 0, 0.03, 1]), label=label, extend=extend)
    if v == "z":
        for z_interface in z_interfaces:
            ax.axhline(z_interface, color=interfaces_color, ls="--", lw=0.5)
    ax.set(aspect="equal", xlabel=f"{h} (µm)", ylabel=f"{v} (µm)")


def field_enhancement_map(sim_data, monitor_name, f=f_target):
    field_data = sim_data[monitor_name]
    intensity = field_data.intensity.sel(f=f, method="nearest").squeeze()
    return np.sqrt(intensity.transpose(*in_plane_dims(field_data))) / incident_field(
        sim_data, f
    )


fig, ax = plt.subplots(3, 1, figsize=(5, 10), layout="constrained")
for a, monitor_name in zip(
    ax,
    [
        "field_xy",
        "field_xz",
        "field_yz",
    ],
):
    enhancement = field_enhancement_map(batch_data["opt_fwd"], monitor_name)
    plot_map(
        enhancement, a, "|E| / E$_{inc}$", "magma", "w", vmin=0, vmax=20, extend="max"
    )
    a.set_title(f"{LABELS['opt_fwd']}, {monitor_name}")
# Structure outline: the 0.5 contour of the masked density.
ax[0].contour(
    x_design,
    x_design,
    density_opt.T,
    levels=[0.5],
    colors="w",
    linestyles="--",
    linewidths=0.8,
)
ax[0].set(xlim=(-P / 2, P / 2), ylim=(-P / 2, P / 2))
ax[1].set(xlim=(-P / 2, P / 2), ylim=(z_min, z_max))
ax[2].set(xlim=(-P / 2, P / 2), ylim=(z_min, z_max));

Absorption

The absorbance is the power entering the stack minus the power transmitted into the substrate, normalized to the injected power. It is compared between the cavity with and without the WSe2/hBN stack and the flat Si film. Solid lines use the custom-medium design and dashed lines its PolySlab conversion. The black dashed line is the exact TMM absorbance of the flat film from the grid check above.

fig, ax = plt.subplots()
for name, color, ls in [
    ("opt_fwd", "C0", "-"),
    ("poly_fwd", "C0", "--"),
    ("opt_cavityonly_fwd", "C1", "-"),
    ("poly_cavityonly_fwd", "C1", "--"),
    ("ref_fwd", "C2", "-"),
]:
    absorption = rta_spectra(batch_data[name])["A"]
    ax.plot(energy_list, absorption, color=color, ls=ls, label=LABELS[name])
ax.plot(energy_list, tmm["A"], color="k", ls="--", label="Flat Si (TMM)")

ax.axvline(energy_target, color="k", ls=":", lw=1)
ax.set(
    xlabel="Energy (eV)", ylabel="Absorbance", xlim=energy_list[[0, -1]], ylim=(0, 0.8)
)
ax.legend();

Emission from Dipole Source

An x-oriented dipole at the hotspot models the WSe2 exciton emission. We compare the near field \(\mathrm{Re}(E_x)\) on the xz and yz cuts for the cavity supercell and the flat Si film. The color scale is clipped at the 99.5th percentile so the singular field right at the dipole does not wash out the plot.

def get_field_cut(sim_data, monitor_name, field_name="Ex", f=f_target):
    field_data = sim_data[monitor_name]
    field = getattr(field_data, field_name).sel(f=f, method="nearest").squeeze()
    return field.transpose(*in_plane_dims(field_data))


panels = [
    (name, monitor)
    for monitor in ["field_xz", "field_yz"]
    for name in ["poly_bwd", "ref_bwd"]
]
fig, ax = plt.subplots(
    len(panels), 1, figsize=(9, 7), sharex=True, sharey=True, layout="constrained"
)
for a, (name, monitor) in zip(ax, panels):
    field = np.real(get_field_cut(batch_data[name], monitor))
    vmax = np.percentile(np.abs(field), 99.5)
    plot_map(field, a, "Re($E_x$) (a.u.)", "RdBu_r", "k", vmin=-vmax, vmax=vmax)
    a.set_title(f"{LABELS[name]}, {monitor}")
ax[0].set(xlim=(-P * SUPERCELL[0] / 2, P * SUPERCELL[0] / 2), ylim=(z_min, z_max));

Directivity

From the far-field projection of the dipole emission, we compute the directivity \(D = 4\pi I(\theta, \phi) / P_\mathrm{tot}\) as in Fig. 2 of the paper. The left column maps \(D\) on a linear color scale over the back focal plane (radius \(\sin\theta\)), scaled separately for each structure; the right column shows the xz and yz cuts in dBi on a shared radial axis. We also report the fractions of the total power radiated upward (\(P_\mathrm{up}\)) and into the NA = 0.9 collection cone of the objective (\(P_\mathrm{NA}\)). \(P_\mathrm{tot}\) is the power leaving the closed flux box around the stack. The part leaving through its sides (\(P_\mathrm{side}\)), guided along the layers out of the supercell, is reported separately. For the cavity, a large fraction would mean the supercell is too small; for the flat film, it is the guided mode of the Si layer.

NA = 0.9


def flux_at(sim_data, monitor_name, f=f_target):
    return np.abs(sim_data[monitor_name].flux.sel(f=f, method="nearest").item())


def compute_directivity(sim_data, f=f_target):
    # D = 4 pi I / P_tot, with P_tot from the closed flux box.
    proj = sim_data["angle"]
    intensity = proj.power.sel(f=f, method="nearest").squeeze("r") * proj.r.item() ** 2
    p_tot = flux_at(sim_data, "flux_box", f)
    return 4 * np.pi * intensity.transpose("theta", "phi") / p_tot


def emission_summary(sim_data, na=NA):
    directivity = compute_directivity(sim_data)
    theta, phi = directivity.theta.values, directivity.phi.values
    d_omega = (
        np.sin(theta)[:, None] * np.gradient(theta)[:, None] * np.gradient(phi)[None, :]
    )
    power = directivity.values / (4 * np.pi) * d_omega
    p_tot = flux_at(sim_data, "flux_box")
    i_theta, i_phi = np.unravel_index(directivity.values.argmax(), directivity.shape)
    return directivity, {
        "D_max": directivity.values.max(),
        "theta_max": np.degrees(theta[i_theta]),
        "phi_max": np.degrees(phi[i_phi]),
        "up": power.sum(),
        "NA": power[np.sin(theta) <= na].sum(),
        "side": 1
        - (flux_at(sim_data, "flux_up") + flux_at(sim_data, "flux_down")) / p_tot,
    }


def to_dbi(directivity):
    return 10 * np.log10(np.maximum(directivity, 1e-12))


def plot_radiation_pattern(directivity, ax_bfp, ax_cut, d_max, vmin, vmax, na=NA):
    theta, phi = directivity.theta.values, directivity.phi.values
    d_dbi = to_dbi(directivity).clip(min=vmin)

    # Back-focal-plane view, linear scale.
    im = ax_bfp.pcolormesh(
        phi,
        np.sin(theta),
        directivity.values,
        shading="auto",
        cmap="magma",
        vmin=0,
        vmax=d_max,
    )
    ax_bfp.plot(np.linspace(0, 2 * np.pi, 361), np.full(361, na), "g--", lw=1)
    ax_bfp.set(ylim=(0, 1), yticklabels=[], title=f"D(θ, φ), NA = {na} (dashed)")
    plt.colorbar(im, ax=ax_bfp, pad=0.1, label="Directivity")

    theta_full = np.concatenate([-theta[::-1], theta])
    for phi0, label in [(0, "xz (φ = 0°)"), (np.pi / 2, "yz (φ = 90°)")]:
        d_pos = d_dbi.sel(phi=phi0, method="nearest").values
        d_neg = d_dbi.sel(phi=phi0 + np.pi, method="nearest").values
        ax_cut.plot(theta_full, np.concatenate([d_neg[::-1], d_pos]), label=label)
    ax_cut.set(
        thetamin=-90,
        thetamax=90,
        theta_zero_location="N",
        theta_direction=-1,
        rlim=(vmin, vmax),
        title="Directivity cuts (dBi)",
    )
    # Polar r-axis wraps its locator in RadialLocator, which ignores locator_params.
    ax_cut.yaxis.set_major_locator(plt.MaxNLocator(3))
    ax_cut.legend(loc="lower center", bbox_to_anchor=(0.5, -0.15), ncols=2)


names = ["poly_bwd", "ref_bwd"]
results = {name: emission_summary(batch_data[name]) for name in names}

# Linear colormap per row, from 0 to max(peak D, 2). The dBi cuts share a radial
# axis topped at the overall peak with a 30 dB range.
DYNAMIC_RANGE_DB = 30
vmax = np.ceil(max(to_dbi(s["D_max"]) for _, s in results.values()))
vmin = vmax - DYNAMIC_RANGE_DB

fig = plt.figure(figsize=(10, 4.5 * len(names)), layout="constrained")
label_width = max(len(LABELS[name]) for name in names) + 2
print(
    f"{'':<{label_width}}{'max D (dBi)':>12}{'(θ, φ)':>12}{'P_up':>8}{'P_NA':>8}{'P_side':>8}  (fractions of P_tot)"
)
for row, name in enumerate(names):
    directivity, s = results[name]
    angles = f"({s['theta_max']:.0f}°, {s['phi_max']:.0f}°)"
    print(
        f"{LABELS[name]:<{label_width}}{to_dbi(s['D_max']):>12.2f}{angles:>12}"
        f"{s['up']:>8.3f}{s['NA']:>8.3f}{s['side']:>8.3f}"
    )
    ax_bfp, ax_cut = (
        fig.add_subplot(len(names), 2, 2 * row + i, projection="polar") for i in (1, 2)
    )
    plot_radiation_pattern(directivity, ax_bfp, ax_cut, max(s["D_max"], 2), vmin, vmax)
    ax_bfp.text(
        -0.25, 0.5, LABELS[name], transform=ax_bfp.transAxes, rotation=90, va="center"
    )
                    max D (dBi)      (θ, φ)    P_up    P_NA  P_side  (fractions of P_tot)
Cavity (PolySlab)         14.31    (0°, 1°)   0.452   0.440   0.016
Flat Si                   -3.73    (0°, 0°)   0.099   0.084   0.241