-
Notifications
You must be signed in to change notification settings - Fork 116
/
sources.py
640 lines (538 loc) · 22.5 KB
/
sources.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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
""" Sources are objects that inject the fields into the grid.
Available sources:
- PointSource
- LineSource
"""
## Imports
# other
from math import pi, sin
# typing
from .typing_ import Tuple, Number, ListOrSlice, List
from numpy import ndarray
# relatvie
from .grid import Grid
from .backend import backend as bd
from .waveforms import *
from .detectors import CurrentDetector
## PointSource class
class PointSource:
"""A source placed at a single point (grid cell) in the grid"""
def __init__(
self,
period: Number = 15,
amplitude: float = 1.0,
phase_shift: float = 0.0,
name: str = None,
pulse: bool = False,
cycle: int = 5,
hanning_dt: float = 10.0,
):
"""Create a LineSource with a gaussian profile
Args:
period: The period of the source. The period can be specified
as integer [timesteps] or as float [seconds]
amplitude: The electric field amplitude in simulation units
phase_shift: The phase offset of the source.
name: name of the source.
pulse: Set True to use a Hanning window pulse instead of continuous wavefunction.
cycle: cycles for Hanning window pulse.
hanning_dt: timestep used for Hanning window pulse width (optional).
"""
self.grid = None
self.period = period
self.amplitude = amplitude
self.phase_shift = phase_shift
self.name = name
self.pulse = pulse
self.cycle = cycle
self.frequency = 1.0 / period
self.hanning_dt = hanning_dt if hanning_dt is not None else 0.5 / self.frequency
def _register_grid(self, grid: Grid, x: Number, y: Number, z: Number):
"""Register a grid for the source.
Args:
grid: the grid to place the source into.
x: The x-location of the source in the grid
y: The y-location of the source in the grid
z: The z-location of the source in the grid
Note:
As its name suggests, this source is a POINT source.
Hence it should be placed at a single coordinate tuple
int the grid.
"""
self.grid = grid
self.grid.sources.append(self)
if self.name is not None:
if not hasattr(grid, self.name):
setattr(grid, self.name, self)
else:
raise ValueError(
f"The grid already has an attribute with name {self.name}"
)
try:
(x,), (y,), (z,) = x, y, z
except (TypeError, ValueError):
raise ValueError("a point source should be placed on a single grid cell.")
self.x, self.y, self.z = grid._handle_tuple((x, y, z))
self.period = grid._handle_time(self.period)
def update_E(self):
"""Add the source to the electric field"""
q = self.grid.time_steps_passed
# if pulse
if self.pulse:
t1 = int(2 * pi / (self.frequency * self.hanning_dt / self.cycle))
if q < t1:
src = self.amplitude * hanning(
self.frequency, q * self.hanning_dt, self.cycle
)
else:
# src = - self.grid.E[self.x, self.y, self.z, 2]
src = 0
# if not pulse
else:
src = self.amplitude * sin(2 * pi * q / self.period + self.phase_shift)
self.grid.E[self.x, self.y, self.z, 2] += src
def update_H(self):
"""Add the source to the magnetic field"""
def __repr__(self):
return (
f"{self.__class__.__name__}(period={self.period}, "
f"amplitude={self.amplitude}, phase_shift={self.phase_shift}, "
f"name={repr(self.name)})"
)
def __str__(self):
s = " " + repr(self) + "\n"
x = f"{self.x}"
y = f"{self.y}"
z = f"{self.z}"
s += f" @ x={x}, y={y}, z={z}\n"
return s
## LineSource class
class LineSource:
"""A source along a line in the FDTD grid"""
def __init__(
self,
period: Number = 15,
amplitude: float = 1.0,
phase_shift: float = 0.0,
name: str = None,
pulse: bool = False,
cycle: int = 5,
hanning_dt: float = 10.0,
):
"""Create a LineSource with a gaussian profile
Args:
period: The period of the source. The period can be specified
as integer [timesteps] or as float [seconds]
amplitude: The amplitude of the source in simulation units
phase_shift: The phase offset of the source.
pulse: Set True to use a Hanning window pulse instead of continuous wavefunction.
cycle: cycles for Hanning window pulse.
hanning_dt: timestep used for Hanning window pulse width (optional).
"""
self.grid = None
self.period = period
self.amplitude = amplitude
self.phase_shift = phase_shift
self.name = name
self.pulse = pulse
self.cycle = cycle
self.frequency = 1.0 / period
self.hanning_dt = hanning_dt if hanning_dt is not None else 0.5 / self.frequency
def _register_grid(
self, grid: Grid, x: ListOrSlice, y: ListOrSlice, z: ListOrSlice
):
"""Register a grid for the source.
Args:
grid: the grid to place the source into.
x: The x-location of the source in the grid
y: The y-location of the source in the grid
z: The z-location of the source in the grid
Note:
As its name suggests, this source is a LINE source.
Hence the source spans the diagonal of the cube
defined by the slices in the grid.
"""
self.grid = grid
self.grid.sources.append(self)
if self.name is not None:
if not hasattr(grid, self.name):
setattr(grid, self.name, self)
else:
raise ValueError(
f"The grid already has an attribute with name {self.name}"
)
self.x, self.y, self.z = self._handle_slices(x, y, z)
self.period = grid._handle_time(self.period)
L = len(self.x)
vect = bd.array(
(bd.array(self.x) - self.x[L // 2]) ** 2
+ (bd.array(self.y) - self.y[L // 2]) ** 2
+ (bd.array(self.z) - self.z[L // 2]) ** 2,
bd.float,
)
self.profile = bd.exp(-(vect ** 2) / (2 * (0.5 * vect.max()) ** 2))
self.profile /= self.profile.sum()
self.profile *= self.amplitude
def _handle_slices(
self, x: ListOrSlice, y: ListOrSlice, z: ListOrSlice
) -> Tuple[List, List, List]:
"""Convert slices in the grid to lists
This is necessary to make the source span the diagonal of the volume
defined by the slices.
Args:
x: The x-location of the volume in the grid
y: The y-location of the volume in the grid
z: The z-location of the volume in the grid
Returns:
x, y, z: the x, y and z coordinates of the source as lists
"""
# if list-indices were chosen:
if isinstance(x, list) and isinstance(y, list) and isinstance(z, list):
if len(x) != len(y) or len(y) != len(z) or len(z) != len(x):
raise IndexError(
"sources require grid to be indexed with slices or equal length list-indices"
)
x = [self.grid._handle_distance(_x) for _x in x]
y = [self.grid._handle_distance(_y) for _y in y]
z = [self.grid._handle_distance(_z) for _z in z]
return x, y, z
# if a combination of list-indices and slices were chosen,
# convert the list-indices to slices.
# TODO: maybe issue a warning here?
if isinstance(x, list):
x = slice(
self.grid._handle_distance(x[0]),
self.grid._handle_distance(x[-1]),
None,
)
if isinstance(y, list):
y = slice(
self.grid._handle_distance(y[0]),
self.grid._handle_distance(y[-1]),
None,
)
if isinstance(z, list):
z = slice(
self.grid._handle_distance(z[0]),
self.grid._handle_distance(z[-1]),
None,
)
# if we get here, we can assume slices:
x0 = self.grid._handle_distance(x.start if x.start is not None else 0)
y0 = self.grid._handle_distance(y.start if y.start is not None else 0)
z0 = self.grid._handle_distance(z.start if z.start is not None else 0)
x1 = self.grid._handle_distance(x.stop if x.stop is not None else self.grid.Nx)
y1 = self.grid._handle_distance(y.stop if y.stop is not None else self.grid.Ny)
z1 = self.grid._handle_distance(z.stop if z.stop is not None else self.grid.Nz)
# we can now convert these coordinates into index lists
m = max(abs(x1 - x0), abs(y1 - y0), abs(z1 - z0))
if m < 2:
raise ValueError("a LineSource should consist of at least two gridpoints")
x = [v.item() for v in bd.array(bd.linspace(x0, x1, m, endpoint=False), bd.int)]
y = [v.item() for v in bd.array(bd.linspace(y0, y1, m, endpoint=False), bd.int)]
z = [v.item() for v in bd.array(bd.linspace(z0, z1, m, endpoint=False), bd.int)]
return x, y, z
def update_E(self):
"""Add the source to the electric field"""
q = self.grid.time_steps_passed
# if pulse
if self.pulse:
t1 = int(2 * pi / (self.frequency * self.hanning_dt / self.cycle))
if q < t1:
vect = self.profile * hanning(
self.frequency, q * self.hanning_dt, self.cycle
)
else:
# src = - self.grid.E[self.x, self.y, self.z, 2]
vect = self.profile * 0
# if not pulse
else:
vect = self.profile * sin(2 * pi * q / self.period + self.phase_shift)
# do not use list indexing here, as this is much slower especially for torch backend
# DISABLED: self.grid.E[self.x, self.y, self.z, 2] = vect
for x, y, z, value in zip(self.x, self.y, self.z, vect):
self.grid.E[x, y, z, 2] += value
def update_H(self):
"""Add the source to the magnetic field"""
def __repr__(self):
return (
f"{self.__class__.__name__}(period={self.period}, "
f"amplitude={self.amplitude}, phase_shift={self.phase_shift}, "
f"name={repr(self.name)})"
)
def __str__(self):
s = " " + repr(self) + "\n"
x = f"[{self.x[0]}, ... , {self.x[-1]}]"
y = f"[{self.y[0]}, ... , {self.y[-1]}]"
z = f"[{self.z[0]}, ... , {self.z[-1]}]"
s += f" @ x={x}, y={y}, z={z}\n"
return s
## PlaneSource class
class PlaneSource:
"""A source along a plane in the FDTD grid"""
def __init__(
self,
period: Number = 15,
amplitude: float = 1.0,
phase_shift: float = 0.0,
name: str = None,
polarization: str = 'z',
):
"""Create a PlaneSource.
Args:
period: The period of the source. The period can be specified
as integer [timesteps] or as float [seconds]
amplitude: The amplitude of the source in simulation units
phase_shift: The phase offset of the source.
polarization: Axis of E-field polarization ('x','y',or 'z')
"""
self.grid = None
self.period = period
self.amplitude = amplitude
self.phase_shift = phase_shift
self.name = name
self.polarization = polarization
def _register_grid(
self, grid: Grid, x: ListOrSlice, y: ListOrSlice, z: ListOrSlice
):
"""Register a grid for the source.
Args:
grid: the grid to place the source into.
x: The x-location of the source in the grid
y: The y-location of the source in the grid
z: The z-location of the source in the grid
Note:
As its name suggests, this source is a LINE source.
Hence the source spans the diagonal of the cube
defined by the slices in the grid.
"""
self.grid = grid
self.grid.sources.append(self)
if self.name is not None:
if not hasattr(grid, self.name):
setattr(grid, self.name, self)
else:
raise ValueError(
f"The grid already has an attribute with name {self.name}"
)
self.x, self.y, self.z = self._handle_slices(x, y, z)
self.period = grid._handle_time(self.period)
x = bd.arange(self.x.start, self.x.stop, 1) - (self.x.start + self.x.stop) // 2
y = bd.arange(self.y.start, self.y.stop, 1) - (self.y.start + self.y.stop) // 2
z = bd.arange(self.z.start, self.z.stop, 1) - (self.z.start + self.z.stop) // 2
xvec, yvec, zvec = bd.broadcast_arrays(
x[:, None, None], y[None, :, None], z[None, None, :]
)
_xvec = bd.array(xvec, float)
_yvec = bd.array(yvec, float)
_zvec = bd.array(zvec, float)
profile = bd.ones(_xvec.shape)
self.profile = self.amplitude * profile
def _handle_slices(
self, x: ListOrSlice, y: ListOrSlice, z: ListOrSlice
) -> Tuple[List, List, List]:
"""Validate slices and calculate center of plane
Args:
x: The x-location of the volume in the grid
y: The y-location of the volume in the grid
z: The z-location of the volume in the grid
Returns:
x, y, z: the x, y and z coordinates of the source as slices
"""
# ensure all slices
if not isinstance(x, slice):
if isinstance(x, list):
(x,) = x
x = slice(
self.grid._handle_distance(x), self.grid._handle_distance(x) + 1, None
)
if not isinstance(y, slice):
if isinstance(y, list):
(y,) = y
y = slice(
self.grid._handle_distance(y), self.grid._handle_distance(y) + 1, None
)
if not isinstance(z, slice):
if isinstance(z, list):
(z,) = z
z = slice(
self.grid._handle_distance(z), self.grid._handle_distance(z) + 1, None
)
# if we get here, we can assume slices:
x0 = self.grid._handle_distance(x.start if x.start is not None else 0)
y0 = self.grid._handle_distance(y.start if y.start is not None else 0)
z0 = self.grid._handle_distance(z.start if z.start is not None else 0)
x1 = self.grid._handle_distance(x.stop if x.stop is not None else self.grid.Nx)
y1 = self.grid._handle_distance(y.stop if y.stop is not None else self.grid.Ny)
z1 = self.grid._handle_distance(z.stop if z.stop is not None else self.grid.Nz)
# make sure all slices have a start, stop and no step:
x = (
slice(x0, x1)
if x0 < x1
else (slice(x1, x0) if x0 > x1 else slice(x0, x0 + 1))
)
y = (
slice(y0, y1)
if y0 < y1
else (slice(y1, y0) if y0 > y1 else slice(y0, y0 + 1))
)
z = (
slice(z0, z1)
if z0 < z1
else (slice(z1, z0) if z0 > z1 else slice(z0, z0 + 1))
)
if [x.stop - x.start, y.stop - y.start, z.stop - z.start].count(0) > 0:
raise ValueError(
"Given location for PlaneSource results in slices of length 0!"
)
if [x.stop - x.start, y.stop - y.start, z.stop - z.start].count(1) == 0:
raise ValueError("Given location for PlaneSource is not a 2D plane!")
if [x.stop - x.start, y.stop - y.start, z.stop - z.start].count(1) > 1:
raise ValueError(
"Given location for PlaneSource should have no more than one dimension in which it's flat.\n"
"Use a LineSource for lower dimensional sources."
)
self._Epol = 'xyz'.index(self.polarization)
if (x.stop - x.start == 1 and self.polarization == 'x') or \
(y.stop - y.start == 1 and self.polarization == 'y') or \
(z.stop - z.start == 1 and self.polarization == 'z'):
raise ValueError(
"PlaneSource cannot be polarized perpendicular to the orientation of the plane."
)
_Hpols = [(z,1,2), (z,0,2), (y,0,1)][self._Epol]
if _Hpols[0].stop - _Hpols[0].start == 1:
self._Hpol = _Hpols[1]
else:
self._Hpol = _Hpols[2]
return x, y, z
def update_E(self):
"""Add the source to the electric field"""
q = self.grid.time_steps_passed
vect = self.profile * sin(2 * pi * q / self.period + self.phase_shift)
self.grid.E[self.x, self.y, self.z, self._Epol] = vect
def update_H(self):
"""Add the source to the magnetic field"""
q = self.grid.time_steps_passed
vect = self.profile * sin(2 * pi * q / self.period + self.phase_shift)
self.grid.H[self.x, self.y, self.z, self._Hpol] = vect
def __repr__(self):
return (
f"{self.__class__.__name__}(period={self.period}, "
f"amplitude={self.amplitude}, phase_shift={self.phase_shift}, "
f"name={repr(self.name)}, polarization={repr(self.polarization)})"
)
def __str__(self):
s = " " + repr(self) + "\n"
x = f"[{self.x.start}, ... , {self.x.stop}]"
y = f"[{self.y.start}, ... , {self.y.stop}]"
z = f"[{self.z.start}, ... , {self.z.stop}]"
s += f" @ x={x}, y={y}, z={z}\n"
return s
class SoftArbitraryPointSource:
r"""
A source placed at a single point (grid cell) in the grid.
This source is special: it's both a source and a detector.
Unlike the other sources, the input is a voltage, not an electric field.
(really? why? should we convert back and forth?)
For electrical measurements I've only needed a single-index source,
so I don't know how the volume/line sources above work.
We want the FFT function to operate over any detector.
Maybe all sources should take an arbitary waveform argument?
Each index in the *waveform* array represents 1 value at a timestep.
There are many different *geometries* of "equivalent sources".
The detector/source paradigm used in /fdtd might perhaps not correspond to this in an ideal
fashion.
It's not intuitively clear to me what a "soft" source would imply in the optical case, or what
impedance even means for a laser.
/fdtd/ seems to have found primary use in optical circles,
so the default Z should probably be 0.
"Whilst established for microwaves and electrical circuits,
this concept has only very recently been observed in the optical domain,
yet is not well defined or understood."[1]
[1]: Optical impedance of metallic nano-structures, M. Mazilu and K. Dholakia
https://doi.org/10.1364/OE.14.007709
[2]: http://www.gwoptics.org/learn/02_Plane_waves/01_Fabry_Perot_cavity/02_Impedance_matched.php
/\/\-
"""
def __init__(
self, waveform_array: ndarray, name: str = None, impedance: float = 0.0
):
"""Create
Args:
waveform_array
"""
self.grid = None
self.name = name
self.current_detector = None
self.waveform_array = waveform_array
self.impedance = impedance
self.input_voltage = [] # voltage hard-imposed by the source
self.source_voltage = [] #
# "field" rather than "voltage" might be more meaningful
# FIXME: these voltage time histories have a different dimensionality
def _register_grid(self, grid: Grid, x: Number, y: Number, z: Number):
"""Register a grid for the source.
Args:
grid: the grid to place the source into.
x: The x-location of the source in the grid
y: The y-location of the source in the grid
z: The z-location of the source in the grid
Note:
As its name suggests, this source is a POINT source.
Hence it should be placed at a single coordinate tuple
int the grid.
"""
self.grid = grid
self.grid.sources.append(self)
if self.name is not None:
if not hasattr(grid, self.name):
setattr(grid, self.name, self)
else:
raise ValueError(
f"The grid already has an attribute with name {self.name}"
)
try:
(x,), (y,), (z,) = x, y, z
except (TypeError, ValueError):
raise ValueError("a point source should be placed on a single grid cell.")
self.x, self.y, self.z = grid._handle_tuple((x, y, z))
if self.name is not None:
detector_name += "_I"
else:
detector_name = None
self.current_detector = CurrentDetector(name=detector_name)
grid[x, y, z] = self.current_detector
def update_E(self):
# It is important that this step happen between the E-field update and the
# H-field update.
if self.grid.time_steps_passed < self.waveform_array.shape[0]:
# check for off-by-one error here
input_voltage = self.waveform_array[self.grid.time_steps_passed]
else:
input_voltage = 0.0 # one could taper the last value off smoothly instead
if self.grid.time_steps_passed > 0:
current = self.current_detector.I[-1][0][0][0]
else:
current = 0.0
if self.impedance > 0:
source_resistive_voltage = self.impedance * current
output_voltage = input_voltage + source_resistive_voltage
else:
output_voltage = input_voltage
# right now, this does not compensate for the cell's permittivity!
self.grid.E[self.x, self.y, self.z, 2] += (
output_voltage / self.grid.grid_spacing
)
self.input_voltage.append([[[input_voltage]]])
self.source_voltage.append([[[output_voltage]]])
def update_H(self):
pass
def __repr__(self):
return f"{self.__class__.__name__}()"
def __str__(self):
s = " " + repr(self) + "\n"
x = f"{self.x}"
y = f"{self.y}"
z = f"{self.z}"
s += f" @ x={x}, y={y}, z={z}\n"
return s