Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix FourierFields adjoint for D and B fields in isotropic media #2095

Merged
merged 5 commits into from
Jun 23, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 16 additions & 16 deletions python/tests/test_adjoint_solver.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ def forward_simulation_complex_fields(design_params, frequencies=None):
material=matgrid)]

sim = mp.Simulation(resolution=resolution,
cell_size=cell_size,
cell_size=cell_size,default_material=silicon,
k_point=k_point,
boundary_layers=pml_x,
sources=pt_source,
Expand All @@ -213,23 +213,23 @@ def forward_simulation_complex_fields(design_params, frequencies=None):
if not frequencies:
frequencies = [fcen]

mode = sim.add_dft_fields([mp.Ez],
mode = sim.add_dft_fields([mp.Dz],
frequencies,
center=mp.Vector3(0.9),
size=mp.Vector3(0.2,0.5),
yee_grid=False)

sim.run(until_after_sources=mp.stop_when_dft_decayed())

Ez2 = []
Dz2 = []
for f in range(len(frequencies)):
Ez_dft = sim.get_dft_array(mode, mp.Ez, f)
Ez2.append(np.power(np.abs(Ez_dft[3,9]),2))
Ez2 = np.array(Ez2)
Dz_dft = sim.get_dft_array(mode, mp.Dz, f)
Dz2.append(np.power(np.abs(Dz_dft[3,9]),2))
Dz2 = np.array(Dz2)

sim.reset_meep()

return Ez2
return Dz2


def adjoint_solver_complex_fields(design_params, frequencies=None):
Expand All @@ -249,7 +249,7 @@ def adjoint_solver_complex_fields(design_params, frequencies=None):
material=matgrid)]

sim = mp.Simulation(resolution=resolution,
cell_size=cell_size,
cell_size=cell_size,default_material=silicon,
k_point=k_point,
boundary_layers=pml_x,
sources=pt_source,
Expand All @@ -261,7 +261,7 @@ def adjoint_solver_complex_fields(design_params, frequencies=None):
obj_list = [mpa.FourierFields(sim,
mp.Volume(center=mp.Vector3(0.9),
size=mp.Vector3(0.2,0.5)),
mp.Ez)]
mp.Dz)]

def J(dft_mon):
return npa.power(npa.abs(dft_mon[:,3,9]),2)
Expand Down Expand Up @@ -505,21 +505,21 @@ def test_complex_fields(self):
## compute gradient using adjoint solver
adjsol_obj, adjsol_grad = adjoint_solver_complex_fields(p, frequencies)

## compute unperturbed |Ez|^2
Ez2_unperturbed = forward_simulation_complex_fields(p, frequencies)
## compute unperturbed |Dz|^2
Dz2_unperturbed = forward_simulation_complex_fields(p, frequencies)

## compare objective results
print("Ez2 -- adjoint solver: {}, traditional simulation: {}".format(adjsol_obj,Ez2_unperturbed))
self.assertClose(adjsol_obj,Ez2_unperturbed,epsilon=1e-6)
print("Dz2 -- adjoint solver: {}, traditional simulation: {}".format(adjsol_obj,Dz2_unperturbed))
self.assertClose(adjsol_obj,Dz2_unperturbed,epsilon=1e-6)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like this assert statement is failing for the single-precision build. You can try increasing the tolerance for single precision using e.g.:

self.assertClose(adjsol_obj,Dz2_unperturbed,epsilon=1e-4 if mp.is_single_precision() else 1e-6)

Copy link
Contributor Author

@mawc2019 mawc2019 Jun 17, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In my place, this line does not cause error even with single precision. I guess the error message in my place is different from that given by the online check. But I cannot see the detailed error message in the online-check logs. Can I ask where I should find the detailed error message?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To find the log of the failing CI run, click on the "Details" button below next to "CI / Test Python 3.10 with MPI (true)" or the "Actions" tab above (next to "Discussions" and "Projects"). From there, for the failing run locate the "Artifacts" section and then download the log file. In this case, this would be py3.10-tests-mpi-true.log which shows:

Ran 7 tests in 307.004s

FAILED (failures=1)
FAIL: test_complex_fields (__main__.TestAdjointSolver)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/runner/work/meep/meep/build/meep-1.24.0-beta/_build/sub/python/../../../python/tests/test_adjoint_solver.py", line 525, in test_complex_fields
    self.assertClose(adj_scale,fd_grad,epsilon=tol)
  File "/home/runner/work/meep/meep/build/meep-1.24.0-beta/python/tests/utils.py", line 28, in assertClose
    self.assertLessEqual(diff_norm, epsilon * np.maximum(x_norm, y_norm), msg)
AssertionError: 0.001776412917294544 not less than or equal to 0.0005871758943843297 : 

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! The tolerance for single precision is adjusted further.


## compute perturbed |Ez|^2
Ez2_perturbed = forward_simulation_complex_fields(p+dp, frequencies)
## compute perturbed |Dz|^2
Dz2_perturbed = forward_simulation_complex_fields(p+dp, frequencies)

## compare gradients
if adjsol_grad.ndim < 2:
adjsol_grad = np.expand_dims(adjsol_grad,axis=1)
adj_scale = (dp[None,:]@adjsol_grad).flatten()
fd_grad = Ez2_perturbed-Ez2_unperturbed
fd_grad = Dz2_perturbed-Dz2_unperturbed
print("Directional derivative -- adjoint solver: {}, FD: {}".format(adj_scale,fd_grad))
tol = 0.018 if mp.is_single_precision() else 0.002
self.assertClose(adj_scale,fd_grad,epsilon=tol)
Expand Down
17 changes: 14 additions & 3 deletions src/dft.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1468,7 +1468,10 @@ std::vector<struct sourcedata> dft_fields::fourier_sourcedata(const volume &wher
std::vector<ptrdiff_t> idx_arr;
std::vector<std::complex<double> > amp_arr;
std::complex<double> EH0 = std::complex<double>(0,0);
sourcedata temp_struct = {component(f->c), idx_arr, f->fc->chunk_idx, amp_arr};
component c = component(f->c);
direction cd = component_direction(c);
sourcedata temp_struct = {c, idx_arr, f->fc->chunk_idx, amp_arr};

int position_array[3] = {0, 0, 0}; // array indicating the position of a point relative to the minimum corner of the monitor

LOOP_OVER_IVECS(f->fc->gv, f->is, f->ie, idx) {
Expand All @@ -1491,7 +1494,11 @@ std::vector<struct sourcedata> dft_fields::fourier_sourcedata(const volume &wher
temp_struct.idx_arr.push_back(idx);
for (size_t i = 0; i < Nfreq; ++i) {
EH0 = dJ_weight*dJ[reduced_grid_size*i+idx_1d];
if (is_E_or_D(temp_struct.near_fd_comp)) EH0 *= -1;

if (is_electric(c)) EH0 *= -1;
if (is_D(c) && f->fc->s->chi1inv[c - Dx + Ex][cd]) EH0 /= -f->fc->s->chi1inv[c - Dx + Ex][cd][idx];
if (is_B(c) && f->fc->s->chi1inv[c - Bx + Hx][cd]) EH0 /= f->fc->s->chi1inv[c - Bx + Hx][cd][idx];

EH0 /= f->S.multiplicity(ix0);
temp_struct.amp_arr.push_back(EH0);
}
Expand All @@ -1503,7 +1510,11 @@ std::vector<struct sourcedata> dft_fields::fourier_sourcedata(const volume &wher
temp_struct.idx_arr.push_back(site_ind[j]);
for (size_t i = 0; i < Nfreq; ++i) {
EH0 = dJ_weight*dJ[reduced_grid_size*i+idx_1d]*0.25; // split the amplitude of the adjoint source into four parts
if (is_E_or_D(temp_struct.near_fd_comp)) EH0 *= -1;

if (is_electric(c)) EH0 *= -1;
if (is_D(c) && f->fc->s->chi1inv[c - Dx + Ex][cd]) EH0 /= -f->fc->s->chi1inv[c - Dx + Ex][cd][idx];
if (is_B(c) && f->fc->s->chi1inv[c - Bx + Hx][cd]) EH0 /= f->fc->s->chi1inv[c - Bx + Hx][cd][idx];

EH0 /= f->S.multiplicity(ix0);
temp_struct.amp_arr.push_back(EH0);
}
Expand Down