File: test_adjoint_jax.py

package info (click to toggle)
meep-openmpi 1.25.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 64,556 kB
  • sloc: cpp: 32,214; python: 27,958; lisp: 1,225; makefile: 505; sh: 249; ansic: 131; javascript: 5
file content (309 lines) | stat: -rw-r--r-- 9,008 bytes parent folder | download | duplicates (5)
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
import unittest

import jax
import jax.numpy as jnp
import meep.adjoint as mpa
import numpy as onp
import parameterized
from utils import ApproxComparisonTestCase

import meep as mp

# The calculation of finite-difference gradients
# requires that JAX be operated with double precision
jax.config.update("jax_enable_x64", True)

# The step size for the finite-difference
# gradient calculation
_FD_STEP = 1e-4

# The tolerance for the adjoint and finite-difference
# gradient comparison
_TOL = 0.1 if mp.is_single_precision() else 0.025

# We expect 3 design region monitor pointers
# (one for each field component)
_NUM_DES_REG_MON = 3

mp.verbosity(0)


def build_straight_wg_simulation(
    wg_width=0.5,
    wg_padding=1.0,
    wg_length=1.0,
    pml_width=1.0,
    source_to_pml=0.5,
    source_to_monitor=0.1,
    frequencies=[1 / 1.55],
    gaussian_rel_width=0.2,
    sim_resolution=20,
    design_region_resolution=20,
):
    """Builds a simulation of a straight waveguide with a design region segment."""
    design_region_shape = (1.0, wg_width)

    # Simulation domain size
    sx = 2 * pml_width + 2 * wg_length + design_region_shape[0]
    sy = (
        2 * pml_width
        + 2 * wg_padding
        + max(
            wg_width,
            design_region_shape[1],
        )
    )

    # Mean / center frequency
    fmean = onp.mean(frequencies)

    si = mp.Medium(index=3.4)
    sio2 = mp.Medium(index=1.44)

    sources = [
        mp.EigenModeSource(
            mp.GaussianSource(frequency=fmean, fwidth=fmean * gaussian_rel_width),
            eig_band=1,
            direction=mp.NO_DIRECTION,
            eig_kpoint=mp.Vector3(1, 0, 0),
            size=mp.Vector3(0, wg_width + 2 * wg_padding, 0),
            center=[-sx / 2 + pml_width + source_to_pml, 0, 0],
        ),
        mp.EigenModeSource(
            mp.GaussianSource(frequency=fmean, fwidth=fmean * gaussian_rel_width),
            eig_band=1,
            direction=mp.NO_DIRECTION,
            eig_kpoint=mp.Vector3(-1, 0, 0),
            size=mp.Vector3(0, wg_width + 2 * wg_padding, 0),
            center=[sx / 2 - pml_width - source_to_pml, 0, 0],
        ),
    ]
    nx, ny = int(design_region_shape[0] * design_region_resolution), int(
        design_region_shape[1] * design_region_resolution
    )
    mat_grid = mp.MaterialGrid(
        mp.Vector3(nx, ny),
        sio2,
        si,
        grid_type="U_DEFAULT",
    )

    design_regions = [
        mpa.DesignRegion(
            mat_grid,
            volume=mp.Volume(
                center=mp.Vector3(),
                size=mp.Vector3(
                    design_region_shape[0],
                    design_region_shape[1],
                    0,
                ),
            ),
        )
    ]

    geometry = [
        mp.Block(
            center=mp.Vector3(
                x=-design_region_shape[0] / 2 - wg_length / 2 - pml_width / 2
            ),
            material=si,
            size=mp.Vector3(wg_length + pml_width, wg_width, 0),
        ),  # left wg
        mp.Block(
            center=mp.Vector3(
                x=+design_region_shape[0] / 2 + wg_length / 2 + pml_width / 2
            ),
            material=si,
            size=mp.Vector3(wg_length + pml_width, wg_width, 0),
        ),  # right wg
        mp.Block(
            center=design_regions[0].center,
            size=design_regions[0].size,
            material=mat_grid,
        ),  # design region
    ]

    simulation = mp.Simulation(
        cell_size=mp.Vector3(sx, sy),
        boundary_layers=[mp.PML(pml_width)],
        geometry=geometry,
        sources=sources,
        resolution=sim_resolution,
    )

    monitor_centers = [
        mp.Vector3(-sx / 2 + pml_width + source_to_pml + source_to_monitor),
        mp.Vector3(sx / 2 - pml_width - source_to_pml - source_to_monitor),
    ]
    monitor_size = mp.Vector3(y=wg_width + 2 * wg_padding)

    monitors = [
        mpa.EigenmodeCoefficient(
            simulation,
            mp.Volume(center=center, size=monitor_size),
            mode=1,
            forward=forward,
        )
        for center in monitor_centers
        for forward in [True, False]
    ]
    return simulation, sources, monitors, design_regions, frequencies


class UtilsTest(unittest.TestCase):
    def setUp(self):
        super().setUp()
        (
            self.simulation,
            self.sources,
            self.monitors,
            self.design_regions,
            self.frequencies,
        ) = build_straight_wg_simulation()

    def test_mode_monitor_helpers(self):
        mpa.utils.register_monitors(self.monitors, self.frequencies)
        self.simulation.run(until=100)
        monitor_values = mpa.utils.gather_monitor_values(self.monitors)
        self.assertEqual(monitor_values.dtype, onp.complex128)
        self.assertEqual(
            monitor_values.shape, (len(self.monitors), len(self.frequencies))
        )

    def test_dist_dft_pointers(self):
        fwd_design_region_monitors = mpa.utils.install_design_region_monitors(
            self.simulation,
            self.design_regions,
            self.frequencies,
        )
        self.assertEqual(len(fwd_design_region_monitors[0]), _NUM_DES_REG_MON)


class WrapperTest(ApproxComparisonTestCase):
    @parameterized.parameterized.expand(
        [
            (
                "1500_1550bw_01relative_gaussian_port1",
                onp.linspace(1 / 1.50, 1 / 1.55, 3).tolist(),
                0.1,
                0.5,
                0,
            ),
            (
                "1550_1600bw_02relative_gaussian_port1",
                onp.linspace(1 / 1.55, 1 / 1.60, 3).tolist(),
                0.2,
                0.5,
                0,
            ),
            (
                "1500_1600bw_03relative_gaussian_port1",
                onp.linspace(1 / 1.50, 1 / 1.60, 4).tolist(),
                0.3,
                0.5,
                0,
            ),
            (
                "1500_1550bw_01relative_gaussian_port2",
                onp.linspace(1 / 1.50, 1 / 1.55, 3).tolist(),
                0.1,
                0.5,
                1,
            ),
            (
                "1550_1600bw_02relative_gaussian_port2",
                onp.linspace(1 / 1.55, 1 / 1.60, 3).tolist(),
                0.2,
                0.5,
                1,
            ),
            (
                "1500_1600bw_03relative_gaussian_port2",
                onp.linspace(1 / 1.50, 1 / 1.60, 4).tolist(),
                0.3,
                0.5,
                1,
            ),
        ]
    )
    def test_wrapper_gradients(
        self,
        _,
        frequencies,
        gaussian_rel_width,
        design_variable_fill_value,
        excite_port_idx,
    ):
        """Tests gradient from the JAX-Meep wrapper against finite differences."""
        (
            simulation,
            sources,
            monitors,
            design_regions,
            frequencies,
        ) = build_straight_wg_simulation(
            frequencies=frequencies, gaussian_rel_width=gaussian_rel_width
        )

        design_shape = tuple(
            int(i) for i in design_regions[0].design_parameters.grid_size
        )[:2]
        x = onp.ones(design_shape) * design_variable_fill_value

        # Define a loss function
        def loss_fn(x, excite_port_idx=0):
            wrapped_meep = mpa.MeepJaxWrapper(
                simulation,
                [sources[excite_port_idx]],
                monitors,
                design_regions,
                frequencies,
            )
            monitor_values = wrapped_meep([x])
            s1p, s1m, s2p, s2m = monitor_values
            t = s2p / s1p if excite_port_idx == 0 else s1m / s2m
            return jnp.mean(jnp.square(jnp.abs(t)))

        value, adjoint_grad = jax.value_and_grad(loss_fn)(
            x, excite_port_idx=excite_port_idx
        )

        projection = []
        fd_projection = []

        # Project along 5 random directions in the design parameter space.
        for seed in range(5):
            # Create dp
            random_perturbation_vector = _FD_STEP * jax.random.normal(
                jax.random.PRNGKey(seed),
                x.shape,
            )

            # Calculate p + dp
            x_perturbed = x + random_perturbation_vector

            # Calculate T(p + dp)
            value_perturbed = loss_fn(x_perturbed, excite_port_idx=excite_port_idx)

            projection.append(
                onp.dot(
                    random_perturbation_vector.ravel(),
                    adjoint_grad.ravel(),
                )
            )
            fd_projection.append(value_perturbed - value)

        projection = onp.stack(projection)
        fd_projection = onp.stack(fd_projection)

        # Check that dp . ∇T ~ T(p + dp) - T(p)
        self.assertClose(
            projection,
            fd_projection,
            epsilon=_TOL,
        )


if __name__ == "__main__":
    unittest.main()