<jupyter_start><jupyter_text>Accelerator / Deflector DemoIn this notebook we will optimize a laser-driven electron deflecting structure.In this problem, we'll have an electron flowing in the y direction through the center of our domain.We have a laser source coming in from the left which we will use to deflect the electron in the out of plane direction.We'll optimize the regions around the electron trajectory to maximize this deflection, while leaving a central gap for the electron to flow through.<jupyter_code>#
#                ______  e-   ______
#                ||||||   ^   ||||||        
# driving laser  ||||||   |   ||||||        
# -------------> ||||||   |   ||||||        
#                ||||||   |   ||||||   
#                ||||||   |   ||||||        
#                ------       ------
#                design       design
#                region       region
#
import numpy as np
import matplotlib.pylab as plt
import scipy.sparse as sp
import sys
sys.path.append('..')

from angler import Optimization, Simulation
from angler.structures import accelerator

%load_ext autoreload
%autoreload 2
%matplotlib inline
# fundamental constants and simulation parameters
c0 = 3e8                     # speed of light in vacuum (m/s)
lambda_m = 2e-6              # waveength in meters
omega = 2*np.pi*c0/lambda_m  # angular frequency (2pi/s)
dl = 0.5e-1                  # grid size (microns)
NPML = [15, 0]               # number of pml grid points on x and y borders
pol = 'Hz'                   # polarization (either 'Hz' or 'Ez')
num_cells = 5                # number of cells to tile in plots
# material constants
n_index = np.sqrt(2)               # refractive index
eps_m = n_index**2           # relative permittivity
# geometric parameters
beta = 0.5                  # electron speed / speed of light
gap = 0.4                   # gap size (microns)
lambda0 = lambda_m*1e6      # free space wavelength (microns)
L = 5                       # width of design region (microns)
spc = 2                     # space between PML -> Src. & Src -> Design region
# define permittivity of three port system
eps_r, design_region = accelerator(beta, gap, lambda0, L, spc, dl, NPML, eps_m)
(Nx, Ny) = eps_r.shape
nx, ny = int(Nx/2), int(Ny/2)

# make a new simulation
simulation = Simulation(omega,eps_r,dl,NPML,pol)

print("Computed a domain with {} grids in x and {} grids in y".format(Nx,Ny))
print("The simulation has {} grids per free space wavelength".format(int(lambda0/dl)))

simulation.plt_eps(tiled_y=num_cells)
plt.show()
# set the plane wave source
simulation = Simulation(omega, eps_r, dl, NPML, 'Hz')
simulation.src = np.zeros((Nx, Ny))
simulation.src[NPML[0] + int(spc/dl), :] = 1e-9
# make an empty space simulation for normalization of fields
eps_normalize, _ = accelerator(beta, gap, lambda0, L, spc, dl, NPML, 1)
sim_normalize = Simulation(omega,eps_normalize,dl,NPML,pol)
sim_normalize.src = np.zeros((Nx, Ny))
sim_normalize.src[NPML[0] + int(spc/dl), :] = 1e-9

(_,Ey,Hz) = sim_normalize.solve_fields()
sim_normalize.plt_re(tiled_y=num_cells, outline=False)
plt.show()
E0 = np.mean(np.abs(Ey[nx, :]))
print('E0 = {}'.format(E0))
# initalize the design region randomly
simulation.init_design_region(design_region, eps_m, style='halfway')
simulation.plt_eps(tiled_y=num_cells)
plt.show()
# define objective function  (equal power transmission to bottom and top)
from angler.objective import Objective, obj_arg
arg1 = obj_arg('ey', component='Ey', nl=False)

import autograd.numpy as npa
def J(ey):
    eta = npa.zeros((Nx, Ny), dtype=npa.complex128)
    eta[nx, :] = 1/Ny*npa.exp(1j*2*npa.pi*dl*npa.linspace(0, Ny-1, Ny)/beta/lambda0)
    return npa.sum(npa.real(ey*eta)) / E0

objective = Objective(J, arg_list=[arg1])
# make optimization object and check derivatives
R = None
beta_proj = 1e-9
eta= 0.5
optimization = Optimization(objective=objective, simulation=simulation, design_region=design_region, eps_m=eps_m, R=R, beta=beta_proj, eta=eta)
# check the derivatives (note, full derivatives are checked, linear and nonlinear no longer separate)
(grad_avm, grad_num) = optimization.check_deriv(Npts=5, d_rho=1e-3)
print('adjoint gradient   = {}\nnumerical gradient = {}'.format(grad_avm, grad_num))
# run the optimization
optimization.run(method='lbfgs', Nsteps=1000, step_size=2e-1)
# plot optimization results
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(22,3))

simulation.plt_eps(ax=ax1, tiled_y=num_cells, outline=False)
ax1.set_title('final permittivity distribution')

optimization.plt_objs(ax=ax2)
ax2.set_yscale('linear')
plt.show()
# setup subplots
f, (ax) = plt.subplots(1,1, figsize=(20,5))

# linear fields
(Hx,Hy,Ez) = simulation.solve_fields()
simulation.plt_re(ax=ax, tiled_y=num_cells)
ax1.set_title('linear field')

plt.show()<jupyter_output>/anaconda3/lib/python3.6/site-packages/matplotlib/contour.py:1173: UserWarning: No contour levels were found within the data range.
  warnings.warn("No contour levels were found"
{'fraction_non_alphanumeric': 0.12680868167202572, 'fraction_numerical': 0.018287781350482316, 'mean_word_length': 3.447721179624665, 'pattern_counts': {'":': 0, '<': 4, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '174324', 'license': 'MIT', 'n_tokens_mistral': 1766, 'n_tokens_neox': 1666, 'n_words': 464, 'path': 'Notebooks/Accelerator.ipynb', 'repo_name': 'Ryangoabroad/angler', 'size': '4976'}