-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathtest_autograd.py
2152 lines (1675 loc) · 70.4 KB
/
test_autograd.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
# test autograd integration into tidy3d
import copy
import cProfile
import typing
import warnings
from importlib import reload
from os.path import join
import autograd as ag
import autograd.numpy as anp
import matplotlib.pylab as plt
import numpy as np
import numpy.testing as npt
import pytest
import tidy3d as td
import tidy3d.web as web
import xarray as xr
from autograd.test_util import check_grads
from tidy3d.components.autograd.derivative_utils import DerivativeInfo
from tidy3d.components.autograd.utils import is_tidy_box
from tidy3d.components.data.data_array import DataArray
from tidy3d.exceptions import AdjointError
from tidy3d.plugins.polyslab import ComplexPolySlab
from tidy3d.web import run, run_async
from tidy3d.web.api.autograd.autograd import MAX_NUM_TRACED_STRUCTURES
from tidy3d.web.api.autograd.utils import FieldMap
from ..utils import SIM_FULL, AssertLogLevel, run_emulated, tracer_arr
""" Test configuration """
"""Test modes
pipeline: just run with emulated data, make sure gradient is not 0.0
adjoint: run pipeline with real data through web API
numerical: adjoint with an extra numerical derivative test after
speed: pipeline with cProfile to analyze performance
"""
# make it faster to toggle this
TEST_CUSTOM_MEDIUM_SPEED = False
TEST_POLYSLAB_SPEED = False
# whether to run numerical gradient tests, off by default because it runs real simulations
RUN_NUMERICAL = False
_NUMERICAL_COMBINATION = ("polyslab", "mode")
TEST_MODES = ("pipeline", "adjoint", "speed")
TEST_MODE = "speed" if TEST_POLYSLAB_SPEED else "pipeline"
# number of elements in the parameters / input to the objective function
N_PARAMS = 10
# default starting args
np.random.seed(1)
params0 = np.random.random(N_PARAMS) - 0.5
params0 /= np.linalg.norm(params0)
# whether to plot the simulation within the objective function
PLOT_SIM = False
# whether to include a call to `objective(params)` in addition to gradient
CALL_OBJECTIVE = False
""" simulation configuration """
WVL = 1.0
FREQ0 = td.C_0 / WVL
FREQS = [FREQ0]
FWIDTH = FREQ0 / 10
# sim sizes
LZ = 7.0 * WVL
IS_3D = False
POLYSLAB_AXIS = 2
# angle of the measurement waveguide
ROT_ANGLE_WG = 0 * np.pi / 4
# position of output mode monitor
MODE_FIELD_SPC = 0.75
MODE_FLD_MNT_SPC = MODE_FIELD_SPC * WVL
LX = 3.5 * WVL if IS_3D else 0.0
PML_X = True if IS_3D else False
# shape of the custom medium
DA_SHAPE_X = 1 if IS_3D else 1
DA_SHAPE = (DA_SHAPE_X, 1_000, 1_000) if TEST_CUSTOM_MEDIUM_SPEED else (DA_SHAPE_X, 12, 12)
# number of vertices in the polyslab
NUM_VERTICES = 100_000 if TEST_POLYSLAB_SPEED else 25
PNT_DIPOLE = td.PointDipole(
center=(0, 0, -LZ / 2 + WVL),
polarization="Ey",
source_time=td.GaussianPulse(
freq0=FREQ0,
fwidth=FWIDTH,
amplitude=1.0,
),
)
PLANE_WAVE = td.PlaneWave(
center=(0, 0, -LZ / 2 + WVL),
size=(td.inf, td.inf, 0),
direction="+",
source_time=td.GaussianPulse(
freq0=FREQ0,
fwidth=FWIDTH,
amplitude=1.0,
),
pol_angle=0,
)
# sim that we add traced structures and monitors to
SIM_BASE = td.Simulation(
size=(LX, 3.15, LZ),
run_time=200 / FWIDTH,
sources=[PLANE_WAVE],
structures=[
td.Structure(
geometry=td.Box(
size=(0.5, 0.5, LZ / 2),
center=(0, 0, 0),
)
.rotated(ROT_ANGLE_WG, axis=0)
.translated(x=0, y=-np.tan(ROT_ANGLE_WG) * MODE_FIELD_SPC, z=LZ / 2),
medium=td.Medium(permittivity=2.0),
)
],
monitors=[
td.FieldMonitor(
center=(0, 0, 0),
size=(0, 0, 0),
freqs=[FREQ0],
name="extraneous",
)
],
boundary_spec=td.BoundarySpec.pml(x=PML_X, y=True, z=True),
grid_spec=td.GridSpec.uniform(dl=0.01 * td.C_0 / FREQ0),
)
# variable to store whether the emulated run as used
_run_was_emulated = [False]
@pytest.fixture
def use_emulated_run(monkeypatch):
"""If this fixture is used, the `tests.utils.run_emulated` function is used for simulation."""
import tidy3d
if TEST_MODE in ("pipeline", "speed"):
task_name_fwd = "task_fwd"
AUX_KEY_SIM_FIELDS_KEYS = "sim_fields_keys"
cache = {}
import tidy3d.web.api.webapi as webapi
# reload(tidy3d.web.api.autograd.autograd)
from tidy3d.web.api.autograd.autograd import (
AUX_KEY_SIM_DATA_FWD,
AUX_KEY_SIM_DATA_ORIGINAL,
postprocess_adj,
postprocess_fwd,
)
def emulated_run_fwd(simulation, task_name, **run_kwargs) -> td.SimulationData:
"""What gets called instead of ``web/api/autograd/autograd.py::_run_tidy3d``."""
task_name_fwd = task_name
if run_kwargs.get("simulation_type") == "autograd_fwd":
sim_original = simulation
sim_fields_keys = run_kwargs["sim_fields_keys"]
# add gradient monitors and make combined simulation
sim_combined = sim_original.with_adjoint_monitors(sim_fields_keys)
sim_data_combined = run_emulated(sim_combined, task_name=task_name)
# store both original and fwd data aux_data
aux_data = {}
_ = postprocess_fwd(
sim_data_combined=sim_data_combined,
sim_original=sim_original,
aux_data=aux_data,
)
# cache original and fwd data locally for test
cache[task_name_fwd] = copy.copy(aux_data)
cache[task_name_fwd][AUX_KEY_SIM_FIELDS_KEYS] = sim_fields_keys
# return original data only
return aux_data[AUX_KEY_SIM_DATA_ORIGINAL], task_name_fwd
else:
return run_emulated(simulation, task_name=task_name), task_name_fwd
def emulated_run_bwd(simulation, task_name, **run_kwargs) -> td.SimulationData:
"""What gets called instead of ``web/api/autograd/autograd.py::_run_tidy3d_bwd``."""
task_name_fwd = "".join(task_name.partition("_adjoint")[:-2])
# run the adjoint sim
sim_data_adj = run_emulated(simulation, task_name="task_name")
# grab the fwd and original data from the cache
aux_data_fwd = cache[task_name_fwd]
sim_data_orig = aux_data_fwd[AUX_KEY_SIM_DATA_ORIGINAL]
sim_data_fwd = aux_data_fwd[AUX_KEY_SIM_DATA_FWD]
# get the original traced fields
sim_fields_keys = cache[task_name_fwd][AUX_KEY_SIM_FIELDS_KEYS]
# postprocess (compute adjoint gradients)
traced_fields_vjp = postprocess_adj(
sim_data_adj=sim_data_adj,
sim_data_orig=sim_data_orig,
sim_data_fwd=sim_data_fwd,
sim_fields_keys=sim_fields_keys,
)
return traced_fields_vjp
def emulated_run_async_fwd(simulations, **run_kwargs) -> td.SimulationData:
batch_data_orig, task_ids_fwd = {}, {}
sim_fields_keys_dict = run_kwargs.pop("sim_fields_keys_dict", None)
for task_name, simulation in simulations.items():
if sim_fields_keys_dict is not None:
run_kwargs["sim_fields_keys"] = sim_fields_keys_dict[task_name]
sim_data_orig, task_name_fwd = emulated_run_fwd(simulation, task_name, **run_kwargs)
batch_data_orig[task_name] = sim_data_orig
task_ids_fwd[task_name] = task_name_fwd
class EmulatedBatchData(web.BatchData):
def load_sim_data(self, task_name):
return batch_data_orig[task_name]
task_paths = {task_name: "" for task_name in simulations.keys()}
batch_data = EmulatedBatchData(
task_paths=task_paths,
task_ids=task_ids_fwd,
verbose=False,
)
return batch_data, task_ids_fwd
def emulated_run_async_bwd(simulations, **run_kwargs) -> td.SimulationData:
vjp_dict = {}
for task_name, simulation in simulations.items():
vjp_dict[task_name] = emulated_run_bwd(simulation, task_name, **run_kwargs)
return vjp_dict
monkeypatch.setattr(webapi, "run", run_emulated)
monkeypatch.setattr(tidy3d.web.api.autograd.autograd, "_run_tidy3d", emulated_run_fwd)
monkeypatch.setattr(
tidy3d.web.api.autograd.autograd, "_run_async_tidy3d", emulated_run_async_fwd
)
monkeypatch.setattr(
tidy3d.web.api.autograd.autograd, "_run_async_tidy3d_bwd", emulated_run_async_bwd
)
_run_was_emulated[0] = True
return emulated_run_fwd, emulated_run_bwd
def make_structures(params: anp.ndarray) -> dict[str, td.Structure]:
"""Make a dictionary of the structures given the parameters."""
np.random.seed(0)
vector = np.random.random(N_PARAMS) - 0.5
vector = vector / np.linalg.norm(vector)
# static components
box = td.Box(center=(0, 0, 0), size=(1, 1, 1))
med = td.Medium(permittivity=3.0)
# Structure with variable .medium
eps = 1 + anp.abs(vector @ params)
sigma = 0.1 * (anp.tanh(vector @ params) + 1)
permittivity, conductivity = eps, sigma
medium = td.Structure(
geometry=box,
medium=td.Medium(permittivity=permittivity, conductivity=conductivity),
)
# Structure with variable Box.center
matrix = np.random.random((3, N_PARAMS)) - 0.5
matrix /= np.linalg.norm(matrix)
center = anp.tanh(matrix @ params)
x0, y0, z0 = center
center_list = td.Structure(
geometry=td.Box(center=(x0, y0, z0), size=(1, 1, 1)),
medium=med,
)
# Structure with variable Box.center
size_y = anp.abs(vector @ params)
size_element = td.Structure(
geometry=td.Box(center=(0, 0, 0), size=(1, size_y, 1)),
medium=med,
background_medium=td.Medium(permittivity=5.0),
)
# custom medium with variable permittivity data
len_arr = np.prod(DA_SHAPE)
matrix = np.random.random((len_arr, N_PARAMS))
# matrix /= np.linalg.norm(matrix)
eps_arr = 1.01 + 0.5 * (anp.tanh(matrix @ params).reshape(DA_SHAPE) + 1)
nx, ny, nz = eps_arr.shape
custom_med = td.Structure(
geometry=box,
medium=td.CustomMedium(
permittivity=td.SpatialDataArray(
eps_arr,
coords=dict(
x=np.linspace(-0.5, 0.5, nx),
y=np.linspace(-0.5, 0.5, ny),
z=np.linspace(-0.5, 0.5, nz),
),
),
),
)
# custom medium with vector valued permittivity data
eps_ii = td.ScalarFieldDataArray(
eps_arr.reshape(nx, ny, nz, 1),
coords=dict(
x=np.linspace(-0.5, 0.5, nx),
y=np.linspace(-0.5, 0.5, ny),
z=np.linspace(-0.5, 0.5, nz),
f=[td.C_0],
),
)
custom_med_vec = td.Structure(
geometry=box,
medium=td.CustomMedium(
eps_dataset=td.PermittivityDataset(eps_xx=eps_ii, eps_yy=eps_ii, eps_zz=eps_ii)
),
)
# Polyslab with variable radius about origin
# matrix = np.random.random((NUM_VERTICES, N_PARAMS)) - 0.5
# params_01 = 0.5 * (anp.tanh(matrix @ params / 3) + 1)
matrix = np.random.random((N_PARAMS,)) - 0.5
params_01 = 0.5 * (anp.tanh(matrix @ params / 3) + 1)
free_param = "vertices" if POLYSLAB_AXIS == 0 else "slab_bounds"
if free_param == "vertices":
radii = 0.5 + 0.5 * params_01
slab_bounds = (-0.5, 0.5)
elif free_param == "slab_bounds":
radii = 1.0
shift = 0.1 * params_01
slab_bounds = (-0.5 + shift, 0.5 + shift)
# slab_bounds = (-0.5 + shift, 0.5)
# slab_bounds = (-0.5, 0.5 + shift)
phis = 2 * anp.pi * anp.linspace(0, 1, NUM_VERTICES + 1)[:NUM_VERTICES]
xs = radii * anp.cos(phis)
ys = radii * anp.sin(phis)
vertices = anp.stack((xs, ys), axis=-1)
polyslab = td.Structure(
geometry=td.PolySlab(
vertices=vertices,
slab_bounds=slab_bounds,
axis=POLYSLAB_AXIS,
sidewall_angle=0.00,
dilation=0.00,
),
medium=med,
)
polyslab_dispersive = td.Structure(
geometry=td.PolySlab(
vertices=vertices,
slab_bounds=slab_bounds,
axis=POLYSLAB_AXIS,
sidewall_angle=0.00,
dilation=0.00,
),
medium=td.material_library["Si3N4"]["Philipp1973Sellmeier"],
)
# geometry group
geo_group = td.Structure(
geometry=td.GeometryGroup(
geometries=[
medium.geometry,
center_list.geometry,
size_element.geometry,
],
),
medium=td.Medium(permittivity=eps, conductivity=conductivity),
)
# complex polyslab
polyslab_combined = ComplexPolySlab(
vertices=(
(-eps, 0),
(-eps, eps),
(0, eps / 10),
(eps, eps),
(eps, 0),
),
slab_bounds=(-0.5, 0.5),
axis=1,
sidewall_angle=np.pi / 100,
)
polyslab_geometries = []
for sub_polyslab in polyslab_combined.sub_polyslabs:
polyslab_geometries.append(sub_polyslab)
assert len(polyslab_geometries) >= 2, "need more polyslabs for a proper test of ComplexPolySlab"
complex_polyslab_geo_group = td.Structure(
geometry=td.GeometryGroup(geometries=polyslab_geometries),
medium=td.Medium(permittivity=eps, conductivity=conductivity),
)
# dispersive medium
eps_inf = 1 + anp.abs(vector @ params)
box = td.Box(center=(0, 0, 0), size=(1, 1, 1))
a0 = -FREQ0 * eps_inf + 1j * FREQ0 * eps_inf
c0 = FREQ0 * eps_inf + 1j * FREQ0 * eps_inf
a1 = -2 * FREQ0 * eps_inf + 1j * FREQ0 * eps_inf
c1 = 2 * FREQ0 * eps_inf + 1j * FREQ0 * eps_inf
med = td.PoleResidue(eps_inf=eps_inf, poles=[(a0, c0), (a1, c1)])
pole_res = td.Structure(geometry=box, medium=med)
# custom dispersive medium
len_arr = np.prod(DA_SHAPE)
matrix = np.random.random((len_arr, N_PARAMS))
matrix /= np.linalg.norm(matrix)
eps_arr = 1.01 + 0.5 * (anp.tanh(matrix @ params).reshape(DA_SHAPE) + 1)
custom_disp_values = 1.01 + (0.5 + 0.5j) * (anp.tanh(matrix @ params).reshape(DA_SHAPE) + 1)
nx, ny, nz = custom_disp_values.shape
x = np.linspace(-0.5, 0.5, nx)
y = np.linspace(-0.5, 0.5, ny)
z = np.linspace(-0.5, 0.5, nz)
coords = dict(x=x, y=y, z=z)
eps_inf = td.SpatialDataArray(anp.real(custom_disp_values), coords=coords)
a1 = td.SpatialDataArray(-custom_disp_values, coords=coords)
c1 = td.SpatialDataArray(custom_disp_values, coords=coords)
a2 = td.SpatialDataArray(-custom_disp_values, coords=coords)
c2 = td.SpatialDataArray(custom_disp_values, coords=coords)
custom_med_pole_res = td.CustomPoleResidue(eps_inf=eps_inf, poles=[(a1, c1), (a2, c2)])
custom_pole_res = td.Structure(geometry=box, medium=custom_med_pole_res)
radius = 0.4 * (1 + anp.abs(vector @ params))
cyl_center_y = vector @ params
cyl_center_z = -vector @ params
cylinder_geo = td.Cylinder(
radius=anp.mean(radii) * 0.5,
center=(0, cyl_center_y, cyl_center_z),
axis=0,
length=LX / 2 if IS_3D else td.inf,
)
cylinder = td.Structure(geometry=cylinder_geo, medium=polyslab.medium)
return dict(
medium=medium,
center_list=center_list,
size_element=size_element,
custom_med=custom_med,
custom_med_vec=custom_med_vec,
polyslab=polyslab,
polyslab_dispersive=polyslab_dispersive,
geo_group=geo_group,
complex_polyslab=complex_polyslab_geo_group,
pole_res=pole_res,
custom_pole_res=custom_pole_res,
cylinder=cylinder,
)
def make_monitors() -> dict[str, tuple[td.Monitor, typing.Callable[[td.SimulationData], float]]]:
"""Make a dictionary of all the possible monitors in the simulation."""
mode_mnt = td.ModeMonitor(
size=(2, 2, 0),
center=(0, 0, +LZ / 2 - MODE_FIELD_SPC),
mode_spec=td.ModeSpec(
angle_theta=ROT_ANGLE_WG,
angle_phi=3 * np.pi / 2,
),
freqs=[FREQ0],
name="mode",
)
def mode_postprocess_fn(sim_data, mnt_data):
return anp.sum(abs(mnt_data.amps.values) ** 2)
diff_mnt = td.DiffractionMonitor(
size=(td.inf, td.inf, 0),
center=(0, 0, +LZ / 2 - 2 * WVL),
freqs=[FREQ0],
normal_dir="+",
name="diff",
)
def diff_postprocess_fn(sim_data, mnt_data):
return anp.sum(abs(mnt_data.amps.sel(polarization=["s", "p"]).values) ** 2)
field_vol = td.FieldMonitor(
size=(1, 1, 0),
center=(0, 0, +LZ / 2 - MODE_FIELD_SPC),
freqs=[FREQ0],
name="field_vol",
)
def field_vol_postprocess_fn(sim_data, mnt_data):
value = 0.0
for _, val in mnt_data.field_components.items():
value = value + abs(anp.sum(val.values))
intensity = anp.nan_to_num(anp.sum(sim_data.get_intensity(mnt_data.monitor.name).values))
value += intensity
value += anp.sum(mnt_data.flux.values)
return value
field_point = td.FieldMonitor(
size=(0, 0, 0),
center=(0, 0, LZ / 2 - WVL),
freqs=[FREQ0],
name="field_point",
)
def field_point_postprocess_fn(sim_data, mnt_data):
value = 0.0
for _, val in mnt_data.field_components.items():
value += abs(anp.sum(abs(val.values)))
value += anp.sum(sim_data.get_intensity(mnt_data.monitor.name).values)
return value
return dict(
mode=(mode_mnt, mode_postprocess_fn),
diff=(diff_mnt, diff_postprocess_fn),
field_vol=(field_vol, field_vol_postprocess_fn),
field_point=(field_point, field_point_postprocess_fn),
)
def plot_sim(sim: td.Simulation, plot_eps: bool = True) -> None:
"""Plot the simulation."""
sim = sim.to_static()
plot_fn = sim.plot_eps if plot_eps else sim.plot
f, (ax1, ax2, ax3) = plt.subplots(1, 3, tight_layout=True)
plot_fn(x=0, ax=ax1)
plot_fn(y=0, ax=ax2)
plot_fn(z=0, ax=ax3)
plt.show()
# TODO: grab these automatically
structure_keys_ = (
"medium",
"center_list",
"size_element",
"custom_med",
"custom_med_vec",
"polyslab",
"complex_polyslab",
"geo_group",
"pole_res",
"custom_pole_res",
"cylinder",
)
monitor_keys_ = ("mode", "diff", "field_vol", "field_point")
# generate combos of all structures with each monitor and all monitors with each structure
ALL_KEY = "<ALL>"
args = []
for s in structure_keys_:
args.append((s, ALL_KEY))
for m in monitor_keys_:
args.append((ALL_KEY, m))
# or just set args manually to test certain things
if TEST_CUSTOM_MEDIUM_SPEED:
args = [("custom_med", "mode")]
if TEST_POLYSLAB_SPEED:
args = [("polyslab", "mode")]
# args = [("polyslab", "mode")]
def get_functions(structure_key: str, monitor_key: str) -> typing.Callable:
if structure_key == ALL_KEY:
structure_keys = structure_keys_
else:
structure_keys = [structure_key]
if monitor_key == ALL_KEY:
monitor_keys = monitor_keys_
else:
monitor_keys = [monitor_key]
monitor_dict = make_monitors()
monitors = list(SIM_BASE.monitors)
monitor_pp_fns = {}
for monitor_key in monitor_keys:
monitor_traced, monitor_pp_fn = monitor_dict[monitor_key]
monitors.append(monitor_traced)
monitor_pp_fns[monitor_key] = monitor_pp_fn
def make_sim(*args) -> td.Simulation:
"""Make the simulation with all of the fields."""
structures_traced_dict = make_structures(*args)
structures = list(SIM_BASE.structures)
for structure_key in structure_keys:
structures.append(structures_traced_dict[structure_key])
sim = SIM_BASE
if "diff" in monitor_keys:
sim = sim.updated_copy(boundary_spec=td.BoundarySpec.pml(x=False, y=False, z=True))
sim = sim.updated_copy(structures=structures, monitors=monitors)
return sim
def postprocess(data: td.SimulationData) -> float:
"""Postprocess the dataset."""
mnt_data = data[monitor_key]
return monitor_pp_fn(data, mnt_data)
return dict(sim=make_sim, postprocess=postprocess)
@pytest.mark.parametrize("axis", (0, 1, 2))
def test_polyslab_axis_ops(axis):
vertices = ((0, 0), (0, 1), (1, 1), (1, 0))
p = td.PolySlab(vertices=vertices, axis=axis, slab_bounds=(0, 1))
ax_coords = np.array([0, 1, 2, 3])
plane_coords = np.array([[4, 5], [6, 7], [8, 9], [10, 11]])
coord = p.unpop_axis_vect(ax_coords=ax_coords, plane_coords=plane_coords)
assert np.all(coord[:, axis] == ax_coords)
_ax_coords, _plane_coords = p.pop_axis_vect(coord=coord)
assert np.all(_ax_coords == ax_coords)
assert np.all(_plane_coords == plane_coords)
vertices_next = np.roll(vertices, axis=0, shift=-1)
edges = vertices_next - vertices
basis_vecs = p.edge_basis_vectors(edges=edges)
@pytest.mark.skipif(not RUN_NUMERICAL, reason="Numerical gradient tests runs through web API.")
@pytest.mark.parametrize("structure_key, monitor_key", (_NUMERICAL_COMBINATION,))
def test_autograd_numerical(structure_key, monitor_key):
"""Test an objective function through tidy3d autograd."""
import tidy3d.web as web
fn_dict = get_functions(structure_key, monitor_key)
make_sim = fn_dict["sim"]
postprocess = fn_dict["postprocess"]
def objective(*args):
"""Objective function."""
sim = make_sim(*args)
if PLOT_SIM:
plot_sim(sim, plot_eps=True)
data = web.run(sim, task_name="autograd_test_numerical", verbose=False, local_gradient=True)
value = postprocess(data)
return value
val, grad = ag.value_and_grad(objective)(params0)
print(val, grad)
assert anp.all(grad != 0.0), "some gradients are 0"
# numerical gradients
delta = 1e-1
sims_numerical = {}
params_num = np.zeros((N_PARAMS, N_PARAMS))
def task_name_fn(i: int, sign: int) -> str:
"""Task name for a given index into grad num and sign."""
pm_string = "+" if sign > 0 else "-"
return f"{i}_{pm_string}"
for i in range(N_PARAMS):
for j, sign in enumerate((-1, 1)):
task_name = task_name_fn(i, sign)
params_i = np.copy(params0)
params_i[i] += sign * delta
params_num[:, j] = params_i.copy()
sim_i = make_sim(params_i)
sims_numerical[task_name] = sim_i
datas = web.Batch(simulations=sims_numerical).run(path_dir="data")
grad_num = np.zeros_like(grad)
objectives_num = np.zeros((len(params0), 2))
for i in range(N_PARAMS):
for j, sign in enumerate((-1, 1)):
task_name = task_name_fn(i, sign)
sim_data_i = datas[task_name]
obj_i = postprocess(sim_data_i)
objectives_num[i, j] = obj_i
grad_num[i] += sign * obj_i / 2 / delta
print("adjoint: ", grad)
print("numerical: ", grad_num)
print(objectives_num)
grad_normalized = grad / np.linalg.norm(grad)
grad_num_normalized = grad_num / np.linalg.norm(grad_num)
rms_error = np.linalg.norm(grad_normalized - grad_num_normalized)
norm_factor = np.linalg.norm(grad) / np.linalg.norm(grad_num)
diff_objectives_num = np.mean(abs(np.diff(objectives_num, axis=-1)))
print(f"rms_error = {rms_error:.4f}")
print(f"|grad| / |grad_num| = {norm_factor:.4f}")
print(f"avg(diff(objectives)) = {diff_objectives_num:.4f}")
def test_run_zero_grad(use_emulated_run):
"""Test warning if no adjoint sim is run (no adjoint sources).
This checks the case where a simulation is still part of the computational
graph (i.e. the output technically depends on the simulation),
but no adjoint sources are placed because their amplitudes are zero and thus
no adjoint simulation is run.
"""
# only needs to be checked for one monitor
fn_dict = get_functions(args[0][0], args[0][1])
make_sim = fn_dict["sim"]
postprocess = fn_dict["postprocess"]
def objective(*args):
sim = make_sim(*args)
sim_data = run(sim, task_name="adjoint_test", verbose=False)
return 0 * postprocess(sim_data)
with AssertLogLevel("WARNING", contains_str="no sources"):
grad = ag.grad(objective)(params0)
@pytest.mark.parametrize("structure_key, monitor_key", args)
def test_autograd_objective(use_emulated_run, structure_key, monitor_key):
"""Test an objective function through tidy3d autograd."""
fn_dict = get_functions(structure_key, monitor_key)
make_sim = fn_dict["sim"]
postprocess = fn_dict["postprocess"]
def objective(*args):
"""Objective function."""
sim = make_sim(*args)
if PLOT_SIM:
plot_sim(sim, plot_eps=True)
data = run(sim, task_name="autograd_test", verbose=False)
value = postprocess(data)
return value
# if speed test, get the profile
if TEST_MODE == "speed":
with cProfile.Profile() as pr:
val, grad = ag.value_and_grad(objective)(params0)
pr.print_stats(sort="cumtime")
pr.dump_stats("results.prof")
# otherwise, just test that it ran and the gradients are all non-zero
else:
if CALL_OBJECTIVE:
val = objective(params0)
val, grad = ag.value_and_grad(objective)(params0)
print(val, grad)
assert anp.all(grad != 0.0), "some gradients are 0"
@pytest.mark.parametrize("structure_key, monitor_key", args)
def test_autograd_async(use_emulated_run, structure_key, monitor_key):
"""Test an objective function through tidy3d autograd."""
fn_dict = get_functions(structure_key, monitor_key)
make_sim = fn_dict["sim"]
postprocess = fn_dict["postprocess"]
task_names = {"test_a", "adjoint", "task1", "_test"}
def objective(*args):
sims = {task_name: make_sim(*args) for task_name in task_names}
batch_data = run_async(sims, verbose=False)
value = 0.0
for _, sim_data in batch_data.items():
value += postprocess(sim_data)
return value
val, grad = ag.value_and_grad(objective)(params0)
print(val, grad)
assert anp.all(grad != 0.0), "some gradients are 0"
class TestTupleGrads:
center0 = (0.0, 0.0, 0.0)
size0 = (0.5, 1.0, 1.5)
@staticmethod
def make_simulation(center: tuple, size: tuple) -> td.Simulation:
wavelength = 1.0
freq0 = td.C_0 / wavelength
src = td.PointDipole(
center=(-1.4, 0, 0),
source_time=td.GaussianPulse(freq0=freq0, fwidth=freq0 / 10),
polarization="Ex",
)
mnt = td.FieldMonitor(
size=(0, 0, 1),
center=(1.4, 0, 0),
freqs=[freq0, freq0 + freq0 / 50],
name="fields",
)
scatterer = td.Structure(
geometry=td.Box(center=center, size=size),
medium=td.Medium(permittivity=3.0),
)
return td.Simulation(
size=(3, 3, 3),
run_time=2e-13,
structures=[scatterer],
sources=[src],
monitors=[mnt],
boundary_spec=td.BoundarySpec.all_sides(td.PML()),
grid_spec=td.GridSpec.auto(min_steps_per_wvl=30),
)
@pytest.mark.parametrize("run_async", [False, True])
@pytest.mark.parametrize("zero", [False, True])
@pytest.mark.parametrize("local_gradient", [False, True])
def test_zero_grad_tuple(self, use_emulated_run, run_async, zero, local_gradient, tmp_path):
"""Checks that tuple gradients don't return empty tuples"""
def obj(center: tuple, size: tuple) -> float:
sim = self.make_simulation(center=center, size=size)
if run_async:
batch_data = web.run_async(
{"lossy_test_async": sim},
path_dir=tmp_path,
local_gradient=local_gradient,
)
sim_data = list(batch_data.values())[0]
else:
sim_data = web.run(
sim,
task_name="lossy_test",
local_gradient=local_gradient,
)
objval = anp.mean(sim_data["fields"].intensity.data).item()
if zero:
objval *= 0
return objval
d_power = ag.value_and_grad(obj, argnum=(0, 1))
val, (dp_dcenter, dp_dsize) = d_power(self.center0, self.size0)
assert len(dp_dcenter) == 3
assert len(dp_dsize) == 3
if zero:
assert np.allclose(dp_dcenter, 0)
assert np.allclose(dp_dsize, 0)
else:
assert not np.allclose(dp_dcenter, 0)
assert not np.allclose(dp_dsize, 0)
@pytest.mark.parametrize("structure_key, monitor_key", args)
def test_autograd_async_some_zero_grad(use_emulated_run, structure_key, monitor_key):
"""Test objective where only some simulations in batch have adjoint sources."""
fn_dict = get_functions(structure_key, monitor_key)
make_sim = fn_dict["sim"]
postprocess = fn_dict["postprocess"]
task_names = {"1", "2", "3", "4"}
def objective(*args):
sims = {task_name: make_sim(*args) for task_name in task_names}
batch_data = run_async(sims, verbose=False)
values = []
for _, sim_data in batch_data.items():
values.append(postprocess(sim_data))
return min(values)
val, grad = ag.value_and_grad(objective)(params0)
assert anp.all(grad != 0.0), "some gradients are 0"
def test_autograd_async_all_zero_grad(use_emulated_run):
"""Test objective where no simulation in batch has adjoint sources."""
fn_dict = get_functions(args[0][0], args[0][1])
make_sim = fn_dict["sim"]
postprocess = fn_dict["postprocess"]
task_names = {"1", "2", "3", "4"}
def objective(*args):
sims = {task_name: make_sim(*args) for task_name in task_names}
batch_data = run_async(sims, verbose=False)
values = []
for _, sim_data in batch_data.items():
values.append(postprocess(sim_data))
return 0 * sum(values)
with AssertLogLevel("WARNING", contains_str="contains adjoint sources"):
grad = ag.grad(objective)(params0)
def test_autograd_speed_num_structures(use_emulated_run):
"""Test an objective function through tidy3d autograd."""
num_structures_test = 10
import time
fn_dict = get_functions(ALL_KEY, ALL_KEY)
monitor_key = "mode"
structure_key = "size_element"
monitor, postprocess = make_monitors()[monitor_key]
def make_sim(*args):
structure = make_structures(*args)[structure_key]
structures = num_structures_test * [structure]
return SIM_BASE.updated_copy(structures=structures, monitors=[monitor])
def objective(*args):
"""Objective function."""
sim = make_sim(*args)
data = run(sim, task_name="autograd_test", verbose=False)
value = postprocess(data, data[monitor_key])
return value
# if speed test, get the profile
with cProfile.Profile() as pr:
t = time.time()
val, grad = ag.value_and_grad(objective)(params0)
t2 = time.time() - t
pr.print_stats(sort="cumtime")
pr.dump_stats("results.prof")
print(f"{num_structures_test} structures took {t2:.2e} seconds")
@pytest.mark.parametrize("monitor_key", ("mode",))
def test_autograd_polyslab_cylinder(use_emulated_run, monitor_key):
"""Test an objective function through tidy3d autograd."""
t0 = 1.0
axis = 0
num_pts = 819
monitor, postprocess = make_monitors()[monitor_key]
def make_cylinder(radius, x0, y0, t):
return td.Cylinder(
center=td.Cylinder.unpop_axis(0.0, (x0, y0), axis=axis),
radius=radius,
length=t,
axis=axis,