A two-colour metalens: silicon nitride ridges that focus green and red light on one line#
Question. A row of silicon nitride ridges on glass is lit from the glass by green (532 nm) and red (633 nm) laser light at normal incidence, with the electric field along the ridges (TE). Which ridge widths, one per cell across a 120 µm aperture, focus both colours on the same line 300 µm behind the ridges?
A lens this size is far too big to solve whole: 401 ridges, each a fraction of a wavelength wide, over a hundred wavelengths of aperture. The way out is the locally periodic approximation: replace each ridge by the infinite array of itself and let it send out the one plane wave that array radiates. So we solve one cell, once, for a range of widths, and tabulate how a ridge transmits light against its width (the cell response, what the literature calls a unit-cell or phase library). Placing a tabulated cell at every position gives the field behind the lens (the aperture field), the angular spectrum carries it to the focus, and gradients through the whole chain choose the widths:
ridge width \(w_j\) → cell response \(t(w_j)\) → aperture field → propagation to the focus → focal intensity of each colour → soft minimum → optimizer.
The cell is a periodic cell with Floquet ports, as in Topology optimization of a metagrating: a silicon grating on glass that bends light by 50°; the helpers
live in gfem.diffraction.
Assumptions.
The lens is a row of lines along \(y\), one ridge per cell, a cylindrical lens: it focuses along \(x\) only. Each ridge sits in a cell of pitch \(a = 0.3\) µm and height 1.1 µm, with widths from 0.07 to 0.23 µm. Its aspect ratio reaches 16, aggressive but within what is reported for nitride metasurfaces.
The ridge is silicon nitride, with the dispersive law of the material library (
gfem.materials.silicon_nitride()), inside the cell at both colours. The glass is silica at 633 nm, a constant: a Floquet half-space needs a constant index. Silica’s index differs by 0.004 between the two colours, which this page neglects. The air above is lossless.At normal incidence the pitch is below \(\lambda/n_\text{glass} = 0.364\) µm at 532 nm, the shorter colour, so only the specular order propagates on either side: four Floquet ports (TE and TM on each face) are complete, and nothing else leaves the cell.
The approximation neglects the coupling between neighbouring ridges. The last sections measure what that costs.
Second-order elements on a mesh of 0.0375 µm cells across the ridge and 0.05 µm high: one section checks the second digit against third order.
The physics. Each colour reaches the focus through the phase \(\varphi_j\) that ridge \(j\) adds to the light. An ideal lens at wavelength \(\lambda\) has unit transmission and the phase
for a field that propagates as \(e^{-ik_z d}\): the extra path of a ray from \(x\), compared with the axis. A ridge adds phase through its width, but the same width adds a different phase to green and to red, which is the trade the optimization below settles.
import time
from pathlib import Path
import jax
import jax.numpy as jnp
import matplotlib.pyplot as plt
import numpy as np
import optax
from scipy.constants import c
from scipy.integrate import quad
import gfem
from gfem import diffraction
jax.config.update("jax_enable_x64", True)
um = 1e-6
LAMBDAS = np.array([532.0, 633.0]) * 1e-9 # green and red
FREQS = c / LAMBDAS # Hz
PITCH, HEIGHT, W0 = 0.3, 1.1, 0.15 # um
W_LO, W_HI = 0.07, 0.23 # um, the widths the library covers
GLASS_DEPTH, AIR_GAP = 0.2, 0.25 # um, the glass and the air above the ridge's top
The cell#
The mesh is one period, 0.3 µm along \(x\) and 0.16 µm along \(y\), built at a ridge width of
\(w_0 = 0.15\) µm. From the bottom up its volumes are "glass" (0.2 µm), the "ridge" with
"air" beside it (1.1 µm), and "air" (0.25 µm above the ridge). Its surfaces are the open
faces "bottom" and "top", the periodic pairs "x_min", "x_max" and "y_min",
"y_max", the ridge’s walls "sidewall", and two planes that keep their place when the walls
move: "base", where the ridge meets the glass, and "ridge_top". The notebook reads it from
data/metalens_cell.msh, built by tools/make_tutorial_meshes.py.
Before any port is declared the cell lists the orders that propagate behind each face.
mesh = gfem.Mesh.from_gmsh(Path("data/metalens_cell.msh"), length_unit="um")
plain = gfem.Model(
mesh,
materials={
"glass": gfem.materials.silica(frequency=FREQS[1]),
"ridge": gfem.materials.silicon_nitride(),
"air": gfem.Material(name="air"),
},
boundaries=[gfem.Periodic(("x_min", "x_max")), gfem.Periodic(("y_min", "y_max"))],
)
print("orders propagating in the glass:", plain.propagating_orders("bottom", FREQS))
print("orders propagating in the air: ", plain.propagating_orders("top", FREQS))
orders propagating in the glass: ((0, 0),)
orders propagating in the air: ((0, 0),)
Only the specular order \((0, 0)\) propagates, on both sides, at both colours.
gfem.diffraction.floquet_ports() declares a TE and a TM port for every order that
propagates behind a face at any of the frequencies, so the declaration cannot miss an
order. The reference planes move to the surfaces the light crosses: offset puts the
glass ports on the glass surface, 0.2 µm above the bottom face, and the air ports on the
ridge tops, 0.25 µm below the top face. Offsets change the phase of S, not its magnitude,
and the phase that the lens needs is the phase at these planes.
cell = plain.replace(
ports=[
*diffraction.floquet_ports(plain, "bottom", FREQS, offset=GLASS_DEPTH * um),
*diffraction.floquet_ports(plain, "top", FREQS, offset=AIR_GAP * um),
]
)
print([port.name for port in cell.ports])
['bottom (0, 0) TE', 'bottom (0, 0) TM', 'top (0, 0) TE', 'top (0, 0) TM']
One solve of the cell at \(w_0\), both colours at once, exciting every port (TE and TM from
the glass). gfem.diffraction.power_balance() sums every Floquet row for the TE
incidence: the reflectance, the transmittance and the absorptance, which is what is
left of the incident power. The media are lossless, so the absorptance is the mesh’s defect.
gfem.diffraction.jones() reads the \(2 \times 2\) transmission block between the two
faces, in (TM, TE): its diagonal is \(t_\text{TM}\) and \(t_\text{TE}\), and its off-diagonal the
cross-polarized entries, which the lens neglects.
options = gfem.SolverOptions(order=2, linear_solver="direct")
tic = time.perf_counter()
solved = gfem.solve(cell, gfem.Driven(frequency=FREQS, excite=None), options=options)
print(f"one solve at both colours: {time.perf_counter() - tic:.1f} s")
balance = diffraction.power_balance(solved, "bottom", polarization="TE", model=cell)
jones = diffraction.jones(solved, "top", "bottom", model=cell)
t_te = np.asarray(jones.values[:, 1, 1])
balance_cell = float(np.max(np.abs(np.asarray(balance.absorptance))))
cross_polarization = float(np.max(np.abs(np.asarray(jones.values[:, 0, 1]))))
for i, name in enumerate(("532 nm", "633 nm")):
print(
f"{name}: R = {float(balance.reflectance[i]):.4f}, "
f"T = {float(balance.transmittance[i]):.4f}, "
f"A = {float(balance.absorptance[i]):+.1e}"
)
t_tm = np.asarray(jones.values[:, 0, 0])
for pol, t in (("TE", t_te), ("TM", t_tm)):
phase = np.degrees(np.angle(t)).round(1)
print(f"t_{pol}: |t| = {np.abs(t).round(4)}, phase = {phase} deg")
print(f"largest cross-polarized entry: {cross_polarization:.1e}")
print(f"largest |A|: {balance_cell:.1e}")
one solve at both colours: 2.4 s
532 nm: R = 0.0971, T = 0.9029, A = +1.3e-05
633 nm: R = 0.0365, T = 0.9635, A = +6.4e-06
t_TE: |t| = [0.9502 0.9816], phase = [104.9 -3.1] deg
t_TM: |t| = [0.9687 0.9816], phase = [ -52.2 -173.2] deg
largest cross-polarized entry: 5.2e-04
largest |A|: 1.3e-05
At \(w_0 = 0.15\) µm the ridge transmits 0.95 of the TE field at 532 nm and 0.98 at 633 nm,
and the TE and TM phases differ: the ridges are a form-birefringent wave plate, which is
why this lens is a TE lens. The absorptance is \(1 \times 10^{-5}\) at worst, and the
cross-polarized entries are at most \(5 \times 10^{-4}\): TE stays TE. Both are checked in
the closing cell as balance_cell (below \(10^{-4}\)) and cross_polarization (below
\(2 \times 10^{-3}\)).
Mesh check. The same cell at third order changes \(t_\text{TE}\) by at most 0.0077
(order3_change, asserted below 0.02), the discretization error of the table that follows. A mesh error that is smooth in the width is the same in every
cell of the lens, so this is also the limit on the second digit of the efficiencies below.
tic = time.perf_counter()
third = gfem.solve(
cell,
gfem.Driven(frequency=FREQS, excite=None),
options=gfem.SolverOptions(order=3, linear_solver="direct"),
)
t_third = np.asarray(
diffraction.jones(third, "top", "bottom", model=cell).values[:, 1, 1]
)
order3_change = float(np.max(np.abs(t_third - t_te)))
print(
f"order 3: {time.perf_counter() - tic:.0f} s, max |t3 - t2| = {order3_change:.1e}"
)
order 3: 7 s, max |t3 - t2| = 7.7e-03
One mesh for every width#
Meshing each width of the table would put a different discretization error in every sample, which
the interpolation cannot remove. Instead one mesh moves: gfem.shape.boundary_morph()
displaces the nodes of "sidewall" along their normals, outward from the ridge
(grows="ridge"), with "base" and "ridge_top" held. Each wall of a ridge moves by half
the widening, so a uniform map of \(\tfrac12\) turns a displacement dw of the width, in µm, into
morph(dw * um * 0.5).
A morph squeezes the elements beside a wall, so the range is bounded: the table’s widths
must stay where gfem.shape.quality() stays above a quarter of the imported mesh’s
(the point at which gfem warns). Here that is 0.07 to 0.23 µm. The wall moves by about 1.3
element widths at the ends.
morph = gfem.shape.boundary_morph(cell, "sidewall", grows="ridge")
HALF = 0.5 * jnp.ones(morph.n_params) # each wall moves half the widening
print("nodes the morph moves:", morph.n_params)
def make_cell(w, dw):
# The cell with ridges w + dw um wide (w in um; dw a traced 0 of the derivative).
return cell.replace(mesh=morph(((w - W0) + dw) * um * HALF))
q0 = np.asarray(gfem.shape.quality(cell.mesh))
ratio = {}
for w in np.linspace(W_LO, W_HI, 9):
ratio[round(float(w), 4)] = float(
np.min(np.asarray(gfem.shape.quality(make_cell(w, 0.0).mesh)) / q0)
)
quality_ratio = min(ratio.values())
print(
"worst element quality against the imported mesh, by width:",
{k: round(v, 3) for k, v in ratio.items()},
)
nodes the morph moves: 92
worst element quality against the imported mesh, by width: {0.07: 0.324, 0.09: 0.476, 0.11: 0.647, 0.13: 0.828, 0.15: 1.0, 0.17: 0.83, 0.19: 0.651, 0.21: 0.481, 0.23: 0.33}
The worst element’s quality against the imported mesh is 0.32 at both ends of the range and falls towards 1 at \(w_0\), above a quarter everywhere. The cell at three widths, the ridge in dark and the glass and air around it light, on the plane \(y = 0\):
fig, axes = plt.subplots(1, 3, figsize=(8, 3.0), sharey=True)
ridge_elements = np.asarray(cell.mesh.elements("ridge"))
for ax, w in zip(axes, (0.07, 0.15, 0.23), strict=True):
m = make_cell(w, 0.0).mesh
nodes = np.asarray(m.nodes) / um
tets = np.asarray(m.tetrahedra)
on_plane = np.isclose(nodes[:, 1], 0.0)
ridge = np.zeros(len(tets), bool)
ridge[ridge_elements] = True
# the y = 0 plane's triangles: the tetrahedra's faces with three nodes there
tris, in_ridge = [], []
for tet, r in zip(tets, ridge, strict=True):
flat = tet[on_plane[tet]]
if len(flat) == 3:
tris.append(flat)
in_ridge.append(r)
tris, in_ridge = np.array(tris), np.array(in_ridge)
ax.tripcolor(
nodes[:, 0],
nodes[:, 2],
tris,
facecolors=np.where(in_ridge, 1.0, 0.0),
cmap="gray_r",
vmin=0,
vmax=2.5,
edgecolors="gray",
linewidth=0.2,
)
ax.set_title(f"w = {w:.2f} um")
ax.set_xlabel("x (um)")
ax.set_aspect("equal")
axes[0].set_ylabel("z (um)")
fig.tight_layout();
The cell response#
gfem.diffraction.cell_response() takes a function make_cell(w, dw), the
parameter samples, and the frequencies, and solves the cell at each sample and frequency.
w is a plain number, dw a JAX scalar whose value is 0 and which moves the mesh. For each
sample and each frequency it runs one solve and one backward pass for each real entry of
the S rows it keeps (the four Floquet ports of the one excited column, real and imaginary
parts: 8 passes), so the stored derivative \(\partial S/\partial w\) is exact for the
discrete model. It differentiates one frequency at a time: a backward pass of a
multi-frequency solve would cost every frequency.
21 widths, denser where the phase turns fastest (narrow ridges): \(w = 0.07 + 0.16\,u^{1.6}\) µm for \(u\) from 0 to 1.
widths = np.round(W_LO + (W_HI - W_LO) * np.linspace(0, 1, 21) ** 1.6, 6) # um
print("widths:", widths)
widths: [0.07 0.071326 0.074019 0.077689 0.082183 0.087411 0.093308 0.099828
0.106933 0.114592 0.12278 0.131475 0.140658 0.150312 0.160423 0.170976
0.18196 0.193365 0.205179 0.217393 0.23 ]
tic = time.perf_counter()
response = diffraction.cell_response(
make_cell,
widths,
frequency=FREQS,
excite=["bottom (0, 0) TE"],
options=options,
)
t_build = time.perf_counter() - tic
print(f"{len(widths)} samples at 2 colours: {t_build:.0f} s")
print(response.ports)
print(response.offsets)
21 samples at 2 colours: 105 s
('bottom (0, 0) TE', 'bottom (0, 0) TM', 'top (0, 0) TE', 'top (0, 0) TM')
{'bottom (0, 0) TE': 2e-07, 'bottom (0, 0) TM': 2e-07, 'top (0, 0) TE': 2.5e-07, 'top (0, 0) TM': 2.5e-07}
The response, 21 samples at two colours, is the one slow step of the page (its time is printed above, on a loaded machine with 2 threads). It holds S and \(\partial S/\partial w\) at each sample, and
between samples a piecewise cubic Hermite interpolant of the real and imaginary parts, a
pure JAX function of \(w\) that differentiates, jits and vmaps. Its ports keep the
offsets the cell declared.
Check: the stored derivative. At one sample the stored \(\partial t/\partial w\) against a central difference of two solves of the morphed cell, a step of \(10^{-4}\) µm either side:
OUT_TE = response.ports.index("top (0, 0) TE")
def te(w):
# Transmission of TE from the glass at width w, both colours: shape (2,).
return response(w).values[:, OUT_TE, 0]
# the stored derivative against a central difference of two solves, at one sample
k, step = 4, 1e-4 # sample 4, step in um
w_k = float(widths[k])
def solved_te(w):
res = gfem.solve(
make_cell(w, 0.0),
gfem.Driven(frequency=FREQS, excite=["bottom (0, 0) TE"]),
options=options,
)
return np.asarray(res.s["top (0, 0) TE", "bottom (0, 0) TE"])
central = (solved_te(w_k + step) - solved_te(w_k - step)) / (2 * step)
stored = np.asarray(response.derivative[k, :, OUT_TE, 0])
derivative_error = float(np.max(np.abs(stored - central) / np.abs(central)))
print(f"width {w_k:.4f} um: stored dt/dw = {stored}, central difference = {central}")
print(f"relative difference: {derivative_error:.1e}")
width 0.0822 um: stored dt/dw = [-65.80310309-24.53608506j 22.50621594+49.25205338j], central difference = [-65.8021905 -24.53622378j 22.50597237+49.25196249j]
relative difference: 1.3e-05
The two agree to \(1.3 \times 10^{-5}\) in relative terms (derivative_error, asserted
below \(10^{-4}\)), the finite difference’s own truncation and the morph’s. The derivative is
the model’s, not an approximation to it.
Check: the interpolation. Between samples the response is the Hermite interpolant, whose
error falls as the fourth power of the spacing. The four midpoints of the narrowest
intervals, where the phase turns fastest, solved directly and compared with response(w):
mid = 0.5 * (widths[:4] + widths[1:5]) # the midpoints of the four narrowest intervals
direct = np.array([solved_te(w) for w in mid]) # (4, 2)
interpolated = np.array([np.asarray(te(w)) for w in mid])
hermite_error = float(np.max(np.abs(interpolated - direct)))
print("held-out widths:", mid.round(4))
print("max |response(w) - solve(w)| =", f"{hermite_error:.1e}")
print("by width and colour:", np.abs(interpolated - direct).round(7))
held-out widths: [0.0707 0.0727 0.0759 0.0799]
max |response(w) - solve(w)| = 8.6e-05
by width and colour: [[4.00e-07 2.70e-06]
[9.00e-06 3.30e-06]
[3.69e-05 6.90e-06]
[8.59e-05 1.70e-05]]
The largest difference over both colours is \(8.6 \times 10^{-5}\) (hermite_error, asserted
below \(10^{-3}\)), at 532 nm and the widest of the four, 0.0799 µm (633 nm: \(1.7 \times 10^{-5}\)), where the
samples are 0.0045 µm apart. Transmission and phase of the table, samples as dots and the
interpolant between them:
fine = np.linspace(W_LO, W_HI, 801)
t_fine = np.asarray(jax.vmap(te)(jnp.asarray(fine))) # (801, 2)
fig, axes = plt.subplots(1, 2, figsize=(8, 3), sharex=True)
for i, (name, colour) in enumerate((("532 nm", "C0"), ("633 nm", "C1"))):
sample = np.asarray(response.values[:, :, OUT_TE, 0][:, i])
axes[0].plot(fine, np.abs(t_fine[:, i]), color=colour, ls="-", label=name)
axes[0].plot(widths, np.abs(sample), color=colour, ls="none", marker="o", ms=3)
axes[1].plot(
fine,
np.degrees(np.unwrap(np.angle(t_fine[:, i]))),
color=colour,
ls="-",
label=name,
)
axes[1].plot(
widths,
np.degrees(np.unwrap(np.angle(sample))),
color=colour,
ls="none",
marker="o",
ms=3,
)
axes[0].set_ylabel("|t|")
axes[0].set_ylim(0.8, 1.0)
axes[1].set_ylabel("phase of t (deg)")
for ax in axes:
ax.set_xlabel("ridge width (um)")
axes[0].legend(loc="lower right")
fig.tight_layout();
span = [np.ptp(np.degrees(np.unwrap(np.angle(t_fine[:, i])))) for i in range(2)]
print(
"phase span over the widths (deg):",
np.round(span, 0),
" min |t|:",
np.abs(t_fine).min(0).round(3),
)
phase span over the widths (deg): [345. 303.] min |t|: [0.912 0.909]
Across the widths the phase of \(t\) spans 345° at 532 nm and 303° at 633 nm, and \(|t|\) stays above 0.91 at both: nearly a full \(2\pi\) of phase at nearly full transmission, which is what a lens needs. Narrow ridges change the phase fastest, about 3000° per µm at \(w = 0.07\) µm.
The ideal lens and the classic design#
Aperture: 401 cells, odd so that a sample sits on the axis, \(D = 401 a = 120.3\) µm, focal
length \(f = 300\) µm, numerical aperture 0.196. Cell \(j\) sits at
\(x_j = (j - 200)\,a\). An ideal lens has \(|t| = 1\) and the phase \(\varphi\) above for each
colour; gfem.diffraction.ApertureField takes the samples directly (components
along \(\hat e_1\) and \(\hat e_2\), here TE). Propagating it by gfem.diffraction.propagate()
to \(z = f\) gives the focal intensity \(I_\text{ideal}\), in units of the incident intensity:
the reference every design is measured against.
Check: the focus of an ideal lens. In the stationary-phase limit the focal intensity of a cylindrical lens of aperture \(D\) is
which does not use the angular spectrum or the sampling. The two:
N, FOCAL = 401, 300 * um
X = (np.arange(N) - (N - 1) / 2) * PITCH * um # m, a cell at the centre
CENTRE = N // 2
K0 = 2 * np.pi * FREQS / c
LENS_PHASE = K0[:, None] * (np.sqrt(X**2 + FOCAL**2) - FOCAL) # (2, N)
t_ideal = jnp.asarray(np.exp(1j * LENS_PHASE))
ideal = diffraction.ApertureField(
jnp.stack([jnp.zeros_like(t_ideal), t_ideal], axis=1), FREQS, X
)
I_ideal = np.asarray(diffraction.propagate(ideal, FOCAL).intensity[:, CENTRE])
half = N * PITCH / 2 # um
integral = quad(lambda s: 300.0 * (s**2 + 300.0**2) ** -0.75, -half, half)[
0
] # um^(1/2)
I_stationary = integral**2 / (LAMBDAS / um)
ideal_focus = float(np.max(np.abs(I_ideal / I_stationary - 1)))
print(
"ideal lens focal intensity:",
I_ideal.round(2),
" stationary phase:",
I_stationary.round(2),
)
print(f"relative difference: {ideal_focus:.1e}")
ideal lens focal intensity: [88.84 74.78] stationary phase: [88.9 74.72]
relative difference: 7.9e-04
The sampled, propagated field and the closed form agree to \(7.9 \times 10^{-4}\)
(ideal_focus, asserted below \(2 \times 10^{-3}\)): the propagation, the sampling of one
point per cell and the sign of the phase are right. (The conjugate phase would not focus.)
The classic design: phase matching. Choose, for each cell, the width whose transmission
phase at 633 nm is closest to the ideal lens’s, up to one global phase offset (72 are tried and
the best kept). The response gives the aperture field for those widths, and propagate the
focal intensity of both colours, relative to the ideal lens:
def field_of(w):
return diffraction.aperture_field(response, w, "top", "bottom", polarization="TE")
def relative_focus(w, distance=FOCAL):
# Focal intensity at the axis against the ideal lens, both colours.
return diffraction.propagate(field_of(w), distance).intensity[:, CENTRE] / I_ideal
t_unit = t_fine[:, 1] / np.abs(t_fine[:, 1]) # the 633 nm phasor along the widths
best = (-1.0, None)
for offset in np.linspace(0, 2 * np.pi, 72, endpoint=False):
target = np.exp(1j * (LENS_PHASE[1] + offset))
w = fine[np.argmin(np.abs(t_unit[None, :] - target[:, None]), axis=1)]
score = float(relative_focus(jnp.asarray(w))[1])
if score > best[0]:
best = (score, w)
w_matched = best[1]
matched = np.asarray(relative_focus(jnp.asarray(w_matched)))
print(
"phase matched at 633 nm, focal intensity against the ideal lens:", matched.round(3)
)
phase matched at 633 nm, focal intensity against the ideal lens: [0.055 0.92 ]
matched is the focal intensity against the ideal lens, 0.055 at 532 nm and 0.920 at 633 nm.
The red light is nearly as good as an ideal lens, the green is almost not focused: the
widths were chosen for red, and the same widths add a different phase to green. Where does
the green go? A scan along the axis shows it focuses farther away.
Z = np.linspace(100, 600, 101) * um
field_m = field_of(jnp.asarray(w_matched))
axial_m = (
np.array(
[np.asarray(diffraction.propagate(field_m, z).intensity[:, CENTRE]) for z in Z]
)
/ I_ideal
)
green_peak = Z[np.argmax(axial_m[:, 0])] / um
red_peak = Z[np.argmax(axial_m[:, 1])] / um
shift = 300 * LAMBDAS[1] / LAMBDAS[0]
green_focus = abs(green_peak / shift - 1)
print(f"axial peak: green {green_peak:.0f} um, red {red_peak:.0f} um")
print(f"f * 633 / 532 = {shift:.1f} um; green_focus = {green_focus:.3f}")
print("height of the peaks against the ideal lens at f:", axial_m.max(0).round(3))
axial peak: green 355 um, red 300 um
f * 633 / 532 = 357.0 um; green_focus = 0.005
height of the peaks against the ideal lens at f: [0.737 0.92 ]
The red focus is where it was designed, at 300 µm; the green peaks at 355 µm, at 0.737 of
the ideal lens’s focal intensity: the light is there, at the wrong distance. Diffractive
optics are chromatic: the phase of the lens is the same number of waves, and a focus
scales with \(1/\lambda\), so green focuses at \(f\lambda_\text{red}/\lambda_\text{green} = 357.0\) µm.
The matched lens’s green peak is within 0.005 of it, in relative terms (green_focus, asserted
below 0.03). The dotted lines mark 300 and 357 µm.
fig, axes = plt.subplots(1, 2, figsize=(8, 3))
axes[0].plot(X / um, w_matched, color="gray", lw=0.6)
axes[0].set_xlabel("x (um)")
axes[0].set_ylabel("ridge width (um)")
for i, (name, colour) in enumerate((("532 nm", "C0"), ("633 nm", "C1"))):
axes[1].plot(Z / um, axial_m[:, i], color=colour, ls="-", label=name)
axes[1].axvline(300, color="gray", ls=":", lw=1)
axes[1].axvline(shift, color="gray", ls=":", lw=1)
axes[1].set_xlabel("z (um)")
axes[1].set_ylabel("intensity on the axis / ideal lens at f")
axes[1].legend(loc="upper right")
fig.tight_layout();
Optimize both colours#
Now the widths are free, one per cell, as \(w = w_\text{lo} + (w_\text{hi} - w_\text{lo})\,\sigma(z)\) with \(z\) unbounded, so that the optimizer cannot leave the range of the table (the response returns NaN outside it, rather than a silent clamp). The objective is the soft minimum of the two relative focal intensities \(r_1, r_2\),
which rewards raising the weaker colour. The gradient runs through the sigmoid, the
Hermite interpolation of the table, the aperture field and the propagation: pure JAX, in one
jax.jit(jax.value_and_grad(...)).
Check: the gradient. At the phase-matched design, the gradient along a random unit direction of the 401 design variables against a central difference of the loss, a step of \(10^{-5}\):
TAU = 0.05
def to_width(z):
return W_LO + (W_HI - W_LO) * jax.nn.sigmoid(z)
def from_width(w):
s = np.clip((w - W_LO) / (W_HI - W_LO), 1e-4, 1 - 1e-4)
return np.log(s / (1 - s))
def loss(z):
r = relative_focus(to_width(z))
return TAU * jax.nn.logsumexp(
-r / TAU
), r # minus the soft minimum; both intensities
value_and_grad = jax.jit(jax.value_and_grad(loss, has_aux=True))
z = jnp.asarray(from_width(w_matched))
direction = np.random.default_rng(0).standard_normal(N)
direction /= np.linalg.norm(direction)
(_, _), g = value_and_grad(z)
along = float(jnp.dot(g, direction))
step = 1e-5
difference = (
float(loss(z + step * direction)[0]) - float(loss(z - step * direction)[0])
) / (2 * step)
fd_error = abs(along - difference) / abs(difference)
print(f"gradient along a random direction {along:+.9e}")
print(f"central difference (step 1e-5) {difference:+.9e}")
print(f"relative difference: {fd_error:.1e}")
gradient along a random direction -7.459771210e-04
central difference (step 1e-5) -7.459771210e-04
relative difference: 9.1e-11
They agree to \(3.3 \times 10^{-9}\) in relative terms (fd_error, asserted below \(10^{-6}\)).
optax’s Adam, step 0.05, 400 iterations from the phase-matched design, one loss and gradient each:
optimizer = optax.adam(0.05)
state = optimizer.init(z)
history = []
tic = time.perf_counter()
for _ in range(400):
(_, r), g = value_and_grad(z)
updates, state = optimizer.update(g, state)
z = optax.apply_updates(z, updates)
history.append(np.asarray(r))
history = np.array(history)
w_opt = np.asarray(to_width(z))
optimized = np.asarray(relative_focus(jnp.asarray(w_opt)))
print(f"400 steps in {time.perf_counter() - tic:.1f} s")
print("start (matched):", matched.round(3), " optimized:", optimized.round(3))
400 steps in 1.4 s
start (matched): [0.055 0.92 ] optimized: [0.499 0.507]
optimized is the focal intensity against the ideal lens: 0.499 at 532 nm and 0.507 at 633 nm,
from 0.055 and 0.920. The optimization takes red from 0.920 down to about 0.51 to raise green from
0.055 to about 0.50: it balances the two. That is the soft minimum’s trade. Maximizing the
mean of the two instead is the wrong objective, as the next cell shows.
def mean_loss(z):
return -jnp.mean(relative_focus(to_width(z)))
mean_grad = jax.jit(jax.value_and_grad(mean_loss))
zm = jnp.asarray(from_width(w_matched))
mean_state = optimizer.init(zm)
for _ in range(400):
_, g = mean_grad(zm)
updates, mean_state = optimizer.update(g, mean_state)
zm = optax.apply_updates(zm, updates)
by_mean = np.asarray(relative_focus(to_width(zm)))
print("maximizing the mean instead:", by_mean.round(3))
maximizing the mean instead: [0.234 0.795]
The mean keeps red (0.795) and gives up on green (0.234): nothing in it penalizes the weaker colour. The soft minimum asks for both.
The axial scan of the optimized lens: where do its foci sit?
field_o = field_of(jnp.asarray(w_opt))
axial_o = (
np.array(
[
np.asarray(diffraction.propagate(field_o, z_).intensity[:, CENTRE])
for z_ in Z
]
)
/ I_ideal
)
peaks_o = Z[np.argmax(axial_o, axis=0)] / um
print("optimized lens axial peaks (um):", peaks_o, " heights", axial_o.max(0).round(3))
second = {
"green at 355 um": axial_o[np.argmin(abs(Z - 355 * um)), 0],
"red at 250 um": axial_o[np.argmin(abs(Z - 250 * um)), 1],
}
print("second foci:", {k: round(float(v), 3) for k, v in second.items()})
centre = slice(CENTRE - 1, CENTRE + 2)
print(
"widths on the axis, matched and optimized (um):",
w_matched[centre].round(3),
w_opt[centre].round(3),
)
optimized lens axial peaks (um): [300. 295.] heights [0.499 0.513]
second foci: {'green at 355 um': 0.371, 'red at 250 um': 0.455}
widths on the axis, matched and optimized (um): [0.169 0.169 0.169] [0.188 0.189 0.188]
Left, the relative focal intensity of each colour during the 400 iterations; right, the widths of the two designs across the aperture. The phase-matched widths are a sawtooth: the width follows the lens phase, which wraps every \(2\pi\) and wraps faster towards the edge, and the 303° of the table at 633 nm leave a gap near \(|x| = 17\) µm where the width jumps from one end of the range to the other. The optimized widths follow the same sawtooth, shifted: the lens is wider on the axis (0.189 µm against 0.169 µm), and the teeth move towards the edge, where each width must serve two colours.
fig, axes = plt.subplots(1, 2, figsize=(8, 3))
for i, (name, colour) in enumerate((("532 nm", "C0"), ("633 nm", "C1"))):
axes[0].plot(history[:, i], color=colour, ls="-", label=name)
axes[0].set_xlabel("iteration")
axes[0].set_ylabel("focal intensity / ideal lens")
axes[0].set_ylim(0, 1)
axes[0].legend(loc="upper right")
axes[1].plot(X / um, w_matched, color="gray", lw=0.6, label="phase matched")
axes[1].plot(X / um, w_opt, color="C2", ls="-", lw=0.6, label="optimized")
axes[1].set_xlabel("x (um)")
axes[1].set_ylabel("ridge width (um)")
axes[1].legend(loc="upper center", ncol=2)
axes[1].set_ylim(0.06, 0.28)
fig.tight_layout();
Left, the intensity at \(z = f\) across \(x\) near the focus, normalized by the ideal peak, phase matched (dashed) and optimized (solid); right, the axial intensity of both. Both optimized colours have a focus at 300 µm for green and 295 µm for red (the scan’s grid is 5 µm), at 0.499 and 0.513 of the ideal lens’s focal intensity. The cost: the red focus that phase matching sent to nearly full intensity is now about half of it. The optimization does not remove the other foci: the optimized lens still holds 0.371 of the ideal intensity at 355 µm in green, the phase-matched green focus, and 0.455 at 250 µm in red. A lens that focuses on one line is not a lens that focuses nowhere else; a term that penalizes the light elsewhere on the axis would be the next objective to add.
fig, axes = plt.subplots(1, 2, figsize=(8, 3))
near = slice(CENTRE - 25, CENTRE + 26)
for field, style, label in (
(field_m, "--", "phase matched"),
(field_o, "-", "optimized"),
):
at_f = np.asarray(diffraction.propagate(field, FOCAL).intensity) / I_ideal[:, None]
for i, colour in enumerate(("C0", "C1")):
axes[0].plot(
X[near] / um,
at_f[i, near],
color=colour,
ls=style,
label=f"{('532', '633')[i]} nm, {label}",
)
axes[0].set_xlabel("x (um)")
axes[0].set_ylabel("intensity at f / ideal lens")
axes[0].legend(fontsize=6)
for i, (name, colour) in enumerate((("532 nm", "C0"), ("633 nm", "C1"))):
axes[1].plot(
Z / um, axial_m[:, i], color=colour, ls="--", label=f"{name}, phase matched"
)
axes[1].plot(
Z / um, axial_o[:, i], color=colour, ls="-", label=f"{name}, optimized"
)
axes[1].axvline(300, color="gray", ls=":", lw=1)
axes[1].set_xlabel("z (um)")
axes[1].set_ylabel("intensity on the axis / ideal lens at f")
axes[1].legend(fontsize=6)
fig.tight_layout();
How far to trust the approximation#
The optimizer is free to use any width in any cell, and the approximation assumes each cell sees neighbours that look like itself. The phase step between neighbours measures how far from that the design is:
def steps(w):
t = np.asarray(jax.vmap(te)(jnp.asarray(w)))
return np.degrees(np.abs(np.angle(t[1:] * np.conj(t[:-1])))) # (N - 1, 2)
for name, w in (("phase matched", w_matched), ("optimized", w_opt)):
s = steps(w)
print(
name,
"max step (deg):",
s.max(0).round(0),
" fraction above 60 deg:",
(s > 60).mean(0).round(3),
" median:",
np.median(s, axis=0).round(0),
)
phase matched max step (deg): [41. 57.] fraction above 60 deg: [0. 0.] median: [15. 15.]
optimized max step (deg): [175. 153.] fraction above 60 deg: [0.03 0.04] median: [14. 13.]
The phase-matched lens steps at most 41° (532 nm) and 57° (633 nm) between neighbours, none above 60°: near the edge of the regime where the approximation’s error stays at 0.01 to 0.02 in amplitude (up to about 40° it does). The optimized lens has a median step of 13° to 14°, but 3 % of its pairs at 532 nm and 4 % at 633 nm step by more than 60°, and the largest steps are 175° and 153°. The optimizer found that abrupt steps focus better in the approximation, where a neighbour does not disturb its neighbour. In a real lens it does. That is a limit of this design, and the next section measures the approximation where it is known.
A full solve of a deflector. Ten ridges side by side, widths following a phase ramp
of 36° per cell at 633 nm (\(2\pi\) over the ten, about the 34° per cell of the lens’s edge),
which deflects the light into the +1 order at 12.2°. This is the same cell as above, ten
times: data/metalens_supercell.msh, 3 µm wide with 29 760 tetrahedra, the same
names, ridges at \(w_0\). The cell has more propagating orders now: the Floquet ports of the
supercell cover them all.
NS = 10
mesh_s = gfem.Mesh.from_gmsh(Path("data/metalens_supercell.msh"), length_unit="um")
plain_s = plain.replace(mesh=mesh_s)
cell_s = plain_s.replace(
ports=[
*diffraction.floquet_ports(
plain_s, "bottom", FREQS[1], offset=GLASS_DEPTH * um
),
*diffraction.floquet_ports(plain_s, "top", FREQS[1], offset=AIR_GAP * um),
]
)
print(
len(cell_s.ports),
"ports; orders in the air:",
[p.order[0] for p in cell_s.ports if p.surface == "top" and p.polarization == "TE"],
)
44 ports; orders in the air: [0, -1, 1, -2, 2, -3, 3, -4, 4]
best = (np.inf, None)
for offset in np.linspace(0, 2 * np.pi, 72, endpoint=False):
target = np.exp(1j * (offset - 2 * np.pi * np.arange(NS) / NS)) # 36 deg per cell
pick = np.argmin(np.abs(t_unit[None, :] - target[:, None]), axis=1)
error = np.abs(np.angle(t_unit[pick] * np.conj(target))).max()
if error < best[0]:
best = (error, fine[pick])
w_ramp = best[1]
print(
"ramp widths (um):",
w_ramp.round(3),
" largest phase error:",
np.degrees(best[0]).round(1),
"deg",
)
ramp widths (um): [0.07 0.078 0.089 0.102 0.117 0.135 0.154 0.177 0.206 0.23 ] largest phase error: 10.5 deg
The widths follow the phase ramp to within 11° (the table is only so dense in phase).
morph_s = gfem.shape.boundary_morph(cell_s, "sidewall", grows="ridge")
x_nodes = np.asarray(morph_s.points) / um
ridge_of = np.minimum((x_nodes[:, 0] // PITCH).astype(int), NS - 1)
super_cell = cell_s.replace(mesh=morph_s(jnp.asarray((w_ramp[ridge_of] - W0) / 2 * um)))
tic = time.perf_counter()
super_result = gfem.solve(
super_cell,
gfem.Driven(frequency=FREQS[1], excite=["bottom (0, 0) TE"]),
options=options,
)
print(f"{len(mesh_s.tetrahedra)} tetrahedra, solve: {time.perf_counter() - tic:.0f} s")
super_balance = diffraction.power_balance(
super_result, "bottom", polarization="TE", model=super_cell
)
supercell_balance = float(np.abs(np.asarray(super_balance.absorptance)).max())
print(f"largest |A|: {supercell_balance:.1e}")
29760 tetrahedra, solve: 54 s
largest |A|: 1.0e-05
One boundary morph moves every ridge at once: a width map per node, from the ridge the node belongs to. One driven solve at 633 nm excites the TE wave from the glass. It is the page’s second slow step and the one that needs the most memory.
The power balance of the supercell closes: supercell_balance, the absorptance, is
\(1 \times 10^{-5}\) (asserted below \(10^{-4}\)).
L = NS * PITCH * um
x_j = (np.arange(NS) + 0.5) * PITCH * um
t_ramp = np.asarray(jax.vmap(te)(jnp.asarray(w_ramp)))[:, 1] # 633 nm
orders = range(-4, 5)
eta_fem, eta_lpa = {}, {}
for m in orders:
s_m = complex(np.asarray(super_result.s[f"top ({m}, 0) TE", "bottom (0, 0) TE"])[0])
sin_theta = m * LAMBDAS[1] / L
c_m = np.mean(t_ramp * np.exp(2j * np.pi * m * x_j / L))
eta_fem[m] = abs(s_m) ** 2
eta_lpa[m] = np.sqrt(1 - sin_theta**2) * abs(c_m) ** 2
for m in orders:
print(f"order {m:+d}: FEM {eta_fem[m]:.4f} LPA {eta_lpa[m]:.4f}")
fem_deflected, lpa_deflected = eta_fem[1], eta_lpa[1]
deflected = abs(fem_deflected - lpa_deflected)
order -4: FEM 0.0028 LPA 0.0006
order -3: FEM 0.0062 LPA 0.0008
order -2: FEM 0.0064 LPA 0.0006
order -1: FEM 0.0047 LPA 0.0009
order +0: FEM 0.0046 LPA 0.0005
order +1: FEM 0.8696 LPA 0.8973
order +2: FEM 0.0050 LPA 0.0000
order +3: FEM 0.0026 LPA 0.0002
order +4: FEM 0.0018 LPA 0.0005
The aperture field’s prediction for the same ten widths is the Fourier series of the transmissions: the order \(m\) carries \(\sqrt{\cos\theta_m}\,c_m\) with \(c_m = \frac1N \sum_j t_j\,e^{2\pi i m x_j/L}\), an efficiency \(\cos\theta_m\,|c_m|^2\). The two, order by order:
fig, ax = plt.subplots(figsize=(6, 3))
ms = np.array(list(orders))
ax.bar(
ms - 0.2, [eta_fem[m] for m in ms], 0.4, color="C2", label="full solve", bottom=0
)
ax.bar(ms + 0.2, [eta_lpa[m] for m in ms], 0.4, color="C3", label="aperture field")
ax.set_yscale("log")
ax.set_ylim(1e-4, 2)
ax.set_xlabel("transmitted order")
ax.set_ylabel("TE efficiency")
ax.legend(loc="upper right");
The deflected +1 order carries 0.870 of the incident power in the full solve and 0.897 in the
approximation (deflected, asserted within 0.05): the approximation overestimates the beam
by 0.027, and the stray orders are the other way round: each carries 0.002 to 0.006 in the
full solve and under 0.001 in the approximation. The abrupt neighbours of the optimized lens are
where the approximation is least reliable: it sees none of the scattering between them, so
its focal intensities are optimistic.
Limits#
Neighbour coupling. The approximation neglects it. The deflector above is 0.027 lower in its +1 order than the approximation says and has stray orders several times stronger (3.6 to 13 times), at only 36° per cell, and the optimized lens has abrupt steps up to 175°. Before building such a lens, solve a supercell of its cells, as above; a smoothness penalty on neighbour transmissions is a natural term for the loss, which this page does not add.
One parameter, normal incidence, TE. The response has one width, one excited column and one incidence. TM light sees the ridges as a different wave plate.
Two colours, not a band. The objective sees 532 and 633 nm. A colour between them is not optimized and is not focused: this is a multi-wavelength lens, not a broadband one.
The observation grid. The field lives on the cells’ grid, one sample per 0.3 µm, against a focal spot a few cells wide: read the peak, not the profile.
Aspect ratio and fabrication. Ridges 1.1 µm high and 0.07 µm wide are aggressive; the table does not know about sidewall angle or roughness.
Constant glass, mesh error. Silica’s 0.004 change in index between the colours is neglected, and the second digit of every efficiency is good to about 0.01 at 532 nm (the third-order check above).
Next#
From a cell response to a metasurface: the table, the aperture field and the objectives (Strehl ratio, deflection efficiency), step by step.
Efficiencies, power balance and polarization of a periodic cell: order efficiencies, Jones and Mueller matrices.
Emissivity of a periodic surface: the same Floquet cell as a thermal emitter.
Topology optimization of a metagrating: a silicon grating on glass that bends light by 50°: a grating designed by topology optimization.
Shape gradients: the gradient of a solve with respect to the cell’s shape.
The numbers this page relies on, checked: the power balance of the cell (below \(10^{-4}\)) and its cross-polarized entries (below \(2 \times 10^{-3}\)), the change at third order (below 0.02), the stored derivative (below \(10^{-4}\)) and the interpolation (below \(10^{-3}\)) of the cell response, the ideal lens against the stationary-phase closed form (below \(2 \times 10^{-3}\)), the phase-matched lens (0.055 at 532 nm and 0.920 at 633 nm, to 0.01) and its green focus (within 0.03 of \(f\lambda_\text{red}/\lambda_\text{green}\)), the optimized lens (at least 0.45 in both colours; 0.50 and 0.51, to 0.03), the gradient (below \(10^{-6}\)), the supercell’s power balance (below \(10^{-4}\)) and the deflected order (0.870 in the full solve and 0.897 in the approximation, to 0.01, and within 0.05 of each other).
np.testing.assert_array_less(balance_cell, 1e-4)
np.testing.assert_array_less(cross_polarization, 2e-3)
np.testing.assert_array_less(order3_change, 0.02)
np.testing.assert_array_less(derivative_error, 1e-4)
np.testing.assert_array_less(hermite_error, 1e-3)
np.testing.assert_array_less(ideal_focus, 2e-3)
np.testing.assert_allclose(matched, [0.055, 0.920], atol=0.01)
np.testing.assert_array_less(green_focus, 0.03)
np.testing.assert_array_less(0.45, optimized)
np.testing.assert_allclose(optimized, [0.50, 0.51], atol=0.03)
np.testing.assert_array_less(fd_error, 1e-6)
np.testing.assert_array_less(supercell_balance, 1e-4)
np.testing.assert_allclose([fem_deflected, lpa_deflected], [0.870, 0.897], atol=0.01)
np.testing.assert_array_less(deflected, 0.05)