Skip to content

Commit bd4bfac

Browse files
splitting lululxvi#1932 into an independent PR(examples)
Co-Authored-By: Chaoming Wang <[email protected]>
1 parent b944422 commit bd4bfac

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

51 files changed

+5441
-0
lines changed

examples/experimental_examples/examples-function/dataset.ipynb

Lines changed: 277 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import os
2+
3+
import brainstate as bst
4+
import numpy as np
5+
6+
import deepxde.experimental as deepxde
7+
8+
PATH = os.path.dirname(os.path.abspath(__file__))
9+
train_data = np.loadtxt(os.path.join(PATH, "../..", "dataset", "dataset.train"))
10+
test_data = np.loadtxt(os.path.join(PATH, "../..", "dataset", "dataset.test"))
11+
12+
net = deepxde.nn.Model(
13+
deepxde.nn.DictToArray(x=None),
14+
deepxde.nn.FNN([1] + [50] * 3 + [1], "tanh", bst.init.KaimingUniform()),
15+
deepxde.nn.ArrayToDict(y=None),
16+
)
17+
18+
data = deepxde.problem.DataSet(
19+
X_train={"x": train_data[:, 0]},
20+
y_train={"y": train_data[:, 1]},
21+
X_test={"x": test_data[:, 0]},
22+
y_test={"y": test_data[:, 1]},
23+
standardize=True,
24+
approximator=net,
25+
)
26+
27+
model = deepxde.Trainer(data)
28+
model.compile(bst.optim.Adam(0.001), metrics=["l2 relative error"]).train(
29+
iterations=50000
30+
)
31+
model.saveplot(issave=True, isplot=True)

examples/experimental_examples/examples-function/func.ipynb

Lines changed: 243 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import brainstate as bst
2+
import brainunit as u
3+
4+
import deepxde.experimental as deepxde
5+
6+
7+
def func(x):
8+
return {"y": x["x"] * u.math.sin(5 * x["x"])}
9+
10+
11+
geom = deepxde.geometry.Interval(-1, 1).to_dict_point("x")
12+
num_train = 160
13+
num_test = 100
14+
15+
net = deepxde.nn.Model(
16+
deepxde.nn.DictToArray(x=None),
17+
deepxde.nn.FNN([1] + [20] * 3 + [1], "tanh", bst.init.LecunUniform()),
18+
deepxde.nn.ArrayToDict(y=None),
19+
)
20+
21+
data = deepxde.problem.Function(geom, func, num_train, num_test, approximator=net)
22+
23+
trainer = deepxde.Trainer(data)
24+
trainer.compile(bst.optim.Adam(0.001), metrics=["l2 relative error"]).train(
25+
iterations=10000
26+
)
27+
trainer.saveplot(issave=False, isplot=True)
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import brainstate as bst
2+
import brainunit as u
3+
4+
import deepxde.experimental as deepxde
5+
6+
7+
def func(x):
8+
return {"y": x["x"] * u.math.sin(5 * x["x"])}
9+
10+
11+
layer_size = [1] + [50] * 3 + [1]
12+
net = deepxde.nn.Model(
13+
deepxde.nn.DictToArray(x=None),
14+
deepxde.nn.FNN(layer_size, "tanh", bst.init.KaimingUniform()),
15+
deepxde.nn.ArrayToDict(y=None),
16+
)
17+
18+
geom = deepxde.geometry.Interval(-1, 1).to_dict_point("x")
19+
num_train = 100
20+
num_test = 1000
21+
data = deepxde.problem.Function(geom, func, num_train, num_test, approximator=net)
22+
23+
trainer = deepxde.Trainer(data)
24+
uncertainty = deepxde.callbacks.DropoutUncertainty(period=1000)
25+
trainer.compile(bst.optim.Adam(0.001), metrics=["l2 relative error"]).train(
26+
iterations=30000, callbacks=uncertainty
27+
)
28+
trainer.saveplot(issave=True, isplot=True)
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
import matplotlib.pyplot as plt
2+
import numpy as np
3+
4+
5+
def solve_ADR(xmin, xmax, tmin, tmax, k, v, g, dg, f, u0, Nx, Nt):
6+
"""Solve 1D
7+
u_t = (k(x) u_x)_x - v(x) u_x + g(u) + f(x, t)
8+
with zero boundary condition.
9+
"""
10+
x = np.linspace(xmin, xmax, Nx)
11+
t = np.linspace(tmin, tmax, Nt)
12+
h = x[1] - x[0]
13+
dt = t[1] - t[0]
14+
h2 = h**2
15+
16+
D1 = np.eye(Nx, k=1) - np.eye(Nx, k=-1)
17+
D2 = -2 * np.eye(Nx) + np.eye(Nx, k=-1) + np.eye(Nx, k=1)
18+
D3 = np.eye(Nx - 2)
19+
k = k(x)
20+
M = -np.diag(D1 @ k) @ D1 - 4 * np.diag(k) @ D2
21+
m_bond = 8 * h2 / dt * D3 + M[1:-1, 1:-1]
22+
v = v(x)
23+
v_bond = 2 * h * np.diag(v[1:-1]) @ D1[1:-1, 1:-1] + 2 * h * np.diag(
24+
v[2:] - v[: Nx - 2]
25+
)
26+
mv_bond = m_bond + v_bond
27+
c = 8 * h2 / dt * D3 - M[1:-1, 1:-1] - v_bond
28+
f = f(x[:, None], t)
29+
30+
u = np.zeros((Nx, Nt))
31+
u[:, 0] = u0(x)
32+
for i in range(Nt - 1):
33+
gi = g(u[1:-1, i])
34+
dgi = dg(u[1:-1, i])
35+
h2dgi = np.diag(4 * h2 * dgi)
36+
A = mv_bond - h2dgi
37+
b1 = 8 * h2 * (0.5 * f[1:-1, i] + 0.5 * f[1:-1, i + 1] + gi)
38+
b2 = (c - h2dgi) @ u[1:-1, i].T
39+
u[1:-1, i + 1] = np.linalg.solve(A, b1 + b2)
40+
return x, t, u
41+
42+
43+
def main():
44+
xmin, xmax = -1, 1
45+
tmin, tmax = 0, 1
46+
k = lambda x: x**2 - x**2 + 1
47+
v = lambda x: np.ones_like(x)
48+
g = lambda u: u**3
49+
dg = lambda u: 3 * u**2
50+
f = lambda x, t: np.exp(-t) * (1 + x**2 - 2 * x) - (np.exp(-t) * (1 - x**2)) ** 3
51+
u0 = lambda x: (x + 1) * (1 - x)
52+
u_true = lambda x, t: np.exp(-t) * (1 - x**2)
53+
54+
# xmin, xmax = 0, 1
55+
# tmin, tmax = 0, 1
56+
# k = lambda x: np.ones_like(x)
57+
# v = lambda x: np.zeros_like(x)
58+
# g = lambda u: u ** 2
59+
# dg = lambda u: 2 * u
60+
# f = lambda x, t: x * (1 - x) + 2 * t - t ** 2 * (x - x ** 2) ** 2
61+
# u0 = lambda x: np.zeros_like(x)
62+
# u_true = lambda x, t: t * x * (1 - x)
63+
64+
Nx, Nt = 100, 100
65+
x, t, u = solve_ADR(xmin, xmax, tmin, tmax, k, v, g, dg, f, u0, Nx, Nt)
66+
67+
print(np.max(abs(u - u_true(x[:, None], t))))
68+
plt.plot(x, u)
69+
plt.show()
70+
71+
72+
if __name__ == "__main__":
73+
main()
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
import brainstate as bst
2+
import brainunit as u
3+
import jax
4+
import matplotlib.pyplot as plt
5+
import numpy as np
6+
7+
import deepxde
8+
import deepxde.experimental as deepxde_exp
9+
10+
geom = deepxde_exp.geometry.Interval(0, 1)
11+
timedomain = deepxde_exp.geometry.TimeDomain(0, 1)
12+
geomtime = deepxde_exp.geometry.GeometryXTime(geom, timedomain)
13+
geomtime = geomtime.to_dict_point("x", "t")
14+
15+
16+
# PDE
17+
def pde_eqs(x, y, aux):
18+
def solve_jac(inp1):
19+
f1 = lambda i: deepxde_exp.grad.jacobian(
20+
lambda inp: net((x[0], inp))["y"][i], inp1, vmap=False
21+
)
22+
return jax.vmap(f1)(np.arange(x[0].shape[0]))
23+
24+
jacobian = jax.vmap(solve_jac, out_axes=1)(jax.numpy.expand_dims(x[1], 1))
25+
dy_x = u.math.squeeze(jacobian[..., 0])
26+
dy_t = u.math.squeeze(jacobian[..., 1])
27+
return dy_t + dy_x
28+
29+
30+
# Net
31+
def periodic(x):
32+
x, t = x[..., :1], x[..., 1:]
33+
x = x * 2 * u.math.pi
34+
return u.math.concatenate(
35+
[u.math.cos(x), u.math.sin(x), u.math.cos(2 * x), u.math.sin(2 * x), t], axis=-1
36+
)
37+
38+
39+
dim_x = 5
40+
net = bst.nn.Sequential(
41+
deepxde_exp.nn.DeepONetCartesianProd(
42+
[50, 128, 128, 128],
43+
[dim_x, 128, 128, 128],
44+
"tanh",
45+
input_transform=periodic,
46+
),
47+
deepxde_exp.nn.ArrayToDict(y=None),
48+
)
49+
50+
ic = deepxde_exp.icbc.IC(lambda x, aux: {"y": aux})
51+
52+
# Function space
53+
func_space = deepxde.data.GRF(kernel="ExpSineSquared", length_scale=1)
54+
55+
# Problem
56+
eval_pts = np.linspace(0, 1, num=50)[:, None]
57+
problem = deepxde_exp.problem.PDEOperatorCartesianProd(
58+
geomtime,
59+
pde_eqs,
60+
ic,
61+
func_space,
62+
eval_pts,
63+
approximator=net,
64+
num_function=1000,
65+
function_variables=[0],
66+
num_fn_test=100,
67+
batch_size=32,
68+
num_domain=250,
69+
num_initial=50,
70+
num_test=500,
71+
)
72+
73+
model = deepxde_exp.Trainer(problem)
74+
model.compile(bst.optim.Adam(0.0005)).train(iterations=50000)
75+
model.saveplot(issave=True, isplot=True)
76+
77+
x = np.linspace(0, 1, num=100)
78+
t = np.linspace(0, 1, num=100)
79+
u_true = np.sin(2 * np.pi * (x - t[:, None]))
80+
plt.figure()
81+
plt.imshow(u_true)
82+
plt.colorbar()
83+
84+
v_branch = np.sin(2 * np.pi * eval_pts).T
85+
xv, tv = np.meshgrid(x, t)
86+
x_trunk = np.vstack((np.ravel(xv), np.ravel(tv))).T
87+
u_pred = model.predict((v_branch, x_trunk))["y"]
88+
u_pred = u_pred.reshape((100, 100))
89+
plt.figure()
90+
plt.imshow(u_pred)
91+
plt.colorbar()
92+
plt.show()
93+
print(deepxde_exp.metrics.l2_relative_error(u_true, u_pred))
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
import brainstate as bst
2+
import brainunit as u
3+
import jax
4+
import matplotlib.pyplot as plt
5+
import numpy as np
6+
7+
import deepxde
8+
import deepxde.experimental as deepxde_exp
9+
10+
dim_x = 5
11+
12+
13+
# PDE
14+
def pde(x, y, aux):
15+
def solve_jac(inp1):
16+
f1 = lambda i: deepxde_exp.grad.jacobian(
17+
lambda inp: net((x[0], inp))["u"][i], inp1, vmap=False
18+
)
19+
return jax.vmap(f1)(np.arange(x[0].shape[0]))
20+
21+
jacobian = jax.vmap(solve_jac, out_axes=1)(jax.numpy.expand_dims(x[1], 1))
22+
dy_x = u.math.squeeze(jacobian[..., 0])
23+
dy_t = u.math.squeeze(jacobian[..., 1])
24+
return dy_t + dy_x
25+
26+
27+
# The same problem as advection_aligned_pideeponet.py
28+
# But consider time as the 2nd space coordinate
29+
# to demonstrate the implementation of 2D problems
30+
geom = deepxde_exp.geometry.Rectangle([0, 0], [1, 1])
31+
geom = geom.to_dict_point("x", "y")
32+
33+
34+
def periodic(x):
35+
x, t = x[..., :1], x[..., 1:]
36+
x = x * 2 * np.pi
37+
return u.math.concatenate(
38+
[u.math.cos(x), u.math.sin(x), u.math.cos(2 * x), u.math.sin(2 * x), t], axis=-1
39+
)
40+
41+
42+
# Net
43+
net = bst.nn.Sequential(
44+
deepxde_exp.nn.DeepONetCartesianProd(
45+
[50, 128, 128, 128],
46+
[dim_x, 128, 128, 128],
47+
"tanh",
48+
input_transform=periodic,
49+
),
50+
deepxde_exp.nn.ArrayToDict(u=None),
51+
)
52+
53+
54+
def boundary(x, on_boundary):
55+
return u.math.logical_and(on_boundary, u.math.isclose(x["y"], 0))
56+
57+
58+
ic = deepxde_exp.icbc.DirichletBC(lambda x, aux: {"u": aux}, boundary)
59+
60+
# Function space
61+
func_space = deepxde.data.GRF(kernel="ExpSineSquared", length_scale=1)
62+
63+
# Problem
64+
eval_pts = np.linspace(0, 1, num=50)[:, None]
65+
data = deepxde_exp.problem.PDEOperatorCartesianProd(
66+
geom,
67+
pde,
68+
ic,
69+
func_space,
70+
eval_pts,
71+
approximator=net,
72+
num_function=1000,
73+
function_variables=[0],
74+
num_fn_test=100,
75+
batch_size=32,
76+
num_domain=200,
77+
num_boundary=200,
78+
)
79+
80+
trainer = deepxde_exp.Trainer(data)
81+
trainer.compile(bst.optim.Adam(0.0005)).train(iterations=30000)
82+
trainer.saveplot()
83+
84+
x = np.linspace(0, 1, num=100)
85+
t = np.linspace(0, 1, num=100)
86+
u_true = np.sin(2 * np.pi * (x - t[:, None]))
87+
plt.figure()
88+
plt.imshow(u_true)
89+
plt.colorbar()
90+
91+
v_branch = np.sin(2 * np.pi * eval_pts).T
92+
xv, tv = np.meshgrid(x, t)
93+
x_trunk = np.vstack((np.ravel(xv), np.ravel(tv))).T
94+
u_pred = trainer.predict((v_branch, x_trunk))["u"]
95+
u_pred = u_pred.reshape((100, 100))
96+
plt.figure()
97+
plt.imshow(u_pred)
98+
plt.colorbar()
99+
plt.show()
100+
print(deepxde_exp.metrics.l2_relative_error(u_true, u_pred))

0 commit comments

Comments
 (0)