-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathtest_microwave.py
More file actions
2327 lines (1926 loc) · 85.7 KB
/
test_microwave.py
File metadata and controls
2327 lines (1926 loc) · 85.7 KB
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
"""Tests microwave tools."""
from __future__ import annotations
from math import isclose
from typing import Literal
import matplotlib.pyplot as plt
import numpy as np
import pydantic as pd
import pytest
import xarray as xr
from shapely import LineString
import tidy3d as td
from tidy3d.components.data.data_array import FreqModeDataArray, _isinstance
from tidy3d.components.data.monitor_data import FreqDataArray
from tidy3d.components.microwave.formulas.circuit_parameters import (
capacitance_colinear_cylindrical_wire_segments,
capacitance_rectangular_sheets,
inductance_straight_rectangular_wire,
mutual_inductance_colinear_wire_segments,
total_inductance_colinear_rectangular_wire_segments,
)
from tidy3d.components.microwave.path_integrals.factory import (
make_current_integral,
make_path_integrals,
make_voltage_integral,
)
from tidy3d.components.microwave.path_integrals.mode_plane_analyzer import (
ModePlaneAnalyzer,
)
from tidy3d.components.mode.mode_solver import ModeSolver
from tidy3d.constants import EPSILON_0
from tidy3d.exceptions import DataError, SetupError, ValidationError
from ..test_data.test_monitor_data import make_directivity_data
from ..utils import AssertLogLevel, get_spatial_coords_dict, run_emulated
MAKE_PLOTS = False
if MAKE_PLOTS:
# Interactive plotting for debugging
from matplotlib import use
use("TkAgg")
# Constant parameters and simulation for path integral tests
mm = 1e3
# Using similar code as "test_data/test_data_arrays.py"
MON_SIZE = (2, 1, 0)
FIELDS = ("Ex", "Ey", "Hx", "Hy")
FSTART = 0.5e9
FSTOP = 1.5e9
F0 = (FSTART + FSTOP) / 2
FWIDTH = FSTOP - FSTART
FS = np.linspace(FSTART, FSTOP, 3)
FIELD_MONITOR = td.FieldMonitor(size=MON_SIZE, fields=FIELDS, name="strip_field", freqs=FS)
STRIP_WIDTH = 1.5
STRIP_HEIGHT = 0.5
COAX_R1 = 0.04
COAX_R2 = 0.5
SIM_Z = td.Simulation(
size=(2, 1, 1),
grid_spec=td.GridSpec.uniform(dl=0.04),
monitors=[
FIELD_MONITOR,
td.FieldMonitor(center=(0, 0, 0), size=(1, 1, 1), freqs=FS, name="field", colocate=False),
td.FieldMonitor(
center=(0, 0, 0), size=(1, 1, 1), freqs=FS, fields=["Ex", "Hx"], name="ExHx"
),
td.FieldTimeMonitor(center=(0, 0, 0), size=(1, 1, 0), colocate=False, name="field_time"),
td.ModeSolverMonitor(
center=(0, 0, 0),
size=(1, 1, 0),
freqs=FS,
mode_spec=td.ModeSpec(num_modes=2),
name="mode_solver",
),
td.ModeMonitor(
center=(0, 0, 0),
size=(1, 1, 0),
freqs=FS,
mode_spec=td.ModeSpec(num_modes=3),
store_fields_direction="+",
name="mode",
),
],
sources=[
td.PointDipole(
center=(0, 0, 0),
polarization="Ex",
source_time=td.GaussianPulse(freq0=F0, fwidth=FWIDTH),
)
],
run_time=5e-16,
)
SIM_Z_DATA = run_emulated(SIM_Z)
""" Generate the data arrays for testing path integral computations """
def make_stripline_scalar_field_data_array(grid_key: str):
"""Populate FIELD_MONITOR with a idealized stripline mode, where fringing fields are assumed 0."""
XS, YS, ZS = get_spatial_coords_dict(SIM_Z, FIELD_MONITOR, grid_key).values()
XGRID, YGRID = np.meshgrid(XS, YS, indexing="ij")
XGRID = XGRID.reshape((len(XS), len(YS), 1, 1))
YGRID = YGRID.reshape((len(XS), len(YS), 1, 1))
values = np.zeros((len(XS), len(YS), len(ZS), len(FS)))
ones = np.ones((len(XS), len(YS), len(ZS), len(FS)))
XGRID = np.broadcast_to(XGRID, values.shape)
YGRID = np.broadcast_to(YGRID, values.shape)
# Numpy masks for quickly determining location
above_in_strip = np.logical_and(YGRID >= 0, YGRID <= STRIP_HEIGHT / 2)
below_in_strip = np.logical_and(YGRID < 0, YGRID >= -STRIP_HEIGHT / 2)
within_strip_width = np.logical_and(XGRID >= -STRIP_WIDTH / 2, XGRID < STRIP_WIDTH / 2)
above_and_within = np.logical_and(above_in_strip, within_strip_width)
below_and_within = np.logical_and(below_in_strip, within_strip_width)
# E field is perpendicular to strip surface and magnetic field is parallel
if grid_key == "Ey":
values = np.where(above_and_within, ones, values)
values = np.where(below_and_within, -ones, values)
elif grid_key == "Hx":
values = np.where(above_and_within, -ones / td.ETA_0, values)
values = np.where(below_and_within, ones / td.ETA_0, values)
return td.ScalarFieldDataArray(values, coords={"x": XS, "y": YS, "z": ZS, "f": FS})
def make_coaxial_field_data_array(grid_key: str):
"""Populate FIELD_MONITOR with a coaxial transmission line mode."""
# Get a normalized electric field that represents the electric field within a coaxial cable transmission line.
def compute_coax_radial_electric(rin, rout, x, y, is_x):
# Radial distance
r = np.sqrt((x) ** 2 + (y) ** 2)
# Remove division by 0
r_valid = np.where(r == 0.0, 1, r)
# Compute current density so that the total current
# is 1 flowing through surfaces of constant r
# Extra r is for changing to Cartesian coordinates
denominator = 2 * np.pi * r_valid**2
if is_x:
Exy = np.where(r <= rin, 0, (x / denominator))
Exy = np.where(r >= rout, 0, Exy)
else:
Exy = np.where(r <= rin, 0, (y / denominator))
Exy = np.where(r >= rout, 0, Exy)
return Exy
XS, YS, ZS = get_spatial_coords_dict(SIM_Z, FIELD_MONITOR, grid_key).values()
XGRID, YGRID = np.meshgrid(XS, YS, indexing="ij")
XGRID = XGRID.reshape((len(XS), len(YS), 1, 1))
YGRID = YGRID.reshape((len(XS), len(YS), 1, 1))
values = np.zeros((len(XS), len(YS), len(ZS), len(FS)))
XGRID = np.broadcast_to(XGRID, values.shape)
YGRID = np.broadcast_to(YGRID, values.shape)
is_x = grid_key[1] == "x"
if grid_key[0] == "E":
field = compute_coax_radial_electric(COAX_R1, COAX_R2, XGRID, YGRID, is_x)
else:
field = compute_coax_radial_electric(COAX_R1, COAX_R2, XGRID, YGRID, not is_x)
# H field is perpendicular and oriented for positive z propagation
# We want to compute Hx which is -Ey/eta0, Hy which is Ex/eta0
if is_x:
field /= -td.ETA_0
else:
field /= td.ETA_0
return td.ScalarFieldDataArray(field, coords={"x": XS, "y": YS, "z": ZS, "f": FS})
def make_field_data():
return td.FieldData(
monitor=FIELD_MONITOR,
Ex=make_stripline_scalar_field_data_array("Ex"),
Ey=make_stripline_scalar_field_data_array("Ey"),
Hx=make_stripline_scalar_field_data_array("Hx"),
Hy=make_stripline_scalar_field_data_array("Hy"),
symmetry=SIM_Z.symmetry,
symmetry_center=SIM_Z.center,
grid_expanded=SIM_Z.discretize_monitor(FIELD_MONITOR),
)
def make_coax_field_data():
return td.FieldData(
monitor=FIELD_MONITOR,
Ex=make_coaxial_field_data_array("Ex"),
Ey=make_coaxial_field_data_array("Ey"),
Hx=make_coaxial_field_data_array("Hx"),
Hy=make_coaxial_field_data_array("Hy"),
symmetry=SIM_Z.symmetry,
symmetry_center=SIM_Z.center,
grid_expanded=SIM_Z.discretize_monitor(FIELD_MONITOR),
)
def make_mw_sim(
use_2D: bool = False,
colocate: bool = False,
transmission_line_type: Literal["microstrip", "cpw", "coax", "stripline"] = "microstrip",
width=3 * mm,
height=1 * mm,
metal_thickness=0.2 * mm,
) -> td.Simulation:
"""Helper to create a microwave simulation with a single type of transmission line present."""
freq_start = 1e9
freq_stop = 10e9
freq0 = (freq_start + freq_stop) / 2
fwidth = freq_stop - freq_start
freqs = np.arange(freq_start, freq_stop, 1e9)
run_time = 60 / fwidth
length = 40 * mm
sim_width = length
pec = td.PEC
if use_2D:
metal_thickness = 0.0
pec = td.PEC2D
epsr = 4.4
diel = td.Medium(permittivity=epsr)
metal_geos = []
if transmission_line_type == "microstrip":
substrate = td.Structure(
geometry=td.Box(
center=[0, 0, 0],
size=[td.inf, td.inf, 2 * height],
),
medium=diel,
)
metal_geos.append(
td.Box(
center=[0, 0, height + metal_thickness / 2],
size=[td.inf, width, metal_thickness],
)
)
elif transmission_line_type == "cpw":
substrate = td.Structure(
geometry=td.Box(
center=[0, 0, 0],
size=[td.inf, td.inf, 2 * height],
),
medium=diel,
)
metal_geos.append(
td.Box(
center=[0, 0, height + metal_thickness / 2],
size=[td.inf, width, metal_thickness],
)
)
gnd_width = 10 * width
gap = width / 5
gnd_shift = gnd_width / 2 + gap + width / 2
metal_geos.append(
td.Box(
center=[0, -gnd_shift, height + metal_thickness / 2],
size=[td.inf, gnd_width, metal_thickness],
)
)
metal_geos.append(
td.Box(
center=[0, gnd_shift, height + metal_thickness / 2],
size=[td.inf, gnd_width, metal_thickness],
)
)
elif transmission_line_type == "coax":
substrate = td.Structure(
geometry=td.Box(
center=[0, 0, 0],
size=[td.inf, td.inf, 2 * height],
),
medium=diel,
)
metal_geos.append(
td.GeometryGroup(
geometries=(
td.ClipOperation(
operation="difference",
geometry_a=td.Cylinder(
axis=0, radius=2 * mm, center=(0, 0, 5 * mm), length=td.inf
),
geometry_b=td.Cylinder(
axis=0, radius=1.8 * mm, center=(0, 0, 5 * mm), length=td.inf
),
),
td.Cylinder(axis=0, radius=0.6 * mm, center=(0, 0, 5 * mm), length=td.inf),
)
)
)
elif transmission_line_type == "stripline":
substrate = td.Structure(
geometry=td.Box(
center=[0, 0, 0],
size=[td.inf, td.inf, 2 * height + metal_thickness],
),
medium=diel,
)
metal_geos.append(
td.Box(
center=[0, 0, 0],
size=[td.inf, width, metal_thickness],
)
)
gnd_width = 10 * width
metal_geos.append(
td.Box(
center=[0, 0, height + metal_thickness],
size=[td.inf, gnd_width, metal_thickness],
)
)
metal_geos.append(
td.Box(
center=[0, 0, -height - metal_thickness],
size=[td.inf, gnd_width, metal_thickness],
)
)
else:
raise AssertionError("Incorrect argument")
metal_structures = [td.Structure(geometry=geo, medium=pec) for geo in metal_geos]
structures = [substrate, *metal_structures]
boundary_spec = td.BoundarySpec(
x=td.Boundary(plus=td.PML(), minus=td.PML()),
y=td.Boundary(plus=td.PML(), minus=td.PML()),
z=td.Boundary(plus=td.PML(), minus=td.PECBoundary()),
)
size_sim = [
length + 2 * width,
sim_width,
20 * mm + height + metal_thickness,
]
center_sim = [0, 0, size_sim[2] / 2]
# Slightly different setup for stripline substrate sandwiched between ground planes
if transmission_line_type == "stripline":
center_sim[2] = 0
boundary_spec = td.BoundarySpec(
x=td.Boundary(plus=td.PML(), minus=td.PML()),
y=td.Boundary(plus=td.PML(), minus=td.PML()),
z=td.Boundary(plus=td.PML(), minus=td.PML()),
)
size_port = [0, sim_width, size_sim[2]]
center_port = [0, 0, center_sim[2]]
impedance_specs = (td.AutoImpedanceSpec(),) * 4
mode_spec = td.MicrowaveModeSpec(
num_modes=4,
target_neff=1.8,
impedance_specs=impedance_specs,
)
mode_monitor = td.MicrowaveModeMonitor(
center=center_port, size=size_port, freqs=freqs, name="mode_1", colocate=colocate
)
gaussian = td.GaussianPulse(freq0=freq0, fwidth=fwidth)
mode_src = td.ModeSource(
center=(-length / 2, 0, center_sim[2]),
size=size_port,
direction="+",
mode_spec=mode_spec,
mode_index=0,
source_time=gaussian,
)
sim = td.Simulation(
center=center_sim,
size=size_sim,
grid_spec=td.GridSpec.uniform(dl=0.1 * mm),
structures=structures,
sources=[mode_src],
monitors=[mode_monitor],
run_time=run_time,
boundary_spec=boundary_spec,
plot_length_units="mm",
symmetry=(0, 0, 0),
subpixel=False,
)
return sim
def test_inductance_formulas():
"""Run the formulas for inductance and compare to precomputed results."""
bar_size = (1000e4, 1e4, 1e4) # case from reference
L1 = inductance_straight_rectangular_wire(bar_size, 0)
assert isclose(L1, 14.816e-6, rel_tol=1e-4)
length = 1e3
L2 = mutual_inductance_colinear_wire_segments(length, length, length / 10)
assert isclose(L2, 0.11181e-9, rel_tol=1e-4)
side = length / 10
L3 = total_inductance_colinear_rectangular_wire_segments(
(side, length, side), (side, length, side), length / 10, 1
)
assert isclose(L3, 1.3625e-9, rel_tol=1e-4)
def test_capacitance_formulas():
"""Run the formulas for capacitance and compare to precomputed results."""
width = 3e3
length = 1e3
d = length / 4.5 # case from reference
C1 = capacitance_rectangular_sheets(width, length, d)
result = 2.347 * EPSILON_0 * width # from reference
assert isclose(C1, result, rel_tol=1e-3)
# case from reference
radius = 0.1e-3
C2 = capacitance_colinear_cylindrical_wire_segments(radius, length, length / 5)
D2 = 0.345
C_ref = np.pi * EPSILON_0 * length / (np.log(length / radius) - 2.303 * D2)
assert isclose(C2, C_ref, rel_tol=1e-3)
# case from reference
C3 = capacitance_colinear_cylindrical_wire_segments(radius, length, length * 5)
D2 = 0.144
C_ref = np.pi * EPSILON_0 * length / (np.log(length / radius) - 2.303 * D2)
assert isclose(C3, C_ref, rel_tol=1e-2)
def test_antenna_parameters():
"""Test basic antenna parameters computation and validation."""
# Create from random directivity data
directivity_data = make_directivity_data()
f = directivity_data.coords["f"]
power_inc = FreqDataArray(0.8 * np.ones(len(f)), coords={"f": f})
power_refl = 0.25 * power_inc
antenna_params = td.AntennaMetricsData.from_directivity_data(
directivity_data, power_inc, power_refl
)
# Test that all essential parameters exist and are correct type
assert _isinstance(antenna_params.radiation_efficiency, FreqDataArray)
assert _isinstance(antenna_params.reflection_efficiency, FreqDataArray)
assert np.allclose(antenna_params.reflection_efficiency, 0.75)
assert isinstance(antenna_params.gain, xr.DataArray)
assert isinstance(antenna_params.realized_gain, xr.DataArray)
# Test partial gain computations in linear basis
partial_gain_linear = antenna_params.partial_gain(pol_basis="linear")
assert isinstance(partial_gain_linear, xr.Dataset)
assert "Gtheta" in partial_gain_linear
assert "Gphi" in partial_gain_linear
# Test partial gain computations in linear basis with tilt angle = 0 matches partial gain in the original basis
partial_gain_linear_tilted = antenna_params.partial_gain(pol_basis="linear", tilt_angle=0)
assert isinstance(partial_gain_linear_tilted, xr.Dataset)
assert "Gco" in partial_gain_linear_tilted
assert "Gcross" in partial_gain_linear_tilted
assert np.allclose(partial_gain_linear_tilted.Gco, partial_gain_linear.Gtheta)
assert np.allclose(partial_gain_linear_tilted.Gcross, partial_gain_linear.Gphi)
# Test validation of tilt angle that only works with linear basis
with pytest.raises(ValueError):
antenna_params.partial_gain(pol_basis="circular", tilt_angle=1)
# Test partial gain computations in circular basis
partial_gain_circular = antenna_params.partial_gain(pol_basis="circular")
assert isinstance(partial_gain_circular, xr.Dataset)
assert "Gright" in partial_gain_circular
assert "Gleft" in partial_gain_circular
# Test partial realized gain computations in both bases
assert isinstance(antenna_params.partial_realized_gain("linear"), xr.Dataset)
assert isinstance(antenna_params.partial_realized_gain("circular"), xr.Dataset)
# Test validation of pol_basis parameter
with pytest.raises(ValueError):
antenna_params.partial_gain("invalid")
with pytest.raises(ValueError):
antenna_params.partial_realized_gain("invalid")
def test_path_spec_plotting():
"""Test that all types of path specification correctly plot themselves."""
mean_radius = (COAX_R2 + COAX_R1) * 0.5
size = [COAX_R2 - COAX_R1, 0, 0]
center = [mean_radius, 0, 0]
voltage_integral = td.AxisAlignedVoltageIntegralSpec(
center=center, size=size, sign="-", extrapolate_to_endpoints=True, snap_path_to_grid=True
)
current_integral = td.Custom2DCurrentIntegralSpec.from_circular_path(
center=(0, 0, 0), radius=0.4, num_points=31, normal_axis=2, clockwise=False
)
ax = voltage_integral.plot(z=0)
current_integral.plot(z=0, ax=ax)
plt.close()
# Test off center plotting
ax = voltage_integral.plot(z=2)
current_integral.plot(z=2, ax=ax)
plt.close()
# Plot
voltage_integral = td.Custom2DVoltageIntegralSpec(
axis=1, position=0, vertices=[(-1, -1), (0, 0), (1, 1)]
)
current_integral = td.AxisAlignedCurrentIntegralSpec(
center=(0, 0, 0),
size=(2, 0, 1),
sign="-",
extrapolate_to_endpoints=False,
snap_contour_to_grid=False,
)
ax = voltage_integral.plot(y=0)
current_integral.plot(y=0, ax=ax)
plt.close()
# Test off center plotting
ax = voltage_integral.plot(y=2)
current_integral.plot(y=2, ax=ax)
plt.close()
current_integral = td.CompositeCurrentIntegralSpec(
path_specs=(
td.AxisAlignedCurrentIntegralSpec(center=(-1, -1, 0), size=(1, 1, 0), sign="-"),
td.AxisAlignedCurrentIntegralSpec(center=(1, 1, 0), size=(1, 1, 0), sign="-"),
),
sum_spec="sum",
)
ax = current_integral.plot(z=0)
plt.close()
@pytest.mark.parametrize("clockwise", [False, True])
def test_custom_current_specification_sign(clockwise):
"""Make sure the sign is correctly calculated for custom current specs."""
current_integral = td.Custom2DCurrentIntegralSpec.from_circular_path(
center=(0, 0, 0), radius=0.4, num_points=31, normal_axis=2, clockwise=clockwise
)
if clockwise:
assert current_integral.sign == "-"
else:
assert current_integral.sign == "+"
# When aligned with y, the sign has to be handled carefully
current_integral = td.Custom2DCurrentIntegralSpec.from_circular_path(
center=(0, 0, 0), radius=0.4, num_points=31, normal_axis=1, clockwise=clockwise
)
if clockwise:
assert current_integral.sign == "-"
else:
assert current_integral.sign == "+"
def test_composite_current_integral_validation():
"""Ensures that the CompositeCurrentIntegralSpec is validated correctly."""
current_spec = td.AxisAlignedCurrentIntegralSpec(center=(1, 2, 3), size=(0, 1, 1), sign="-")
voltage_spec = td.AxisAlignedVoltageIntegralSpec(center=(1, 2, 3), size=(0, 0, 1), sign="-")
path_spec = td.CompositeCurrentIntegralSpec(path_specs=[current_spec], sum_spec="sum")
with pytest.raises(pd.ValidationError):
path_spec.updated_copy(path_specs=[])
with pytest.raises(pd.ValidationError):
path_spec.updated_copy(path_specs=[voltage_spec])
def test_composite_current_integral_bounds():
"""Test that CompositeCurrentIntegralSpec correctly computes overall bounding box."""
# Single axis-aligned spec
spec1 = td.AxisAlignedCurrentIntegralSpec(center=(0, 0, 0), size=(2, 2, 0), sign="+")
composite1 = td.CompositeCurrentIntegralSpec(path_specs=(spec1,), sum_spec="sum")
expected_bounds1 = ((-1.0, -1.0, 0.0), (1.0, 1.0, 0.0))
assert composite1.bounds == expected_bounds1
# Two disjoint axis-aligned specs
spec2 = td.AxisAlignedCurrentIntegralSpec(center=(5, 5, 0), size=(2, 2, 0), sign="+")
composite2 = td.CompositeCurrentIntegralSpec(path_specs=(spec1, spec2), sum_spec="sum")
# Should span from (-1, -1, 0) to (6, 6, 0)
expected_bounds2 = ((-1.0, -1.0, 0.0), (6.0, 6.0, 0.0))
assert composite2.bounds == expected_bounds2
# Custom 2D spec
vertices = np.array([[0, 0], [2, 0], [2, 1], [0, 1], [0, 0]])
spec3 = td.Custom2DCurrentIntegralSpec(axis=2, position=0, vertices=vertices)
composite3 = td.CompositeCurrentIntegralSpec(path_specs=(spec3,), sum_spec="sum")
expected_bounds3 = ((0.0, 0.0, 0.0), (2.0, 1.0, 0.0))
assert composite3.bounds == expected_bounds3
# Mixed spec types (axis-aligned + custom 2D)
spec4 = td.AxisAlignedCurrentIntegralSpec(center=(-3, -3, 0), size=(1, 1, 0), sign="-")
composite4 = td.CompositeCurrentIntegralSpec(path_specs=(spec3, spec4), sum_spec="split")
# Custom spec: (0, 0, 0) to (2, 1, 0)
# Axis-aligned spec: (-3.5, -3.5, 0) to (-2.5, -2.5, 0)
# Overall: (-3.5, -3.5, 0) to (2, 1, 0)
expected_bounds4 = ((-3.5, -3.5, 0.0), (2.0, 1.0, 0.0))
assert composite4.bounds == expected_bounds4
# Overlapping specs
spec5 = td.AxisAlignedCurrentIntegralSpec(center=(1, 1, 0), size=(4, 4, 0), sign="+")
spec6 = td.AxisAlignedCurrentIntegralSpec(center=(2, 2, 0), size=(2, 2, 0), sign="+")
composite5 = td.CompositeCurrentIntegralSpec(path_specs=(spec5, spec6), sum_spec="sum")
# spec5: (-1, -1, 0) to (3, 3, 0)
# spec6: (1, 1, 0) to (3, 3, 0)
# Overall: (-1, -1, 0) to (3, 3, 0)
expected_bounds5 = ((-1.0, -1.0, 0.0), (3.0, 3.0, 0.0))
assert composite5.bounds == expected_bounds5
def test_path_integral_creation():
"""Check that path integrals are correctly constructed from path specifications."""
path_spec = td.AxisAlignedVoltageIntegralSpec(center=(1, 2, 3), size=(0, 0, 1), sign="-")
voltage_integral = make_voltage_integral(path_spec)
path_spec = td.AxisAlignedCurrentIntegralSpec(center=(1, 2, 3), size=(0, 1, 1), sign="-")
current_integral = make_current_integral(path_spec)
path_spec = td.Custom2DVoltageIntegralSpec(vertices=[(0, 1), (0, 4)], axis=1, position=2)
voltage_integral = make_voltage_integral(path_spec)
path_spec = td.Custom2DCurrentIntegralSpec(
vertices=[
(0, 1),
(0, 4),
(3, 4),
(3, 1),
],
axis=1,
position=2,
)
_ = make_current_integral(path_spec)
with pytest.raises(pd.ValidationError):
path_spec = td.Custom2DCurrentIntegralSpec(
vertices=[
(0, 1, 3),
(0, 4, 5),
(3, 4, 5),
(3, 1, 5),
],
axis=1,
position=2,
)
def test_mode_plane_analyzer_errors():
"""Check that the ModePlaneAnalyzer reports errors properly."""
path_spec_gen = ModePlaneAnalyzer(size=(0, 2, 2), field_data_colocated=False)
# First some quick sanity checks with the helper
test_path = td.Box(center=(0, 0, 0), size=(0, 0.9, 0.1))
test_shapely = [LineString([(-1, 0), (1, 0)])]
assert path_spec_gen._check_box_intersects_with_conductors(test_shapely, test_path)
test_path = td.Box(center=(0, 0, 0), size=(0, 2.1, 0.1))
test_shapely = [LineString([(-1, 0), (1, 0)])]
assert not path_spec_gen._check_box_intersects_with_conductors(test_shapely, test_path)
sim = make_mw_sim(False, False, "microstrip")
coax = td.GeometryGroup(
geometries=(
td.ClipOperation(
operation="difference",
geometry_a=td.Cylinder(axis=0, radius=2 * mm, center=(0, 0, 5 * mm), length=td.inf),
geometry_b=td.Cylinder(
axis=0, radius=1.4 * mm, center=(0, 0, 5 * mm), length=td.inf
),
),
td.Cylinder(axis=0, radius=1 * mm, center=(0, 0, 5 * mm), length=td.inf),
)
)
coax_struct = td.Structure(geometry=coax, medium=td.PEC)
sim = sim.updated_copy(structures=[coax_struct])
mode_monitor = sim.monitors[0]
modal_plane = td.Box(center=mode_monitor.center, size=mode_monitor.size)
path_spec_gen = ModePlaneAnalyzer(
center=modal_plane.center,
size=modal_plane.size,
field_data_colocated=mode_monitor.colocate,
)
with pytest.raises(SetupError):
path_spec_gen.get_conductor_bounding_boxes(
sim.structures,
sim.grid,
sim.symmetry,
sim.bounding_box,
)
# Error when no conductors intersecting mode plane
path_spec_gen = path_spec_gen.updated_copy(size=(0, 0.1, 0.1), center=(0, 0, 1.5))
with pytest.raises(SetupError):
path_spec_gen.get_conductor_bounding_boxes(
sim.structures,
sim.grid,
sim.symmetry,
sim.bounding_box,
)
@pytest.mark.parametrize("include_ground_plane", [True, False])
def test_mode_plane_analyzer_coarse_grid_errors(include_ground_plane):
"""Test that coarse grids produce appropriate errors for auto path generation.
With a coarse grid the snapped bounding box around the signal trace can:
- intersect other conductors,
- extend outside the mode plane bounds which is beyond the domain of the monitor data.
"""
width = 3 * mm
metal_thickness = 0.1 * mm
coarse_dl = 1.0 * mm
sim_size = (10 * mm, 10 * mm, 10 * mm)
sim_center = (0, 0, sim_size[2] / 2)
# Signal trace near bottom of mode plane
signal_trace = td.Structure(
geometry=td.Box(
center=(0, 0, 0.3 * mm),
size=(td.inf, width, metal_thickness),
),
medium=td.PEC,
)
structures = [signal_trace]
if include_ground_plane:
# Ground plane at z=0, extending infinitely in y to touch mode plane y-boundaries
# This will be filtered out, but should still be checked for path intersections
ground_plane = td.Structure(
geometry=td.Box(
center=(0, 0, 0),
size=(td.inf, td.inf, metal_thickness),
),
medium=td.PEC,
)
structures.append(ground_plane)
# Mode plane spans full simulation for ground plane case
mode_plane_size = (0, sim_size[1], sim_size[2])
mode_plane_center = (0, 0, sim_center[2])
else:
# Small mode plane that doesn't span full sim, so bounding box extends outside
mode_plane_size = (0, sim_size[1], 1.0 * mm)
mode_plane_center = (0, 0, 0.5 * mm)
sim = td.Simulation(
center=sim_center,
size=sim_size,
grid_spec=td.GridSpec.uniform(dl=coarse_dl),
structures=structures,
sources=[],
run_time=1e-12,
)
mode_plane = td.Box(center=mode_plane_center, size=mode_plane_size)
path_spec_gen = ModePlaneAnalyzer(
center=mode_plane.center,
size=mode_plane.size,
field_data_colocated=False,
)
if include_ground_plane:
# Should raise SetupError because auto-generated path intersects the ground plane
with pytest.raises(SetupError, match="intersect with a conductor"):
path_spec_gen.get_conductor_bounding_boxes(
sim.structures,
sim.grid,
sim.symmetry,
sim.bounding_box,
)
else:
# Should raise SetupError because bounding box extends outside mode plane
with pytest.raises(SetupError, match="extends outside the mode solving plane"):
path_spec_gen.get_conductor_bounding_boxes(
sim.structures,
sim.grid,
sim.symmetry,
sim.bounding_box,
)
@pytest.mark.parametrize("colocate", [False, True])
@pytest.mark.parametrize("tline_type", ["microstrip", "cpw", "coax"])
def test_mode_plane_analyzer_canonical_shapes(colocate, tline_type):
"""Test canonical transmission line types to make sure the correct path integrals are generated."""
sim = make_mw_sim(False, colocate, tline_type)
mode_monitor = sim.monitors[0]
modal_plane = td.Box(center=mode_monitor.center, size=mode_monitor.size)
mode_plane_analyzer = ModePlaneAnalyzer(
center=modal_plane.center,
size=modal_plane.size,
field_data_colocated=mode_monitor.colocate,
)
bounding_boxes, geos = mode_plane_analyzer.get_conductor_bounding_boxes(
sim.structures,
sim.grid,
sim.symmetry,
sim.bounding_box,
)
if tline_type == "coax":
assert len(bounding_boxes) == 2
for path_spec in bounding_boxes:
assert np.all(np.isclose(path_spec.center, (0, 0, 5 * mm)))
else:
assert len(bounding_boxes) == 1
assert np.all(np.isclose(bounding_boxes[0].center, (0, 0, 1.1 * mm)))
@pytest.mark.parametrize("use_2D", [False, True])
@pytest.mark.parametrize("symmetry", [(0, 0, 1), (0, 1, 1), (0, 1, 0)])
def test_mode_plane_analyzer_advanced(use_2D, symmetry):
"""The various symmetry permutations as well as with and without 2D structures."""
sim = make_mw_sim(use_2D, False, "stripline")
# Add shapes outside the portion considered for the symmetric simulation
bottom_left = td.Structure(
geometry=td.Box(
center=[0, -5 * mm, -5 * mm],
size=[td.inf, 1 * mm, 1 * mm],
),
medium=td.PEC,
)
# Add shape only in the symmetric portion
top_right = td.Structure(
geometry=td.Box(
center=[0, 5 * mm, 5 * mm],
size=[td.inf, 1 * mm, 1 * mm],
),
medium=td.PEC,
)
structures = [*list(sim.structures), bottom_left, top_right]
sim = sim.updated_copy(symmetry=symmetry, structures=structures)
mode_monitor = sim.monitors[0]
modal_plane = td.Box(center=mode_monitor.center, size=mode_monitor.size)
mode_plane_analyzer = ModePlaneAnalyzer(
center=modal_plane.center,
size=modal_plane.size,
field_data_colocated=mode_monitor.colocate,
)
bounding_boxes, geos = mode_plane_analyzer.get_conductor_bounding_boxes(
sim.structures,
sim.grid,
sim.symmetry,
sim.bounding_box,
)
if symmetry[1] == 1 and symmetry[2] == 1:
assert len(bounding_boxes) == 7
else:
assert len(bounding_boxes) == 5
@pytest.mark.parametrize(
"mode_size", [(1.4 * mm, 1.0 * mm, 0), (1.4 * mm, 2 * mm, 0), (1.4 * mm - 1, 1.0 * mm + 1, 0)]
)
@pytest.mark.parametrize("symmetry", [(0, 0, 0), (0, 1, 0), (1, 1, 0)])
def test_mode_plane_analyzer_mode_bounds(mode_size, symmetry):
"""Test that the the mode plane bounds matches the mode solver grid bounds exactly."""
dl = 0.1 * mm
freq0 = (5e9) / 2
fwidth = 4e9
run_time = 60 / fwidth
boundary_spec = td.BoundarySpec(
x=td.Boundary(plus=td.PECBoundary(), minus=td.PECBoundary()),
y=td.Boundary(plus=td.PECBoundary(), minus=td.PECBoundary()),
z=td.Boundary(plus=td.PECBoundary(), minus=td.PECBoundary()),
)
impedance_specs = (td.AutoImpedanceSpec(),) * 4
mode_spec = td.MicrowaveModeSpec(
num_modes=4,
target_neff=1.8,
impedance_specs=impedance_specs,
)
metal_box = td.Structure(
geometry=td.Box.from_bounds(
rmin=(0.5 * mm, 0.5 * mm, 0.5 * mm), rmax=(1 * mm - 1 * dl, 0.5 * mm, 0.5 * mm)
),
medium=td.PEC,
)
sim = td.Simulation(
center=(0, 0, 0),
size=(2 * mm, 2 * mm, 2 * mm),
grid_spec=td.GridSpec.uniform(dl=dl),
structures=(metal_box,),
run_time=run_time,
boundary_spec=boundary_spec,
plot_length_units="mm",
symmetry=symmetry,
)
mode_center = [0, 0, 0]
mode_plane = td.Box(center=mode_center, size=mode_size)
mms = ModeSolver(
simulation=sim,
plane=mode_plane,
mode_spec=mode_spec,
colocate=True,
freqs=[freq0],
)
mode_solver_boundaries = mms._solver_grid.boundaries.to_list
mode_plane_analyzer = ModePlaneAnalyzer(
center=mode_center,
size=mode_size,
field_data_colocated=False,
)
mode_plane_limits = mode_plane_analyzer._get_mode_limits(sim.grid, sim.symmetry)
for dim in (0, 1):
solver_dim_boundaries = mode_solver_boundaries[dim]
# TODO: Need the second check because the mode solver erroneously adds
# an extra grid cell even when touching the simulation boundary
assert (
solver_dim_boundaries[0] == mode_plane_limits[0][dim]
or mode_plane_limits[0][dim] == sim.bounds[0][dim]
)
assert (
solver_dim_boundaries[-1] == mode_plane_limits[1][dim]
or mode_plane_limits[1][dim] == sim.bounds[1][dim]
)
def test_impedance_spec_validation():
"""Check that the various allowed methods for supplying path specifications are validated."""
_ = td.AutoImpedanceSpec()
v_spec = td.AxisAlignedVoltageIntegralSpec(center=(1, 2, 3), size=(0, 0, 1), sign="-")
i_spec = td.AxisAlignedCurrentIntegralSpec(center=(1, 2, 3), size=(0, 1, 1), sign="-")
# All valid methods
both = td.CustomImpedanceSpec(voltage_spec=v_spec, current_spec=i_spec)
voltage_only = td.CustomImpedanceSpec(
voltage_spec=v_spec,
)
current_only = td.CustomImpedanceSpec(
current_spec=i_spec,
)
# Invalid
with pytest.raises(pd.ValidationError):
_ = td.CustomImpedanceSpec(voltage_spec=None, current_spec=None)
_ = td.MicrowaveModeSpec(num_modes=4, impedance_specs=(both, voltage_only, current_only, None))
def test_path_integral_factory_voltage_validation():
"""Test make_voltage_integral validation and error handling."""
# Valid voltage specs
axis_aligned_spec = td.AxisAlignedVoltageIntegralSpec(
center=(1, 2, 3), size=(0, 0, 1), sign="-"
)
custom_2d_spec = td.Custom2DVoltageIntegralSpec(vertices=[(0, 1), (0, 4)], axis=1, position=2)
# Test successful creation with axis-aligned spec
voltage_integral = make_voltage_integral(axis_aligned_spec)
assert voltage_integral is not None
assert voltage_integral.center == (1, 2, 3)
assert voltage_integral.size == (0, 0, 1)
# Test successful creation with custom 2D spec
voltage_integral = make_voltage_integral(custom_2d_spec)
assert voltage_integral is not None
assert voltage_integral.axis == 1
assert voltage_integral.position == 2
# Test ValidationError with unsupported type
class UnsupportedVoltageSpec:
def dict(self, exclude=None):
return {}
with pytest.raises(ValidationError, match="Unsupported voltage path specification type"):
make_voltage_integral(UnsupportedVoltageSpec())
def test_path_integral_factory_current_validation():
"""Test make_current_integral validation and error handling."""
# Valid current specs
axis_aligned_spec = td.AxisAlignedCurrentIntegralSpec(
center=(1, 2, 3), size=(0, 1, 1), sign="-"
)