Skip to content

NSFNet4

AI Studio Quick Experience

# VP_NSFNet4
# linux
wget -c https://paddle-org.bj.bcebos.com/paddlescience/datasets/NSFNet/NSF4_data.zip -P ./data/
unzip ./data/NSF4_data.zip
# windows
# curl https://paddle-org.bj.bcebos.com/paddlescience/datasets/NSFNet/NSF4_data.zip --create-dirs -o ./data/NSF4_data.zip
# unzip ./data/NSF4_data.zip
python VP_NSFNet4.py data_dir=./data/
# VP_NSFNet4
# linux
wget -c https://paddle-org.bj.bcebos.com/paddlescience/datasets/NSFNet/NSF4_data.zip -P ./data/
unzip ./data/NSF4_data.zip
# windows
# curl https://paddle-org.bj.bcebos.com/paddlescience/datasets/NSFNet/NSF4_data.zip --create-dirs -o ./data/NSF4_data.zip
# unzip ./data/NSF4_data.zip
python VP_NSFNet4.py mode=eval data_dir=./data/ EVAL.pretrained_model_path=https://paddle-org.bj.bcebos.com/paddlescience/models/nsfnet/nsfnet4.pdparams
python VP_NSFNet4.py mode=export
# VP_NSFNet4
# linux
wget -c https://paddle-org.bj.bcebos.com/paddlescience/datasets/NSFNet/NSF4_data.zip -P ./data/
unzip ./data/NSF4_data.zip
# windows
# curl https://paddle-org.bj.bcebos.com/paddlescience/datasets/NSFNet/NSF4_data.zip --create-dirs -o ./data/NSF4_data.zip
# unzip ./data/NSF4_data.zip
python VP_NSFNet4.py mode=infer

1. Background Introduction

In recent years, deep learning has achieved remarkable achievements in many fields, especially in computer vision and natural language processing. Inspired by the rapid development of deep learning and based on the powerful function approximation ability of deep learning, neural networks have also achieved success in the field of scientific computing. Current research is mainly divided into two categories. One is to add physical information and physical constraints to the loss function to train neural networks, represented by PINN and Deep Ritz Net. The other is data-driven deep neural network operators, represented by FNO and DeepONet. These methods have been widely used in scientific practice, such as weather forecasting, quantum chemistry, biological engineering, and computational fluid dynamics. In order to fully explore the ability of PINN to solve fluid equations, the author of this reproduction paper designed NSFNets, and successively used two-dimensional and three-dimensional Navier-Stokes equations with analytical or numerical solutions, as well as datasets solved with high precision using the DNS method as references, to perform forward problem solving training. The paper experiments show that PINN has excellent numerical solving capabilities for incompressible Navier-Stokes equations. The main goal of this project is to use PaddleScience to reproduce the code for high-precision solving of Navier-Stokes equations implemented in the paper.

2. Problem Definition

The classic PINN model is used for this problem, so I won't go into details.

Mainly introduce several types of Navier-Stokes equations solved:

The incompressible Navier-Stokes equation can be expressed as:

\[\frac{\partial \mathbf{u}}{\partial t}+(\mathbf{u} \cdot \nabla) \mathbf{u} =-\nabla p+\frac{1}{Re} \nabla^2 \mathbf{u} \quad \text { in } \Omega, \]
\[\nabla \cdot \mathbf{u} =0 \quad \text { in } \Omega, \]
\[\mathbf{u} =\mathbf{u}_{\Gamma} \quad \text { on } \Gamma_D, \]
\[\frac{\partial \mathbf{u}}{\partial n} =0 \quad \text { on } \Gamma_N.\]

2.1 JHTDB Dataset

The dataset is a high-precision dataset of three-dimensional incompressible forced isotropic turbulence at Re=999.35 solved using DNS. Detailed parameters can be found in readme.

3. Problem Solving

3.1 Model Construction

This paper uses the classic PINN MLP model for training.

model = ppsci.arch.MLP(**cfg.MODEL)

3.2 Data Generation

Boundary points, initial value points, and internal points for calculating residuals are taken successively (see section 3.3 of paper for specific selection method) and test points are generated.

# load data
(
    x_train,
    y_train,
    z_train,
    t_train,
    x0_train,
    y0_train,
    z0_train,
    t0_train,
    u0_train,
    v0_train,
    w0_train,
    xb_train,
    yb_train,
    zb_train,
    tb_train,
    ub_train,
    vb_train,
    wb_train,
    x_star,
    y_star,
    z_star,
    t_star,
    u_star,
    v_star,
    w_star,
    p_star,
) = generate_data(cfg.data_dir)

3.3 Normalization

To change the selected smaller rectangular area into a cubic area, we embed the normalization function before the network training.

# normalization
Xb = np.concatenate([xb_train, yb_train, zb_train, tb_train], 1)
lowb = Xb.min(0)  # minimal number in each column
upb = Xb.max(0)
trans = Transform(paddle.to_tensor(lowb), paddle.to_tensor(upb))
model.register_input_transform(trans.input_trans)

3.4 Constraint Construction

Since our boundary points and initial value points have analytical solutions, we use supervised constraints, where alpha and beta are the weights of the loss function, which are both taken as 100 in this code, consistent with the description in the paper.

sup_constraint_b = ppsci.constraint.SupervisedConstraint(
    train_dataloader_cfg_b,
    ppsci.loss.MSELoss("mean", cfg.alpha),
    name="Sup_b",
)

# supervised constraint s.t ||u-u_0||
sup_constraint_0 = ppsci.constraint.SupervisedConstraint(
    train_dataloader_cfg_ic,
    ppsci.loss.MSELoss("mean", cfg.beta),
    name="Sup_ic",
)

Use internal points to construct residual constraints of Navier-Stokes equations

# set equation constraint s.t. ||F(u)||
equation = {
    "NavierStokes": ppsci.equation.NavierStokes(
        nu=1.0 / cfg.re, rho=1.0, dim=3, time=True
    ),
}

pde_constraint = ppsci.constraint.InteriorConstraint(
    equation["NavierStokes"].equations,
    {"continuity": 0, "momentum_x": 0, "momentum_y": 0, "momentum_z": 0},
    geom,
    {
        "dataset": {"name": "NamedArrayDataset"},
        "batch_size": cfg.ntrain,
        "iters_per_epoch": cfg.TRAIN.lr_scheduler.iters_per_epoch,
        "sampler": {
            "name": "BatchSampler",
            "drop_last": False,
            "shuffle": True,
        },
    },
    ppsci.loss.MSELoss("mean"),
    name="EQ",
)

3.5 Validator Construction

Use the test set generated during data generation for model evaluation:

residual_validator = ppsci.validate.SupervisedValidator(
    valid_dataloader_cfg,
    ppsci.loss.L2RelLoss(),
    metric={"L2R": ppsci.metric.L2Rel()},
    name="Residual",
)

3.6 Optimizer Construction

Consistent with the description in the paper, we use piecewise learning rate to construct the Adam optimizer, where the number of training epochs can be adjusted by adjusting epoch_list.

# set optimizer
lr_scheduler = ppsci.optimizer.lr_scheduler.Piecewise(**cfg.TRAIN.lr_scheduler)()
optimizer = ppsci.optimizer.Adam(lr_scheduler)(model)

3.7 Model Training and Evaluation

After completing the above settings, you only need to pass the instantiated objects to ppsci.solver.Solver.

# initialize solver
solver = ppsci.solver.Solver(
    model=model,
    constraint=constraint,
    output_dir=cfg.output_dir,
    optimizer=optimizer,
    lr_scheduler=lr_scheduler,
    epochs=cfg.epochs,
    iters_per_epoch=cfg.TRAIN.lr_scheduler.iters_per_epoch,
    log_freq=cfg.TRAIN.log_freq,
    save_freq=cfg.TRAIN.save_freq,
    eval_freq=cfg.TRAIN.eval_freq,
    eval_during_train=True,
    seed=cfg.seed,
    equation=equation,
    geom=geom,
    validator=validator,
    eval_with_no_grad=cfg.TRAIN.eval_with_no_grad,
)

Finally start training:

# train model
solver.train()

4. Complete Code

NSFNet.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
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
# Copyright (c) 2023 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os.path as osp

import hydra
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import paddle
from omegaconf import DictConfig

import ppsci
from ppsci.utils import logger


def generate_data(data_dir):
    train_ini1 = np.load(osp.join(data_dir, "train_ini2.npy")).astype(
        paddle.get_default_dtype()
    )
    train_iniv1 = np.load(osp.join(data_dir, "train_iniv2.npy")).astype(
        paddle.get_default_dtype()
    )
    train_xb1 = np.load(osp.join(data_dir, "train_xb2.npy")).astype(
        paddle.get_default_dtype()
    )
    train_vb1 = np.load(osp.join(data_dir, "train_vb2.npy")).astype(
        paddle.get_default_dtype()
    )

    xnode = np.linspace(12.47, 12.66, 191).astype(paddle.get_default_dtype())
    ynode = np.linspace(-1, -0.0031, 998).astype(paddle.get_default_dtype())
    znode = np.linspace(4.61, 4.82, 211).astype(paddle.get_default_dtype())

    x0_train = train_ini1[:, 0:1]
    y0_train = train_ini1[:, 1:2]
    z0_train = train_ini1[:, 2:3]
    t0_train = np.zeros_like(train_ini1[:, 0:1]).astype(paddle.get_default_dtype())
    u0_train = train_iniv1[:, 0:1]
    v0_train = train_iniv1[:, 1:2]
    w0_train = train_iniv1[:, 2:3]

    xb_train = train_xb1[:, 0:1]
    yb_train = train_xb1[:, 1:2]
    zb_train = train_xb1[:, 2:3]
    tb_train = train_xb1[:, 3:4]
    ub_train = train_vb1[:, 0:1]
    vb_train = train_vb1[:, 1:2]
    wb_train = train_vb1[:, 2:3]

    x_train1 = xnode.reshape(-1, 1)[np.random.choice(191, 100000, replace=True), :]
    y_train1 = ynode.reshape(-1, 1)[np.random.choice(998, 100000, replace=True), :]
    z_train1 = znode.reshape(-1, 1)[np.random.choice(211, 100000, replace=True), :]
    x_train = np.tile(x_train1, (17, 1))
    y_train = np.tile(y_train1, (17, 1))
    z_train = np.tile(z_train1, (17, 1))

    total_times1 = (np.array(list(range(17))) * 0.0065).astype(
        paddle.get_default_dtype()
    )
    t_train1 = total_times1.repeat(100000)
    t_train = t_train1.reshape(-1, 1)
    # test data
    test_x = np.load(osp.join(data_dir, "test43_l.npy")).astype(
        paddle.get_default_dtype()
    )
    test_v = np.load(osp.join(data_dir, "test43_vp.npy")).astype(
        paddle.get_default_dtype()
    )
    t = np.array([0.0065, 4 * 0.0065, 7 * 0.0065, 10 * 0.0065, 13 * 0.0065]).astype(
        paddle.get_default_dtype()
    )
    t_star = np.tile(t.reshape(5, 1), (1, 3000)).reshape(-1, 1)
    x_star = np.tile(test_x[:, 0:1], (5, 1))
    y_star = np.tile(test_x[:, 1:2], (5, 1))
    z_star = np.tile(test_x[:, 2:3], (5, 1))
    u_star = test_v[:, 0:1]
    v_star = test_v[:, 1:2]
    w_star = test_v[:, 2:3]
    p_star = test_v[:, 3:4]

    return (
        x_train,
        y_train,
        z_train,
        t_train,
        x0_train,
        y0_train,
        z0_train,
        t0_train,
        u0_train,
        v0_train,
        w0_train,
        xb_train,
        yb_train,
        zb_train,
        tb_train,
        ub_train,
        vb_train,
        wb_train,
        x_star,
        y_star,
        z_star,
        t_star,
        u_star,
        v_star,
        w_star,
        p_star,
    )


class Transform:
    def __init__(self, lowb, upb) -> None:
        self.lowb = {"x": lowb[0], "y": lowb[1], "z": lowb[2], "t": lowb[3]}
        self.upb = {"x": upb[0], "y": upb[1], "z": upb[2], "t": upb[3]}

    def input_trans(self, input_dict):
        for key, v in input_dict.items():
            v = 2.0 * (v - self.lowb[key]) / (self.upb[key] - self.lowb[key]) - 1.0
            input_dict[key] = v
        return input_dict


def train(cfg: DictConfig):
    # set model
    model = ppsci.arch.MLP(**cfg.MODEL)

    # load data
    (
        x_train,
        y_train,
        z_train,
        t_train,
        x0_train,
        y0_train,
        z0_train,
        t0_train,
        u0_train,
        v0_train,
        w0_train,
        xb_train,
        yb_train,
        zb_train,
        tb_train,
        ub_train,
        vb_train,
        wb_train,
        x_star,
        y_star,
        z_star,
        t_star,
        u_star,
        v_star,
        w_star,
        p_star,
    ) = generate_data(cfg.data_dir)

    # normalization
    Xb = np.concatenate([xb_train, yb_train, zb_train, tb_train], 1)
    lowb = Xb.min(0)  # minimal number in each column
    upb = Xb.max(0)
    trans = Transform(paddle.to_tensor(lowb), paddle.to_tensor(upb))
    model.register_input_transform(trans.input_trans)

    # set dataloader config
    train_dataloader_cfg_b = {
        "dataset": {
            "name": "NamedArrayDataset",
            "input": {"x": xb_train, "y": yb_train, "z": zb_train, "t": tb_train},
            "label": {"u": ub_train, "v": vb_train, "w": wb_train},
        },
        "batch_size": cfg.nb_train,
        "iters_per_epoch": cfg.TRAIN.lr_scheduler.iters_per_epoch,
        "sampler": {
            "name": "BatchSampler",
            "drop_last": False,
            "shuffle": True,
        },
    }

    train_dataloader_cfg_ic = {
        "dataset": {
            "name": "NamedArrayDataset",
            "input": {"x": x0_train, "y": y0_train, "z": z0_train, "t": t0_train},
            "label": {"u": u0_train, "v": v0_train, "w": w0_train},
        },
        "batch_size": cfg.n0_train,
        "iters_per_epoch": cfg.TRAIN.lr_scheduler.iters_per_epoch,
        "sampler": {
            "name": "BatchSampler",
            "drop_last": False,
            "shuffle": True,
        },
    }

    valid_dataloader_cfg = {
        "dataset": {
            "name": "NamedArrayDataset",
            "input": {"x": x_star, "y": y_star, "z": z_star, "t": t_star},
            "label": {"u": u_star, "v": v_star, "w": w_star, "p": p_star},
        },
        "total_size": u_star.shape[0],
        "batch_size": u_star.shape[0],
        "sampler": {
            "name": "BatchSampler",
            "drop_last": False,
            "shuffle": True,
        },
    }

    geom = ppsci.geometry.PointCloud(
        {"x": x_train, "y": y_train, "z": z_train, "t": t_train}, ("x", "y", "z", "t")
    )
    # supervised constraint s.t ||u-u_b||
    sup_constraint_b = ppsci.constraint.SupervisedConstraint(
        train_dataloader_cfg_b,
        ppsci.loss.MSELoss("mean", cfg.alpha),
        name="Sup_b",
    )

    # supervised constraint s.t ||u-u_0||
    sup_constraint_0 = ppsci.constraint.SupervisedConstraint(
        train_dataloader_cfg_ic,
        ppsci.loss.MSELoss("mean", cfg.beta),
        name="Sup_ic",
    )

    # set equation constraint s.t. ||F(u)||
    equation = {
        "NavierStokes": ppsci.equation.NavierStokes(
            nu=1.0 / cfg.re, rho=1.0, dim=3, time=True
        ),
    }

    pde_constraint = ppsci.constraint.InteriorConstraint(
        equation["NavierStokes"].equations,
        {"continuity": 0, "momentum_x": 0, "momentum_y": 0, "momentum_z": 0},
        geom,
        {
            "dataset": {"name": "NamedArrayDataset"},
            "batch_size": cfg.ntrain,
            "iters_per_epoch": cfg.TRAIN.lr_scheduler.iters_per_epoch,
            "sampler": {
                "name": "BatchSampler",
                "drop_last": False,
                "shuffle": True,
            },
        },
        ppsci.loss.MSELoss("mean"),
        name="EQ",
    )

    # wrap constraints
    constraint = {
        pde_constraint.name: pde_constraint,
        sup_constraint_b.name: sup_constraint_b,
        sup_constraint_0.name: sup_constraint_0,
    }

    residual_validator = ppsci.validate.SupervisedValidator(
        valid_dataloader_cfg,
        ppsci.loss.L2RelLoss(),
        metric={"L2R": ppsci.metric.L2Rel()},
        name="Residual",
    )

    # wrap validator
    validator = {residual_validator.name: residual_validator}

    # set optimizer
    lr_scheduler = ppsci.optimizer.lr_scheduler.Piecewise(**cfg.TRAIN.lr_scheduler)()
    optimizer = ppsci.optimizer.Adam(lr_scheduler)(model)
    # initialize solver
    solver = ppsci.solver.Solver(
        model=model,
        constraint=constraint,
        output_dir=cfg.output_dir,
        optimizer=optimizer,
        lr_scheduler=lr_scheduler,
        epochs=cfg.epochs,
        iters_per_epoch=cfg.TRAIN.lr_scheduler.iters_per_epoch,
        log_freq=cfg.TRAIN.log_freq,
        save_freq=cfg.TRAIN.save_freq,
        eval_freq=cfg.TRAIN.eval_freq,
        eval_during_train=True,
        seed=cfg.seed,
        equation=equation,
        geom=geom,
        validator=validator,
        eval_with_no_grad=cfg.TRAIN.eval_with_no_grad,
    )
    # train model
    solver.train()

    # evaluate after finished training
    solver.eval()

    solver.plot_loss_history()


def evaluate(cfg: DictConfig):
    # set model
    model = ppsci.arch.MLP(**cfg.MODEL)

    # test Data
    test_x = np.load(osp.join(cfg.data_dir, "test43_l.npy")).astype(
        paddle.get_default_dtype()
    )
    test_v = np.load(osp.join(cfg.data_dir, "test43_vp.npy")).astype(
        paddle.get_default_dtype()
    )
    t = np.array([0.0065, 4 * 0.0065, 7 * 0.0065, 10 * 0.0065, 13 * 0.0065]).astype(
        paddle.get_default_dtype()
    )
    t_star = paddle.to_tensor(np.tile(t.reshape(5, 1), (1, 3000)).reshape(-1, 1))
    x_star = paddle.to_tensor(np.tile(test_x[:, 0:1], (5, 1)).reshape(-1, 1))
    y_star = paddle.to_tensor(np.tile(test_x[:, 1:2], (5, 1)).reshape(-1, 1))
    z_star = paddle.to_tensor(np.tile(test_x[:, 2:3], (5, 1)).reshape(-1, 1))
    u_star = paddle.to_tensor(test_v[:, 0:1])
    v_star = paddle.to_tensor(test_v[:, 1:2])
    w_star = paddle.to_tensor(test_v[:, 2:3])
    p_star = paddle.to_tensor(test_v[:, 3:4])

    # wrap validator
    ppsci.utils.load_pretrain(model, cfg.EVAL.pretrained_model_path)

    # print the relative error
    solution = model(
        {
            "x": x_star,
            "y": y_star,
            "z": z_star,
            "t": t_star,
        }
    )
    u_pred = solution["u"].reshape((5, -1))
    v_pred = solution["v"].reshape((5, -1))
    w_pred = solution["w"].reshape((5, -1))
    p_pred = solution["p"].reshape((5, -1))
    u_star = u_star.reshape((5, -1))
    v_star = v_star.reshape((5, -1))
    w_star = w_star.reshape((5, -1))
    p_star = p_star.reshape((5, -1))

    # NS equation can figure out pressure drop, need background pressure p_star.mean()
    p_pred = p_pred - p_pred.mean() + p_star.mean()

    u_error = paddle.linalg.norm(u_pred - u_star, axis=1) / np.linalg.norm(
        u_star, axis=1
    )
    v_error = paddle.linalg.norm(v_pred - v_star, axis=1) / np.linalg.norm(
        v_star, axis=1
    )
    w_error = paddle.linalg.norm(w_pred - w_star, axis=1) / np.linalg.norm(
        w_star, axis=1
    )
    p_error = paddle.linalg.norm(p_pred - p_star, axis=1) / np.linalg.norm(
        w_star, axis=1
    )
    t = np.array([0.0065, 4 * 0.0065, 7 * 0.0065, 10 * 0.0065, 13 * 0.0065])
    plt.plot(t, np.array(u_error))
    plt.plot(t, np.array(v_error))
    plt.plot(t, np.array(w_error))
    plt.plot(t, np.array(p_error))
    plt.legend(["u_error", "v_error", "w_error", "p_error"])
    plt.xlabel("t")
    plt.ylabel("Relative l2 Error")
    plt.title("Relative l2 Error, on test dataset")
    plt.savefig(osp.join(cfg.output_dir, "error.jpg"))
    logger.info("L2 error picture is saved")

    grid_x, grid_y = np.mgrid[
        x_star.min().item() : x_star.max().item() : 100j,
        y_star.min().item() : y_star.max().item() : 100j,
    ]
    x_plot = paddle.to_tensor(grid_x.reshape(-1, 1), paddle.float32)
    y_plot = paddle.to_tensor(grid_y.reshape(-1, 1), paddle.float32)
    z_plot = paddle.to_tensor(z_star.min() * paddle.ones(y_plot.shape), paddle.float32)
    t_plot = paddle.to_tensor((t[-1]) * np.ones(x_plot.shape), paddle.float32)
    sol = model({"x": x_plot, "y": y_plot, "z": z_plot, "t": t_plot})
    fig, ax = plt.subplots(1, 4, figsize=(16, 4))
    cmap = matplotlib.colormaps.get_cmap("jet")

    ax[0].contourf(grid_x, grid_y, sol["u"].reshape(grid_x.shape), levels=50, cmap=cmap)
    ax[0].set_title("u prediction")
    ax[1].contourf(grid_x, grid_y, sol["v"].reshape(grid_x.shape), levels=50, cmap=cmap)
    ax[1].set_title("v prediction")
    ax[2].contourf(grid_x, grid_y, sol["w"].reshape(grid_x.shape), levels=50, cmap=cmap)
    ax[2].set_title("w prediction")
    ax[3].contourf(grid_x, grid_y, sol["p"].reshape(grid_x.shape), levels=50, cmap=cmap)
    ax[3].set_title("p prediction")
    norm = matplotlib.colors.Normalize(
        vmin=sol["u"].min(), vmax=sol["u"].max()
    )  # set maximum and minimum
    im = plt.cm.ScalarMappable(norm=norm, cmap=cmap)
    ax13 = fig.add_axes([0.125, 0.0, 0.175, 0.02])
    plt.colorbar(im, cax=ax13, orientation="horizontal")
    ax13 = fig.add_axes([0.325, 0.0, 0.175, 0.02])
    plt.colorbar(im, cax=ax13, orientation="horizontal")
    ax13 = fig.add_axes([0.525, 0.0, 0.175, 0.02])
    plt.colorbar(im, cax=ax13, orientation="horizontal")
    ax13 = fig.add_axes([0.725, 0.0, 0.175, 0.02])
    plt.colorbar(im, cax=ax13, orientation="horizontal")
    plt.savefig(osp.join(cfg.output_dir, "z=0 plane"))

    grid_y, grid_z = np.mgrid[
        y_star.min().item() : y_star.max().item() : 100j,
        z_star.min().item() : z_star.max().item() : 100j,
    ].astype(paddle.get_default_dtype())
    z_plot = paddle.to_tensor(grid_z.reshape(-1, 1))
    y_plot = paddle.to_tensor(grid_y.reshape(-1, 1))
    x_plot = paddle.to_tensor(x_star.min() * paddle.ones(y_plot.shape))
    t_plot = paddle.to_tensor((t[-1]) * np.ones(x_plot.shape), paddle.float32)
    sol = model({"x": x_plot, "y": y_plot, "z": z_plot, "t": t_plot})
    fig, ax = plt.subplots(1, 4, figsize=(16, 4))
    cmap = matplotlib.colormaps.get_cmap("jet")

    ax[0].contourf(grid_y, grid_z, sol["u"].reshape(grid_x.shape), levels=50, cmap=cmap)
    ax[0].set_title("u prediction")
    ax[1].contourf(grid_y, grid_z, sol["v"].reshape(grid_x.shape), levels=50, cmap=cmap)
    ax[1].set_title("v prediction")
    ax[2].contourf(grid_y, grid_z, sol["w"].reshape(grid_x.shape), levels=50, cmap=cmap)
    ax[2].set_title("w prediction")
    ax[3].contourf(grid_y, grid_z, sol["p"].reshape(grid_x.shape), levels=50, cmap=cmap)
    ax[3].set_title("p prediction")
    norm = matplotlib.colors.Normalize(
        vmin=sol["u"].min(), vmax=sol["u"].max()
    )  # set maximum and minimum
    im = plt.cm.ScalarMappable(norm=norm, cmap=cmap)
    ax13 = fig.add_axes([0.125, 0.0, 0.175, 0.02])
    plt.colorbar(im, cax=ax13, orientation="horizontal")
    ax13 = fig.add_axes([0.325, 0.0, 0.175, 0.02])
    plt.colorbar(im, cax=ax13, orientation="horizontal")
    ax13 = fig.add_axes([0.525, 0.0, 0.175, 0.02])
    plt.colorbar(im, cax=ax13, orientation="horizontal")
    ax13 = fig.add_axes([0.725, 0.0, 0.175, 0.02])
    plt.colorbar(im, cax=ax13, orientation="horizontal")
    plt.savefig(osp.join(cfg.output_dir, "x=0 plane"))


def export(cfg: DictConfig):
    from paddle.static import InputSpec

    # set models
    model = ppsci.arch.MLP(**cfg.MODEL)

    # load pretrained model
    solver = ppsci.solver.Solver(
        model=model, pretrained_model_path=cfg.INFER.pretrained_model_path
    )

    # export models
    input_spec = [
        {key: InputSpec([None, 1], "float32", name=key) for key in model.input_keys},
    ]
    solver.export(input_spec, cfg.INFER.export_path)


def inference(cfg: DictConfig):
    from deploy.python_infer import pinn_predictor

    # set model predictor
    predictor = pinn_predictor.PINNPredictor(cfg)

    # infer Data
    test_x = np.load(osp.join(cfg.data_dir, "test43_l.npy")).astype(np.float32)
    test_v = np.load(osp.join(cfg.data_dir, "test43_vp.npy")).astype(np.float32)
    t = np.array([0.0065, 4 * 0.0065, 7 * 0.0065, 10 * 0.0065, 13 * 0.0065]).astype(
        np.float32
    )
    t_star = np.tile(t.reshape(5, 1), (1, 3000)).reshape(-1, 1)
    x_star = np.tile(test_x[:, 0:1], (5, 1)).reshape(-1, 1)
    y_star = np.tile(test_x[:, 1:2], (5, 1)).reshape(-1, 1)
    z_star = np.tile(test_x[:, 2:3], (5, 1)).reshape(-1, 1)
    u_star = test_v[:, 0:1]
    v_star = test_v[:, 1:2]
    w_star = test_v[:, 2:3]
    p_star = test_v[:, 3:4]

    pred = predictor.predict(
        {
            "x": x_star,
            "y": y_star,
            "z": z_star,
            "t": t_star,
        },
        cfg.INFER.batch_size,
    )

    pred = {
        store_key: pred[infer_key]
        for store_key, infer_key in zip(cfg.INFER.output_keys, pred.keys())
    }

    u_pred = pred["u"].reshape((5, -1))
    v_pred = pred["v"].reshape((5, -1))
    w_pred = pred["w"].reshape((5, -1))
    p_pred = pred["p"].reshape((5, -1))
    u_star = u_star.reshape((5, -1))
    v_star = v_star.reshape((5, -1))
    w_star = w_star.reshape((5, -1))
    p_star = p_star.reshape((5, -1))

    # NS equation can figure out pressure drop, need background pressure p_star.mean()
    p_pred = p_pred - p_pred.mean() + p_star.mean()

    u_error = np.linalg.norm(u_pred - u_star, axis=1) / np.linalg.norm(u_star, axis=1)
    v_error = np.linalg.norm(v_pred - v_star, axis=1) / np.linalg.norm(v_star, axis=1)
    w_error = np.linalg.norm(w_pred - w_star, axis=1) / np.linalg.norm(w_star, axis=1)
    p_error = np.linalg.norm(p_pred - p_star, axis=1) / np.linalg.norm(w_star, axis=1)
    t = np.array([0.0065, 4 * 0.0065, 7 * 0.0065, 10 * 0.0065, 13 * 0.0065])
    plt.plot(t, np.array(u_error))
    plt.plot(t, np.array(v_error))
    plt.plot(t, np.array(w_error))
    plt.plot(t, np.array(p_error))
    plt.legend(["u_error", "v_error", "w_error", "p_error"])
    plt.xlabel("t")
    plt.ylabel("Relative l2 Error")
    plt.title("Relative l2 Error, on test dataset")
    plt.savefig(osp.join(cfg.output_dir, "error.jpg"))

    grid_x, grid_y = np.mgrid[
        x_star.min().item() : x_star.max().item() : 100j,
        y_star.min().item() : y_star.max().item() : 100j,
    ].astype(np.float32)
    x_plot = grid_x.reshape(-1, 1)
    y_plot = grid_y.reshape(-1, 1)
    z_plot = (z_star.min() * np.ones(y_plot.shape)).astype(np.float32)
    t_plot = ((t[-1]) * np.ones(x_plot.shape)).astype(np.float32)
    sol = predictor.predict(
        {"x": x_plot, "y": y_plot, "z": z_plot, "t": t_plot}, cfg.INFER.batch_size
    )
    sol = {
        store_key: sol[infer_key]
        for store_key, infer_key in zip(cfg.INFER.output_keys, sol.keys())
    }
    fig, ax = plt.subplots(1, 4, figsize=(16, 4))
    cmap = matplotlib.colormaps.get_cmap("jet")

    ax[0].contourf(grid_x, grid_y, sol["u"].reshape(grid_x.shape), levels=50, cmap=cmap)
    ax[0].set_title("u prediction")
    ax[1].contourf(grid_x, grid_y, sol["v"].reshape(grid_x.shape), levels=50, cmap=cmap)
    ax[1].set_title("v prediction")
    ax[2].contourf(grid_x, grid_y, sol["w"].reshape(grid_x.shape), levels=50, cmap=cmap)
    ax[2].set_title("w prediction")
    ax[3].contourf(grid_x, grid_y, sol["p"].reshape(grid_x.shape), levels=50, cmap=cmap)
    ax[3].set_title("p prediction")
    norm = matplotlib.colors.Normalize(
        vmin=sol["u"].min(), vmax=sol["u"].max()
    )  # set maximum and minimum
    im = plt.cm.ScalarMappable(norm=norm, cmap=cmap)
    ax13 = fig.add_axes([0.125, 0.0, 0.175, 0.02])
    plt.colorbar(im, cax=ax13, orientation="horizontal")
    ax13 = fig.add_axes([0.325, 0.0, 0.175, 0.02])
    plt.colorbar(im, cax=ax13, orientation="horizontal")
    ax13 = fig.add_axes([0.525, 0.0, 0.175, 0.02])
    plt.colorbar(im, cax=ax13, orientation="horizontal")
    ax13 = fig.add_axes([0.725, 0.0, 0.175, 0.02])
    plt.colorbar(im, cax=ax13, orientation="horizontal")
    plt.savefig(osp.join(cfg.output_dir, "z=0 plane"))

    grid_y, grid_z = np.mgrid[
        y_star.min().item() : y_star.max().item() : 100j,
        z_star.min().item() : z_star.max().item() : 100j,
    ].astype(np.float32)
    z_plot = grid_z.reshape(-1, 1)
    y_plot = grid_y.reshape(-1, 1)
    x_plot = (x_star.min() * np.ones(y_plot.shape)).astype(np.float32)
    t_plot = ((t[-1]) * np.ones(x_plot.shape)).astype(np.float32)
    sol = predictor.predict(
        {"x": x_plot, "y": y_plot, "z": z_plot, "t": t_plot}, cfg.INFER.batch_size
    )
    sol = {
        store_key: sol[infer_key]
        for store_key, infer_key in zip(cfg.INFER.output_keys, sol.keys())
    }
    fig, ax = plt.subplots(1, 4, figsize=(16, 4))
    cmap = matplotlib.colormaps.get_cmap("jet")

    ax[0].contourf(grid_y, grid_z, sol["u"].reshape(grid_x.shape), levels=50, cmap=cmap)
    ax[0].set_title("u prediction")
    ax[1].contourf(grid_y, grid_z, sol["v"].reshape(grid_x.shape), levels=50, cmap=cmap)
    ax[1].set_title("v prediction")
    ax[2].contourf(grid_y, grid_z, sol["w"].reshape(grid_x.shape), levels=50, cmap=cmap)
    ax[2].set_title("w prediction")
    ax[3].contourf(grid_y, grid_z, sol["p"].reshape(grid_x.shape), levels=50, cmap=cmap)
    ax[3].set_title("p prediction")
    norm = matplotlib.colors.Normalize(
        vmin=sol["u"].min(), vmax=sol["u"].max()
    )  # set maximum and minimum
    im = plt.cm.ScalarMappable(norm=norm, cmap=cmap)
    ax13 = fig.add_axes([0.125, 0.0, 0.175, 0.02])
    plt.colorbar(im, cax=ax13, orientation="horizontal")
    ax13 = fig.add_axes([0.325, 0.0, 0.175, 0.02])
    plt.colorbar(im, cax=ax13, orientation="horizontal")
    ax13 = fig.add_axes([0.525, 0.0, 0.175, 0.02])
    plt.colorbar(im, cax=ax13, orientation="horizontal")
    ax13 = fig.add_axes([0.725, 0.0, 0.175, 0.02])
    plt.colorbar(im, cax=ax13, orientation="horizontal")
    plt.savefig(osp.join(cfg.output_dir, "x=0 plane"))


@hydra.main(version_base=None, config_path="./conf", config_name="VP_NSFNet4.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()

5. Result Display

NSFNet4

As shown in the figure, the error of NSFNet in time is relatively stable, and the error accumulation problem often found in traditional methods does not appear. Among them, although the velocities in the three directions were not weighted during the training process, it can be seen from the training results that the neural network has the best approximation effect on the first velocity direction u, followed by the third velocity direction w, and the second velocity v has the worst approximation effect and a relatively obvious error accumulation phenomenon appears. image

As shown in the figure, in the contour map of the y-z plane at x=12.47, the first one is the contour map of velocity u, the second is the contour map of velocity v, the third is the contour map of velocity w, and the fourth is the contour map of velocity p. It can be seen that the contour map of velocity u is relatively smoother than v, w, p. image

As shown in the figure, in the contour map of the x-y plane at z=4.61, the first one is the contour map of velocity u, the second is the contour map of velocity v, the third is the contour map of velocity w, and the fourth is the contour map of velocity p. It can be seen that the contour map of velocity u is relatively smoother than v, w, p. image

In summary, although u, v, w three velocity directions all require neural network training, for the JHTDB dataset, u direction data is smoother and easier to be learned by neural networks. Therefore, in subsequent research, we can try to divide and conquer the components in three different directions, increase the training intensity of complex component directions, and reduce the training intensity of simple component directions.

6. Results Description

We use PINN to numerically solve the incompressible Navier-Stokes equations. In PINN, randomly selected time and space coordinates are used as input values, corresponding velocity fields and pressure fields are used as output values, and initial values, boundary conditions are used as supervised constraints and the Navier-Stokes equation itself is used as unsupervised constraints added to the loss function for training. We use high-precision JHTDB dataset for training. Through the decrease of the loss function, the convergence of the neural network in solving the Navier-Stokes equation can be proven, indicating that PINN possesses the ability to solve incompressible forced isotropic turbulence. The experimental results show that PINN can well approximate the corresponding high-precision incompressible forced isotropic turbulence dataset, and we found that increasing the weights of boundary constraints and initial value constraints can enable the neural network to have better approximation effects. In contrast, within the allowable error range, using PINN to solve the Navier-Stokes equation is faster than the original DNS method inference speed.

7. References