import deepxde as dde
import numpy as np
import matplotlib.pyplot as plt
def pde(x, u):
du_t = dde.grad.jacobian(u, x, i=0, j=0)
du_x = dde.grad.jacobian(u, x, i=0, j=1)
du_xx = dde.grad.hessian(u, x, i=0, j=1)
return du_t + u * du_x - (0.01 / np.pi) * du_xx
geom = dde.geometry.Interval(-1, 1)
timedomain = dde.geometry.TimeDomain(0, 1)
geomtime = dde.geometry.GeometryXTime(geom, timedomain)
def initial_condition(x):
return -np.sin(np.pi * x[:, 0:1])
def boundary_left(x, on_boundary):
return on_boundary and np.isclose(x[1], -1)
def boundary_right(x, on_boundary):
return on_boundary and np.isclose(x[1], 1)
def boundary_bottom(x, on_boundary):
return on_boundary and np.isclose(x[0], 0)
bc_left = dde.DirichletBC(geomtime, lambda x: 0, boundary_left)
bc_right = dde.DirichletBC(geomtime, lambda x: 0, boundary_right)
ic = dde.DirichletBC(geomtime, initial_condition, boundary_bottom)
data = dde.data.TimePDE(
geomtime, pde, [bc_left, bc_right, ic],
num_domain=2000,
num_boundary=200,
num_initial=100,
num_test=10000,
)
net = dde.nn.FNN([2] + [50] * 3 + [1], "tanh", "Glorot normal")
model = dde.Model(data, net)
model.compile("adam", lr=1e-3, loss="MSE")
losshistory, train_state = model.train(epochs=15000)
dde.saveplot(losshistory, train_state, issave=True, isplot=True)
t = np.linspace(0, 1, 100)
x = np.linspace(-1, 1, 100)
t_grid, x_grid = np.meshgrid(t, x)
X = np.vstack((t_grid.flatten(), x_grid.flatten())).T
u_pred = model.predict(X).reshape(t_grid.shape)
plt.figure(figsize=(10, 6))
plt.contourf(t_grid, x_grid, u_pred, levels=100, cmap="viridis")
plt.colorbar(label="u(t, x)")
plt.xlabel("t")
plt.ylabel("x")
plt.title("PINN 求解一维伯格斯方程的时空分布")
plt.show()