poisson-dedalus / dataset.py
ajthor's picture
Upload folder using huggingface_hub
258a5b6 verified
"""
2D Poisson equation dataset with mixed boundary conditions.
Solves the boundary value problem:
∇²u = f(x,y) in Ω = [0, Lx] × [0, Ly]
u(x,0) = g(x) on bottom boundary
∂u/∂y(x,Ly) = h(x) on top boundary
Uses Dedalus spectral methods with Fourier(x) × Chebyshev(y) discretization.
The forcing function f(x,y) is randomly generated using Gaussian processes
to create diverse training samples.
Physical applications: electrostatic potential, steady-state heat conduction,
fluid stream functions.
"""
import numpy as np
from torch.utils.data import IterableDataset
import dedalus.public as d3
from functools import partial
from sklearn.metrics.pairwise import rbf_kernel
import logging
logger = logging.getLogger(__name__)
def sample_gp_prior(kernel, X, n_samples=1):
"""
Sample from Gaussian Process prior for generating smooth random fields.
"""
if X.ndim == 1:
X = X.reshape(-1, 1)
K = kernel(X, X)
prior = np.random.multivariate_normal(
mean=np.zeros(X.shape[0]),
cov=K,
size=n_samples,
)
return prior
def sample_gp_posterior(kernel, X, y, xt, n_samples=1):
"""Sample from Gaussian Process posterior for boundary conditions."""
if X.ndim == 1:
X = X.reshape(-1, 1)
if y.ndim == 1:
y = y.reshape(-1, 1)
if xt.ndim == 1:
xt = xt.reshape(-1, 1)
K = kernel(X, X)
Kt = kernel(X, xt)
Ktt = kernel(xt, xt)
K_inv = np.linalg.inv(K)
mu = Kt.T @ K_inv @ y
cov = Ktt - Kt.T @ K_inv @ Kt
mu = mu.ravel() # Ensure 1D array
posterior = np.random.multivariate_normal(
mean=mu,
cov=cov,
size=n_samples,
)
return posterior
class PoissonDataset(IterableDataset):
"""
Dataset for 2D Poisson equation with mixed boundary conditions.
Generates random smooth forcing functions using Gaussian processes
and solves: ∇²u = f(x,y) with u(x,0) = g(x) and ∂u/∂y(x,Ly) = h(x).
"""
def __init__(
self,
Lx=2*np.pi, # Domain length in x-direction
Ly=np.pi, # Domain length in y-direction
Nx=256, # Grid points in x-direction
Ny=128, # Grid points in y-direction
dtype=np.float64,
):
"""
Initialize 2D Poisson equation dataset.
Args:
Lx: Domain length in x-direction
Ly: Domain length in y-direction
Nx: Number of grid points in x-direction
Ny: Number of grid points in y-direction
dtype: Data type for computations
"""
super().__init__()
# Store domain and grid parameters
self.Lx = Lx
self.Ly = Ly
self.Nx = Nx
self.Ny = Ny
self.dtype = dtype
# Setup Dedalus solver components
self.coords = d3.CartesianCoordinates('x', 'y')
self.dist = d3.Distributor(self.coords, dtype=dtype)
self.xbasis = d3.RealFourier(self.coords['x'], size=Nx, bounds=(0, Lx))
self.ybasis = d3.Chebyshev(self.coords['y'], size=Ny, bounds=(0, Ly))
# Create coordinate grids
self.x, self.y = self.dist.local_grids(self.xbasis, self.ybasis)
# Setup fields
self.u = self.dist.Field(name='u', bases=(self.xbasis, self.ybasis))
self.tau_1 = self.dist.Field(name='tau_1', bases=self.xbasis)
self.tau_2 = self.dist.Field(name='tau_2', bases=self.xbasis)
self.f = self.dist.Field(bases=(self.xbasis, self.ybasis))
self.g = self.dist.Field(bases=self.xbasis)
self.h = self.dist.Field(bases=self.xbasis)
# Setup operators and namespace for boundary value problem
dy = lambda A: d3.Differentiate(A, self.coords['y'])
lift_basis = self.ybasis.derivative_basis(2)
lift = lambda A, n: d3.Lift(A, lift_basis, n)
f = self.f
g = self.g
h = self.h
u = self.u
tau_1 = self.tau_1
tau_2 = self.tau_2
Ly = self.Ly
self.problem = d3.LBVP([self.u, self.tau_1, self.tau_2], namespace=locals())
self.problem.add_equation("lap(u) + lift(tau_1,-1) + lift(tau_2,-2) = f")
self.problem.add_equation("u(y=0) = g")
self.problem.add_equation("dy(u)(y=Ly) = h")
def __iter__(self):
"""Generate infinite samples from the dataset."""
while True:
# Generate random forcing function using filtered noise
self.f.fill_random('g', seed=np.random.randint(0, 2**31))
filter_x = np.random.randint(32, 128)
filter_y = np.random.randint(16, 64)
self.f.low_pass_filter(shape=(filter_x, filter_y))
# Generate random Dirichlet boundary condition using GP
# Get x-coordinates for bottom boundary (1D array)
x_boundary = self.dist.local_grid(self.xbasis)
sigma_g = 0.2 * self.Lx
gamma_g = 1 / (2 * sigma_g**2)
g_sample = sample_gp_posterior(
kernel=partial(rbf_kernel, gamma=gamma_g),
X=np.array([0, self.Lx]),
y=np.array([0, 0]),
xt=x_boundary.ravel(),
n_samples=1
)[0]
self.g['g'] = (np.random.uniform(0.01, 0.1) * g_sample).reshape(-1, 1)
# Generate random Neumann boundary condition using GP
sigma_h = 0.3 * self.Lx
gamma_h = 1 / (2 * sigma_h**2)
h_sample = sample_gp_posterior(
kernel=partial(rbf_kernel, gamma=gamma_h),
X=np.array([0, self.Lx]),
y=np.array([0, 0]),
xt=x_boundary.ravel(),
n_samples=1
)[0]
self.h['g'] = (np.random.uniform(0.005, 0.05) * h_sample).reshape(-1, 1)
yield self.solve()
def solve(self):
"""
Solve the 2D Poisson boundary value problem.
The forcing function and boundary conditions have already been set in __iter__.
Returns:
A dictionary containing the solution and related data.
"""
# Build and solve the LBVP
solver = self.problem.build_solver()
solver.solve()
# Gather global data for return
x_global = self.xbasis.global_grid(self.dist, scale=1)
y_global = self.ybasis.global_grid(self.dist, scale=1)
u_global = self.u.allgather_data('g')
f_global = self.f.allgather_data('g')
g_global = self.g.allgather_data('g')
h_global = self.h.allgather_data('g')
# Create coordinate meshgrids
X, Y = np.meshgrid(x_global.ravel(), y_global.ravel(), indexing='ij')
return {
# Combined spatial coordinates
"spatial_coordinates": np.array([X, Y]), # Shape: (2, Nx, Ny)
# Solution field
"solution_field": u_global, # Shape: (Nx, Ny)
# Forcing function
"forcing_function": f_global, # Shape: (Nx, Ny)
# Boundary conditions
"boundary_condition_bottom": g_global, # Shape: (Nx,)
"boundary_condition_top_gradient": h_global, # Shape: (Nx,)
}