import collections
import autograd.numpy as npa
from ceviche import fdfd_ez, jacobian
from ceviche.modes import insert_mode
from jax.example_libraries.optimizers import adam
from tqdm.notebook import trange
Inverse Design Test
Preparation
plot_abs
plot_abs (val, outline=None, ax=None, cbar=False, cmap='magma', outline_alpha=0.5, outline_val=None)
Plots the absolute value of ‘val’, optionally overlaying an outline of ‘outline’
plot_real
plot_real (val, outline=None, ax=None, cbar=False, cmap='RdBu', outline_alpha=0.5)
Plots the real part of ‘val’, optionally overlaying an outline of ‘outline’
insert_mode
insert_mode (omega, dx, x, y, epsr, target=None, npml=0, m=1, filtering=False)
Solve for the modes in a cross section of epsr at the location defined by ‘x’ and ‘y’ The mode is inserted into the ‘target’ array if it is suppled, if the target array is not supplied, then a target array is created with the same shape as epsr, and the mode is inserted into it.
= collections.namedtuple('Slice', 'x y') Slice
Simulation and optimization parameters
Our toy optimization problem will be to design a device that converts an input in the first-order mode into an output as the second-order mode. First, we define the parameters of our device and optimization:
# Angular frequency of the source in Hz
= 2 * np.pi * 200e12
omega # Spatial resolution in meters
= 40e-9
dl # Number of pixels in x-direction
= 100
Nx # Number of pixels in y-direction
= 100
Ny # Number of pixels in the PMLs in each direction
= 20
Npml # Initial value of the structure's relative permittivity
= 12.0
epsr_init # Space between the PMLs and the design region (in pixels)
= 10
space # Width of the waveguide (in pixels)
= 12
wg_width # Length in pixels of the source/probe slices on each side of the center point
= 8
space_slice # Number of epochs in the optimization
= 100
Nsteps # Step size for the Adam optimizer
= 1e-2 step_size
Utility functions
We now define some utility functions for initialization and optimization:
def init_domain(
=Nx, Ny=Ny, Npml=Npml, space=space, wg_width=wg_width, space_slice=space_slice
Nx
):"""Initializes the domain and design region
space : The space between the PML and the structure
wg_width : The feed and probe waveguide width
space_slice : The added space for the probe and source slices
"""
# Parametrization of the permittivity of the structure
= np.ones((Nx, Ny))
bg_epsr = np.ones((Nx, Ny))
epsr
# Region within which the permittivity is allowed to change
= np.zeros((Nx, Ny))
design_region
# Input waveguide
0 : int(Npml + space), int(Ny / 2 - wg_width / 2) : int(Ny / 2 + wg_width / 2)] = epsr_init
bg_epsr[
# Input probe slice
= Slice(
input_slice =np.array(Npml + 1),
x=np.arange(
yint(Ny / 2 - wg_width / 2 - space_slice),
int(Ny / 2 + wg_width / 2 + space_slice),
),
)
# Output waveguide
bg_epsr[int(Nx - Npml - space) : :,
int(Ny / 2 - wg_width / 2) : int(Ny / 2 + wg_width / 2),
= epsr_init
]
# Output probe slice
= Slice(
output_slice =np.array(Nx - Npml - 1),
x=np.arange(
yint(Ny / 2 - wg_width / 2 - space_slice),
int(Ny / 2 + wg_width / 2 + space_slice),
),
)
+ space: Nx - Npml - space, Npml + space: Ny - Npml - space] = 1.0
design_region[Npml + space : Nx - Npml - space, Npml + space : Ny - Npml - space] = epsr_init
epsr[Npml
return epsr, bg_epsr, design_region, input_slice, output_slice
def mask_combine_epsr(epsr, bg_epsr, design_region):
"""Utility function for combining the design region epsr and the background epsr"""
return epsr * design_region + bg_epsr * np.asarray(design_region == 0, dtype=float)
def viz_sim(epsr, source, slices=[]):
"""Solve and visualize a simulation with permittivity 'epsr'"""
= fdfd_ez(omega, dl, epsr, [Npml, Npml])
simulation = simulation.solve(source)
_, _, Ez = plt.subplots(1, 2, constrained_layout=True, figsize=(6, 3))
_, ax =epsr, ax=ax[0], cbar=False)
ceviche.viz.real(Ez, outlinefor sl in slices:
0].plot(sl.x * np.ones(len(sl.y)), sl.y, "b-")
ax[abs(epsr, ax=ax[1], cmap="Greys")
ceviche.viz.
plt.show()return (simulation, ax)
def mode_overlap(E1, E2):
"""Defines an overlap integral between the simulated field and desired field"""
return npa.abs(npa.sum(npa.conj(E1) * E2))
Visualizing the starting device
We can visualize what our starting device looks like and how it behaves. Our device is initialized by the init_domain()
function which was defined several cells above.
# Initialize the parametrization rho and the design region
= init_domain(
epsr, bg_epsr, design_region, input_slice, output_slice =space, wg_width=wg_width, space_slice=space_slice
Nx, Ny, Npml, space
)
= mask_combine_epsr(epsr, bg_epsr, design_region)
epsr_total
# Setup source
= insert_mode(omega, dl, input_slice.x, input_slice.y, epsr_total, m=1)
source
# Setup probe
= insert_mode(omega, dl, output_slice.x, output_slice.y, epsr_total, m=2) probe
# Simulate initial device
= viz_sim(epsr_total, source, slices=[input_slice, output_slice])
simulation, ax
# get normalization factor (field overlap before optimizing)
= simulation.solve(source)
_, _, Ez = mode_overlap(Ez, probe) E0
Define objective function
We will now define our objective function. This is a scalar-valued function which our optimizer uses to improve the device’s performance.
Our objective function will consist of maximizing an overlap integral of the field in the output waveguide of the simulated device and the field of the waveguide’s second order mode (minimizing the negative overlap). The function takes in a single argument, epsr
and returns the value of the overlap integral. The details of setting the permittivity and solving for the fields happens inside the objective function.
# Simulate initial device
= viz_sim(epsr_total, source, slices=[input_slice, output_slice]) simulation, ax
Jaxit
from javiche import jaxit
import jax
@jaxit(cache=True)
def loss_fn(epsr, factor):
"""Objective function called by optimizer
1) Takes the epsr distribution as input
2) Runs the simulation
3) Returns the overlap integral between the output wg field
and the desired mode field
"""
#epsr = epsr.reshape((Nx, Ny))
= mask_combine_epsr(epsr, bg_epsr, design_region)
simulation.eps_r = simulation.solve(source)
_, _, Ez return -mode_overlap(Ez, probe) / E0 * factor
The @jaxit()
decorator enables the automatic differntiation with the decorated function while internally calculating the gradients using ceviche
s jacobian
which is based on autograd.
= jax.grad(loss_fn) grad_fn
With the decorator in place we can
2.0)) plt.imshow(grad_fn(epsr,
<matplotlib.image.AxesImage>
= adam(step_size)
init_fn, update_fn, params_fn = init_fn(epsr)
state = 2.0 lossfactor
def step_fn(step, state):
#latent = np.asarray(params_fn(state), dtype=float) # we need autograd arrays here...
= params_fn(state) # we need autograd arrays here...
latent = loss_fn(latent, lossfactor)
loss = grad_fn(latent, lossfactor)
grads = update_fn(step, grads, state)
optim_state return loss, optim_state
= trange(20)
range_ for step in range_:
= step_fn(step, state)
loss, state =float(loss)) range_.set_postfix(loss
= params_fn(state)
latent plt.imshow(latent)
<matplotlib.image.AxesImage>
= mask_combine_epsr(epsr, bg_epsr, design_region)
simulation.eps_r = simulation.solve(source) _, _, Ez
plt.imshow(np.real(Ez))
<matplotlib.image.AxesImage>