From 0d89d880c0dbc280bd3c10c9744f2d1e7bc91bd5 Mon Sep 17 00:00:00 2001 From: Wenchao Ma <60903466+mawc2019@users.noreply.github.com> Date: Wed, 25 May 2022 21:25:32 -0400 Subject: [PATCH] fix calculate_fd_gradient to deal with design pixel weights near 0 or 1 (#2073) --- python/adjoint/optimization_problem.py | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/python/adjoint/optimization_problem.py b/python/adjoint/optimization_problem.py index e86fbe219..8a024520e 100644 --- a/python/adjoint/optimization_problem.py +++ b/python/adjoint/optimization_problem.py @@ -321,6 +321,8 @@ def calculate_fd_gradient( "The requested number of gradients must be less than or equal to the total number of design parameters." ) + assert db < 0.2, "The step size of finite difference is too large." + # cleanup simulation object self.sim.reset_meep() self.sim.change_sources(self.forward_sources) @@ -339,7 +341,10 @@ def calculate_fd_gradient( self.sim.reset_meep() # assign new design vector - b0[k] -= db + in_interior = True # b0[k] is not too close to the boundaries 0 and 1 + if b0[k] < db or b0[k]+db > 1: in_interior = False # b0[k] is too close to 0 or 1 + + if b0[k] >= db: b0[k] -= db self.design_regions[design_variables_idx].update_design_parameters( b0) @@ -367,7 +372,9 @@ def calculate_fd_gradient( self.sim.reset_meep() # assign new design vector - b0[k] += 2 * db # central difference rule... + if in_interior: b0[k] += 2 * db # central difference rule... + else: b0[k] += db # forward or backward difference... + self.design_regions[design_variables_idx].update_design_parameters( b0) @@ -394,7 +401,7 @@ def calculate_fd_gradient( # estimate derivative # -------------------------------------------- # fd_gradient.append([ - np.squeeze((fp[fi] - fm[fi]) / (2 * db)) + np.squeeze((fp[fi] - fm[fi]) / db / (2 if in_interior else 1)) for fi in range(len(self.objective_functions)) ])