File size: 16,267 Bytes
a1a1fbf | 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 | """
.. _fourier_continuation :
Fourier Continuation
====================
This tutorial demonstrates Fourier continuation methods for extending non-periodic
functions to periodic ones, enabling efficient spectral analysis and neural operator
applications. Fourier continuation is crucial for:
- Converting non-periodic data to periodic form
- Enabling spectral methods on arbitrary domains
- Improving convergence of Fourier-based neural operators
- Handling boundary conditions in spectral computations
The tutorial covers both FC-Legendre and FC-Gram methods for 1D, 2D, and 3D data.
"""
# %%
# .. raw:: html
#
# <div style="margin-top: 3em;"></div>
#
# Import the library
# ------------------
# We first import our `neuralop` library and required dependencies.
import torch
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from neuralop.layers.fourier_continuation import FCLegendre, FCGram
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# %%
# .. raw:: html
#
# <div style="margin-top: 3em;"></div>
#
# Creating an example of 1D non-periodic function
# ----------------------------------------------
# We consider f(x) = sin(16x) - cos(8x) on the interval [0,1].
# This function is not periodic on [0,1], making it a good test case
# for Fourier continuation methods.
length_signal = 101 # Length of the original 1D signal
add_pts = 50 # Number of additional points for continuation
batch_size = 3 # Batch size for processing multiple signals
# Create the input signal
x = torch.linspace(0, 1, length_signal).repeat(batch_size, 1)
f = torch.sin(16 * x) - torch.cos(8 * x)
# %%
# .. raw:: html
#
# <div style="margin-top: 3em;"></div>
#
# Extending the signal
# -----------------------------------------
# We use the FC-Legendre and FC-Gram Fourier continuation layers to extend the signal.
# FC-Legendre: Uses Legendre polynomial basis for continuation
Extension_Legendre = FCLegendre(d=2, n_additional_pts=add_pts)
f_extend_Legendre = Extension_Legendre(f, dim=1)
# FC-Gram: Uses Gram polynomial basis for continuation
Extension_Gram = FCGram(d=4, n_additional_pts=add_pts)
f_extend_Gram = Extension_Gram(f, dim=1)
# %%
# .. raw:: html
#
# <div style="margin-top: 3em;"></div>
#
# Visualizing the 1D Fourier continuation results
# ----------------------------------------------
# We plot the original function and both continuation methods to compare
# their effectiveness in creating smooth periodic extensions.
# Define the extended coordinates
x_extended = torch.linspace(-0.25, 1.25, 151)
# Adjust the extended functions for visualization purposes
f_extend_Legendre_adjusted = f_extend_Legendre - 0.6
f_extend_Gram_adjusted = f_extend_Gram + 0.6
plt.figure(figsize=(13, 6))
plt.plot(x[0], f[0], "k", label="Original Function", lw=2.2)
plt.plot(x_extended, f_extend_Gram_adjusted[0], "b", label="FC-Gram Extension", lw=2.2)
plt.plot(x_extended, f_extend_Legendre_adjusted[0], "g", label="FC-Legendre Extension", lw=2.2)
plt.plot([0, 0], [-2.9, 1.9], "-", color="gray", lw=1.5)
plt.plot([1, 1], [-2.9, 1.1], "-", color="gray", lw=1.5)
plt.plot([-0.25, 1.25], [f_extend_Legendre_adjusted[0, 0], f_extend_Legendre_adjusted[0, 0]], "--", color="g", lw=1.6)
plt.plot([-0.25, 1.25], [f_extend_Gram_adjusted[0, 0], f_extend_Gram_adjusted[0, 0]], "--", color="b", lw=1.6)
legend_elements = [
Line2D([0], [0], color="k", lw=2.2, label="Original Function"),
Line2D([0], [0], color="b", lw=2.2, label="FC-Gram Extension"),
Line2D([0], [0], color="g", lw=2.2, label="FC-Legendre Extension"),
]
legend = plt.legend(handles=legend_elements, fontsize=19)
plt.xlim([-0.28, 1.31])
plt.ylim([-3.1, 2.6])
ax = plt.gca()
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.tick_params(axis="x", which="major", labelsize=19)
ax.tick_params(axis="y", which="major", labelsize=19)
plt.xticks([-0.25, 0, 1, 1.25], ["-0.25", "0", "1", "1.25"])
plt.yticks([-2, 2])
plt.tight_layout()
plt.show()
# %%
# .. raw:: html
#
# <div style="margin-top: 3em;"></div>
#
# Creating an example of 2D non-periodic function
# ------------------------------------------------
# We consider f(x,y) = sin(12x) - cos(14y) + 3xy on the domain [0,1]×[0,1].
# This function is not periodic on the unit square, making it suitable
# for testing 2D Fourier continuation methods.
length_signal = 101 # Length of the signal in each dimension
add_pts = 50 # Number of additional points for continuation in each dimension
batch_size = 3 # Batch size for processing multiple signals
# Create the 2D coordinate grids
x = torch.linspace(0, 1, length_signal).view(1, length_signal, 1).repeat(batch_size, 1, length_signal)
y = torch.linspace(0, 1, length_signal).view(1, 1, length_signal).repeat(batch_size, length_signal, 1)
# Define the 2D test function
f = torch.sin(12 * x) - torch.cos(14 * y) + 3 * x * y
# %%
# .. raw:: html
#
# <div style="margin-top: 3em;"></div>
#
# Extending the signal
# -----------------------------------------
# We use the FC-Legendre and FC-Gram Fourier continuation layers to extend the signal.
# FC-Legendre: Uses Legendre polynomial basis for 2D continuation
Extension_Legendre = FCLegendre(d=3, n_additional_pts=add_pts)
f_extend_Legendre = Extension_Legendre(f, dim=2)
# FC-Gram: Uses Gram polynomial basis for 2D continuation
Extension_Gram = FCGram(d=3, n_additional_pts=add_pts)
f_extend_Gram = Extension_Gram(f, dim=2)
# %%
# .. raw:: html
#
# <div style="margin-top: 3em;"></div>
#
# Visualizing the 2D Fourier continuation results
# ----------------------------------------------
# We plot the original function and both continuation methods to compare
# their effectiveness in creating smooth 2D periodic extensions.
# Black lines delineate the original domain boundaries.
fig, axs = plt.subplots(figsize=(15, 5), nrows=1, ncols=3)
# Plot the original function
axs[0].imshow(f[0])
axs[0].set_title(r"Original Function", fontsize=15.5)
axs[1].imshow(f_extend_Legendre[0])
axs[1].plot([add_pts//2, length_signal + add_pts//2], [add_pts//2, add_pts//2], "-", color="k", lw=3)
axs[1].plot([add_pts//2, add_pts//2], [add_pts//2, length_signal + add_pts//2], "-", color="k", lw=3)
axs[1].plot([add_pts//2, length_signal + add_pts//2], [length_signal + add_pts//2, length_signal + add_pts//2], "-", color="k", lw=3)
axs[1].plot([length_signal + add_pts//2, length_signal + add_pts//2], [add_pts//2, length_signal + add_pts//2], "-", color="k", lw=3)
axs[1].set_title(r"FC-Legendre Extension", fontsize=15.5)
axs[2].imshow(f_extend_Gram[0])
axs[2].plot([add_pts//2, length_signal + add_pts//2], [add_pts//2, add_pts//2], "-", color="k", lw=3)
axs[2].plot([add_pts//2, add_pts//2], [add_pts//2, length_signal + add_pts//2], "-", color="k", lw=3)
axs[2].plot([add_pts//2, length_signal + add_pts//2], [length_signal + add_pts//2, length_signal + add_pts//2], "-", color="k", lw=3)
axs[2].plot([length_signal + add_pts//2, length_signal + add_pts//2], [add_pts//2, length_signal + add_pts//2], "-", color="k", lw=3)
axs[2].set_title(r"FC-Gram Extension", fontsize=15.5)
for ax in axs.flat:
ax.set_xticks([])
ax.set_yticks([])
plt.subplots_adjust(wspace=0.05) # Reduce white space between plots
plt.show()
# %%
# .. raw:: html
#
# <div style="margin-top: 3em;"></div>
#
# Creating an example of a 3D function
# --------------------
# Here we consider f(x,y,z) = exp(-2z) + 2xz + sin(12xy) + y sin(10yz)
# which is not periodic on [0,1]x[0,1]x[0,1]
batch_size = 2
length_signal = 101
add_pts = 50
# Create 3D grid
x = torch.linspace(0, 1, length_signal).view(1, length_signal, 1, 1).repeat(batch_size, 1, length_signal, length_signal)
y = torch.linspace(0, 1, length_signal).view(1, 1, length_signal, 1).repeat(batch_size, length_signal, 1, length_signal)
z = torch.linspace(0, 1, length_signal).view(1, 1, 1, length_signal).repeat(batch_size, length_signal, length_signal, 1)
# Create 3D function
f = torch.exp(-2 * z) + 2 * z * x + torch.sin(12 * x * y) + y * torch.sin(10 * y * z)
# %%
# .. raw:: html
#
# <div style="margin-top: 3em;"></div>
#
# Extending the signal
# -----------------------------------------
# We use the FC-Legendre and FC-Gram Fourier continuation layers to extend the signal.
Extension_Legendre = FCLegendre(d=3, n_additional_pts=add_pts)
f_extend_Legendre = Extension_Legendre(f, dim=3)
Extension_Gram = FCGram(d=3, n_additional_pts=add_pts)
f_extend_Gram = Extension_Gram(f, dim=3)
# %%
# .. raw:: html
#
# <div style="margin-top: 3em;"></div>
#
# Plot the FC-Legendre and FC-Gram results for 3D
# ----------------------
# We also add white lines to deliminate the original signal
f_min = f.min().item()
f_max = f.max().item()
f_ext_legendre_min = f_extend_Legendre.min().item()
f_ext_legendre_max = f_extend_Legendre.max().item()
f_ext_gram_min = f_extend_Gram.min().item()
f_ext_gram_max = f_extend_Gram.max().item()
global_min = min(f_min, f_ext_legendre_min, f_ext_gram_min)
global_max = max(f_max, f_ext_legendre_max, f_ext_gram_max)
# %%
# .. raw:: html
#
# <div style="margin-top: 3em;"></div>
#
# Figure for X slices
fig = plt.figure(figsize=(24, 20))
slice_indices = [length_signal//4, length_signal//2, 3*length_signal//4]
slice_names = ["First Quarter", "Middle", "Third Quarter"]
for i, (idx, name) in enumerate(zip(slice_indices, slice_names)):
# Original function - X-slice
ax = fig.add_subplot(3, 3, i + 1)
im = ax.imshow(f[0, idx, :, :].numpy(), cmap="viridis", aspect="auto", vmin=global_min, vmax=global_max)
ax.set_title(f"Original: X-slice {name}", fontsize=22, fontweight="bold")
ax.set_xlabel("Y", fontsize=20)
ax.set_ylabel("Z", fontsize=20)
ax.set_xticks([])
ax.set_yticks([])
cbar = plt.colorbar(im, ax=ax)
cbar.ax.tick_params(labelsize=18)
# FC-Legendre extension - X-slice
ax = fig.add_subplot(3, 3, i + 4)
ext_idx = idx + add_pts//2
im = ax.imshow(f_extend_Legendre[0, ext_idx, :, :].numpy(), cmap="viridis", aspect="auto", vmin=global_min, vmax=global_max)
ax.set_title(f"FC-Legendre: X-slice {name}", fontsize=22, fontweight="bold")
ax.set_xlabel("Y", fontsize=20)
ax.set_ylabel("Z", fontsize=20)
# Draw boundary lines
ax.axhline(y=add_pts//2, color="white", linewidth=2, linestyle="-")
ax.axhline(y=length_signal + add_pts//2, color="white", linewidth=2, linestyle="-")
ax.axvline(x=add_pts//2, color="white", linewidth=2, linestyle="-")
ax.axvline(x=length_signal + add_pts//2, color="white", linewidth=2, linestyle="-")
ax.set_xticks([])
ax.set_yticks([])
cbar = plt.colorbar(im, ax=ax)
cbar.ax.tick_params(labelsize=18)
# FC-Gram extension - X-slice
ax = fig.add_subplot(3, 3, i + 7)
im = ax.imshow(f_extend_Gram[0, ext_idx, :, :].numpy(), cmap="viridis", aspect="auto", vmin=global_min, vmax=global_max)
ax.set_title(f"FC-Gram: X-slice {name}", fontsize=22, fontweight="bold")
ax.set_xlabel("Y", fontsize=20)
ax.set_ylabel("Z", fontsize=20)
# Draw boundary lines
ax.axhline(y=add_pts//2, color="white", linewidth=2, linestyle="-")
ax.axhline(y=length_signal + add_pts//2, color="white", linewidth=2, linestyle="-")
ax.axvline(x=add_pts//2, color="white", linewidth=2, linestyle="-")
ax.axvline(x=length_signal + add_pts//2, color="white", linewidth=2, linestyle="-")
ax.set_xticks([])
ax.set_yticks([])
cbar = plt.colorbar(im, ax=ax)
cbar.ax.tick_params(labelsize=18)
plt.subplots_adjust(hspace=0.15, wspace=0.05, top=0.95)
plt.show()
# %%
# .. raw:: html
#
# <div style="margin-top: 3em;"></div>
#
# Figure for Y-slices
fig2 = plt.figure(figsize=(24, 20))
for i, (idx, name) in enumerate(zip(slice_indices, slice_names)):
# Original function - Y-slice
ax = fig2.add_subplot(3, 3, i + 1)
im = ax.imshow(f[0, :, idx, :].numpy(), cmap="viridis", aspect="auto", vmin=global_min, vmax=global_max)
ax.set_title(f"Original: Y-slice {name}", fontsize=22, fontweight="bold")
ax.set_xlabel("X", fontsize=20)
ax.set_ylabel("Z", fontsize=20)
ax.set_xticks([])
ax.set_yticks([])
cbar = plt.colorbar(im, ax=ax)
cbar.ax.tick_params(labelsize=18)
# FC-Legendre extension - Y-slice
ax = fig2.add_subplot(3, 3, i + 4)
ext_idx = idx + add_pts//2
im = ax.imshow(f_extend_Legendre[0, :, ext_idx, :].numpy(), cmap="viridis", aspect="auto", vmin=global_min, vmax=global_max)
ax.set_title(f"FC-Legendre: Y-slice {name}", fontsize=22, fontweight="bold")
ax.set_xlabel("X", fontsize=20)
ax.set_ylabel("Z", fontsize=20)
# Draw boundary lines
ax.axhline(y=add_pts//2, color="white", linewidth=2, linestyle="-")
ax.axhline(y=length_signal + add_pts//2, color="white", linewidth=2, linestyle="-")
ax.axvline(x=add_pts//2, color="white", linewidth=2, linestyle="-")
ax.axvline(x=length_signal + add_pts//2, color="white", linewidth=2, linestyle="-")
ax.set_xticks([])
ax.set_yticks([])
cbar = plt.colorbar(im, ax=ax)
cbar.ax.tick_params(labelsize=18)
# FC-Gram extension - Y-slice
ax = fig2.add_subplot(3, 3, i + 7)
im = ax.imshow(f_extend_Gram[0, :, ext_idx, :].numpy(), cmap="viridis", aspect="auto", vmin=global_min, vmax=global_max)
ax.set_title(f"FC-Gram: Y-slice {name}", fontsize=22, fontweight="bold")
ax.set_xlabel("X", fontsize=20)
ax.set_ylabel("Z", fontsize=20)
# Draw boundary lines
ax.axhline(y=add_pts//2, color="white", linewidth=2, linestyle="-")
ax.axhline(y=length_signal + add_pts//2, color="white", linewidth=2, linestyle="-")
ax.axvline(x=add_pts//2, color="white", linewidth=2, linestyle="-")
ax.axvline(x=length_signal + add_pts//2, color="white", linewidth=2, linestyle="-")
ax.set_xticks([])
ax.set_yticks([])
cbar = plt.colorbar(im, ax=ax)
cbar.ax.tick_params(labelsize=18)
plt.subplots_adjust(hspace=0.15, wspace=0.05, top=0.95)
plt.show()
# %%
# .. raw:: html
#
# <div style="margin-top: 3em;"></div>
#
# Figure for Z-slices
fig3 = plt.figure(figsize=(24, 20))
for i, (idx, name) in enumerate(zip(slice_indices, slice_names)):
# Original function - Z-slice
ax = fig3.add_subplot(3, 3, i + 1)
im = ax.imshow(f[0, :, :, idx].numpy(), cmap="viridis", aspect="auto", vmin=global_min, vmax=global_max)
ax.set_title(f"Original: Z-slice {name}", fontsize=22, fontweight="bold")
ax.set_xlabel("X", fontsize=20)
ax.set_ylabel("Y", fontsize=20)
ax.set_xticks([])
ax.set_yticks([])
cbar = plt.colorbar(im, ax=ax)
cbar.ax.tick_params(labelsize=18)
# FC-Legendre extension - Z-slice
ax = fig3.add_subplot(3, 3, i + 4)
ext_idx = idx + add_pts//2
im = ax.imshow(f_extend_Legendre[0, :, :, ext_idx].numpy(), cmap="viridis", aspect="auto", vmin=global_min, vmax=global_max)
ax.set_title(f"FC-Legendre: Z-slice {name}", fontsize=22, fontweight="bold")
ax.set_xlabel("X", fontsize=20)
ax.set_ylabel("Y", fontsize=20)
# Draw boundary lines
ax.axhline(y=add_pts//2, color="white", linewidth=2, linestyle="-")
ax.axhline(y=length_signal + add_pts//2, color="white", linewidth=2, linestyle="-")
ax.axvline(x=add_pts//2, color="white", linewidth=2, linestyle="-")
ax.axvline(x=length_signal + add_pts//2, color="white", linewidth=2, linestyle="-")
ax.set_xticks([])
ax.set_yticks([])
cbar = plt.colorbar(im, ax=ax)
cbar.ax.tick_params(labelsize=18)
# FC-Gram extension - Z-slice
ax = fig3.add_subplot(3, 3, i + 7)
im = ax.imshow(f_extend_Gram[0, :, :, ext_idx].numpy(), cmap="viridis", aspect="auto", vmin=global_min, vmax=global_max)
ax.set_title(f"FC-Gram: Z-slice {name}", fontsize=22, fontweight="bold")
ax.set_xlabel("X", fontsize=20)
ax.set_ylabel("Y", fontsize=20)
# Draw boundary lines
ax.axhline(y=add_pts//2, color="white", linewidth=2, linestyle="-")
ax.axhline(y=length_signal + add_pts//2, color="white", linewidth=2, linestyle="-")
ax.axvline(x=add_pts//2, color="white", linewidth=2, linestyle="-")
ax.axvline(x=length_signal + add_pts//2, color="white", linewidth=2, linestyle="-")
ax.set_xticks([])
ax.set_yticks([])
cbar = plt.colorbar(im, ax=ax)
cbar.ax.tick_params(labelsize=18)
plt.subplots_adjust(hspace=0.15, wspace=0.05, top=0.95)
plt.show()
|