跳转至

Bracket

# linux
wget -nc https://paddle-org.bj.bcebos.com/paddlescience/datasets/bracket/bracket_dataset.tar
# windows
# curl https://paddle-org.bj.bcebos.com/paddlescience/datasets/bracket/bracket_dataset.tar -o bracket_dataset.tar
# unzip it
tar -xvf bracket_dataset.tar
python bracket.py
# linux
wget -nc https://paddle-org.bj.bcebos.com/paddlescience/datasets/bracket/bracket_dataset.tar
# windows
# curl https://paddle-org.bj.bcebos.com/paddlescience/datasets/bracket/bracket_dataset.tar -o bracket_dataset.tar
# unzip it
tar -xvf bracket_dataset.tar
python bracket.py mode=eval EVAL.pretrained_model_path=https://paddle-org.bj.bcebos.com/paddlescience/models/bracket/bracket_pretrained.pdparams
python bracket.py mode=export
# linux
wget -nc https://paddle-org.bj.bcebos.com/paddlescience/datasets/bracket/bracket_dataset.tar
# windows
# curl https://paddle-org.bj.bcebos.com/paddlescience/datasets/bracket/bracket_dataset.tar -o bracket_dataset.tar
# unzip it
tar -xvf bracket_dataset.tar
python bracket.py mode=infer
预训练模型 指标
bracket_pretrained.pdparams loss(commercial_ref_u_v_w_sigmas): 32.28704
MSE.u(commercial_ref_u_v_w_sigmas): 0.00005
MSE.v(commercial_ref_u_v_w_sigmas): 0.00000
MSE.w(commercial_ref_u_v_w_sigmas): 0.00734
MSE.sigma_xx(commercial_ref_u_v_w_sigmas): 27.64751
MSE.sigma_yy(commercial_ref_u_v_w_sigmas): 1.23101
MSE.sigma_zz(commercial_ref_u_v_w_sigmas): 0.89106
MSE.sigma_xy(commercial_ref_u_v_w_sigmas): 0.84370
MSE.sigma_xz(commercial_ref_u_v_w_sigmas): 1.42126
MSE.sigma_yz(commercial_ref_u_v_w_sigmas): 0.24510

1. 背景简介

线弹性方程在形变分析中起着核心的作用。在物理和工程领域,形变分析是研究物体在外力作用下的形状和尺寸变化的方法。线弹性方程是描述物体在受力后恢复原状的能力的数学模型。具体来说,线弹性方程通常是指应力和应变之间的关系。应力是一个物理量,用于描述物体内部由于外力而产生的单位面积上的力。应变则描述了物体的形状和尺寸的变化。线弹性方程通常可以表示为应力和应变之间的线性关系,即应力和应变是成比例的。这种关系可以用一个线性方程来表示,其中系数被称为弹性模量(或杨氏模量)。这种模型假设物体在受力后能够完全恢复原状,即没有永久变形。这种假设在许多情况下是合理的,例如在研究金属的力学行为时。然而,对于某些材料(如塑料或橡胶),这种假设可能不准确,因为它们在受力后可能会产生永久变形。线弹性方程只是形变分析中的一部分。要全面理解形变,还需要考虑其他因素,例如物体的初始形状和尺寸、外力的历史、材料的其他物理性质(如热膨胀系数和密度)等。然而,线弹性方程提供了一个基本的框架,用于描述和理解物体在受力后的行为。

本案例主要研究如下金属连接件在给定载荷下的形变情况,并使用深度学习方法根据线弹性等方程进行求解,连接件如下所示(参考 Matlab deflection-analysis-of-a-bracket)。

bracket

Bracket 金属件载荷示意图,红色区域表示载荷面

2. 问题定义

上述连接件包括一个垂直于 x 轴的背板和与之连接的垂直于 z 轴的带孔平板。其中背板处于固定状态,带孔平板的最右侧表面(红色区域)受到 z 轴负方向,单位面积大小为 \(4 \times 10^4 Pa\) 的应力;除此之外,其他参数包括弹性模量 \(E=10^{11} Pa\),泊松比 \(\nu=0.3\)。通过设置特征长度 \(L=1m\),特征位移 \(U=0.0001m\),无量纲剪切模量 \(0.01\mu\),目标求解该金属件表面每个点的 \(u\)\(v\)\(w\)\(\sigma_{xx}\)\(\sigma_{yy}\)\(\sigma_{zz}\)\(\sigma_{xy}\)\(\sigma_{xz}\)\(\sigma_{yz}\) 共 9 个物理量。常量定义代码如下:

# specify parameters
LAMBDA_ = cfg.NU * cfg.E / ((1 + cfg.NU) * (1 - 2 * cfg.NU))
MU = cfg.E / (2 * (1 + cfg.NU))
MU_C = 0.01 * MU
LAMBDA_ = LAMBDA_ / MU_C
MU = MU / MU_C
SIGMA_NORMALIZATION = cfg.CHARACTERISTIC_LENGTH / (
    cfg.CHARACTERISTIC_DISPLACEMENT * MU_C
)
T = -4.0e4 * SIGMA_NORMALIZATION

3. 问题求解

接下来开始讲解如何将问题一步一步地转化为 PaddleScience 代码,用深度学习的方法求解该问题。 为了快速理解 PaddleScience,接下来仅对模型构建、方程构建、计算域构建等关键步骤进行阐述,而其余细节请参考 API文档

3.1 模型构建

在 bracket 问题中,每一个已知的坐标点 \((x, y, z)\) 都有对应的待求解的未知量:三个方向的应变 \((u, v, w)\) 和应力 \((\sigma_{xx}, \sigma_{yy}, \sigma_{zz}, \sigma_{xy}, \sigma_{xz}, \sigma_{yz})\)

这里考虑到两组物理量对应着不同的方程,因此使用两个模型来分别预测这两组物理量:

\[ \begin{cases} u, v, w = f(x,y,z) \\ \sigma_{xx}, \sigma_{yy}, \sigma_{zz}, \sigma_{xy}, \sigma_{xz}, \sigma_{yz} = g(x,y,z) \end{cases} \]

上式中 \(f\) 即为应变模型 disp_net\(g\) 为应力模型 stress_net,用 PaddleScience 代码表示如下:

# set model
disp_net = ppsci.arch.MLP(**cfg.MODEL.disp_net)
stress_net = ppsci.arch.MLP(**cfg.MODEL.stress_net)
# wrap to a model_list
model = ppsci.arch.ModelList((disp_net, stress_net))

为了在计算时,准确快速地访问具体变量的值,在这里指定应变模型的输入变量名是 ("x", "y", "z"),输出变量名是 ("u", "v", "w"),这些命名与后续代码保持一致(应力模型同理)。

接着通过指定 MLP 的层数、神经元个数,就实例化出了一个拥有 6 层隐藏神经元,每层神经元数为 512 的神经网络模型 disp_net,使用 silu 作为激活函数,并使用 WeightNorm 权重归一化(应力模型 stress_net 同理)。

3.2 方程构建

Bracket 案例涉及到以下线弹性方程,使用 PaddleScience 内置的 LinearElasticity 即可。

$$ \begin{cases} stress_disp_{xx} = \lambda(\dfrac{\partial u}{\partial x} + \dfrac{\partial v}{\partial y} + \dfrac{\partial w}{\partial z}) + 2\mu \dfrac{\partial u}{\partial x} - \sigma_{xx} \ stress_disp_{yy} = \lambda(\dfrac{\partial u}{\partial x} + \dfrac{\partial v}{\partial y} + \dfrac{\partial w}{\partial z}) + 2\mu \dfrac{\partial v}{\partial y} - \sigma_{yy} \ stress_disp_{zz} = \lambda(\dfrac{\partial u}{\partial x} + \dfrac{\partial v}{\partial y} + \dfrac{\partial w}{\partial z}) + 2\mu \dfrac{\partial w}{\partial z} - \sigma_{zz} \ stress_disp_{xy} = \mu(\dfrac{\partial u}{\partial y} + \dfrac{\partial v}{\partial x}) - \sigma_{xy} \ stress_disp_{xz} = \mu(\dfrac{\partial u}{\partial z} + \dfrac{\partial w}{\partial x}) - \sigma_{xz} \ stress_disp_{yz} = \mu(\dfrac{\partial v}{\partial z} + \dfrac{\partial w}{\partial y}) - \sigma_{yz} \ equilibrium_{x} = \rho \dfrac{\partial^2 u}{\partial t^2} - (\dfrac{\partial \sigma_{xx}}{\partial x} + \dfrac{\partial \sigma_{xy}}{\partial y} + \dfrac{\partial \sigma_{xz}}{\partial z}) \ equilibrium_{y} = \rho \dfrac{\partial^2 u}{\partial t^2} - (\dfrac{\partial \sigma_{xy}}{\partial x} + \dfrac{\partial \sigma_{yy}}{\partial y} + \dfrac{\partial \sigma_{yz}}{\partial z}) \ equilibrium_{z} = \rho \dfrac{\partial^2 u}{\partial t^2} - (\dfrac{\partial \sigma_{xz}}{\partial x} + \dfrac{\partial \sigma_{yz}}{\partial y} + \dfrac{\partial \sigma_{zz}}{\partial z}) \ \end{cases}

对应的方程实例化代码如下:

# set equation
equation = {
    "LinearElasticity": ppsci.equation.LinearElasticity(
        lambda_=LAMBDA_, mu=MU, dim=3
    )
}

3.3 计算域构建

本问题的几何区域由 stl 文件指定,按照下方命令,下载并解压到 bracket/ 文件夹下。

注:数据集中的 stl 文件和测试集数据均来自 Bracket - NVIDIA Modulus

# linux
wget -nc https://paddle-org.bj.bcebos.com/paddlescience/datasets/bracket/bracket_dataset.tar

# windows
# curl https://paddle-org.bj.bcebos.com/paddlescience/datasets/bracket/bracket_dataset.tar -o bracket_dataset.tar

# unzip it
tar -xvf bracket_dataset.tar

解压完毕之后,bracket/stl 文件夹下即存放了计算域构建所需的 stl 几何文件。

注意

使用 Mesh 类之前,必须先按照1.4.2 额外依赖安装[可选]文档,安装好 open3d、pysdf、PyMesh 3 个几何依赖包。

然后通过 PaddleScience 内置的 STL 几何类 Mesh 来读取、解析这些几何文件,并且通过布尔运算,组合出各个计算域,代码如下:

# set geometry
support = ppsci.geometry.Mesh(cfg.SUPPORT_PATH)
bracket = ppsci.geometry.Mesh(cfg.BRACKET_PATH)
aux_lower = ppsci.geometry.Mesh(cfg.AUX_LOWER_PATH)
aux_upper = ppsci.geometry.Mesh(cfg.AUX_UPPER_PATH)
cylinder_hole = ppsci.geometry.Mesh(cfg.CYLINDER_HOLE_PATH)
cylinder_lower = ppsci.geometry.Mesh(cfg.CYLINDER_LOWER_PATH)
cylinder_upper = ppsci.geometry.Mesh(cfg.CYLINDER_UPPER_PATH)
# geometry bool operation
curve_lower = aux_lower - cylinder_lower
curve_upper = aux_upper - cylinder_upper
geo = support + bracket + curve_lower + curve_upper - cylinder_hole
geom = {"geo": geo}

3.4 约束构建

本案例共涉及到 5 个约束,在具体约束构建之前,可以先构建数据读取配置,以便后续构建多个约束时复用该配置。

# set dataloader config
train_dataloader_cfg = {
    "dataset": "NamedArrayDataset",
    "iters_per_epoch": cfg.TRAIN.iters_per_epoch,
    "sampler": {
        "name": "BatchSampler",
        "drop_last": True,
        "shuffle": True,
    },
    "num_workers": 1,
}

3.4.1 内部点约束

以作用在背板内部点的 InteriorConstraint 为例,代码如下:

support_interior = ppsci.constraint.InteriorConstraint(
    equation["LinearElasticity"].equations,
    {
        "stress_disp_xx": 0,
        "stress_disp_yy": 0,
        "stress_disp_zz": 0,
        "stress_disp_xy": 0,
        "stress_disp_xz": 0,
        "stress_disp_yz": 0,
        "equilibrium_x": 0,
        "equilibrium_y": 0,
        "equilibrium_z": 0,
    },
    geom["geo"],
    {**train_dataloader_cfg, "batch_size": cfg.TRAIN.batch_size.support_interior},
    ppsci.loss.MSELoss("sum"),
    criteria=lambda x, y, z: (
        (BOUNDS_SUPPORT_X[0] < x)
        & (x < BOUNDS_SUPPORT_X[1])
        & (BOUNDS_SUPPORT_Y[0] < y)
        & (y < BOUNDS_SUPPORT_Y[1])
        & (BOUNDS_SUPPORT_Z[0] < z)
        & (z < BOUNDS_SUPPORT_Z[1])
    ),
    weight_dict={
        "stress_disp_xx": "sdf",
        "stress_disp_yy": "sdf",
        "stress_disp_zz": "sdf",
        "stress_disp_xy": "sdf",
        "stress_disp_xz": "sdf",
        "stress_disp_yz": "sdf",
        "equilibrium_x": "sdf",
        "equilibrium_y": "sdf",
        "equilibrium_z": "sdf",
    },
    name="SUPPORT_INTERIOR",
)

InteriorConstraint 的第一个参数是方程(组)表达式,用于描述如何计算约束目标,此处填入在 3.2 方程构建 章节中实例化好的 equation["LinearElasticity"].equations

第二个参数是约束变量的目标值,在本问题中希望与 LinearElasticity 方程相关的 9 个值 equilibrium_x, equilibrium_y, equilibrium_z, stress_disp_xx, stress_disp_yy, stress_disp_zz, stress_disp_xy, stress_disp_xz, stress_disp_yz 均被优化至 0;

第三个参数是约束方程作用的计算域,此处填入在 3.3 计算域构建 章节实例化好的 geom["geo"] 即可;

第四个参数是在计算域上的采样配置,此处设置 batch_size2048

第五个参数是损失函数,此处选用常用的 MSE 函数,且 reduction 设置为 "sum",即会将参与计算的所有数据点产生的损失项求和;

第六个参数是几何点筛选,由于这个约束只施加在背板区域,因此需要对 geo 上采样出的点进行筛选,此处传入一个 lambda 筛选函数即可,其接受点集构成的张量 x, y, z,返回布尔值张亮,表示每个点是否符合筛选条件,不符合为 False,符合为 True

第七个参数是每个点参与损失计算时的权重,此处我们使用 "sdf" 表示使用每个点到边界的最短距离(符号距离函数值)来作为权重,这种 sdf 加权的方法可以加大远离边界(难样本)点的权重,减少靠近边界的(简单样本)点的权重,有利于提升模型的精度和收敛速度。

第八个参数是约束条件的名字,需要给每一个约束条件命名,方便后续对其索引。此处命名为 "support_interior" 即可。

另一个作用在带孔平板上的约束条件则与之类似,代码如下:

bracket_interior = ppsci.constraint.InteriorConstraint(
    equation["LinearElasticity"].equations,
    {
        "stress_disp_xx": 0,
        "stress_disp_yy": 0,
        "stress_disp_zz": 0,
        "stress_disp_xy": 0,
        "stress_disp_xz": 0,
        "stress_disp_yz": 0,
        "equilibrium_x": 0,
        "equilibrium_y": 0,
        "equilibrium_z": 0,
    },
    geom["geo"],
    {**train_dataloader_cfg, "batch_size": cfg.TRAIN.batch_size.bracket_interior},
    ppsci.loss.MSELoss("sum"),
    criteria=lambda x, y, z: (
        (BOUNDS_BRACKET_X[0] < x)
        & (x < BOUNDS_BRACKET_X[1])
        & (BOUNDS_BRACKET_Y[0] < y)
        & (y < BOUNDS_BRACKET_Y[1])
        & (BOUNDS_BRACKET_Z[0] < z)
        & (z < BOUNDS_BRACKET_Z[1])
    ),
    weight_dict={
        "stress_disp_xx": "sdf",
        "stress_disp_yy": "sdf",
        "stress_disp_zz": "sdf",
        "stress_disp_xy": "sdf",
        "stress_disp_xz": "sdf",
        "stress_disp_yz": "sdf",
        "equilibrium_x": "sdf",
        "equilibrium_y": "sdf",
        "equilibrium_z": "sdf",
    },
    name="BRACKET_INTERIOR",
)

3.4.2 边界约束

对于背板后表面,由于被固定,所以其上的点在三个方向的形变均为 0,因此有如下的边界约束条件:

bc_back = ppsci.constraint.BoundaryConstraint(
    {"u": lambda d: d["u"], "v": lambda d: d["v"], "w": lambda d: d["w"]},
    {"u": 0, "v": 0, "w": 0},
    geom["geo"],
    {**train_dataloader_cfg, "batch_size": cfg.TRAIN.batch_size.bc_back},
    ppsci.loss.MSELoss("sum"),
    criteria=lambda x, y, z: x == SUPPORT_ORIGIN[0],
    weight_dict=cfg.TRAIN.weight.bc_back,
    name="BC_BACK",
)

对于带孔平板右侧长方形载荷面,其上的每个点只受 z 正方向的载荷,大小为 \(T\),其余方向应力为 0,有如下边界条件约束:

bc_front = ppsci.constraint.BoundaryConstraint(
    equation["LinearElasticity"].equations,
    {"traction_x": 0, "traction_y": 0, "traction_z": T},
    geom["geo"],
    {**train_dataloader_cfg, "batch_size": cfg.TRAIN.batch_size.bc_front},
    ppsci.loss.MSELoss("sum"),
    criteria=lambda x, y, z: x == BRACKET_ORIGIN[0] + BRACKET_DIM[0],
    name="BC_FRONT",
)

对于除背板后面、带孔平板右侧长方形载荷面外的表面,不受任何载荷,即三个方向的内力平衡,合力为 0,有如下边界条件约束:

bc_surface = ppsci.constraint.BoundaryConstraint(
    equation["LinearElasticity"].equations,
    {"traction_x": 0, "traction_y": 0, "traction_z": 0},
    geom["geo"],
    {**train_dataloader_cfg, "batch_size": cfg.TRAIN.batch_size.bc_surface},
    ppsci.loss.MSELoss("sum"),
    criteria=lambda x, y, z: np.logical_and(
        x > SUPPORT_ORIGIN[0] + 1e-7, x < BRACKET_ORIGIN[0] + BRACKET_DIM[0] - 1e-7
    ),
    name="BC_SURFACE",
)

在方程约束、边界约束构建完毕之后,以刚才的命名为关键字,封装到一个字典中,方便后续访问。

# wrap constraints together
constraint = {
    bc_back.name: bc_back,
    bc_front.name: bc_front,
    bc_surface.name: bc_surface,
    support_interior.name: support_interior,
    bracket_interior.name: bracket_interior,
}

3.5 超参数设定

接下来需要在配置文件中指定训练轮数,此处按实验经验,使用 2000 轮训练轮数,每轮进行 1000 步优化。

# training settings
TRAIN:
  epochs: 2000
  iters_per_epoch: 1000

3.6 优化器构建

训练过程会调用优化器来更新模型参数,此处选择较为常用的 Adam 优化器,并配合使用机器学习中常用的 ExponentialDecay 学习率调整策略。

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

3.7 评估器构建

在训练过程中通常会按一定轮数间隔,用验证集(测试集)评估当前模型的训练情况,而验证集的数据来自外部 txt 文件,因此首先使用 ppsci.utils.reader 模块从 txt 文件中读取验证点集:

# set validator
ref_xyzu = ppsci.utils.reader.load_csv_file(
    cfg.DEFORMATION_X_PATH,
    ("x", "y", "z", "u"),
    {
        "x": "X Location (m)",
        "y": "Y Location (m)",
        "z": "Z Location (m)",
        "u": "Directional Deformation (m)",
    },
    "\t",
)
ref_v = ppsci.utils.reader.load_csv_file(
    cfg.DEFORMATION_Y_PATH,
    ("v",),
    {"v": "Directional Deformation (m)"},
    "\t",
)
ref_w = ppsci.utils.reader.load_csv_file(
    cfg.DEFORMATION_Z_PATH,
    ("w",),
    {"w": "Directional Deformation (m)"},
    "\t",
)

ref_sxx = ppsci.utils.reader.load_csv_file(
    cfg.NORMAL_X_PATH,
    ("sigma_xx",),
    {"sigma_xx": "Normal Stress (Pa)"},
    "\t",
)
ref_syy = ppsci.utils.reader.load_csv_file(
    cfg.NORMAL_Y_PATH,
    ("sigma_yy",),
    {"sigma_yy": "Normal Stress (Pa)"},
    "\t",
)
ref_szz = ppsci.utils.reader.load_csv_file(
    cfg.NORMAL_Z_PATH,
    ("sigma_zz",),
    {"sigma_zz": "Normal Stress (Pa)"},
    "\t",
)

ref_sxy = ppsci.utils.reader.load_csv_file(
    cfg.SHEAR_XY_PATH,
    ("sigma_xy",),
    {"sigma_xy": "Shear Stress (Pa)"},
    "\t",
)
ref_sxz = ppsci.utils.reader.load_csv_file(
    cfg.SHEAR_XZ_PATH,
    ("sigma_xz",),
    {"sigma_xz": "Shear Stress (Pa)"},
    "\t",
)
ref_syz = ppsci.utils.reader.load_csv_file(
    cfg.SHEAR_YZ_PATH,
    ("sigma_yz",),
    {"sigma_yz": "Shear Stress (Pa)"},
    "\t",
)

然后将其转换为字典并进行无量纲化和归一化,再将其包装成字典和 eval_dataloader_cfg(验证集dataloader配置,构造方式与 train_dataloader_cfg 类似)一起传递给 ppsci.validate.SupervisedValidator 构造评估器。

input_dict = {
    "x": ref_xyzu["x"],
    "y": ref_xyzu["y"],
    "z": ref_xyzu["z"],
}
label_dict = {
    "u": ref_xyzu["u"] / cfg.CHARACTERISTIC_DISPLACEMENT,
    "v": ref_v["v"] / cfg.CHARACTERISTIC_DISPLACEMENT,
    "w": ref_w["w"] / cfg.CHARACTERISTIC_DISPLACEMENT,
    "sigma_xx": ref_sxx["sigma_xx"] * SIGMA_NORMALIZATION,
    "sigma_yy": ref_syy["sigma_yy"] * SIGMA_NORMALIZATION,
    "sigma_zz": ref_szz["sigma_zz"] * SIGMA_NORMALIZATION,
    "sigma_xy": ref_sxy["sigma_xy"] * SIGMA_NORMALIZATION,
    "sigma_xz": ref_sxz["sigma_xz"] * SIGMA_NORMALIZATION,
    "sigma_yz": ref_syz["sigma_yz"] * SIGMA_NORMALIZATION,
}
eval_dataloader_cfg = {
    "dataset": {
        "name": "NamedArrayDataset",
        "input": input_dict,
        "label": label_dict,
    },
    "sampler": {
        "name": "BatchSampler",
        "drop_last": False,
        "shuffle": False,
    },
}
sup_validator = ppsci.validate.SupervisedValidator(
    {**eval_dataloader_cfg, "batch_size": cfg.EVAL.batch_size.sup_validator},
    ppsci.loss.MSELoss("mean"),
    {
        "u": lambda out: out["u"],
        "v": lambda out: out["v"],
        "w": lambda out: out["w"],
        "sigma_xx": lambda out: out["sigma_xx"],
        "sigma_yy": lambda out: out["sigma_yy"],
        "sigma_zz": lambda out: out["sigma_zz"],
        "sigma_xy": lambda out: out["sigma_xy"],
        "sigma_xz": lambda out: out["sigma_xz"],
        "sigma_yz": lambda out: out["sigma_yz"],
    },
    metric={"MSE": ppsci.metric.MSE()},
    name="commercial_ref_u_v_w_sigmas",
)
validator = {sup_validator.name: sup_validator}

3.8 可视化器构建

在模型评估时,如果评估结果是可以可视化的数据,可以选择合适的可视化器来对输出结果进行可视化。

本文中的输入数据是评估器构建中准备好的输入字典 input_dict,输出数据是对应的 9 个预测的物理量,因此只需要将评估的输出数据保存成 vtu格式 文件,最后用可视化软件打开查看即可。代码如下:

# set visualizer(optional)
visualizer = {
    "visualize_u_v_w_sigmas": ppsci.visualize.VisualizerVtu(
        input_dict,
        {
            "u": lambda out: out["u"],
            "v": lambda out: out["v"],
            "w": lambda out: out["w"],
            "sigma_xx": lambda out: out["sigma_xx"],
            "sigma_yy": lambda out: out["sigma_yy"],
            "sigma_zz": lambda out: out["sigma_zz"],
            "sigma_xy": lambda out: out["sigma_xy"],
            "sigma_xz": lambda out: out["sigma_xz"],
            "sigma_yz": lambda out: out["sigma_yz"],
        },
        prefix="result_u_v_w_sigmas",
    )
}

3.9 模型训练、评估与可视化

完成上述设置之后,只需要将上述实例化的对象按顺序传递给 ppsci.solver.Solver,然后启动训练、评估、可视化。

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

# evaluate after finished training
solver.eval()
# visualize prediction after finished training
solver.visualize()

4. 完整代码

bracket.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
"""
Reference: https://docs.nvidia.com/deeplearning/modulus/modulus-v2209/user_guide/foundational/linear_elasticity.html
STL data files download link: https://paddle-org.bj.bcebos.com/paddlescience/datasets/bracket/bracket_dataset.tar
pretrained model download link: https://paddle-org.bj.bcebos.com/paddlescience/models/bracket/bracket_pretrained.pdparams
"""

import hydra
import numpy as np
from omegaconf import DictConfig

import ppsci


def train(cfg: DictConfig):
    # set model
    disp_net = ppsci.arch.MLP(**cfg.MODEL.disp_net)
    stress_net = ppsci.arch.MLP(**cfg.MODEL.stress_net)
    # wrap to a model_list
    model = ppsci.arch.ModelList((disp_net, stress_net))

    # specify parameters
    LAMBDA_ = cfg.NU * cfg.E / ((1 + cfg.NU) * (1 - 2 * cfg.NU))
    MU = cfg.E / (2 * (1 + cfg.NU))
    MU_C = 0.01 * MU
    LAMBDA_ = LAMBDA_ / MU_C
    MU = MU / MU_C
    SIGMA_NORMALIZATION = cfg.CHARACTERISTIC_LENGTH / (
        cfg.CHARACTERISTIC_DISPLACEMENT * MU_C
    )
    T = -4.0e4 * SIGMA_NORMALIZATION

    # set equation
    equation = {
        "LinearElasticity": ppsci.equation.LinearElasticity(
            lambda_=LAMBDA_, mu=MU, dim=3
        )
    }

    # set geometry
    support = ppsci.geometry.Mesh(cfg.SUPPORT_PATH)
    bracket = ppsci.geometry.Mesh(cfg.BRACKET_PATH)
    aux_lower = ppsci.geometry.Mesh(cfg.AUX_LOWER_PATH)
    aux_upper = ppsci.geometry.Mesh(cfg.AUX_UPPER_PATH)
    cylinder_hole = ppsci.geometry.Mesh(cfg.CYLINDER_HOLE_PATH)
    cylinder_lower = ppsci.geometry.Mesh(cfg.CYLINDER_LOWER_PATH)
    cylinder_upper = ppsci.geometry.Mesh(cfg.CYLINDER_UPPER_PATH)
    # geometry bool operation
    curve_lower = aux_lower - cylinder_lower
    curve_upper = aux_upper - cylinder_upper
    geo = support + bracket + curve_lower + curve_upper - cylinder_hole
    geom = {"geo": geo}

    # set dataloader config
    train_dataloader_cfg = {
        "dataset": "NamedArrayDataset",
        "iters_per_epoch": cfg.TRAIN.iters_per_epoch,
        "sampler": {
            "name": "BatchSampler",
            "drop_last": True,
            "shuffle": True,
        },
        "num_workers": 1,
    }

    # set constraint
    SUPPORT_ORIGIN = (-1, -1, -1)
    BRACKET_ORIGIN = (-0.75, -1, -0.1)
    BRACKET_DIM = (1.75, 2, 0.2)
    BOUNDS_SUPPORT_X = (-1, -0.65)
    BOUNDS_SUPPORT_Y = (-1, 1)
    BOUNDS_SUPPORT_Z = (-1, 1)
    BOUNDS_BRACKET_X = (-0.65, 1)
    BOUNDS_BRACKET_Y = (-1, 1)
    BOUNDS_BRACKET_Z = (-0.1, 0.1)

    bc_back = ppsci.constraint.BoundaryConstraint(
        {"u": lambda d: d["u"], "v": lambda d: d["v"], "w": lambda d: d["w"]},
        {"u": 0, "v": 0, "w": 0},
        geom["geo"],
        {**train_dataloader_cfg, "batch_size": cfg.TRAIN.batch_size.bc_back},
        ppsci.loss.MSELoss("sum"),
        criteria=lambda x, y, z: x == SUPPORT_ORIGIN[0],
        weight_dict=cfg.TRAIN.weight.bc_back,
        name="BC_BACK",
    )
    bc_front = ppsci.constraint.BoundaryConstraint(
        equation["LinearElasticity"].equations,
        {"traction_x": 0, "traction_y": 0, "traction_z": T},
        geom["geo"],
        {**train_dataloader_cfg, "batch_size": cfg.TRAIN.batch_size.bc_front},
        ppsci.loss.MSELoss("sum"),
        criteria=lambda x, y, z: x == BRACKET_ORIGIN[0] + BRACKET_DIM[0],
        name="BC_FRONT",
    )
    bc_surface = ppsci.constraint.BoundaryConstraint(
        equation["LinearElasticity"].equations,
        {"traction_x": 0, "traction_y": 0, "traction_z": 0},
        geom["geo"],
        {**train_dataloader_cfg, "batch_size": cfg.TRAIN.batch_size.bc_surface},
        ppsci.loss.MSELoss("sum"),
        criteria=lambda x, y, z: np.logical_and(
            x > SUPPORT_ORIGIN[0] + 1e-7, x < BRACKET_ORIGIN[0] + BRACKET_DIM[0] - 1e-7
        ),
        name="BC_SURFACE",
    )
    support_interior = ppsci.constraint.InteriorConstraint(
        equation["LinearElasticity"].equations,
        {
            "stress_disp_xx": 0,
            "stress_disp_yy": 0,
            "stress_disp_zz": 0,
            "stress_disp_xy": 0,
            "stress_disp_xz": 0,
            "stress_disp_yz": 0,
            "equilibrium_x": 0,
            "equilibrium_y": 0,
            "equilibrium_z": 0,
        },
        geom["geo"],
        {**train_dataloader_cfg, "batch_size": cfg.TRAIN.batch_size.support_interior},
        ppsci.loss.MSELoss("sum"),
        criteria=lambda x, y, z: (
            (BOUNDS_SUPPORT_X[0] < x)
            & (x < BOUNDS_SUPPORT_X[1])
            & (BOUNDS_SUPPORT_Y[0] < y)
            & (y < BOUNDS_SUPPORT_Y[1])
            & (BOUNDS_SUPPORT_Z[0] < z)
            & (z < BOUNDS_SUPPORT_Z[1])
        ),
        weight_dict={
            "stress_disp_xx": "sdf",
            "stress_disp_yy": "sdf",
            "stress_disp_zz": "sdf",
            "stress_disp_xy": "sdf",
            "stress_disp_xz": "sdf",
            "stress_disp_yz": "sdf",
            "equilibrium_x": "sdf",
            "equilibrium_y": "sdf",
            "equilibrium_z": "sdf",
        },
        name="SUPPORT_INTERIOR",
    )
    bracket_interior = ppsci.constraint.InteriorConstraint(
        equation["LinearElasticity"].equations,
        {
            "stress_disp_xx": 0,
            "stress_disp_yy": 0,
            "stress_disp_zz": 0,
            "stress_disp_xy": 0,
            "stress_disp_xz": 0,
            "stress_disp_yz": 0,
            "equilibrium_x": 0,
            "equilibrium_y": 0,
            "equilibrium_z": 0,
        },
        geom["geo"],
        {**train_dataloader_cfg, "batch_size": cfg.TRAIN.batch_size.bracket_interior},
        ppsci.loss.MSELoss("sum"),
        criteria=lambda x, y, z: (
            (BOUNDS_BRACKET_X[0] < x)
            & (x < BOUNDS_BRACKET_X[1])
            & (BOUNDS_BRACKET_Y[0] < y)
            & (y < BOUNDS_BRACKET_Y[1])
            & (BOUNDS_BRACKET_Z[0] < z)
            & (z < BOUNDS_BRACKET_Z[1])
        ),
        weight_dict={
            "stress_disp_xx": "sdf",
            "stress_disp_yy": "sdf",
            "stress_disp_zz": "sdf",
            "stress_disp_xy": "sdf",
            "stress_disp_xz": "sdf",
            "stress_disp_yz": "sdf",
            "equilibrium_x": "sdf",
            "equilibrium_y": "sdf",
            "equilibrium_z": "sdf",
        },
        name="BRACKET_INTERIOR",
    )
    # wrap constraints together
    constraint = {
        bc_back.name: bc_back,
        bc_front.name: bc_front,
        bc_surface.name: bc_surface,
        support_interior.name: support_interior,
        bracket_interior.name: bracket_interior,
    }

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

    # set validator
    ref_xyzu = ppsci.utils.reader.load_csv_file(
        cfg.DEFORMATION_X_PATH,
        ("x", "y", "z", "u"),
        {
            "x": "X Location (m)",
            "y": "Y Location (m)",
            "z": "Z Location (m)",
            "u": "Directional Deformation (m)",
        },
        "\t",
    )
    ref_v = ppsci.utils.reader.load_csv_file(
        cfg.DEFORMATION_Y_PATH,
        ("v",),
        {"v": "Directional Deformation (m)"},
        "\t",
    )
    ref_w = ppsci.utils.reader.load_csv_file(
        cfg.DEFORMATION_Z_PATH,
        ("w",),
        {"w": "Directional Deformation (m)"},
        "\t",
    )

    ref_sxx = ppsci.utils.reader.load_csv_file(
        cfg.NORMAL_X_PATH,
        ("sigma_xx",),
        {"sigma_xx": "Normal Stress (Pa)"},
        "\t",
    )
    ref_syy = ppsci.utils.reader.load_csv_file(
        cfg.NORMAL_Y_PATH,
        ("sigma_yy",),
        {"sigma_yy": "Normal Stress (Pa)"},
        "\t",
    )
    ref_szz = ppsci.utils.reader.load_csv_file(
        cfg.NORMAL_Z_PATH,
        ("sigma_zz",),
        {"sigma_zz": "Normal Stress (Pa)"},
        "\t",
    )

    ref_sxy = ppsci.utils.reader.load_csv_file(
        cfg.SHEAR_XY_PATH,
        ("sigma_xy",),
        {"sigma_xy": "Shear Stress (Pa)"},
        "\t",
    )
    ref_sxz = ppsci.utils.reader.load_csv_file(
        cfg.SHEAR_XZ_PATH,
        ("sigma_xz",),
        {"sigma_xz": "Shear Stress (Pa)"},
        "\t",
    )
    ref_syz = ppsci.utils.reader.load_csv_file(
        cfg.SHEAR_YZ_PATH,
        ("sigma_yz",),
        {"sigma_yz": "Shear Stress (Pa)"},
        "\t",
    )

    input_dict = {
        "x": ref_xyzu["x"],
        "y": ref_xyzu["y"],
        "z": ref_xyzu["z"],
    }
    label_dict = {
        "u": ref_xyzu["u"] / cfg.CHARACTERISTIC_DISPLACEMENT,
        "v": ref_v["v"] / cfg.CHARACTERISTIC_DISPLACEMENT,
        "w": ref_w["w"] / cfg.CHARACTERISTIC_DISPLACEMENT,
        "sigma_xx": ref_sxx["sigma_xx"] * SIGMA_NORMALIZATION,
        "sigma_yy": ref_syy["sigma_yy"] * SIGMA_NORMALIZATION,
        "sigma_zz": ref_szz["sigma_zz"] * SIGMA_NORMALIZATION,
        "sigma_xy": ref_sxy["sigma_xy"] * SIGMA_NORMALIZATION,
        "sigma_xz": ref_sxz["sigma_xz"] * SIGMA_NORMALIZATION,
        "sigma_yz": ref_syz["sigma_yz"] * SIGMA_NORMALIZATION,
    }
    eval_dataloader_cfg = {
        "dataset": {
            "name": "NamedArrayDataset",
            "input": input_dict,
            "label": label_dict,
        },
        "sampler": {
            "name": "BatchSampler",
            "drop_last": False,
            "shuffle": False,
        },
    }
    sup_validator = ppsci.validate.SupervisedValidator(
        {**eval_dataloader_cfg, "batch_size": cfg.EVAL.batch_size.sup_validator},
        ppsci.loss.MSELoss("mean"),
        {
            "u": lambda out: out["u"],
            "v": lambda out: out["v"],
            "w": lambda out: out["w"],
            "sigma_xx": lambda out: out["sigma_xx"],
            "sigma_yy": lambda out: out["sigma_yy"],
            "sigma_zz": lambda out: out["sigma_zz"],
            "sigma_xy": lambda out: out["sigma_xy"],
            "sigma_xz": lambda out: out["sigma_xz"],
            "sigma_yz": lambda out: out["sigma_yz"],
        },
        metric={"MSE": ppsci.metric.MSE()},
        name="commercial_ref_u_v_w_sigmas",
    )
    validator = {sup_validator.name: sup_validator}

    # set visualizer(optional)
    visualizer = {
        "visualize_u_v_w_sigmas": ppsci.visualize.VisualizerVtu(
            input_dict,
            {
                "u": lambda out: out["u"],
                "v": lambda out: out["v"],
                "w": lambda out: out["w"],
                "sigma_xx": lambda out: out["sigma_xx"],
                "sigma_yy": lambda out: out["sigma_yy"],
                "sigma_zz": lambda out: out["sigma_zz"],
                "sigma_xy": lambda out: out["sigma_xy"],
                "sigma_xz": lambda out: out["sigma_xz"],
                "sigma_yz": lambda out: out["sigma_yz"],
            },
            prefix="result_u_v_w_sigmas",
        )
    }

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

    # evaluate after finished training
    solver.eval()
    # visualize prediction after finished training
    solver.visualize()


def evaluate(cfg: DictConfig):
    # set model
    disp_net = ppsci.arch.MLP(**cfg.MODEL.disp_net)
    stress_net = ppsci.arch.MLP(**cfg.MODEL.stress_net)
    # wrap to a model_list
    model = ppsci.arch.ModelList((disp_net, stress_net))

    # Specify parameters
    LAMBDA_ = cfg.NU * cfg.E / ((1 + cfg.NU) * (1 - 2 * cfg.NU))
    MU = cfg.E / (2 * (1 + cfg.NU))
    MU_C = 0.01 * MU
    LAMBDA_ = LAMBDA_ / MU_C
    MU = MU / MU_C
    SIGMA_NORMALIZATION = cfg.CHARACTERISTIC_LENGTH / (
        cfg.CHARACTERISTIC_DISPLACEMENT * MU_C
    )

    # set validator
    ref_xyzu = ppsci.utils.reader.load_csv_file(
        cfg.DEFORMATION_X_PATH,
        ("x", "y", "z", "u"),
        {
            "x": "X Location (m)",
            "y": "Y Location (m)",
            "z": "Z Location (m)",
            "u": "Directional Deformation (m)",
        },
        "\t",
    )
    ref_v = ppsci.utils.reader.load_csv_file(
        cfg.DEFORMATION_Y_PATH,
        ("v",),
        {"v": "Directional Deformation (m)"},
        "\t",
    )
    ref_w = ppsci.utils.reader.load_csv_file(
        cfg.DEFORMATION_Z_PATH,
        ("w",),
        {"w": "Directional Deformation (m)"},
        "\t",
    )

    ref_sxx = ppsci.utils.reader.load_csv_file(
        cfg.NORMAL_X_PATH,
        ("sigma_xx",),
        {"sigma_xx": "Normal Stress (Pa)"},
        "\t",
    )
    ref_syy = ppsci.utils.reader.load_csv_file(
        cfg.NORMAL_Y_PATH,
        ("sigma_yy",),
        {"sigma_yy": "Normal Stress (Pa)"},
        "\t",
    )
    ref_szz = ppsci.utils.reader.load_csv_file(
        cfg.NORMAL_Z_PATH,
        ("sigma_zz",),
        {"sigma_zz": "Normal Stress (Pa)"},
        "\t",
    )

    ref_sxy = ppsci.utils.reader.load_csv_file(
        cfg.SHEAR_XY_PATH,
        ("sigma_xy",),
        {"sigma_xy": "Shear Stress (Pa)"},
        "\t",
    )
    ref_sxz = ppsci.utils.reader.load_csv_file(
        cfg.SHEAR_XZ_PATH,
        ("sigma_xz",),
        {"sigma_xz": "Shear Stress (Pa)"},
        "\t",
    )
    ref_syz = ppsci.utils.reader.load_csv_file(
        cfg.SHEAR_YZ_PATH,
        ("sigma_yz",),
        {"sigma_yz": "Shear Stress (Pa)"},
        "\t",
    )

    input_dict = {
        "x": ref_xyzu["x"],
        "y": ref_xyzu["y"],
        "z": ref_xyzu["z"],
    }
    label_dict = {
        "u": ref_xyzu["u"] / cfg.CHARACTERISTIC_DISPLACEMENT,
        "v": ref_v["v"] / cfg.CHARACTERISTIC_DISPLACEMENT,
        "w": ref_w["w"] / cfg.CHARACTERISTIC_DISPLACEMENT,
        "sigma_xx": ref_sxx["sigma_xx"] * SIGMA_NORMALIZATION,
        "sigma_yy": ref_syy["sigma_yy"] * SIGMA_NORMALIZATION,
        "sigma_zz": ref_szz["sigma_zz"] * SIGMA_NORMALIZATION,
        "sigma_xy": ref_sxy["sigma_xy"] * SIGMA_NORMALIZATION,
        "sigma_xz": ref_sxz["sigma_xz"] * SIGMA_NORMALIZATION,
        "sigma_yz": ref_syz["sigma_yz"] * SIGMA_NORMALIZATION,
    }
    eval_dataloader_cfg = {
        "dataset": {
            "name": "NamedArrayDataset",
            "input": input_dict,
            "label": label_dict,
        },
        "sampler": {
            "name": "BatchSampler",
            "drop_last": False,
            "shuffle": False,
        },
    }
    sup_validator = ppsci.validate.SupervisedValidator(
        {**eval_dataloader_cfg, "batch_size": cfg.EVAL.batch_size.sup_validator},
        ppsci.loss.MSELoss("mean"),
        {
            "u": lambda out: out["u"],
            "v": lambda out: out["v"],
            "w": lambda out: out["w"],
            "sigma_xx": lambda out: out["sigma_xx"],
            "sigma_yy": lambda out: out["sigma_yy"],
            "sigma_zz": lambda out: out["sigma_zz"],
            "sigma_xy": lambda out: out["sigma_xy"],
            "sigma_xz": lambda out: out["sigma_xz"],
            "sigma_yz": lambda out: out["sigma_yz"],
        },
        metric={"MSE": ppsci.metric.MSE()},
        name="commercial_ref_u_v_w_sigmas",
    )
    validator = {sup_validator.name: sup_validator}

    # set visualizer(optional)
    visualizer = {
        "visualize_u_v_w_sigmas": ppsci.visualize.VisualizerVtu(
            input_dict,
            {
                "u": lambda out: out["u"],
                "v": lambda out: out["v"],
                "w": lambda out: out["w"],
                "sigma_xx": lambda out: out["sigma_xx"],
                "sigma_yy": lambda out: out["sigma_yy"],
                "sigma_zz": lambda out: out["sigma_zz"],
                "sigma_xy": lambda out: out["sigma_xy"],
                "sigma_xz": lambda out: out["sigma_xz"],
                "sigma_yz": lambda out: out["sigma_yz"],
            },
            prefix="result_u_v_w_sigmas",
        )
    }

    # initialize solver
    solver = ppsci.solver.Solver(
        model,
        output_dir=cfg.output_dir,
        log_freq=cfg.log_freq,
        seed=cfg.seed,
        validator=validator,
        visualizer=visualizer,
        pretrained_model_path=cfg.EVAL.pretrained_model_path,
        eval_with_no_grad=cfg.EVAL.eval_with_no_grad,
    )
    # evaluate
    solver.eval()
    # visualize prediction
    solver.visualize()


def export(cfg: DictConfig):
    # set model
    disp_net = ppsci.arch.MLP(**cfg.MODEL.disp_net)
    stress_net = ppsci.arch.MLP(**cfg.MODEL.stress_net)
    # wrap to a model_list
    model = ppsci.arch.ModelList((disp_net, stress_net))

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

    # 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)


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

    predictor = pinn_predictor.PINNPredictor(cfg)
    ref_xyzu = ppsci.utils.reader.load_csv_file(
        cfg.DEFORMATION_X_PATH,
        ("x", "y", "z", "u"),
        {
            "x": "X Location (m)",
            "y": "Y Location (m)",
            "z": "Z Location (m)",
            "u": "Directional Deformation (m)",
        },
        "\t",
    )
    input_dict = {
        "x": ref_xyzu["x"],
        "y": ref_xyzu["y"],
        "z": ref_xyzu["z"],
    }
    output_dict = predictor.predict(input_dict, cfg.INFER.batch_size)

    # mapping data to cfg.INFER.output_keys
    output_keys = cfg.MODEL.disp_net.output_keys + cfg.MODEL.stress_net.output_keys
    output_dict = {
        store_key: output_dict[infer_key]
        for store_key, infer_key in zip(output_keys, output_dict.keys())
    }

    ppsci.visualize.save_vtu_from_dict(
        "./bracket_pred",
        {**input_dict, **output_dict},
        input_dict.keys(),
        output_keys,
    )


@hydra.main(version_base=None, config_path="./conf", config_name="bracket.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'], but got '{cfg.mode}'")


if __name__ == "__main__":
    main()

5. 结果展示

下面展示了在测试点集上,3 个方向的挠度 \(u, v, w\) 以及 6 个应力 \(\sigma_{xx}, \sigma_{yy}, \sigma_{zz}, \sigma_{xy}, \sigma_{xz}, \sigma_{yz}\) 的模型预测结果、传统算法求解结果以及两者的差值。

bracket_compare.jpg

左侧为金属件表面预测的挠度 u;中间表示传统算法求解的挠度 u;右侧表示两者差值

bracket_compare.jpg

左侧为金属件表面预测的挠度 v;中间表示传统算法求解的挠度 v;右侧表示两者差值

bracket_compare.jpg

左侧为金属件表面预测的挠度 w;中间表示传统算法求解的挠度 w;右侧表示两者差值

bracket_compare.jpg

左侧为金属件表面预测的应力 sigma_xx;中间表示传统算法求解的应力 sigma_xx;右侧表示两者差值

bracket_compare.jpg

左侧为金属件表面预测的应力 sigma_xy;中间表示传统算法求解的应力 sigma_xy;右侧表示两者差值

bracket_compare.jpg

左侧为金属件表面预测的应力 sigma_xz;中间表示传统算法求解的应力 sigma_xz;右侧表示两者差值

bracket_compare.jpg

左侧为金属件表面预测的应力 sigma_yy;中间表示传统算法求解的应力 sigma_yy;右侧表示两者差值

bracket_compare.jpg

左侧为金属件表面预测的应力sigma_yz;中间表示传统算法求解的应力sigma_yz;右侧表示两者差值

bracket_compare.jpg

左侧为金属件表面预测的应力sigma_zz;中间表示传统算法求解的应力sigma_zz;右侧表示两者差值

可以看到模型预测的结果与 传统算法求解结果基本一致。

6. 参考资料