/
modes.py
1128 lines (987 loc) · 35.5 KB
/
modes.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
"""tidy3d mode solver.
tidy3d has a powerful open source mode solver.
tidy3d can:
- compute bend modes.
- compute mode overlaps.
"""
from __future__ import annotations
import itertools as it
import pathlib
import subprocess
import sys
import time
from pathlib import Path
from types import SimpleNamespace
from typing import Dict, List, Optional, Tuple, Union
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib import colors
from pydantic import BaseModel, Extra
from scipy.constants import c as SPEED_OF_LIGHT
from scipy.interpolate import griddata
from tidy3d.plugins.mode.solver import compute_modes
from tqdm.auto import tqdm
from typing_extensions import Literal
from gdsfactory.config import logger
from gdsfactory.pdk import MaterialSpec, get_material_index, get_modes_path
from gdsfactory.serialization import get_hash
from gdsfactory.simulation.gtidy3d.materials import si, sin, sio2
from gdsfactory.types import PathType
nm = 1e-3
def plot(
X,
Y,
n,
mode=None,
num_levels: int = 8,
n_cmap=None,
mode_cmap=None,
axes="xy",
title=None,
normalize_mode=False,
) -> None:
"""Plot waveguide index or mode in matplotlib.
Args:
X: x array.
Y: y array.
n: refractive index.
mode: mode number.
num_levels: for plot.
n_cmap: refractive index color map.
mode_cmap: mode color map.
axes: "xy".
title: for the plot.
normalize_mode: divide by maximum value.
"""
x, y = axes
if n_cmap is None:
n_cmap = colors.LinearSegmentedColormap.from_list(
name="custom", colors=["#ffffff", "#c1d9ed"]
)
if mode_cmap is None:
mode_cmap = "inferno"
if mode is not None:
mode = np.abs(mode)
if normalize_mode:
mode = mode / mode.max()
plt.contour(
X,
Y,
mode,
cmap=mode_cmap,
levels=np.linspace(mode.min(), mode.max(), num_levels),
)
plt.colorbar(label="mode")
n = np.real(n)
plt.pcolormesh(X, Y, n, cmap=n_cmap)
plt.colorbar(label="n")
plt.xlabel(x)
plt.ylabel(y)
plt.grid(True, alpha=0.4)
plt.axis("scaled")
if title is not None:
plt.title(title)
def _mesh_1d(x_min, x_max, mesh_x):
if isinstance(mesh_x, int):
x = np.linspace(x_min, x_max, mesh_x + 1)
dx = x[1] - x[0]
elif isinstance(mesh_x, float):
dx = mesh_x
x = np.arange(x_min, x_max + 0.999 * dx, dx)
mesh_x = x.shape[0]
else:
raise ValueError("Invalid 'mesh_x'")
return x, mesh_x, dx
def create_mesh(x_min, y_min, x_max, y_max, mesh_x, mesh_y):
x, mesh_x, dx = _mesh_1d(x_min, x_max, mesh_x)
y, mesh_y, dy = _mesh_1d(y_min, y_max, mesh_y)
Yx, Xx = np.meshgrid(y[:-1], x[:-1] + dx / 2)
Yy, Xy = np.meshgrid(y[:-1] + dy / 2, x[:-1])
Yz, Xz = np.meshgrid(y[:-1], x[:-1])
return x, y, Xx, Yx, Xy, Yy, Xz, Yz
SETTINGS = [
"wavelength",
"wg_width",
"wg_thickness",
"ncore",
"nclad",
"slab_thickness",
"t_box",
"t_clad",
"xmargin",
"resolution",
"nmodes",
"bend_radius",
]
SETTINGS_COUPLER = set(SETTINGS + ["wg_width1", "wg_width2", "gap"])
Precision = Literal["single", "double"]
FilterPol = Literal["te", "tm"]
class Waveguide(BaseModel):
"""Waveguide Model.
Parameters:
wavelength: (um).
wg_width: waveguide width.
wg_thickness: thickness waveguide (um).
ncore: core refractive index.
nclad: cladding refractive index.
dn_dict: unstructured mesh array with columns field "x", "y", "dn" of local index perturbations to be interpolated.
slab_thickness: thickness slab (um).
t_box: thickness BOX (um).
t_clad: thickness cladding (um).
xmargin: margin from waveguide edge to each side (um).
resolution: pixels/um. Can be a single number or tuple (x, y).
nmodes: number of modes to compute.
bend_radius: optional bend radius (um).
cache: True uses file cache from PDK.modes_path. False skips cache.
precision: single or double.
filter_pol: te, tm or None.
loss_model: whether to include a scattering loss region at the interfaces. Default is False
sidewall_sigma: size of the region to append to the sidewalls in the loss model. Default is 10 nm.
sidewall_k: imaginary index addition for the sidewall loss region. Default is 0 (no extra loss).
top_sigma: size of the loss region to append to the top surfaces in the loss model. Default is 10 nm.
top_k: imaginary index addition for the top surfaces loss region. Default is 0 (no extra loss).
::
__________________________
|
|
| width xmargin
| <----------> <------>
| ___________ _ _ _
| | | |
|_____| ncore |_______|
| | wg_thickness
|slab_thickness nslab |
|_________________________|
|
| nclad
|__________________________
<------------------------>
w_sim
"""
wavelength: float
wg_width: float
wg_thickness: float
ncore: MaterialSpec
nclad: MaterialSpec
dn_dict: Optional[Dict] = None
slab_thickness: float
t_box: float = 2.0
t_clad: float = 2.0
xmargin: float = 1.0
resolution: Union[int, Tuple[int, int]] = 100
nmodes: int = 4
bend_radius: Optional[float] = None
cache: bool = True
precision: Precision = "single"
filter_pol: Optional[FilterPol] = None
loss_model: Optional[bool] = False
sidewall_sigma: Optional[float] = 10 * nm
sidewall_k: Optional[float] = 0.1
top_sigma: Optional[float] = 10 * nm
top_k: Optional[float] = 0.1
class Config:
"""Config for Waveguide."""
extra = Extra.allow
@property
def cache_path(self) -> Optional[PathType]:
return get_modes_path()
@property
def t_sim(self) -> float:
return self.t_box + self.wg_thickness + self.t_clad
@property
def settings(self):
return SETTINGS
@property
def w_sim(self) -> float:
return self.wg_width + 2 * self.xmargin
@property
def filepath(self) -> Optional[pathlib.Path]:
if not self.cache:
return
cache = pathlib.Path(self.cache_path)
cache.mkdir(exist_ok=True, parents=True)
settings = {setting: getattr(self, setting) for setting in self.settings}
return cache / f"{get_hash(settings)}.npz"
def get_ncore(self, wavelength: Optional[float] = None) -> float:
wavelength = wavelength or self.wavelength
return get_material_index(self.ncore, wavelength)
def get_nclad(self, wavelength: Optional[float] = None) -> float:
wavelength = wavelength or self.wavelength
return get_material_index(self.nclad, wavelength)
def get_n(self, Y, Z):
"""Return index matrix for a waveguide.
Args:
Y: 2D array.
Z: 2D array.
"""
w = self.wg_width
ncore = self.get_ncore()
nclad = self.get_nclad()
t_box = self.t_box
wg_thickness = self.wg_thickness
slab_thickness = self.slab_thickness
t_clad = self.t_clad
inds_core = (
(-w / 2 <= Y) & (Y <= w / 2) & (Z >= t_box) & (Z <= t_box + wg_thickness)
)
inds_slab = (Z >= t_box) & (Z <= t_box + slab_thickness)
complex_solver = False
mat_dtype = np.float32
if isinstance(ncore, complex) or isinstance(nclad, complex):
complex_solver = True
elif self.dn_dict is not None:
complex_solver = True
elif self.loss_model:
complex_solver = True
if complex_solver:
mat_dtype = np.complex128 if self.precision == "double" else np.complex64
elif self.precision == "double":
mat_dtype = np.float64
n = np.ones_like(Y, dtype=mat_dtype) * nclad
n[
(-w / 2 - t_clad / 2 <= Y)
& (Y <= w / 2 + t_clad / 2)
& (Z >= t_box)
& (Z <= t_box + wg_thickness + t_clad)
] = nclad
n[(Z <= 1.0 + slab_thickness + t_clad)] = nclad
n[inds_core] = ncore
n[inds_slab] = ncore if slab_thickness else nclad
if self.loss_model:
inds_top = (
(Z >= t_box + wg_thickness - self.top_sigma / 2)
& (Z <= t_box + wg_thickness + self.top_sigma / 2)
& (-w / 2 <= Y)
& (Y <= w / 2)
)
inds_top_slab_left = (
(Z >= t_box + slab_thickness - self.top_sigma / 2)
& (Z <= t_box + slab_thickness + self.top_sigma / 2)
& (-w / 2 >= Y)
)
inds_top_slab_right = (
(Z >= t_box + slab_thickness - self.top_sigma / 2)
& (Z <= t_box + slab_thickness + self.top_sigma / 2)
& (Y >= w / 2)
)
inds_sidewall_left = (
(Z >= t_box + slab_thickness)
& (Z <= t_box + wg_thickness)
& (Y >= -w / 2 - self.sidewall_sigma / 2)
& (Y <= -w / 2 + self.sidewall_sigma / 2)
)
inds_sidewall_right = (
(Z >= t_box + slab_thickness)
& (Z <= t_box + wg_thickness)
& (Y >= w / 2 - self.sidewall_sigma / 2)
& (Y <= w / 2 + self.sidewall_sigma / 2)
)
n[inds_top] += 1j * self.top_k
n[inds_top_slab_left] += 1j * self.top_k
n[inds_top_slab_right] += 1j * self.top_k
n[inds_sidewall_left] += 1j * self.sidewall_k
n[inds_sidewall_right] += 1j * self.sidewall_k
if self.dn_dict is not None:
dn = griddata(
(self.dn_dict["x"], self.dn_dict["y"]),
self.dn_dict["dn"],
(Y, Z),
method="cubic",
fill_value=0.0,
)
n[inds_core] += dn[inds_core]
n[inds_slab] += dn[inds_slab]
return n
def plot_index(self, func=None) -> None:
x, y, Xx, Yx, Xy, Yy, Xz, Yz = create_mesh(
-self.w_sim / 2,
0.0,
+self.w_sim / 2,
self.t_sim,
self.resolution[0]
if isinstance(self.resolution, tuple)
else self.resolution,
self.resolution[1]
if isinstance(self.resolution, tuple)
else self.resolution,
)
nx = self.get_n(
Xx,
Yx,
)
if func is None:
plot(Xx, Yx, nx)
else:
plot(Xx, Yx, func(nx))
plt.show()
def compute_modes(
self,
overwrite: bool = False,
with_fields: bool = True,
isolate: bool = False,
) -> None:
"""Compute modes.
Args:
overwrite: overwrite file cache.
with_fields: include field data.
isolate: whether to run the solver in this interpreter (False) or a separate one (True)
temp_dir: if isolate, which directory to save temporary files to
"""
if hasattr(self, "neffs") and not overwrite:
return
wavelength = self.wavelength
x, y, Xx, Yx, Xy, Yy, Xz, Yz = create_mesh(
-self.w_sim / 2,
0.0,
+self.w_sim / 2,
self.t_sim,
self.resolution[0]
if isinstance(self.resolution, tuple)
else self.resolution,
self.resolution[1]
if isinstance(self.resolution, tuple)
else self.resolution,
)
nx = self.get_n(
Xx,
Yx,
)
ny = self.get_n(
Xy,
Yy,
)
nz = self.get_n(
Xz,
Yz,
)
self.nx, self.ny, self.nz = nx, ny, nz
self.Xx, self.Yx, self.Xy, self.Yy, self.Xz, self.Yz = Xx, Yx, Xy, Yy, Xz, Yz
if self.cache and self.filepath and self.filepath.exists():
data = np.load(self.filepath)
if with_fields:
self.Ex = data["Ex"]
self.Ey = data["Ey"]
self.Ez = data["Ez"]
self.Hx = data["Hx"]
self.Hy = data["Hy"]
self.Hz = data["Hz"]
self.neffs = data["neffs"]
logger.info(f"load {self.filepath} mode data from file cache.")
return
if isolate:
# TODO: make a package that does this automatically
import pickle
# Setup paths
temp_dir = Path.cwd() / "temp"
temp_dir.mkdir(exist_ok=True, parents=True)
args_file_str = "args"
argsfile = temp_dir / args_file_str
argsfile = argsfile.with_suffix(".pkl")
script_file_str = "script"
scriptfile = temp_dir / script_file_str
scriptfile = scriptfile.with_suffix(".py")
outputs_file_str = "outputs"
outputsfile = temp_dir / outputs_file_str
outputsfile = outputsfile.with_suffix(".pkl")
arguments_dict = {
"nx": nx,
"ny": ny,
"nz": nz,
"x": x,
"y": y,
"SPEED_OF_LIGHT": SPEED_OF_LIGHT,
"wavelength": wavelength,
"nmodes": self.nmodes,
"bend_radius": self.bend_radius,
"bend_axis": 1,
"angle_theta": 0.0,
"angle_phi": 0.0,
"num_pml": (0, 0),
"target_neff": self.get_ncore(wavelength),
"sort_by": "largest_neff",
"precision": self.precision,
"filter_pol": self.filter_pol,
}
with open(argsfile, "wb") as outp:
pickle.dump(arguments_dict, outp, pickle.HIGHEST_PROTOCOL)
# Write execution file
script_lines = [
"import pickle\n",
"import numpy as np\n",
"from types import SimpleNamespace\n",
"from tidy3d.plugins.mode.solver import compute_modes\n\n",
'if __name__ == "__main__":\n\n',
f"\twith open(\"{argsfile}\", 'rb') as inp:\n",
"\t\targuments_dict = pickle.load(inp)\n\n",
]
script_lines.extend(
f'\t{key} = arguments_dict["{key}"]\n' for key in arguments_dict
)
script_lines.extend(
[
"\t((Ex, Ey, Ez), (Hx, Hy, Hz)), neffs = (\n",
"\t x.squeeze()\n",
"\t for x in compute_modes(\n",
"\t eps_cross=[nx**2, ny**2, nz**2],\n",
"\t coords=[x, y],\n",
"\t freq=SPEED_OF_LIGHT / (wavelength * 1e-6),\n",
"\t mode_spec=SimpleNamespace(\n",
"\t num_modes=nmodes,\n",
"\t bend_radius=bend_radius,\n",
"\t bend_axis=bend_axis,\n",
"\t angle_theta=angle_theta,\n",
"\t angle_phi=angle_phi,\n",
"\t num_pml=num_pml,\n",
"\t target_neff=target_neff,\n",
"\t sort_by=sort_by,\n",
"\t precision=precision,\n",
"\t filter_pol=filter_pol,\n",
"\t ),\n",
"\t )\n",
"\t)\n",
]
)
script_lines.extend(
[
f'\toutputsfile = "{outputsfile}"\n',
"\toutputs_dict = {\n",
'\t\t "Ex": Ex,\n',
'\t\t "Ey": Ey,\n',
'\t\t "Ez": Ez,\n',
'\t\t "Hx": Hx,\n',
'\t\t "Hy": Hy,\n',
'\t\t "Hz": Hz,\n',
'\t\t "neffs": neffs,\n',
"\t\t}\n",
'\twith open(outputsfile, "wb") as outp:\n',
"\t\t pickle.dump(outputs_dict, outp, pickle.HIGHEST_PROTOCOL)\n",
]
)
with open(scriptfile, "w") as script_file_obj:
script_file_obj.writelines(script_lines)
with subprocess.Popen(
["python", scriptfile],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
) as proc:
if not proc.stderr:
while not outputsfile.exists():
print(proc.stdout.read().decode())
print(proc.stderr.read().decode())
sys.stdout.flush()
sys.stderr.flush()
time.sleep(1)
logger.info(f"python {scriptfile}")
with open(outputsfile, "rb") as inp:
outputs_dict = pickle.load(inp)
Ex = outputs_dict["Ex"]
Ey = outputs_dict["Ey"]
Ez = outputs_dict["Ez"]
Hx = outputs_dict["Hx"]
Hy = outputs_dict["Hy"]
Hz = outputs_dict["Hz"]
neffs = outputs_dict["neffs"]
import shutil
shutil.rmtree(temp_dir)
else: # legacy
((Ex, Ey, Ez), (Hx, Hy, Hz)), neffs = (
x.squeeze()
for x in compute_modes(
eps_cross=[nx**2, ny**2, nz**2],
coords=[x, y],
freq=SPEED_OF_LIGHT / (wavelength * 1e-6),
mode_spec=SimpleNamespace(
num_modes=self.nmodes,
bend_radius=self.bend_radius,
bend_axis=1,
angle_theta=0.0,
angle_phi=0.0,
num_pml=(0, 0),
target_neff=self.get_ncore(wavelength),
sort_by="largest_neff",
precision=self.precision,
filter_pol=self.filter_pol,
),
)
)
self.Ex, self.Ey, self.Ez = Ex, Ey, Ez
self.Hx, self.Hy, self.Hz = Hx, Hy, Hz
self.neffs = neffs
if with_fields:
data = dict(
Ex=self.Ex,
Ey=self.Ey,
Ez=self.Ez,
Hx=self.Hx,
Hy=self.Hy,
Hz=self.Hz,
neffs=self.neffs,
)
else:
data = dict(neffs=self.neffs)
if self.filepath:
np.savez_compressed(self.filepath, **data)
logger.info(f"write {self.filepath} mode data to file cache.")
def compute_mode_properties(self) -> Tuple[List[float], List[float], List[float]]:
"""Computes mode areas, fraction_te and fraction_tm."""
if not hasattr(self, "neffs"):
self.compute_modes()
mode_areas = []
fraction_te = []
fraction_tm = []
for mode_index in range(self.nmodes):
e_fields = (
self.Ex[..., mode_index],
self.Ey[..., mode_index],
self.Ez[..., mode_index],
)
h_fields = (
self.Hx[..., mode_index],
self.Hy[..., mode_index],
self.Hz[..., mode_index],
)
areas_e = [np.sum(np.abs(e) ** 2) for e in e_fields]
areas_e /= np.sum(areas_e)
areas_e *= 100
areas_h = [np.sum(np.abs(h) ** 2) for h in h_fields]
areas_h /= np.sum(areas_h)
areas_h *= 100
fraction_te.append(areas_e[0] / (areas_e[0] + areas_e[1]))
fraction_tm.append(areas_e[1] / (areas_e[0] + areas_e[1]))
areas = areas_e.tolist()
areas.extend(areas_h)
mode_areas.append(areas)
self.mode_areas = mode_areas
self.fraction_te = fraction_te
self.fraction_tm = fraction_tm
return mode_areas, fraction_te, fraction_tm
def plot_Ex(self, mode_index: int = 0) -> None:
if not hasattr(self, "neffs"):
self.compute_modes()
nx, neffs, Ex = self.nx, self.neffs, self.Ex
neff_, Ex_ = np.real(neffs[mode_index]), Ex[..., mode_index]
plot(self.Xx, self.Yx, nx, mode=np.abs(Ex_) ** 2, title=f"Ex::{neff_:.3f}")
plt.show()
def plot_Ey(self, mode_index: int = 0) -> None:
if not hasattr(self, "neffs"):
self.compute_modes()
nx, neffs, Ey = self.nx, self.neffs, self.Ey
neff_, Ey_ = np.real(neffs[mode_index]), Ey[..., mode_index]
plot(self.Xx, self.Yx, nx, mode=np.abs(Ey_) ** 2, title=f"Ey::{neff_:.3f}")
plt.show()
def _repr_html_(self) -> str:
"""Show index in matplotlib for Jupyter Notebooks."""
self.plot_index()
return self.__repr__()
def __repr__(self) -> str:
"""Show waveguide name."""
return ", \n".join([f"{k} = {getattr(self, k)!r}" for k in self.settings])
def get_overlap(
self, wg: Waveguide, mode_index1: int = 0, mode_index2: int = 0
) -> float:
"""Returns mode overlap integral.
Args:
wg: other waveguide.
"""
wg1 = self
wg2 = wg
wg1.compute_modes()
wg2.compute_modes()
return np.sum(
np.conj(wg1.Ex[..., mode_index1]) * wg2.Hy[..., mode_index2]
- np.conj(wg1.Ey[..., mode_index1]) * wg2.Hx[..., mode_index2]
+ wg2.Ex[..., mode_index2] * np.conj(wg1.Hy[..., mode_index1])
- wg2.Ey[..., mode_index2] * np.conj(wg1.Hx[..., mode_index1])
)
def get_loss(self):
"""Returns loss for computed modes in dB/cm."""
if not hasattr(self, "neffs"):
self.compute_modes()
wavelength = self.wavelength * 1e-6 # convert to m
alphas = 4 * np.pi * np.imag(self.neffs) / wavelength # lin/m loss
return 10 * np.log10(np.exp(1)) * alphas * 1e-2 # dB/cm loss
class WaveguideCoupler(Waveguide):
"""Waveguide coupler Model.
Parameters:
wavelength: (um).
wg_width1: left waveguide width in um.
wg_width2: right waveguide width in um.
wg_thickness: thickness waveguide (um).
ncore: core refractive index.
nclad: cladding refractive index.
slab_thickness: thickness slab (um).
t_box: thickness BOX (um).
t_clad: thickness cladding (um).
xmargin: margin from waveguide edge to each side (um).
resolution: pixels/um. Can be a single number or tuple (x, y).
nmodes: number of modes to compute.
bend_radius: optional bend radius (um).
cache: True uses file cache from PDK.modes_path. False skips cache.
::
-w1-gap/2
wg_width1 wg_width2
<-------> <------->
_______ | _______ __
| | | | | |
| | | | | |
| |_____| | | wg_thickness
|slab_thickness | |
|_____________________| |__
<----->
gap
<--------------------->
w_sim
"""
wg_width: Optional[float] = None
wg_width1: float
wg_width2: float
gap: float
@property
def w_sim(self):
return self.wg_width1 + self.wg_width2 + self.gap + 2 * self.xmargin
def get_n(self, Y, Z):
"""Return index matrix for a waveguide coupler.
Args:
Y: 2D array.
Z: 2D array.
"""
w1 = self.wg_width1
w2 = self.wg_width2
gap = self.gap
ncore = self.get_ncore()
nclad = self.get_nclad()
t_box = self.t_box
wg_thickness = self.wg_thickness
slab_thickness = self.slab_thickness
t_clad = self.t_clad
n = np.ones_like(Y) * nclad
n[(Z <= 1.0 + slab_thickness + t_clad)] = nclad
n[
(-w1 - gap / 2 <= Y)
& (Y <= -gap / 2)
& (Z >= t_box)
& (Z <= t_box + wg_thickness)
] = ncore
n[
(gap / 2 <= Y)
& (Y <= gap / 2 + w2)
& (Z >= t_box)
& (Z <= t_box + wg_thickness)
] = ncore
n[(Z >= t_box) & (Z <= t_box + slab_thickness)] = (
ncore if slab_thickness else nclad
)
return n
@property
def settings(self):
return SETTINGS_COUPLER
def find_coupling(self, power_ratio: float = 1.0) -> float:
"""Returns the coupling length (um) of the directional coupler to achieve power_ratio, where 1 means 100% power transfer."""
if not hasattr(self, "neffs"):
self.compute_modes()
neff1 = self.neffs[0]
neff2 = self.neffs[1]
dneff = (neff1 - neff2).real
return self.wavelength / (np.pi * dneff) * np.arcsin(np.sqrt(power_ratio))
def sweep_bend_loss(
bend_radius_min: float = 2.0,
bend_radius_max: float = 5,
steps: int = 4,
mode_index: int = 0,
**kwargs,
) -> Tuple[np.ndarray, np.ndarray]:
"""Returns overlap integral squared for the bend mode mismatch loss.
The loss is squared because you hit the bend loss twice
(from bend to straight and from straight to bend).
Args:
bend_radius_min: min bend radius (um).
bend_radius_max: max bend radius (um).
steps: number of steps.
mode_index: where 0 is the fundamental mode.
Keyword Args:
wavelength: (um).
wg_width: waveguide width in um.
wg_thickness: thickness waveguide (um).
slab_thickness: thickness slab (um).
t_box: thickness BOX (um).
t_clad: thickness cladding (um).
ncore: core refractive index.
nclad: cladding refractive index.
xmargin: margin from waveguide edge to each side (um).
resolution: pixels/um.
nmodes: number of modes to compute.
"""
r = np.linspace(bend_radius_min, bend_radius_max, steps)
integral = np.zeros_like(r)
wg = Waveguide(**kwargs)
for i, radius in tqdm(enumerate(r)):
wg_bent = Waveguide(bend_radius=radius, **kwargs)
wg.get_overlap(wg_bent, mode_index1=mode_index, mode_index2=mode_index)
# normalized overlap integral
integral[i] = np.abs(
wg.get_overlap(wg_bent, mode_index, mode_index) ** 2
/ wg.get_overlap(wg, mode_index, mode_index)
/ wg.get_overlap(wg_bent, mode_index, mode_index)
)
return r, integral**2
def sweep_neff(
wavelength: float = 1.55,
thicknesses: Tuple[float, ...] = (220 * nm,),
widths: Tuple[float, ...] = (500 * nm,),
mode_index: int = 0,
**kwargs,
) -> pd.DataFrame:
"""Sweep waveguide width and compute effective index.
Args:
wavelength: (um).
thicknesses: in um.
widths: in um.
mode_index: integer, where 0 is the fundamental mode.
Keyword Args:
mode_index: integer.
ncore: core refractive index.
nclad: cladding refractive index.
slab_thickness: thickness slab (um).
t_box: thickness BOX (um).
t_clad: thickness cladding (um).
xmargin: margin from waveguide edge to each side (um).
resolution: pixels/um.
nmodes: number of modes to compute.
bend_radius: optional bend radius (um).
"""
widths_thicknesses = list(it.product(widths, thicknesses))
neff = np.zeros(len(widths_thicknesses))
w = np.zeros(len(widths_thicknesses))
t = np.zeros(len(widths_thicknesses))
for i, (wg_width, wg_thickness) in enumerate(tqdm(widths_thicknesses)):
wg = Waveguide(
wg_width=wg_width,
wg_thickness=wg_thickness,
wavelength=wavelength,
**kwargs,
)
wg.compute_modes()
wg.compute_mode_properties()
neff[i] = np.real(wg.neffs[mode_index])
w[i] = wg_width
t[i] = wg_thickness
return pd.DataFrame(dict(neff=neff, widths=w, thickness=t))
def group_index(
wavelength: float, wavelength_step: float = 0.01, mode_index: int = 0, **kwargs
) -> float:
"""Returns group_index.
Args:
wavelength: (um).
wavelength_step: in um.
mode_index: integer, where 0 is the fundamental mode.
Keyword Args:
wg_width: waveguide width.
wg_thickness: thickness waveguide (um).
ncore: core refractive index.
nclad: cladding refractive index.
slab_thickness: thickness slab (um).
t_box: thickness BOX (um).
t_clad: thickness cladding (um).
xmargin: margin from waveguide edge to each side (um).
resolution: pixels/um.
nmodes: number of modes to compute.
bend_radius: optional bend radius (um).
"""
wc = Waveguide(wavelength=wavelength, **kwargs)
wf = Waveguide(
wavelength=wavelength + wavelength_step,
**kwargs,
)
wb = Waveguide(
wavelength=wavelength - wavelength_step,
**kwargs,
)
wc.compute_modes()
wb.compute_modes()
wf.compute_modes()
nc = np.real(wc.neffs[mode_index])
nb = np.real(wb.neffs[mode_index])
nf = np.real(wf.neffs[mode_index])
return nc - wavelength * (nf - nb) / (2 * wavelength_step)
def sweep_group_index(
wavelength: float = 1.55,
thicknesses: Tuple[float, ...] = (220 * nm,),
widths: Tuple[float, ...] = (500 * nm,),
**kwargs,
) -> pd.DataFrame:
"""Sweep waveguide width and compute group index.
Args:
wavelength: (um).
thicknesses: in um.
widths: in um.
Keyword Args:
mode_index: integer.
ncore: core refractive index.
nclad: cladding refractive index.
slab_thickness: thickness slab (um).
t_box: thickness BOX (um).
t_clad: thickness cladding (um).
xmargin: margin from waveguide edge to each side (um).
resolution: pixels/um.
nmodes: number of modes to compute.
bend_radius: optional bend radius (um).
"""
widths_thicknesses = list(it.product(widths, thicknesses))
ng = np.zeros(len(widths_thicknesses))
w = np.zeros(len(widths_thicknesses))
t = np.zeros(len(widths_thicknesses))
for i, (wg_width, wg_thickness) in enumerate(tqdm(widths_thicknesses)):
ng[i] = group_index(
wavelength=wavelength,
wg_width=wg_width,
wg_thickness=wg_thickness,
**kwargs,
)
w[i] = wg_width
t[i] = wg_thickness
return pd.DataFrame(dict(ng=ng, widths=w, thickness=t))
def sweep_width(
width1: float = 200 * nm,
width2: float = 1000 * nm,
steps: int = 12,
nmodes: int = 4,
**kwargs,
) -> pd.DataFrame:
"""Sweep waveguide width and compute effective index.
Returns pandas dataframe with effective index (neff) and fraction_te.
Args:
width1: starting waveguide width in um.
width2: end waveguide width in um.
steps: number of points.
nmodes: number of modes to compute.
Keyword Args:
wavelength: (um).
wg_width: waveguide width in um.
wg_thickness: thickness waveguide (um).
ncore: core refractive index.
nclad: cladding refractive index.
slab_thickness: thickness slab (um).
t_box: thickness BOX (um).
t_clad: thickness cladding (um).
xmargin: margin from waveguide edge to each side (um).
resolution: pixels/um.
nmodes: number of modes to compute.
bend_radius: optional bend radius (um).
"""
width = np.linspace(width1, width2, steps)
neff = {}
for mode_number in range(nmodes):
neff[f"neff{mode_number}"] = []