/
geom.py
executable file
·1627 lines (1316 loc) · 63.5 KB
/
geom.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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
import functools
import math
import numbers
import operator
import warnings
from collections import namedtuple
from copy import deepcopy
from numbers import Number
import numpy as np
import meep as mp
FreqRange = namedtuple('FreqRange', ['min', 'max'])
def check_nonnegative(prop, val):
if val >= 0:
return val
else:
raise ValueError("{} cannot be negative. Got {}".format(prop, val))
def init_do_averaging(mat_func):
if not hasattr(mat_func, 'do_averaging'):
mat_func.do_averaging = False
class Vector3(object):
"""
Properties:
**`x`, `y`, `z` [`float` or `complex`]** — The `x`, `y`, and `z` components of the
vector. Generally, functions that take a `Vector3` as an argument will accept an
iterable (e.g., a tuple or list) and automatically convert to a `Vector3`.
"""
def __init__(self, x=0.0, y=0.0, z=0.0):
"""
Create a new `Vector3` with the given components. All three components default to
zero. This can also be represented simply as `(x,y,z)` or `[x,y,z]`.
"""
self.x = float(x) if type(x) is int else x
self.y = float(y) if type(y) is int else y
self.z = float(z) if type(z) is int else z
def __eq__(self, other):
"""
Returns whether or not the two vectors are numerically equal. Beware of using this
function after operations that may have some error due to the finite precision of
floating-point numbers; use `close` instead.
```python
v1 == v2
```
"""
return self.x == other.x and self.y == other.y and self.z == other.z
def __ne__(self, other):
"""
Returns whether or not the two vectors are numerically unequal. Beware of using
this function after operations that may have some error due to the finite
precision of floating-point numbers; use `close` instead.
```python
v1 != v2
```
"""
return not self == other
def __add__(self, other):
"""
Return the sum of the two vectors.
```python
v3 = v1 + v2
```
"""
if isinstance(other, GeometricObject):
return NotImplemented
x = self.x + other.x
y = self.y + other.y
z = self.z + other.z
return Vector3(x, y, z)
def __sub__(self, other):
"""
Return the difference of the two vectors.
```python
v3 = v1 - v2
```
"""
x = self.x - other.x
y = self.y - other.y
z = self.z - other.z
return Vector3(x, y, z)
def __mul__(self, other):
"""
If `other` is a `Vector3`, returns the dot product of `v1` and `other`. If `other`
is a number, then `v1` is scaled by the number.
```python
c = v1 * other
```
"""
if type(other) is Vector3:
return self.dot(other)
elif isinstance(other, Number):
return self.scale(other)
else:
raise TypeError("No operation known for 'Vector3 * {}'".format(type(other)))
def __truediv__(self, other):
if type(other) is Vector3:
return Vector3(self.x / other.x, self.y / other.y, self.z / other.z)
elif isinstance(other, Number):
return Vector3(self.x / other, self.y / other, self.z / other)
else:
raise TypeError("No operation known for 'Vector3 / {}'".format(type(other)))
def __rmul__(self, other):
"""
If `other` is a `Vector3`, returns the dot product of `v1` and `other`. If `other`
is a number, then `v1` is scaled by the number.
```python
c = other * v1
```
"""
if isinstance(other, Number):
return self.scale(other)
else:
raise TypeError("No operation known for '{} * Vector3'".format(type(other)))
def __getitem__(self, i):
if i == 0:
return self.x
elif i == 1:
return self.y
elif i == 2:
return self.z
else:
raise IndexError("No value at index {}".format(i))
def __repr__(self):
return "Vector3<{}, {}, {}>".format(self.x, self.y, self.z)
def __array__(self):
return np.array([self.x, self.y, self.z])
def conj(self):
return Vector3(self.x.conjugate(), self.y.conjugate(), self.z.conjugate())
def scale(self, s):
x = self.x * s
y = self.y * s
z = self.z * s
return Vector3(x, y, z)
def dot(self, v):
"""
Returns the dot product of *`self`* and *`v`*.
```python
v3 = v1.dot(v2)
```
"""
return self.x * v.x + self.y * v.y + self.z * v.z
def cdot(self, v):
"""Returns the conjugated dot product: `conj(self)` dot `v`."""
return self.conj().dot(v)
def cross(self, v):
"""
Return the cross product of `self` and `v`.
```python
v3 = v1.cross(v2)
```
"""
x = self.y * v.z - self.z * v.y
y = self.z * v.x - self.x * v.z
z = self.x * v.y - self.y * v.x
return Vector3(x, y, z)
def norm(self):
"""
Returns the length `math.sqrt(abs(self.dot(self)))` of the given vector.
```python
v2 = v1.norm()
```
"""
return math.sqrt(abs(self.cdot(self).real))
def unit(self):
"""
Returns a unit vector in the direction of the vector.
```python
v2 = v1.unit()
```
"""
return self.scale(1 / self.norm())
def close(self, v, tol=1.0e-7):
"""
Returns whether or not the corresponding components of the `self` and `v` vectors
are within `tol` of each other. Defaults to 1e-7.
```python
v1.close(v2, [tol])
```
"""
return (abs(self.x - v.x) <= tol and
abs(self.y - v.y) <= tol and
abs(self.z - v.z) <= tol)
def rotate(self, axis, theta):
"""
Returns the vector rotated by an angle *`theta`* (in radians) in the right-hand
direction around the *`axis`* vector (whose length is ignored). You may find the
python functions `math.degrees` and `math.radians` useful to convert angles
between degrees and radians.
```python
v2 = v1.rotate(axis, theta)
```
"""
u = axis.unit()
vpar = u.scale(u.dot(self))
vcross = u.cross(self)
vperp = self - vpar
return vpar + (vperp.scale(math.cos(theta)) + vcross.scale(math.sin(theta)))
# rotate vectors in lattice/reciprocal coords (note that the axis
# is also given in the corresponding basis):
def rotate_lattice(self, axis, theta, lat):
a = lattice_to_cartesian(axis, lat)
v = lattice_to_cartesian(self, lat)
return cartesian_to_lattice(v.rotate(a, theta), lat)
def rotate_reciprocal(self, axis, theta, lat):
a = reciprocal_to_cartesian(axis, lat)
v = reciprocal_to_cartesian(self, lat)
return cartesian_to_reciprocal(v.rotate(a, theta), lat)
class Medium(object):
"""
This class is used to specify the materials that geometric objects are made of. It
represents an electromagnetic medium which is possibly nonlinear and/or dispersive.
See also [Materials](Materials.md). To model a perfectly-conducting metal, use the
predefined `metal` object, above. To model imperfect conductors, use a dispersive
dielectric material. See also the [Predefined Variables](#predefined-variables):
`metal`, `perfect_electric_conductor`, and `perfect_magnetic_conductor`.
**Material Function**
Any function that accepts a `Medium` instance can also accept a user-defined Python
function. This allows you to specify the material as an arbitrary function of
position. The function must have one argument, the position `Vector3`, and return the
material at that point, which should be a Python `Medium` instance. This is
accomplished by passing a function to the `material_function` keyword argument in the
`Simulation` constructor, or the `material` keyword argument in any `GeometricObject`
constructor. For an example, see [Subpixel Smoothing/Enabling Averaging for Material
Function](Subpixel_Smoothing.md#enabling-averaging-for-material-function).
Instead of the `material` or `material_function` arguments, you can also use the
`epsilon_func` keyword argument to `Simulation` and `GeometricObject`, which takes a
function of position that returns the dielectric constant at that point.
**Important:** If your material function returns nonlinear, dispersive (Lorentzian or
conducting), or magnetic materials, you should also include a list of these materials
in the `extra_materials` input variable (above) to let Meep know that it needs to
support these material types in your simulation. For dispersive materials, you need to
include a material with the *same* values of $\\gamma_n$ and $\\omega_n$, so
you can only have a finite number of these, whereas $\\sigma_n$ can vary
continuously and a matching $\\sigma_n$ need not be specified in
`extra_materials`. For nonlinear or conductivity materials, your `extra_materials`
list need not match the actual values of $\\sigma$ or $\\chi$ returned by your material function,
which can vary continuously.
**Complex $\\varepsilon$ and $\\mu$**: you cannot specify a
frequency-independent complex $\\varepsilon$ or $\\mu$ in Meep where
the imaginary part is a frequency-independent loss but there is an
alternative. That is because there are only two important
physical situations. First, if you only care about the loss in a
narrow bandwidth around some frequency, you can set the loss at
that frequency via the
[conductivity](Materials.md#conductivity-and-complex). Second, if
you care about a broad bandwidth, then all physical materials have
a frequency-dependent complex $\\varepsilon$ and/or $\\mu$, and you
need to specify that frequency dependence by fitting to Lorentzian
and/or Drude resonances via the `LorentzianSusceptibility` or
`DrudeSusceptibility` classes below.
Dispersive dielectric and magnetic materials, above, are specified via a list of
objects that are subclasses of type `Susceptibility`.
"""
def __init__(self, epsilon_diag=Vector3(1, 1, 1),
epsilon_offdiag=Vector3(),
mu_diag=Vector3(1, 1, 1),
mu_offdiag=Vector3(),
E_susceptibilities=None,
H_susceptibilities=None,
E_chi2_diag=Vector3(),
E_chi3_diag=Vector3(),
H_chi2_diag=Vector3(),
H_chi3_diag=Vector3(),
D_conductivity_diag=Vector3(),
D_conductivity_offdiag=Vector3(),
B_conductivity_diag=Vector3(),
B_conductivity_offdiag=Vector3(),
epsilon=None,
index=None,
mu=None,
chi2=None,
chi3=None,
D_conductivity=None,
B_conductivity=None,
E_chi2=None,
E_chi3=None,
H_chi2=None,
H_chi3=None,
valid_freq_range=FreqRange(min=-mp.inf, max=mp.inf)):
"""
Creates a `Medium` object.
+ **`epsilon` [`number`]** The frequency-independent isotropic relative
permittivity or dielectric constant. Default is 1. You can also use `index=n` as
a synonym for `epsilon=n*n`; note that this is not really the refractive index
if you also specify μ, since the true index is $\\sqrt{\\mu\\varepsilon}$. Using
`epsilon=ep` is actually a synonym for `epsilon_diag=mp.Vector3(ep, ep, ep)`.
+ **`epsilon_diag` and `epsilon_offdiag` [`Vector3`]** — These properties allow
you to specify ε as an arbitrary real-symmetric tensor by giving the diagonal
and offdiagonal parts. Specifying `epsilon_diag=Vector3(a, b, c)` and/or
`epsilon_offdiag=Vector3(u, v, w)` corresponds to a relative permittivity ε
tensor \\begin{pmatrix} a & u & v \\\\ u & b & w \\\\ v & w & c \\end{pmatrix}
Default is the identity matrix ($a = b = c = 1$ and $u = v = w = 0$).
+ **`mu` [`number`]** — The frequency-independent isotropic relative permeability
μ. Default is 1. Using `mu=pm` is actually a synonym for `mu_diag=mp.Vector3(pm,
pm, pm)`.
+ **`mu_diag` and `mu_offdiag` [`Vector3`]** — These properties allow you to
specify μ as an arbitrary real-symmetric tensor by giving the diagonal and
offdiagonal parts exactly as for ε above. Default is the identity matrix.
+ **`D_conductivity` [`number`]** — The frequency-independent electric
conductivity $\\sigma_D$. Default is 0. You can also specify a diagonal
anisotropic conductivity tensor by using the property `D_conductivity_diag`
which takes a `Vector3` to give the $\\sigma_D$ tensor diagonal. See also
[Conductivity](Materials.md#conductivity-and-complex).
+ **`B_conductivity` [`number`]** — The frequency-independent magnetic
conductivity $\\sigma_B$. Default is 0. You can also specify a diagonal
anisotropic conductivity tensor by using the property `B_conductivity_diag`
which takes a `Vector3` to give the $\\sigma_B$ tensor diagonal. See also
[Conductivity](Materials.md#conductivity-and-complex).
+ **`chi2` [`number`]** — The nonlinear electric
[Pockels](https://en.wikipedia.org/wiki/Pockels_effect) susceptibility
$\\chi^{(2)}$ (quadratic nonlinearity). Default is 0. See also [Nonlinearity](Materials.md#nonlinearity).
This is equivalent to setting `E_chi2`; alternatively, an analogous magnetic
nonlinearity can be specified using `H_chi2`. These are isotropic nonlinearities,
but *diagonal* anisotropic polarizations of the form $\\chi_i^{(2)} E_i^2$ can
be specified with `E_chi2_diag` (which defaults to `[E_chi2,E_chi2,E_chi2]`).
+ **`chi3` [`number`]** — The nonlinear electric
[Kerr](https://en.wikipedia.org/wiki/Kerr_effect) susceptibility $\\chi^{(3)}$
(cubic nonlinearity). Default is 0. See also [Nonlinearity](Materials.md#nonlinearity).
This is equivalent to setting `E_chi3`; alternatively, an analogous magnetic nonlinearity
can be specified using `H_chi3`. These are isotropic nonlinearities, but *diagonal*
anisotropic polarizations of the form $\\chi_i^{(3)} |E|^2 E_i$ can be specified with
`E_chi3_diag` (which defaults to `[E_chi3,E_chi3,E_chi3]`).
+ **`E_susceptibilities` [ list of `Susceptibility` class ]** — List of dispersive
susceptibilities (see below) added to the dielectric constant ε in order to
model material dispersion. Defaults to none (empty list). See also [Material
Dispersion](Materials.md#material-dispersion).
+ **`H_susceptibilities` [ list of `Susceptibility` class ]** — List of dispersive
susceptibilities (see below) added to the permeability μ in order to model
material dispersion. Defaults to none (empty list). See also [Material
Dispersion](Materials.md#material-dispersion).
"""
if epsilon:
epsilon_diag = Vector3(epsilon, epsilon, epsilon)
elif index:
i2 = index * index
epsilon_diag = Vector3(i2, i2, i2)
if mu:
mu_diag = Vector3(mu, mu, mu)
if D_conductivity:
D_conductivity_diag = Vector3(D_conductivity, D_conductivity, D_conductivity)
if B_conductivity:
B_conductivity_diag = Vector3(B_conductivity, B_conductivity, B_conductivity)
if E_chi2:
E_chi2_diag = Vector3(E_chi2, E_chi2, E_chi2)
if E_chi3:
E_chi3_diag = Vector3(E_chi3, E_chi3, E_chi3)
if H_chi2:
H_chi2_diag = Vector3(H_chi2, H_chi2, H_chi2)
if H_chi3:
H_chi3_diag = Vector3(H_chi3, H_chi3, H_chi3)
self.epsilon_diag = Vector3(*epsilon_diag)
self.epsilon_offdiag = Vector3(*epsilon_offdiag)
self.mu_diag = Vector3(*mu_diag)
self.mu_offdiag = Vector3(*mu_offdiag)
self.E_susceptibilities = E_susceptibilities if E_susceptibilities else []
self.H_susceptibilities = H_susceptibilities if H_susceptibilities else []
self.E_chi2_diag = Vector3(chi2, chi2, chi2) if chi2 else Vector3(*E_chi2_diag)
self.E_chi3_diag = Vector3(chi3, chi3, chi3) if chi3 else Vector3(*E_chi3_diag)
self.H_chi2_diag = Vector3(*H_chi2_diag)
self.H_chi3_diag = Vector3(*H_chi3_diag)
self.D_conductivity_diag = Vector3(*D_conductivity_diag)
self.D_conductivity_offdiag = Vector3(*D_conductivity_offdiag)
self.B_conductivity_diag = Vector3(*B_conductivity_diag)
self.B_conductivity_offdiag = Vector3(*D_conductivity_offdiag)
self.valid_freq_range = valid_freq_range
def __repr__(self):
return 'Medium()'
def transform(self, m):
"""
Transforms `epsilon`, `mu`, and `sigma` of any [susceptibilities](#susceptibility)
by the 3×3 matrix `m`. If `m` is a [rotation
matrix](https://en.wikipedia.org/wiki/Rotation_matrix), then the principal axes of
the susceptibilities are rotated by `m`. More generally, the susceptibilities χ
are transformed to MχMᵀ/|det M|, which corresponds to [transformation
optics](http://math.mit.edu/~stevenj/18.369/coordinate-transform.pdf) for an
arbitrary curvilinear coordinate transformation with Jacobian matrix M. The
absolute value of the determinant is to prevent inadvertent construction of
left-handed materials, which are [problematic in nondispersive
media](FAQ.md#why-does-my-simulation-diverge-if-0).
"""
eps = Matrix(mp.Vector3(self.epsilon_diag.x, self.epsilon_offdiag.x, self.epsilon_offdiag.y),
mp.Vector3(self.epsilon_offdiag.x, self.epsilon_diag.y, self.epsilon_offdiag.z),
mp.Vector3(self.epsilon_offdiag.y, self.epsilon_offdiag.z, self.epsilon_diag.z))
mu = Matrix(mp.Vector3(self.mu_diag.x, self.mu_offdiag.x, self.mu_offdiag.y),
mp.Vector3(self.mu_offdiag.x, self.mu_diag.y, self.mu_offdiag.z),
mp.Vector3(self.mu_offdiag.y, self.mu_offdiag.z, self.mu_diag.z))
new_eps = (m * eps * m.transpose()) / abs(m.determinant())
new_mu = (m * mu * m.transpose()) / abs(m.determinant())
self.epsilon_diag = mp.Vector3(new_eps.c1.x, new_eps.c2.y, new_eps.c3.z)
self.epsilon_offdiag = mp.Vector3(new_eps.c2.x, new_eps.c3.x, new_eps.c3.y)
self.mu_diag = mp.Vector3(new_mu.c1.x, new_mu.c2.y, new_mu.c3.z)
self.mu_offdiag = mp.Vector3(new_mu.c2.x, new_mu.c3.x, new_mu.c3.y)
for s in self.E_susceptibilities:
s.transform(m)
for s in self.H_susceptibilities:
s.transform(m)
def rotate(self, axis, theta):
T = get_rotation_matrix(axis,theta)
self.transform(T)
def epsilon(self,freq):
"""
Returns the medium's permittivity tensor as a 3x3 Numpy array at the specified
frequency `freq` which can be either a scalar, list, or Numpy array. In the case
of a list/array of N frequency points, a Numpy array of size Nx3x3 is returned.
"""
return self._get_epsmu(self.epsilon_diag, self.epsilon_offdiag, self.E_susceptibilities, self.D_conductivity_diag, self.D_conductivity_offdiag, freq)
def mu(self,freq):
"""
Returns the medium's permeability tensor as a 3x3 Numpy array at the specified
frequency `freq` which can be either a scalar, list, or Numpy array. In the case
of a list/array of N frequency points, a Numpy array of size Nx3x3 is returned.
"""
return self._get_epsmu(self.mu_diag, self.mu_offdiag, self.H_susceptibilities, self.B_conductivity_diag, self.B_conductivity_offdiag, freq)
def _get_epsmu(self, diag, offdiag, susceptibilities, conductivity_diag, conductivity_offdiag, freq):
# Clean the input
if np.isscalar(freq):
freqs = np.array(freq)[np.newaxis, np.newaxis, np.newaxis]
else:
freqs = np.squeeze(freq)
freqs = freqs[:, np.newaxis, np.newaxis]
# Check for values outside of allowed ranges
if np.min(np.squeeze(freqs)) < self.valid_freq_range.min:
raise ValueError('User specified frequency {} is below the Medium\'s limit, {}.'.format(np.min(np.squeeze(freqs)),self.valid_freq_range.min))
if np.max(np.squeeze(freqs)) > self.valid_freq_range.max:
raise ValueError('User specified frequency {} is above the Medium\'s limit, {}.'.format(np.max(np.squeeze(freqs)),self.valid_freq_range.max))
# Initialize with instantaneous dielectric tensor
epsmu = np.expand_dims(Matrix(diag=diag,offdiag=offdiag),axis=0)
# Iterate through susceptibilities
for i_sus in range(len(susceptibilities)):
epsmu = epsmu + susceptibilities[i_sus].eval_susceptibility(freqs)
# Account for conductivity term (only multiply if nonzero to avoid unnecessary complex numbers)
conductivity = np.expand_dims(Matrix(diag=conductivity_diag,offdiag=conductivity_offdiag),axis=0)
if np.count_nonzero(conductivity) > 0:
epsmu = (1 + 1j/(2*np.pi*freqs) * conductivity) * epsmu
# Convert list matrix to 3D numpy array size [freqs,3,3]
return np.squeeze(epsmu)
class MaterialGrid(object):
"""
This class is used to specify materials on a rectilinear grid. A class object is passed
as the `material` argument of a [`Block`](#block) geometric object or the `default_material`
argument of the [`Simulation`](#Simulation) constructor (similar to a [material function](#medium)).
"""
def check_weights(self, w):
if np.amin(w) < 0. or np.amax(w) > 1.:
warnings.warn('The weights parameter of MaterialGrid must be in the range [0,1].')
return np.clip(w, 0., 1.)
else:
return w
def __init__(self,
grid_size,
medium1,
medium2,
weights=None,
grid_type="U_DEFAULT",
do_averaging=True,
beta=0,
eta=0.5,
damping=0):
"""
Creates a `MaterialGrid` object.
The input are two materials `medium1` and `medium2` along with a weight function $u(x)$ which
is defined on a rectilinear grid by the NumPy array `weights` of size `grid_size` (a 3-tuple or
`Vector3` of integers $N_x$,$N_y$,$N_z$). The resolution of the grid may be nonuniform depending
on the `size` property of the `Block` object as shown in the following example for a 2d `MaterialGrid`
with $N_x=5$ and $N_y=4$. $N_z=0$ implies that the `MaterialGrid` is extruded in the $z$ direction.
The grid points are defined at the corners of the voxels.
![](images/material_grid.png)
Elements of the `weights` array must be in the range [0,1] where 0 is `medium1` and 1 is `medium2`.
The `weights` array is used to define a linear interpolation from `medium1` to `medium2`.
Two material types are supported: (1) frequency-independent isotropic $\\varepsilon$ (`epsilon_diag`
and `epsilon_offdiag` are interpolated) and (2) `LorentzianSusceptibility` (`sigma` and `sigma_offdiag`
are interpolated). `medium1` and `medium2` must both be the same type. The materials are
[bilinearly interpolated](https://en.wikipedia.org/wiki/Bilinear_interpolation) from the rectilinear
grid to Meep's [Yee grid](Yee_Lattice.md).
For improving accuracy, [subpixel smoothing](Subpixel_Smoothing.md) can be enabled by specifying
`do_averaging=True`. If you want to use a material grid to define a (nearly) discontinuous,
piecewise-constant material that is *either* `medium1` or `medium2` almost everywhere, you can
optionally enable a (smoothed) *projection* feature by setting the parameter `beta` to a
positive value. When the projection feature is enabled, the weights $u(x)$ can be thought of as a
[level-set function](https://en.wikipedia.org/wiki/Level-set_method) defining an interface at
$u(x)=\\eta$ with a smoothing factor $\\beta$ where $\\beta=+\\infty$ gives an unsmoothed,
discontinuous interface. The projection operator is $(\\tanh(\\beta\\times\\eta)
+\\tanh(\\beta\\times(u-\\eta)))/(\\tanh(\\beta\\times\\eta)+\\tanh(\\beta\\times(1-\\eta)))$
involving the parameters `beta` ($\\beta$: bias or "smoothness" of the turn on) and `eta`
($\\eta$: offset for erosion/dilation). The level set provides a general approach for defining
a *discontinuous* function from otherwise continuously varying (via the bilinear interpolation)
grid values. Subpixel smoothing is fast and accurate because it exploits an analytic formulation
for level-set functions.
A nonzero `damping` term creates an artificial conductivity $\\sigma = u(1-u)*$`damping`, which acts as
dissipation loss that penalizes intermediate pixel values of non-binarized structures. The value of
`damping` should be proportional to $2\\pi$ times the typical frequency of the problem.
It is possible to overlap any number of different `MaterialGrid`s. This can be useful for defining
grids which are symmetric (e.g., mirror, rotation). One way to set this up is by overlapping a
given `MaterialGrid` object with a symmetrized copy of itself. In the case of spatially overlapping
`MaterialGrid` objects (with no intervening objects), any overlapping points are computed using the
method `grid_type` which is one of `"U_MIN"` (minimum of the overlapping grid values), `"U_PROD"`
(product), `"U_MEAN"` (mean), `"U_DEFAULT"` (topmost material grid). In general, these `"U_*"` options
allow you to combine any material grids that overlap in space with no intervening objects.
"""
self.grid_size = mp.Vector3(*grid_size)
self.medium1 = medium1
self.medium2 = medium2
def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
if isclose(self.grid_size.x,0):
self.grid_size.x = 1
if isclose(self.grid_size.y,0):
self.grid_size.y = 1
if isclose(self.grid_size.z,0):
self.grid_size.z = 1
self.num_params=int(self.grid_size.x*self.grid_size.y*self.grid_size.z)
self.do_averaging = do_averaging
self.beta = beta
self.eta = eta
self.damping = damping
if weights is None:
self.weights = np.zeros((self.num_params,))
elif weights.size != self.num_params:
raise ValueError("weights of shape {} do not match user specified grid dimension: {}".format(weights.size,self.grid_size))
else:
self.weights = self.check_weights(weights).flatten().astype(np.float64)
grid_type_dict = {
"U_MIN":0,
"U_PROD":1,
"U_MEAN":2,
"U_DEFAULT":3
}
if grid_type not in grid_type_dict:
raise ValueError("Invalid grid_type: {}. Must be either U_MIN, U_PROD, U_MEAN, or U_DEFAULT".format(grid_type_dict))
self.grid_type = grid_type_dict[grid_type]
self.swigobj = None
def update_weights(self, x):
"""
Reset the `weights` to `x`.
"""
if x.size != self.num_params:
raise ValueError("weights of shape {} do not match user specified grid dimension: {}".format(self.weights.size,self.grid_size))
self.weights[:] = self.check_weights(x).flatten().astype(np.float64)
class Susceptibility(object):
"""
Parent class for various dispersive susceptibility terms, parameterized by an
anisotropic amplitude $\\sigma$. See [Material Dispersion](Materials.md#material-dispersion).
"""
def __init__(self, sigma_diag=Vector3(), sigma_offdiag=Vector3(), sigma=None):
"""
+ **`sigma` [`number`]** — The scale factor $\\sigma$.
You can also specify an anisotropic $\\sigma$ tensor by using the property `sigma_diag`
which takes three numbers or a `Vector3` to give the $\\sigma_n$ tensor diagonal, and
`sigma_offdiag` which specifies the offdiagonal elements (defaults to 0). That is,
`sigma_diag=mp.Vector3(a, b, c)` and `sigma_offdiag=mp.Vector3(u, v, w)`
corresponds to a $\\sigma$ tensor
\\begin{pmatrix} a & u & v \\\\ u & b & w \\\\ v & w & c \\end{pmatrix}
"""
self.sigma_diag = Vector3(sigma, sigma, sigma) if sigma else Vector3(*sigma_diag)
self.sigma_offdiag = Vector3(*sigma_offdiag)
def transform(self, m):
sigma = Matrix(diag=self.sigma_diag,offdiag=self.sigma_offdiag)
new_sigma = (m * sigma * m.transpose()) / abs(m.determinant())
self.sigma_diag = mp.Vector3(new_sigma.c1.x, new_sigma.c2.y, new_sigma.c3.z)
self.sigma_offdiag = mp.Vector3(new_sigma.c2.x, new_sigma.c3.x, new_sigma.c3.y)
class LorentzianSusceptibility(Susceptibility):
"""
Specifies a single dispersive susceptibility of Lorentzian (damped harmonic
oscillator) form. See [Material Dispersion](Materials.md#material-dispersion), with
the parameters (in addition to $\\sigma$):
"""
def __init__(self, frequency=0.0, gamma=0.0, **kwargs):
"""
+ **`frequency` [`number`]** — The resonance frequency $f_n = \\omega_n / 2\\pi$.
+ **`gamma` [`number`]** — The resonance loss rate $\\gamma_n / 2\\pi$.
Note: multiple objects with identical values for the `frequency` and `gamma` but
different `sigma` will appear as a *single* Lorentzian susceptibility term in the
preliminary simulation info output.
"""
super(LorentzianSusceptibility, self).__init__(**kwargs)
self.frequency = frequency
self.gamma = gamma
def eval_susceptibility(self,freq):
sigma = np.expand_dims(Matrix(diag=self.sigma_diag,offdiag=self.sigma_offdiag),axis=0)
if self.gamma == 0:
return self.frequency*self.frequency / (self.frequency*self.frequency - freq*freq) * sigma
else:
return self.frequency*self.frequency / (self.frequency*self.frequency - freq*freq - 1j*self.gamma*freq) * sigma
class DrudeSusceptibility(Susceptibility):
"""
Specifies a single dispersive susceptibility of Drude form. See [Material
Dispersion](Materials.md#material-dispersion), with the parameters (in addition to $\\sigma$):
"""
def __init__(self, frequency=0.0, gamma=0.0, **kwargs):
"""
+ **`frequency` [`number`]** — The frequency scale factor $f_n = \\omega_n / 2\\pi$
which multiplies $\\sigma$ (not a resonance frequency).
+ **`gamma` [`number`]** — The loss rate $\\gamma_n / 2\\pi$.
"""
super(DrudeSusceptibility, self).__init__(**kwargs)
self.frequency = frequency
self.gamma = gamma
def eval_susceptibility(self,freq):
sigma = np.expand_dims(Matrix(diag=self.sigma_diag,offdiag=self.sigma_offdiag),axis=0)
if self.gamma == 0:
return -self.frequency*self.frequency / (freq*(freq)) * sigma
else:
return -self.frequency*self.frequency / (freq*(freq + 1j*self.gamma)) * sigma
class NoisyLorentzianSusceptibility(LorentzianSusceptibility):
"""
Specifies a single dispersive susceptibility of Lorentzian (damped harmonic
oscillator) or Drude form. See [Material
Dispersion](Materials.md#material-dispersion), with the same `sigma`, `frequency`, and
`gamma` parameters, but with an additional Gaussian random noise term (uncorrelated in
space and time, zero mean) added to the **P** damped-oscillator equation.
"""
def __init__(self, noise_amp=0.0, **kwargs):
"""
+ **`noise_amp` [`number`]** — The noise has root-mean square amplitude σ $\\times$
`noise_amp`.
This is a somewhat unusual polarizable medium, a Lorentzian susceptibility with a
random noise term added into the damped-oscillator equation at each point. This
can be used to directly model thermal radiation in both the [far
field](http://journals.aps.org/prl/abstract/10.1103/PhysRevLett.93.213905) and the
[near field](http://math.mit.edu/~stevenj/papers/RodriguezIl11.pdf). Note, however
that it is more efficient to [compute far-field thermal radiation using
Kirchhoff's law](http://www.simpetus.com/projects.html#meep_thermal_radiation) of
radiation, which states that emissivity equals absorptivity. Near-field thermal
radiation can usually be computed more efficiently using frequency-domain methods,
e.g. via [SCUFF-EM](https://github.com/HomerReid/scuff-em), as described e.g.
[here](http://doi.org/10.1103/PhysRevB.92.134202) or
[here](http://doi.org/10.1103/PhysRevB.88.054305).
"""
super(NoisyLorentzianSusceptibility, self).__init__(**kwargs)
self.noise_amp = noise_amp
class NoisyDrudeSusceptibility(DrudeSusceptibility):
"""
Specifies a single dispersive susceptibility of Lorentzian (damped harmonic
oscillator) or Drude form. See [Material
Dispersion](Materials.md#material-dispersion), with the same `sigma`, `frequency`, and
`gamma` parameters, but with an additional Gaussian random noise term (uncorrelated in
space and time, zero mean) added to the **P** damped-oscillator equation.
"""
def __init__(self, noise_amp=0.0, **kwargs):
"""
+ **`noise_amp` [`number`]** — The noise has root-mean square amplitude σ $\\times$
`noise_amp`.
This is a somewhat unusual polarizable medium, a Lorentzian susceptibility with a
random noise term added into the damped-oscillator equation at each point. This
can be used to directly model thermal radiation in both the [far
field](http://journals.aps.org/prl/abstract/10.1103/PhysRevLett.93.213905) and the
[near field](http://math.mit.edu/~stevenj/papers/RodriguezIl11.pdf). Note, however
that it is more efficient to [compute far-field thermal radiation using
Kirchhoff's law](http://www.simpetus.com/projects.html#meep_thermal_radiation) of
radiation, which states that emissivity equals absorptivity. Near-field thermal
radiation can usually be computed more efficiently using frequency-domain methods,
e.g. via [SCUFF-EM](https://github.com/HomerReid/scuff-em), as described e.g.
[here](http://doi.org/10.1103/PhysRevB.92.134202) or
[here](http://doi.org/10.1103/PhysRevB.88.054305).
"""
super(NoisyDrudeSusceptibility, self).__init__(**kwargs)
self.noise_amp = noise_amp
class GyrotropicLorentzianSusceptibility(LorentzianSusceptibility):
"""
(**Experimental feature**) Specifies a single dispersive [gyrotropic
susceptibility](Materials.md#gyrotropic-media) of [Lorentzian (damped harmonic
oscillator) or Drude form](Materials.md#gyrotropic-drude-lorentz-model). Its
parameters are `sigma`, `frequency`, and `gamma`, which have the [usual
meanings](#susceptibility), and an additional 3-vector `bias`:
"""
def __init__(self, bias=Vector3(), **kwargs):
"""
+ **`bias` [`Vector3`]** — The gyrotropy vector. Its direction determines the
orientation of the gyrotropic response, and the magnitude is the precession
frequency $|\\mathbf{b}_n|/2\\pi$.
"""
super(GyrotropicLorentzianSusceptibility, self).__init__(**kwargs)
self.bias = bias
class GyrotropicDrudeSusceptibility(DrudeSusceptibility):
"""
(**Experimental feature**) Specifies a single dispersive [gyrotropic
susceptibility](Materials.md#gyrotropic-media) of [Lorentzian (damped harmonic
oscillator) or Drude form](Materials.md#gyrotropic-drude-lorentz-model). Its
parameters are `sigma`, `frequency`, and `gamma`, which have the [usual
meanings](#susceptibility), and an additional 3-vector `bias`:
"""
def __init__(self, bias=Vector3(), **kwargs):
"""
+ **`bias` [`Vector3`]** — The gyrotropy vector. Its direction determines the
orientation of the gyrotropic response, and the magnitude is the precession
frequency $|\\mathbf{b}_n|/2\\pi$.
"""
super(GyrotropicDrudeSusceptibility, self).__init__(**kwargs)
self.bias = bias
class GyrotropicSaturatedSusceptibility(Susceptibility):
"""
(**Experimental feature**) Specifies a single dispersive [gyrotropic
susceptibility](Materials.md#gyrotropic-media) governed by a [linearized
Landau-Lifshitz-Gilbert
equation](Materials.md#gyrotropic-saturated-dipole-linearized-landau-lifshitz-gilbert-model).
This class takes parameters `sigma`, `frequency`, and `gamma`, whose meanings are
different from the Lorentzian and Drude case. It also takes a 3-vector `bias`
parameter and an `alpha` parameter:
"""
def __init__(self, bias=Vector3(), frequency=0.0, gamma=0.0, alpha=0.0, **kwargs):
"""
+ **`sigma` [`number`]** — The coupling factor $\\sigma_n / 2\\pi$ between the
polarization and the driving field. In [magnetic
ferrites](https://en.wikipedia.org/wiki/Ferrite_(magnet)), this is the Larmor
precession frequency at the saturation field.
+ **`frequency` [`number`]** — The [Larmor
precession](https://en.wikipedia.org/wiki/Larmor_precession) frequency,
$f_n = \\omega_n / 2\\pi$.
+ **`gamma` [`number`]** — The loss rate $\\gamma_n / 2\\pi$ in the off-diagonal
response.
+ **`alpha` [`number`]** — The loss factor $\\alpha_n$ in the diagonal response.
Note that this parameter is dimensionless and contains no 2π factor.
+ **`bias` [`Vector3`]** — Vector specifying the orientation of the gyrotropic
response. Unlike the similarly-named `bias` parameter for the [gyrotropic
Lorentzian/Drude
susceptibilities](#gyrotropiclorentziansusceptibility-or-gyrotropicdrudesusceptibility),
the magnitude is ignored; instead, the relevant precession frequencies are
determined by the `sigma` and `frequency` parameters.
"""
super(GyrotropicSaturatedSusceptibility, self).__init__(**kwargs)
self.frequency = frequency
self.gamma = gamma
self.bias = bias
self.alpha = alpha
class MultilevelAtom(Susceptibility):
"""
Specifies a multievel atomic susceptibility for modeling saturable gain and
absorption. This is a subclass of `E_susceptibilities` which contains two objects: (1)
`transitions`: a list of atomic `Transition`s (defined below), and (2)
`initial_populations`: a list of numbers defining the initial population of each
atomic level. See [Materials/Saturable Gain and
Absorption](Materials.md#saturable-gain-and-absorption).
"""
def __init__(self, initial_populations=None, transitions=None, **kwargs):
super(MultilevelAtom, self).__init__(**kwargs)
self.initial_populations = initial_populations if initial_populations else []
self.transitions = transitions if transitions else []
class Transition(object):
"""
"""
def __init__(self,
from_level,
to_level,
transition_rate=0,
frequency=0,
sigma_diag=Vector3(1, 1, 1),
gamma=0,
pumping_rate=0):
"""
Construct a `Transition`.
+ **`frequency` [`number`]** — The radiative transition frequency $f = \\omega / 2\\pi$.
+ **`gamma` [`number`]** — The loss rate $\\gamma = \\gamma / 2\\pi$.
+ **`sigma_diag` [`Vector3`]** — The per-polarization coupling strength $\\sigma$.
+ **`from_level` [`number`]** — The atomic level from which the transition occurs.
+ **`to_level` [`number`]** — The atomic level to which the transition occurs.
+ **`transition_rate` [`number`]** — The non-radiative transition rate
$f = \\omega / 2\\pi$. Default is 0.
+ **`pumping_rate` [`number`]** — The pumping rate $f = \\omega / 2\\pi$. Default is 0.
"""
self.from_level = check_nonnegative('from_level', from_level)
self.to_level = check_nonnegative('to_level', to_level)
self.transition_rate = transition_rate
self.frequency = frequency
self.sigma_diag = sigma_diag
self.gamma = gamma
self.pumping_rate = pumping_rate
class GeometricObject(object):
"""
This class, and its descendants, are used to specify the solid geometric objects that
form the dielectric structure being simulated.
In a 2d calculation, only the intersections of the objects with the $xy$ plane are
considered.
**Geometry Utilities**
See the [MPB documentation](https://mpb.readthedocs.io/en/latest/Python_User_Interface/#geometry-utilities)
for utility functions to help manipulate geometric objects.
**Examples**
These are some examples of geometric objects created using some `GeometricObject`
subclasses:
```python
# A cylinder of infinite radius and height 0.25 pointing along the x axis,
# centered at the origin:
cyl = mp.Cylinder(center=mp.Vector3(0,0,0), height=0.25, radius=mp.inf,
axis=mp.Vector3(1,0,0), material=mp.Medium(index=3.5))
```
```python
# An ellipsoid with its long axis pointing along (1,1,1), centered on
# the origin (the other two axes are orthogonal and have equal semi-axis lengths):
ell = mp.Ellipsoid(center=mp.Vector3(0,0,0), size=mp.Vector3(0.8,0.2,0.2),
e1=Vector3(1,1,1), e2=Vector3(0,1,-1), e3=Vector3(-2,1,1),
material=mp.Medium(epsilon=13))
```
```python
# A unit cube of material metal with a spherical air hole of radius 0.2 at
# its center, the whole thing centered at (1,2,3):
geometry=[mp.Block(center=Vector3(1,2,3), size=Vector3(1,1,1), material=mp.metal),
mp.Sphere(center=Vector3(1,2,3), radius=0.2, material=mp.air)]
```
```python
# A hexagonal prism defined by six vertices centered on the origin
# of material crystalline silicon (from the materials library)
vertices = [mp.Vector3(-1,0),
mp.Vector3(-0.5,math.sqrt(3)/2),
mp.Vector3(0.5,math.sqrt(3)/2),
mp.Vector3(1,0),
mp.Vector3(0.5,-math.sqrt(3)/2),
mp.Vector3(-0.5,-math.sqrt(3)/2)]
geometry = [mp.Prism(vertices, height=1.5, center=mp.Vector3(), material=cSi)]
```
"""
def __init__(self, material=Medium(), center=Vector3(), epsilon_func=None):
"""
Construct a `GeometricObject`.
+ **`material` [`Medium` class or function ]** — The material that the object is
made of (usually some sort of dielectric). Uses default `Medium`. If a function
is supplied, it must take one argument and return a Python `Medium`.
+ **`epsilon_func` [ function ]** — A function that takes one argument (a
`Vector3`) and returns the dielectric constant at that point. Can be used
instead of `material`. Default is `None`.
+ **`center` [`Vector3`]** — Center point of the object. Defaults to `(0,0,0)`.
One normally does not create objects of type `GeometricObject` directly, however;
instead, you use one of the following subclasses. Recall that subclasses inherit
the properties of their superclass, so these subclasses automatically have the
`material` and `center` properties and can be specified in a subclass's
constructor via keyword arguments.
"""
if type(material) is not Medium and callable(material):
init_do_averaging(material)
material.eps = False
elif epsilon_func:
init_do_averaging(epsilon_func)
epsilon_func.eps = True
material = epsilon_func
self.material = material
self.center = Vector3(*center)
def __contains__(self, point):
return mp.is_point_in_object(Vector3(*point), self)
def __add__(self, vec):
return self.shift(Vector3(*vec))
def __radd__(self, vec):
return self.shift(Vector3(*vec))
def __iadd__(self, vec):
self.center += Vector3(*vec)