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 the shapes of 2d filters #2390

Merged
merged 8 commits into from
Feb 9, 2023
Merged
Show file tree
Hide file tree
Changes from 6 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
95 changes: 49 additions & 46 deletions python/adjoint/filters.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,11 @@
"""
General filter functions to be used in other projection and morphological transform routines.
"""
import meep as mp
import numpy as np
from autograd import numpy as npa
from scipy import signal, special

import meep as mp


def _proper_pad(x, n):
"""
Parameters
----------
x : array_like (2D)
Input array. Must be 2D.
n : int
Total size to be padded to.
"""
N = x.size
k = n - (2 * N - 1)
return np.concatenate((x, np.zeros((k,)), np.flipud(x[1:])))


def _centered(arr, newshape):
"""Helper function that reformats the padded array of the fft filter operation.
Expand All @@ -36,6 +21,37 @@ def _centered(arr, newshape):
return arr[tuple(myslice)]


def _proper_pad(arr, pad_to):
stevengj marked this conversation as resolved.
Show resolved Hide resolved
"""
stevengj marked this conversation as resolved.
Show resolved Hide resolved
Parameters
----------
arr : 2d input array.
stevengj marked this conversation as resolved.
Show resolved Hide resolved
pad_to : 1d array composed of two integers indicating the total size to be padded to.
"""

pad_size = pad_to - 2 * np.array(arr.shape) + 1

top = np.zeros((pad_size[0], arr.shape[1]))
bottom = np.zeros((pad_size[0], arr.shape[1] - 1))
middle = np.zeros((pad_to[0], pad_size[1]))

top_left = arr[:, :]
top_right = npa.flipud(arr[1:, :])
bottom_left = npa.fliplr(arr[:, 1:])
bottom_right = npa.flipud(
npa.fliplr(arr[1:, 1:])
) # equivalent to flip, but flip is incompatible with autograd

return npa.concatenate(
(
npa.concatenate((top_left, top, top_right)),
middle,
npa.concatenate((bottom_left, bottom, bottom_right)),
),
axis=1,
)


def _edge_pad(arr, pad):

# fill sides
Expand Down Expand Up @@ -80,7 +96,10 @@ def simple_2d_filter(x, h):
The output of the 2d convolution.
"""
(kx, ky) = x.shape
h = _proper_pad(h, 3 * np.array([kx, ky]))
h = h / npa.sum(h) # Normalize the kernel
x = _edge_pad(x, ((kx, kx), (ky, ky)))

return _centered(
npa.real(npa.fft.ifft2(npa.fft.fft2(x) * npa.fft.fft2(h))), (kx, ky)
)
Expand Down Expand Up @@ -112,21 +131,15 @@ def cylindrical_filter(x, radius, Lx, Ly, resolution):
[1] Lazarov, B. S., Wang, F., & Sigmund, O. (2016). Length scale and manufacturability in
density-based topology optimization. Archive of Applied Mechanics, 86(1-2), 189-218.
"""
Nx = int(Lx * resolution)
Ny = int(Ly * resolution)
Nx = int(round(Lx * resolution))
Ny = int(round(Ly * resolution))
x = x.reshape(Nx, Ny) # Ensure the input is 2D

xv = np.arange(0, Lx / 2, 1 / resolution)
yv = np.arange(0, Ly / 2, 1 / resolution)

cylindrical = lambda a: np.where(a <= radius, 1, 0)
hx = cylindrical(xv)
hy = cylindrical(yv)

h = np.outer(_proper_pad(hx, 3 * Nx), _proper_pad(hy, 3 * Ny))
stevengj marked this conversation as resolved.
Show resolved Hide resolved

# Normalize kernel
h = h / np.sum(h.flatten()) # Normalize the filter
X, Y = np.meshgrid(xv, yv, sparse=True, indexing="ij")
h = np.where(X**2 + Y**2 < radius**2, 1, 0)
stevengj marked this conversation as resolved.
Show resolved Hide resolved

# Filter the response
return simple_2d_filter(x, h)
Expand Down Expand Up @@ -158,21 +171,17 @@ def conic_filter(x, radius, Lx, Ly, resolution):
[1] Lazarov, B. S., Wang, F., & Sigmund, O. (2016). Length scale and manufacturability in
density-based topology optimization. Archive of Applied Mechanics, 86(1-2), 189-218.
"""
Nx = int(Lx * resolution)
Ny = int(Ly * resolution)
Nx = int(round(Lx * resolution))
Ny = int(round(Ly * resolution))
x = x.reshape(Nx, Ny) # Ensure the input is 2D

xv = np.arange(0, Lx / 2, 1 / resolution)
yv = np.arange(0, Ly / 2, 1 / resolution)

conic = lambda a: np.where(np.abs(a**2) <= radius**2, (1 - a / radius), 0)
hx = conic(xv)
hy = conic(yv)

h = np.outer(_proper_pad(hx, 3 * Nx), _proper_pad(hy, 3 * Ny))

# Normalize kernel
h = h / np.sum(h.flatten()) # Normalize the filter
X, Y = np.meshgrid(xv, yv, sparse=True, indexing="ij")
h = np.where(
X**2 + Y**2 < radius**2, (1 - np.sqrt(abs(X**2 + Y**2)) / radius), 0
)

# Filter the response
return simple_2d_filter(x, h)
Expand Down Expand Up @@ -204,21 +213,15 @@ def gaussian_filter(x, sigma, Lx, Ly, resolution):
[1] Wang, E. W., Sell, D., Phan, T., & Fan, J. A. (2019). Robust design of
topology-optimized metasurfaces. Optical Materials Express, 9(2), 469-482.
"""
Nx = int(Lx * resolution)
Ny = int(Ly * resolution)
Nx = int(round(Lx * resolution))
Ny = int(round(Ly * resolution))
x = x.reshape(Nx, Ny) # Ensure the input is 2D

xv = np.arange(0, Lx / 2, 1 / resolution)
yv = np.arange(0, Ly / 2, 1 / resolution)

gaussian = lambda a: np.exp(-(a**2) / sigma**2)
hx = gaussian(xv)
hy = gaussian(yv)

h = np.outer(_proper_pad(hx, 3 * Nx), _proper_pad(hy, 3 * Ny))

# Normalize kernel
h = h / np.sum(h.flatten()) # Normalize the filter
X, Y = np.meshgrid(xv, yv, sparse=True, indexing="ij")
h = np.exp(-(X**2 + Y**2) / sigma**2)

# Filter the response
return simple_2d_filter(x, h)
Expand Down
6 changes: 3 additions & 3 deletions python/tests/test_adjoint_solver.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ def setUpClass(cls):

cls.design_region_size = mp.Vector3(1.5, 1.5)
cls.design_region_resolution = int(2 * cls.resolution)
cls.Nx = int(cls.design_region_size.x * cls.design_region_resolution)
cls.Ny = int(cls.design_region_size.y * cls.design_region_resolution)
cls.Nx = int(round(cls.design_region_size.x * cls.design_region_resolution))
cls.Ny = int(round(cls.design_region_size.y * cls.design_region_resolution))

# ensure reproducible results
rng = np.random.RandomState(9861548)
Expand Down Expand Up @@ -678,7 +678,7 @@ def test_gradient_backpropagation(self):
# non-center frequencies of a multifrequency simulation
# are expected to be less accurate than the center frequency
if nfrq == 1 and frequencies[0] == self.fcen:
tol = 2e-4 if mp.is_single_precision() else 5e-6
tol = 2.1e-4 if mp.is_single_precision() else 5e-6
else:
tol = 0.005 if mp.is_single_precision() else 0.002

Expand Down
2 changes: 1 addition & 1 deletion python/tests/test_adjoint_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ class TestAdjointUtils(ApproxComparisonTestCase):
def test_filter_offset(self, test_name, Lx, Ly, resolution, radius, filter_func):
"""ensure that the filters are indeed zero-phase"""
print("Testing ", test_name)
Nx, Ny = int(resolution * Lx), int(resolution * Ly)
Nx, Ny = int(round(resolution * Lx)), int(round(resolution * Ly))
x = np.random.rand(Nx, Ny)
x = x + np.fliplr(x)
x = x + np.flipud(x)
Expand Down