-
Notifications
You must be signed in to change notification settings - Fork 204
/
Copy pathallen_cahn_causal.py
287 lines (242 loc) · 7.81 KB
/
allen_cahn_causal.py
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
"""
Reference: https://github.com/PredictiveIntelligenceLab/jaxpi/tree/main/examples/allen_cahn
"""
from os import path as osp
import hydra
import numpy as np
import paddle
import scipy.io as sio
from matplotlib import pyplot as plt
from omegaconf import DictConfig
import ppsci
from ppsci.utils import misc
dtype = paddle.get_default_dtype()
def plot(
t_star: np.ndarray,
x_star: np.ndarray,
u_ref: np.ndarray,
u_pred: np.ndarray,
output_dir: str,
):
fig = plt.figure(figsize=(18, 5))
TT, XX = np.meshgrid(t_star, x_star, indexing="ij")
u_ref = u_ref.reshape([len(t_star), len(x_star)])
plt.subplot(1, 3, 1)
plt.pcolor(TT, XX, u_ref, cmap="jet")
plt.colorbar()
plt.xlabel("t")
plt.ylabel("x")
plt.title("Exact")
plt.tight_layout()
plt.subplot(1, 3, 2)
plt.pcolor(TT, XX, u_pred, cmap="jet")
plt.colorbar()
plt.xlabel("t")
plt.ylabel("x")
plt.title("Predicted")
plt.tight_layout()
plt.subplot(1, 3, 3)
plt.pcolor(TT, XX, np.abs(u_ref - u_pred), cmap="jet")
plt.colorbar()
plt.xlabel("t")
plt.ylabel("x")
plt.title("Absolute error")
plt.tight_layout()
fig_path = osp.join(output_dir, "ac.png")
print(f"Saving figure to {fig_path}")
fig.savefig(fig_path, bbox_inches="tight", dpi=400)
plt.close()
def train(cfg: DictConfig):
# set model
model = ppsci.arch.MLP(**cfg.MODEL)
# set equation
equation = {"AllenCahn": ppsci.equation.AllenCahn(eps=0.01)}
data = sio.loadmat(cfg.DATA_PATH)
u_ref = data["usol"].astype(dtype) # (nt, nx)
t_star = data["t"].flatten().astype(dtype) # [nt, ]
x_star = data["x"].flatten().astype(dtype) # [nx, ]
u0 = u_ref[0, :] # [nx, ]
t0 = t_star[0] # float
t1 = t_star[-1] # float
x0 = x_star[0] # float
x1 = x_star[-1] # float
# set constraint
def gen_input_batch():
tx = np.random.uniform(
[t0, x0],
[t1, x1],
(cfg.TRAIN.batch_size, 2),
).astype(dtype)
return {
"t": np.sort(tx[:, 0:1], axis=0),
"x": tx[:, 1:2],
}
def gen_label_batch(input_batch):
return {"allen_cahn": np.zeros([cfg.TRAIN.batch_size, 1], dtype)}
pde_constraint = ppsci.constraint.SupervisedConstraint(
{
"dataset": {
"name": "ContinuousNamedArrayDataset",
"input": gen_input_batch,
"label": gen_label_batch,
},
},
output_expr=equation["AllenCahn"].equations,
loss=ppsci.loss.CausalMSELoss(
cfg.TRAIN.causal.n_chunks, "mean", tol=cfg.TRAIN.causal.tol
),
name="PDE",
)
ic_input = {"t": np.full([len(x_star), 1], t0), "x": x_star.reshape([-1, 1])}
ic_label = {"u": u0.reshape([-1, 1])}
ic = ppsci.constraint.SupervisedConstraint(
{
"dataset": {
"name": "IterableNamedArrayDataset",
"input": ic_input,
"label": ic_label,
},
},
output_expr={"u": lambda out: out["u"]},
loss=ppsci.loss.MSELoss("mean"),
name="IC",
)
# wrap constraints together
constraint = {
pde_constraint.name: pde_constraint,
ic.name: ic,
}
# set optimizer
lr_scheduler = ppsci.optimizer.lr_scheduler.ExponentialDecay(
**cfg.TRAIN.lr_scheduler
)()
optimizer = ppsci.optimizer.Adam(lr_scheduler)(model)
# set validator
tx_star = misc.cartesian_product(t_star, x_star).astype(dtype)
eval_data = {"t": tx_star[:, 0:1], "x": tx_star[:, 1:2]}
eval_label = {"u": u_ref.reshape([-1, 1])}
u_validator = ppsci.validate.SupervisedValidator(
{
"dataset": {
"name": "NamedArrayDataset",
"input": eval_data,
"label": eval_label,
},
"batch_size": cfg.EVAL.batch_size,
},
ppsci.loss.MSELoss("mean"),
{"u": lambda out: out["u"]},
metric={"L2Rel": ppsci.metric.L2Rel()},
name="u_validator",
)
validator = {u_validator.name: u_validator}
# initialize solver
solver = ppsci.solver.Solver(
model,
constraint,
optimizer=optimizer,
equation=equation,
validator=validator,
cfg=cfg,
)
# train model
solver.train()
# evaluate after finished training
solver.eval()
# visualize prediction after finished training
u_pred = solver.predict(
eval_data, batch_size=cfg.EVAL.batch_size, return_numpy=True
)["u"]
u_pred = u_pred.reshape([len(t_star), len(x_star)])
# plot
plot(t_star, x_star, u_ref, u_pred, cfg.output_dir)
def evaluate(cfg: DictConfig):
# set model
model = ppsci.arch.MLP(**cfg.MODEL)
data = sio.loadmat(cfg.DATA_PATH)
u_ref = data["usol"].astype(dtype) # (nt, nx)
t_star = data["t"].flatten().astype(dtype) # [nt, ]
x_star = data["x"].flatten().astype(dtype) # [nx, ]
# set validator
tx_star = misc.cartesian_product(t_star, x_star).astype(dtype)
eval_data = {"t": tx_star[:, 0:1], "x": tx_star[:, 1:2]}
eval_label = {"u": u_ref.reshape([-1, 1])}
u_validator = ppsci.validate.SupervisedValidator(
{
"dataset": {
"name": "NamedArrayDataset",
"input": eval_data,
"label": eval_label,
},
"batch_size": cfg.EVAL.batch_size,
},
ppsci.loss.MSELoss("mean"),
{"u": lambda out: out["u"]},
metric={"L2Rel": ppsci.metric.L2Rel()},
name="u_validator",
)
validator = {u_validator.name: u_validator}
# initialize solver
solver = ppsci.solver.Solver(
model,
validator=validator,
cfg=cfg,
)
# evaluate after finished training
solver.eval()
# visualize prediction after finished training
u_pred = solver.predict(
eval_data, batch_size=cfg.EVAL.batch_size, return_numpy=True
)["u"]
u_pred = u_pred.reshape([len(t_star), len(x_star)])
# plot
plot(t_star, x_star, u_ref, u_pred, cfg.output_dir)
def export(cfg: DictConfig):
# set model
model = ppsci.arch.MLP(**cfg.MODEL)
# initialize solver
solver = ppsci.solver.Solver(
model,
cfg=cfg,
)
# export model
from paddle.static import InputSpec
input_spec = [
{key: InputSpec([None, 1], "float32", name=key) for key in model.input_keys},
]
solver.export(input_spec, cfg.INFER.export_path, with_onnx=False)
def inference(cfg: DictConfig):
from deploy.python_infer import pinn_predictor
predictor = pinn_predictor.PINNPredictor(cfg)
data = sio.loadmat(cfg.DATA_PATH)
u_ref = data["usol"].astype(dtype) # (nt, nx)
t_star = data["t"].flatten().astype(dtype) # [nt, ]
x_star = data["x"].flatten().astype(dtype) # [nx, ]
tx_star = misc.cartesian_product(t_star, x_star).astype(dtype)
input_dict = {"t": tx_star[:, 0:1], "x": tx_star[:, 1:2]}
output_dict = predictor.predict(input_dict, cfg.INFER.batch_size)
# mapping data to cfg.INFER.output_keys
output_dict = {
store_key: output_dict[infer_key]
for store_key, infer_key in zip(cfg.MODEL.output_keys, output_dict.keys())
}
u_pred = output_dict["u"].reshape([len(t_star), len(x_star)])
plot(t_star, x_star, u_ref, u_pred, cfg.output_dir)
@hydra.main(
version_base=None, config_path="./conf", config_name="allen_cahn_causal.yaml"
)
def main(cfg: DictConfig):
if cfg.mode == "train":
train(cfg)
elif cfg.mode == "eval":
evaluate(cfg)
elif cfg.mode == "export":
export(cfg)
elif cfg.mode == "infer":
inference(cfg)
else:
raise ValueError(
f"cfg.mode should in ['train', 'eval', 'export', 'infer'], but got '{cfg.mode}'"
)
if __name__ == "__main__":
main()