-
Notifications
You must be signed in to change notification settings - Fork 16
/
Fdfd.py
292 lines (211 loc) · 9.79 KB
/
Fdfd.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
from fdfdpy.constants import DEFAULT_LENGTH_SCALE, DEFAULT_MATRIX_FORMAT, DEFAULT_SOLVER
from fdfdpy.constants import EPSILON_0, MU_0
from fdfdpy.linalg import construct_A, solver_direct, grid_average
from fdfdpy.derivatives import unpack_derivs
from fdfdpy.plot import plt_base, plt_base_eps
from fdfdpy.nonlinear_solvers import born_solve, newton_solve, LM_solve
from fdfdpy.source.mode import mode
from numpy import ones, zeros, abs, real, conj, sum
from scipy.sparse import spdiags
from copy import deepcopy
class Fdfd:
def __init__(self, omega, eps_r, dl, NPML, pol, L0=DEFAULT_LENGTH_SCALE):
# initializes Fdfd object
self.L0 = L0
self.omega = float(omega)
self.dl = float(dl)
self.eps_r = eps_r
self.NPML = [int(n) for n in NPML]
self.pol = pol
self._check_inputs()
(Nx,Ny) = eps_r.shape
self.Nx = Nx
self.Ny = Ny
self.mu_r = ones((self.Nx,self.Ny))
self.src = zeros((self.Nx,self.Ny))
self.xrange = [0, float(Nx*self.dl)]
self.yrange = [0, float(Ny*self.dl)]
# construct the system matrix
(A, derivs) = construct_A(self.omega, self.xrange, self.yrange, eps_r, self.NPML, self.pol, self.L0,
matrix_format=DEFAULT_MATRIX_FORMAT,
timing=False)
self.A = A
self.derivs = derivs
self.fields = {f : None for f in ['Ex','Ey','Ez','Hx','Hy','Hz']}
self.modes = [];
def setup_modes(self):
# calculates
for modei in self.modes:
modei.setup_src(self)
def add_mode(self, neff, direction_normal, center, width, scale=1, order=1):
# adds a mode definition to the simulation
self.modes.append( mode(neff, direction_normal, center, width, scale=scale, order=order) )
def reset_eps(self, new_eps):
# sets a new permittivity with the same other parameters and reconstructs a new A
self.eps_r = new_eps
(A, derivs) = construct_A(self.omega, self.xrange, self.yrange, self.eps_r, self.NPML, self.pol, self.L0,
matrix_format=DEFAULT_MATRIX_FORMAT,
timing=False)
self.A = A
self.derivs = derivs
self.fields = {f : None for f in ['Ex','Ey','Ez','Hx','Hy','Hz']}
def solve_fields(self, timing=False, averaging=True, solver=DEFAULT_SOLVER, matrix_format=DEFAULT_MATRIX_FORMAT):
# performs direct solve for A given source
EPSILON_0_ = EPSILON_0*self.L0
MU_0_ = MU_0*self.L0
X = solver_direct(self.A, self.src*1j*self.omega, timing=timing, solver=solver)
(Nx,Ny) = self.src.shape
M = Nx*Ny
(Dyb, Dxb, Dxf, Dyf) = unpack_derivs(self.derivs)
if self.pol == 'Hz':
if averaging:
vector_eps_x = grid_average(EPSILON_0_*self.eps_r, 'x').reshape((-1,))
vector_eps_y = grid_average(EPSILON_0_*self.eps_r, 'y').reshape((-1,))
else:
vector_eps_x = EPSILON_0_*self.eps_r.reshape((-1,))
vector_eps_y = EPSILON_0_*self.eps_r.reshape((-1,))
T_eps_x_inv = spdiags(1/vector_eps_x, 0, M, M, format=matrix_format)
T_eps_y_inv = spdiags(1/vector_eps_y, 0, M, M, format=matrix_format)
ex = -1/1j/self.omega * T_eps_x_inv.dot(Dyb).dot(X)
ey = 1/1j/self.omega * T_eps_x_inv.dot(Dxb).dot(X)
Ex = ex.reshape((Nx, Ny))
Ey = ey.reshape((Nx, Ny))
Hz = X.reshape((Nx, Ny))
self.fields['Ex'] = Ex
self.fields['Ey'] = Ey
self.fields['Hz'] = Hz
return (Ex, Ey ,Hz)
elif self.pol == 'Ez':
hx = -1/1j/self.omega/MU_0_ * Dyb.dot(X)
hy = 1/1j/self.omega/MU_0_ * Dxb.dot(X)
Hx = hx.reshape((Nx, Ny))
Hy = hy.reshape((Nx, Ny))
Ez = X.reshape((Nx, Ny))
self.fields['Hx'] = Hx
self.fields['Hy'] = Hy
self.fields['Ez'] = Ez
return (Hx, Hy, Ez)
else:
raise ValueError('Invalid polarization: {}'.format(str(self.pol)))
def solve_fields_nl(self, nonlinear_fn, nl_region, dnl_de=None, timing=False, averaging=True,
Estart=None, solver_nl='born', conv_threshold=1e-10, max_num_iter=50,
solver=DEFAULT_SOLVER, matrix_format=DEFAULT_MATRIX_FORMAT):
# solves for the nonlinear fields of the simulation.
# store the original permittivity
eps_orig = deepcopy(self.eps_r)
# if the nonlinear objects were not supplied, throw an error
if nonlinear_fn is None or nl_region is None:
raise ValueError("'nonlinear_fn' and 'nl_region' must be supplied")
if self.pol == 'Ez':
# if born solver
if solver_nl == 'born':
(Hx, Hy, Ez, conv_array) = born_solve(self, nonlinear_fn, nl_region, Estart, conv_threshold, max_num_iter, averaging=averaging)
# if newton solver
elif solver_nl == 'newton':
# newton needs the derivative of the nonlinearity.
if dnl_de is None:
raise ValueError("'dnl_de' argument must be set to run Newton solve")
(Hx, Hy, Ez, conv_array) = newton_solve(self, nonlinear_fn, nl_region, dnl_de, Estart, conv_threshold, max_num_iter, averaging=averaging)
elif solver_nl == 'LM':
# LM needs the derivative of the nonlinearity.
if dnl_de is None:
raise ValueError("'dnl_de' argument must be set to run LM solve")
(Hx, Hy, Ez, conv_array) = LM_solve(self, nonlinear_fn, nl_region, dnl_de, Estart, conv_threshold, max_num_iter, averaging=averaging)
# incorrect solver_nl argument
else:
raise AssertionError("solver must be one of {'born', 'newton', 'LM'}")
# reset the permittivity to the original value
self.eps_r = eps_orig # (note, not self.reset_eps or else the fields get destroyed)
# return final nonlinear fields and an array of the norm convergences
self.fields['Hx'] = Hx
self.fields['Hy'] = Hy
self.fields['Ez'] = Ez
return (Hx, Hy, Ez, conv_array)
elif self.pol == 'Hz':
# if born solver
if solver_nl == 'born':
(Ex, Ey, Hz, conv_array) = born_solve(self, nonlinear_fn, nl_region, Estart, conv_threshold, max_num_iter, averaging=averaging)
# if newton solver
elif solver_nl == 'newton':
# newton needs the derivative of the nonlinearity.
if dnl_de is None:
raise ValueError("'dnl_de' argument must be set to run Newton solve")
(Ex, Ey, Hz, conv_array) = newton_solve(self, nonlinear_fn, nl_region, dnl_de, Estart, conv_threshold, max_num_iter, averaging=averaging)
# incorrect solver_nl argument
else:
raise AssertionError("solver must be one of {'born', 'newton'}")
# reset the permittivity to the original value
self.eps_r = eps_orig # (note, not self.reset_eps or else the fields get destroyed)
# return final nonlinear fields and an array of the norm convergences
self.fields['Ex'] = Ex
self.fields['Ey'] = Ey
self.fields['Hz'] = Hz
return (Ex, Ey, Hz, conv_array)
else:
raise ValueError('Invalid polarization: {}'.format(str(self.pol)))
def _check_inputs(self):
# checks the inputs and makes sure they are kosher
assert self.L0 > 0, "L0 must be a positive number, was supplied {},".format(str(self.L0))
assert len(self.NPML) == 2, "yrange must be a list of length 2, was supplied {}, which is of length {}".format(str(self.NPML), len(self.NPML))
assert self.NPML[0] >= 0 and self.NPML[1] >= 0, "both elements of NPML must be >= 0"
assert self.pol in ['Ez','Hz'], "pol must be one of 'Ez' or 'Hz'"
# to do, check for correct types as well.
def flux_probe(self, direction_normal, center, width):
# computes the total flux across the plane (line in 2D) defined by direction_normal, center, width
# first extract the slice of the permittivity
if direction_normal == "x":
inds_x = [center[0], center[0]+1]
inds_y = [int(center[1]-width/2), int(center[1]+width/2)]
elif direction_normal == "y":
inds_x = [int(center[0]-width/2), int(center[0]+width/2)]
inds_y = [center[1], center[1]+1]
else:
raise ValueError("The value of direction_normal is neither x nor y!")
if self.pol == 'Ez':
Ez_x = grid_average(self.fields['Ez'][inds_x[0]:inds_x[1]+1, inds_y[0]:inds_y[1]+1], 'x')[:-1,:-1]
Ez_y = grid_average(self.fields['Ez'][inds_x[0]:inds_x[1]+1, inds_y[0]:inds_y[1]+1], 'y')[:-1,:-1]
# NOTE: Last part drops the extra rows/cols used for grid_average
if direction_normal == "x":
Sx = -1/2*real(Ez_x*conj(self.fields['Hy'][inds_x[0]:inds_x[1], inds_y[0]:inds_y[1]]))
return self.dl*sum(Sx)
elif direction_normal == "y":
Sy = 1/2*real(Ez_y*conj(self.fields['Hy'][inds_x[0]:inds_x[1], inds_y[0]:inds_y[1]]))
return self.dl*sum(Sy)
elif self.pol == 'Hz':
Hz_x = grid_average(self.fields['Hz'][inds_x[0]:inds_x[1]+1, inds_y[0]:inds_y[1]+1], 'x')[:-1,:-1]
Hz_y = grid_average(self.fields['Hz'][inds_x[0]:inds_x[1]+1, inds_y[0]:inds_y[1]+1], 'y')[:-1,:-1]
# NOTE: Last part drops the extra rows/cols used for grid_average
if direction_normal == "x":
Sx = 1/2*real(self.fields['Ey'][inds_x[0]:inds_x[1], inds_y[0]:inds_y[1]]*conj(Hz_x))
return self.dl*sum(Sx)
elif direction_normal == "y":
Sy = -1/2*real(self.fields['Ex'][inds_x[0]:inds_x[1], inds_y[0]:inds_y[1]]*conj(Hz_y))
return self.dl*sum(Sy)
def plt_abs(self, cbar=True, outline=True, ax=None):
# plot absolute value of primary field (e.g. Ez/Hz)
if self.fields[self.pol] is None:
raise ValueError("need to solve the simulation first")
field_val = abs( self.fields[self.pol] )
outline_val = abs( self.eps_r )
vmin = 0.0
vmax = field_val.max()
cmap = "magma"
return plt_base(field_val, outline_val, cmap, vmin, vmax, self.pol, cbar=cbar, outline=outline, ax=ax)
def plt_re(self, cbar=True, outline=True, ax=None):
# plot real part of primary field (e.g. Ez/Hz)
if self.fields[self.pol] is None:
raise ValueError("need to solve the simulation first")
field_val = real( self.fields[self.pol] )
outline_val = abs( self.eps_r )
vmin = -abs(field_val).max()
vmax = +abs(field_val).max()
cmap = "RdBu"
return plt_base(field_val, outline_val, cmap, vmin, vmax, self.pol, cbar=cbar, outline=outline, ax=ax)
def plt_eps(self, cbar=True, outline=True, ax=None):
# plot the permittivity distribution
eps_val = abs(self.eps_r)
outline_val = abs(self.eps_r)
vmin = 1
vmax = abs(self.eps_r).max()
cmap = "Greys"
return plt_base_eps(eps_val, outline_val, cmap, vmin, vmax, cbar=cbar, outline=outline, ax=ax)