File: objective.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 (533 lines) | stat: -rw-r--r-- 19,042 bytes parent folder | download | duplicates (3)
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
"""Handling of objective functions and objective quantities."""
import abc
from collections import namedtuple
from typing import Callable, List, Optional

import numpy as np
from meep.simulation import py_v3_to_vec, FluxData, NearToFarData

import meep as mp

from .filter_source import FilteredSource

Grid = namedtuple("Grid", ["x", "y", "z", "w"])


class ObjectiveQuantity(abc.ABC):
    """A differentiable objective quantity.

    Attributes:
        sim: the Meep simulation object with which the objective quantity is registered.
        frequencies: the frequencies at which the objective quantity is evaluated.
        num_freq: the number of frequencies at which the objective quantity is evaluated.
    """

    def __init__(self, sim):
        self.sim = sim
        self._eval = None
        self._frequencies = None

    @property
    def frequencies(self):
        return self._frequencies

    @property
    def num_freq(self):
        return len(self.frequencies)

    @abc.abstractmethod
    def __call__(self):
        """Evaluates the objective quantity."""

    @abc.abstractmethod
    def register_monitors(self, frequencies):
        """Registers monitors in the forward simulation."""

    @abc.abstractmethod
    def place_adjoint_source(self, dJ):
        """Places appropriate sources for the adjoint simulation."""

    def get_evaluation(self):
        """Evaluates the objective quantity."""
        if self._eval is not None:
            return self._eval
        else:
            raise RuntimeError(
                "You must first run a forward simulation before requesting the evaluation of an objective quantity."
            )

    def _adj_src_scale(self, include_resolution=True):
        """Calculates the scale for the adjoint sources."""
        T = self.sim.meep_time()
        dt = self.sim.fields.dt
        src = self._create_time_profile()

        if include_resolution:
            num_dims = self.sim._infer_dimensions(self.sim.k_point)
            dV = 1 / self.sim.resolution**num_dims
        else:
            dV = 1

        iomega = (1.0 - np.exp(-1j * (2 * np.pi * self._frequencies) * dt)) * (
            1.0 / dt
        )  # scaled frequency factor with discrete time derivative fix

        # an ugly way to calcuate the scaled dtft of the forward source
        y = np.array(
            [src.swigobj.current(t, dt) for t in np.arange(0, T, dt)]
        )  # time domain signal
        fwd_dtft = (
            np.matmul(
                np.exp(
                    1j
                    * 2
                    * np.pi
                    * self._frequencies[:, np.newaxis]
                    * np.arange(y.size)
                    * dt
                ),
                y,
            )
            * dt
            / np.sqrt(2 * np.pi)
        )  # dtft

        # Interestingly, the real parts of the DTFT and fourier transform match, but the imaginary parts are very different...
        # fwd_dtft = src.fourier_transform(src.frequency)
        """
        For some reason, there seems to be an additional phase
        factor at the center frequency that needs to be applied
        to *all* frequencies...
        """
        src_center_dtft = (
            np.matmul(
                np.exp(
                    1j
                    * 2
                    * np.pi
                    * np.array([src.frequency])[:, np.newaxis]
                    * np.arange(y.size)
                    * dt
                ),
                y,
            )
            * dt
            / np.sqrt(2 * np.pi)
        )
        adj_src_phase = np.exp(1j * np.angle(src_center_dtft)) * self.fwidth_scale

        if self._frequencies.size == 1:
            # Single frequency simulations. We need to drive it with a time profile.
            scale = dV * iomega / fwd_dtft / adj_src_phase  # final scale factor
        else:
            # multi frequency simulations
            scale = dV * iomega / adj_src_phase
        # compensate for the fact that real fields take the real part of the current,
        # which halves the Fourier amplitude at the positive frequency (Re[J] = (J + J*)/2)
        if self.sim.using_real_fields():
            scale *= 2
        return scale

    def _create_time_profile(self, fwidth_frac=0.1, adj_cutoff=5):
        """Creates a time domain waveform for normalizing the adjoint source(s).

        For single frequency objective functions, we should generate a guassian pulse with a reasonable
        bandwidth centered at said frequency.

        TODO:
        The user may specify a scalar valued objective function across multiple frequencies (e.g. MSE) in
        which case we should check that all the frequencies fit in the specified bandwidth.
        """
        self.fwidth_scale = np.exp(-2j * np.pi * adj_cutoff / fwidth_frac)
        return mp.GaussianSource(
            np.mean(self._frequencies),
            fwidth=fwidth_frac * np.mean(self._frequencies),
            cutoff=adj_cutoff,
        )


class EigenmodeCoefficient(ObjectiveQuantity):
    """A frequency-dependent eigenmode coefficient.
    Attributes:
        volume: the volume over which the eigenmode coefficient is calculated.
        mode: the eigenmode number.
        forward: whether the forward or backward mode coefficient is returned as
          the result of the evaluation.
        kpoint_func: an optional k-point function to use when evaluating the eigenmode
          coefficient. When specified, this overrides the effect of `forward`.
        kpoint_func_overlap_idx: the index of the mode coefficient to return when
          specifying `kpoint_func`. When specified, this overrides the effect of
          `forward` and should have a value of either 0 or 1.
        subtracted_dft_fields: the DFT fields obtained using `get_flux_data` from
          a previous normalization run. This is subtracted from the DFT fields
          of this mode monitor in order to improve the accuracy of the
          reflectance measurement (i.e., the $S_{11}$ scattering parameter).
          Default is None.
    """

    def __init__(
        self,
        sim: mp.Simulation,
        volume: mp.Volume,
        mode: int,
        forward: Optional[bool] = True,
        kpoint_func: Optional[Callable] = None,
        kpoint_func_overlap_idx: Optional[int] = 0,
        decimation_factor: Optional[int] = 0,
        subtracted_dft_fields: Optional[FluxData] = None,
        **kwargs
    ):
        """
        + **`sim` [ `Simulation` ]** —
        """
        super().__init__(sim)
        if kpoint_func_overlap_idx not in [0, 1]:
            raise ValueError(
                "`kpoint_func_overlap_idx` should be either 0 or 1, but got %d"
                % (kpoint_func_overlap_idx,)
            )
        self.volume = volume
        self.mode = mode
        self.forward = forward
        self.kpoint_func = kpoint_func
        self.kpoint_func_overlap_idx = kpoint_func_overlap_idx
        self.eigenmode_kwargs = kwargs
        self._monitor = None
        self._cscale = None
        self.decimation_factor = decimation_factor
        self.subtracted_dft_fields = subtracted_dft_fields

    def register_monitors(self, frequencies):
        self._frequencies = np.asarray(frequencies)
        self._monitor = self.sim.add_mode_monitor(
            frequencies,
            mp.ModeRegion(center=self.volume.center, size=self.volume.size),
            yee_grid=True,
            decimation_factor=self.decimation_factor,
        )
        if self.subtracted_dft_fields is not None:
            self.sim.load_minus_flux_data(
                self._monitor,
                self.subtracted_dft_fields,
            )
        return self._monitor

    def place_adjoint_source(self, dJ):
        dJ = np.atleast_1d(dJ)
        if dJ.ndim == 2:
            dJ = np.sum(dJ, axis=1)
        time_src = self._create_time_profile()
        da_dE = 0.5 * self._cscale
        scale = self._adj_src_scale()

        if self.kpoint_func:
            eig_kpoint = -1 * self.kpoint_func(time_src.frequency, self.mode)
        else:
            center_frequency = 0.5 * (
                np.min(self.frequencies) + np.max(self.frequencies)
            )
            direction = mp.Vector3(
                *(np.eye(3)[self._monitor.normal_direction] * np.abs(center_frequency))
            )
            eig_kpoint = -1 * direction if self.forward else direction

        if self._frequencies.size == 1:
            amp = da_dE * dJ * scale
            src = time_src
        else:
            scale = da_dE * dJ * scale
            src = FilteredSource(
                time_src.frequency,
                self._frequencies,
                scale,
                self.sim.fields.dt,
            )
            amp = 1
        source = mp.EigenModeSource(
            src,
            eig_band=self.mode,
            direction=mp.NO_DIRECTION,
            eig_kpoint=eig_kpoint,
            amplitude=amp,
            eig_match_freq=True,
            size=self.volume.size,
            center=self.volume.center,
            **self.eigenmode_kwargs,
        )
        return [source]

    def __call__(self):
        if self.kpoint_func:
            kpoint_func = self.kpoint_func
            overlap_idx = self.kpoint_func_overlap_idx
        else:
            center_frequency = 0.5 * (
                np.min(self.frequencies) + np.max(self.frequencies)
            )
            kpoint = mp.Vector3(
                *(np.eye(3)[self._monitor.normal_direction] * np.abs(center_frequency))
            )
            kpoint_func = lambda *not_used: kpoint if self.forward else -1 * kpoint
            overlap_idx = 0
        ob = self.sim.get_eigenmode_coefficients(
            self._monitor,
            [self.mode],
            direction=mp.NO_DIRECTION,
            kpoint_func=kpoint_func,
            **self.eigenmode_kwargs,
        )
        overlaps = ob.alpha.squeeze(axis=0)
        assert overlaps.ndim == 2
        self._eval = overlaps[:, overlap_idx]
        self._cscale = ob.cscale
        return self._eval


class FourierFields(ObjectiveQuantity):
    def __init__(
        self,
        sim: mp.Simulation,
        volume: mp.Volume,
        component: List[int],
        yee_grid: Optional[bool] = False,
        decimation_factor: Optional[int] = 0,
        subtracted_dft_fields: Optional[FluxData] = None,
    ):
        """ """
        super().__init__(sim)
        self.volume = sim._fit_volume_to_simulation(volume)
        self.component = component
        self.yee_grid = yee_grid
        self.decimation_factor = decimation_factor
        self.subtracted_dft_fields = subtracted_dft_fields

    def register_monitors(self, frequencies):
        self._frequencies = np.asarray(frequencies)
        self._monitor = self.sim.add_dft_fields(
            [self.component],
            self._frequencies,
            where=self.volume,
            yee_grid=self.yee_grid,
            decimation_factor=self.decimation_factor,
        )
        if self.subtracted_dft_fields is not None:
            self.sim.load_minus_flux_data(
                self._monitor,
                self.subtracted_dft_fields,
            )
        return self._monitor

    def place_adjoint_source(self, dJ):
        time_src = self._create_time_profile()
        sources = []

        mon_size = self.sim.fields.dft_monitor_size(
            self._monitor.swigobj, self.volume.swigobj, self.component
        )
        dJ = dJ.astype(np.complex128)
        if (
            np.prod(mon_size) * self.num_freq != dJ.size
            and np.prod(mon_size) * self.num_freq**2 != dJ.size
        ):
            raise ValueError("The format of J is incorrect!")

        # The objective function J is a vector. Each component corresponds to a frequency.
        if np.prod(mon_size) * self.num_freq**2 == dJ.size and self.num_freq > 1:
            dJ = np.sum(dJ, axis=1)
        """The adjoint solver requires the objective function
        to be scalar valued with regard to objective arguments
        and position, but the function may be vector valued
        with regard to frequency. In this case, the Jacobian
        will be of the form [F,F,...] where F is the number of
        frequencies. Because of linearity, we can sum across the
        second frequency dimension to calculate a frequency
        scale factor for each point (rather than a scale vector).
        """

        self.all_fouriersrcdata = self._monitor.swigobj.fourier_sourcedata(
            self.volume.swigobj, self.component, self.sim.fields, dJ
        )

        for fourier_data in self.all_fouriersrcdata:
            amp_arr = np.array(fourier_data.amp_arr).reshape(-1, self.num_freq)
            scale = amp_arr * self._adj_src_scale(include_resolution=False)

            if self.num_freq == 1:
                sources += [
                    mp.IndexedSource(
                        time_src, fourier_data, scale[:, 0], not self.yee_grid
                    )
                ]
            else:
                src = FilteredSource(
                    time_src.frequency, self._frequencies, scale, self.sim.fields.dt
                )
                (num_basis, num_pts) = src.nodes.shape
                for basis_i in range(num_basis):
                    sources += [
                        mp.IndexedSource(
                            src.time_src_bf[basis_i],
                            fourier_data,
                            src.nodes[basis_i],
                            not self.yee_grid,
                        )
                    ]
        return sources

    def __call__(self):
        self._eval = np.array(
            [
                self.sim.get_dft_array(self._monitor, self.component, i)
                for i in range(self.num_freq)
            ]
        )
        return self._eval


class Near2FarFields(ObjectiveQuantity):
    def __init__(
        self,
        sim: mp.Simulation,
        Near2FarRegions: List[mp.Near2FarRegion],
        far_pts: List[mp.Vector3],
        decimation_factor: Optional[int] = 0,
        norm_near_fields: Optional[NearToFarData] = None,
    ):
        """ """
        super().__init__(sim)
        self.Near2FarRegions = Near2FarRegions
        self.far_pts = far_pts  # list of far pts
        self._nfar_pts = len(far_pts)
        self.decimation_factor = decimation_factor
        self.norm_near_fields = norm_near_fields

    def register_monitors(self, frequencies):
        self._frequencies = np.asarray(frequencies)
        self._monitor = self.sim.add_near2far(
            self._frequencies,
            *self.Near2FarRegions,
            decimation_factor=self.decimation_factor,
        )
        if self.norm_near_fields is not None:
            self.sim.load_minus_near2far_data(
                self._monitor,
                self.norm_near_fields,
            )
        return self._monitor

    def place_adjoint_source(self, dJ):
        time_src = self._create_time_profile()
        sources = []
        if dJ.ndim == 4:
            dJ = np.sum(dJ, axis=0)

        farpt_list = np.array([list(pi) for pi in self.far_pts]).flatten()
        far_pt0 = self.far_pts[0]
        far_pt_vec = py_v3_to_vec(
            self.sim.dimensions,
            far_pt0,
            self.sim.is_cylindrical,
        )

        all_nearsrcdata = self._monitor.swigobj.near_sourcedata(
            far_pt_vec, farpt_list, self._nfar_pts, dJ
        )
        for near_data in all_nearsrcdata:
            cur_comp = near_data.near_fd_comp
            amp_arr = np.array(near_data.amp_arr).reshape(-1, self.num_freq)
            scale = amp_arr * self._adj_src_scale(include_resolution=False)

            if self.num_freq == 1:
                sources += [mp.IndexedSource(time_src, near_data, scale[:, 0])]
            else:
                src = FilteredSource(
                    time_src.frequency,
                    self._frequencies,
                    scale,
                    self.sim.fields.dt,
                )
                (num_basis, num_pts) = src.nodes.shape
                for basis_i in range(num_basis):
                    sources += [
                        mp.IndexedSource(
                            src.time_src_bf[basis_i],
                            near_data,
                            src.nodes[basis_i],
                        )
                    ]
        return sources

    def __call__(self):
        self._eval = np.array(
            [self.sim.get_farfield(self._monitor, far_pt) for far_pt in self.far_pts]
        ).reshape((self._nfar_pts, self.num_freq, 6))
        return self._eval


class LDOS(ObjectiveQuantity):
    def __init__(
        self, sim: mp.Simulation, decimation_factor: Optional[int] = 0, **kwargs
    ):
        """ """
        super().__init__(sim)
        self.decimation_factor = decimation_factor
        self.srckwarg = kwargs

    def register_monitors(self, frequencies):
        self._frequencies = np.asarray(frequencies)
        self.forward_src = self.sim.sources
        return

    def place_adjoint_source(self, dJ):
        time_src = self._create_time_profile()
        if dJ.ndim == 2:
            dJ = np.sum(dJ, axis=1)
        dJ = dJ.flatten()
        sources = []
        forward_f_scale = np.array(
            [self.ldos_scale / self.ldos_Jdata[k] for k in range(self.num_freq)]
        )
        if self._frequencies.size == 1:
            amp = (dJ * self._adj_src_scale(False) * forward_f_scale)[0]
            src = time_src
        else:
            scale = dJ * self._adj_src_scale(False) * forward_f_scale
            src = FilteredSource(
                time_src.frequency,
                self._frequencies,
                scale,
                self.sim.fields.dt,
            )
            amp = 1
        for forward_src_i in self.forward_src:
            if isinstance(forward_src_i, mp.EigenModeSource):
                src_i = mp.EigenModeSource(
                    src,
                    component=forward_src_i.component,
                    eig_kpoint=forward_src_i.eig_kpoint,
                    amplitude=amp,
                    eig_band=forward_src_i.eig_band,
                    size=forward_src_i.size,
                    center=forward_src_i.center,
                    **self.srckwarg,
                )
            else:
                src_i = mp.Source(
                    src,
                    component=forward_src_i.component,
                    amplitude=amp,
                    size=forward_src_i.size,
                    center=forward_src_i.center,
                    **self.srckwarg,
                )
            if mp.is_electric(src_i.component):
                src_i.amplitude *= -1
            sources += [src_i]

        return sources

    def __call__(self):
        self._eval = self.sim.ldos_data
        self.ldos_scale = self.sim.ldos_scale
        self.ldos_Jdata = self.sim.ldos_Jdata
        return np.array(self._eval)