Skip to content

Commit

Permalink
better error when flux monitor used in autograd
Browse files Browse the repository at this point in the history
  • Loading branch information
tylerflex committed Aug 26, 2024
1 parent 9fc8578 commit 1c76897
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `DataArray` interpolation failure due to incorrect ordering of coordinates when interpolating with autograd tracers.
- Error in `CustomSourceTime` when evaluating at a list of times entirely outside of the range of the envelope definition times.
- Improved passivity enforcement near high-Q poles in `FastDispersionFitter`. Failed passivity enforcement could lead to simulation divergences.
- More helpful error and suggestion if users try to differentiate w.r.t. unsupported `FluxMonitor` output.

## [2.7.2] - 2024-08-07

Expand Down
18 changes: 18 additions & 0 deletions tests/test_components/test_autograd.py
Original file line number Diff line number Diff line change
Expand Up @@ -1415,3 +1415,21 @@ def objective_multi(params, structure_key) -> float:

assert not np.any(np.isclose(grad_indi, 0))
assert not np.any(np.isclose(grad_multi, 0))


def test_error_flux(use_emulated_run, log_capture):
"""Make sure proper error raised if differentiating w.r.t. FluxData."""

def objective(params):
structure_traced = make_structures(params)["medium"]
sim = SIM_BASE.updated_copy(
structures=[structure_traced],
monitors=[td.FluxMonitor(size=(1, 1, 0), center=(0, 0, 0), freqs=[FREQ0], name="flux")],
)
data = run(sim, task_name="flux_error")
return anp.sum(data["flux"].flux.values)

with pytest.raises(
NotImplementedError, match="Could not formulate adjoint source for 'FluxMonitor' output"
):
g = ag.grad(objective)(params0)
8 changes: 8 additions & 0 deletions tests/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -1004,13 +1004,21 @@ def make_mode_data(monitor: td.ModeMonitor) -> td.ModeData:
grid_expanded=simulation.discretize_monitor(monitor),
)

def make_flux_data(monitor: td.FluxMonitor) -> td.FluxData:
"""make a random ModeData from a ModeMonitor."""

coords = dict(f=list(monitor.freqs))
flux = make_data(coords=coords, data_array_type=td.FluxDataArray, is_complex=False)
return td.FluxData(monitor=monitor, flux=flux)

MONITOR_MAKER_MAP = {
td.FieldMonitor: make_field_data,
td.FieldTimeMonitor: make_field_time_data,
td.ModeSolverMonitor: make_mode_solver_data,
td.ModeMonitor: make_mode_data,
td.PermittivityMonitor: make_eps_data,
td.DiffractionMonitor: make_diff_data,
td.FluxMonitor: make_flux_data,
}

data = [MONITOR_MAKER_MAP[type(mnt)](mnt) for mnt in simulation.monitors]
Expand Down
14 changes: 14 additions & 0 deletions tidy3d/components/data/monitor_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -1943,6 +1943,20 @@ class FluxData(MonitorData):
..., title="Flux", description="Flux values in the frequency-domain."
)

def make_adjoint_sources(
self, dataset_names: list[str], fwidth: float
) -> List[Union[CustomCurrentSource, PointDipole]]:
"""Converts a :class:`.FieldData` to a list of adjoint current or point sources."""

raise NotImplementedError(
"Could not formulate adjoint source for 'FluxMonitor' output. To compute derivatives "
"with respect to flux data, please use a 'FieldMonitor' and call '.flux' on the "
"resulting 'FieldData' object. Using 'FluxMonitor' directly is not supported as "
"the full field information is required to construct the adjoint source for this "
"problem. The 'FluxData' does not contain the information necessary for gradient "
"computation."
)

def normalize(self, source_spectrum_fn) -> FluxData:
"""Return copy of self after normalization is applied using source spectrum function."""
source_freq_amps = source_spectrum_fn(self.flux.f)
Expand Down

0 comments on commit 1c76897

Please sign in to comment.