当前位置: 首页 > 工具软件 > Deepxde > 使用案例 >

使用Deepxde求解微分方程

文国发
2023-12-01

Deepxde 安装和学习笔记系列1

1. deepxde 安装

在conda 环境下 使用pip安装 deepxde

// Install deepxde
pip install deepxde

或者

// Install deepxde
conda install -c conda-forge deepxde

2. deepxde 使用pytorch

deepxde 默认使用tensorflow.compat.v1
因为我想使用pytorch,所以需要更换。

方法1

在c盘user文件夹里面找到.deepxde文件夹,C:\Users\hp\.deepxde
打开.deepxde文件夹里面的config.json。
改为

{"backend": "pytorch"}

方法2

打开cmd,依次运行下面的代码

cd .deepxde
config.json

然后修改config.json就可以了,改为

{"backend": "pytorch"}

3. deepxde例子

python 代码(pytorch)- 求解Burgers方程的例子

#Backend supported: tensorflow.compat.v1, tensorflow, pytorch
#Documentation: https://deepxde.readthedocs.io/en/latest/demos/burgers.html

import deepxde as dde
import numpy as np


def gen_testdata():
    data = np.load("dataset/Burgers.npz")
    t, x, exact = data["t"], data["x"], data["usol"].T
    xx, tt = np.meshgrid(x, t)
    X = np.vstack((np.ravel(xx), np.ravel(tt))).T
    y = exact.flatten()[:, None]
    return X, y


def pde(x, y):
    dy_x = dde.grad.jacobian(y, x, i=0, j=0)
    dy_t = dde.grad.jacobian(y, x, i=0, j=1)
    dy_xx = dde.grad.hessian(y, x, i=0, j=0)
    return dy_t + y * dy_x - 0.01 / np.pi * dy_xx


geom = dde.geometry.Interval(-1, 1)
timedomain = dde.geometry.TimeDomain(0, 0.99)
geomtime = dde.geometry.GeometryXTime(geom, timedomain)

bc = dde.DirichletBC(geomtime, lambda x: 0, lambda _, on_boundary: on_boundary)
ic = dde.IC(
    geomtime, lambda x: -np.sin(np.pi * x[:, 0:1]), lambda _, on_initial: on_initial
)

data = dde.data.TimePDE(
    geomtime, pde, [bc, ic], num_domain=2540, num_boundary=80, num_initial=160
)
net = dde.maps.FNN([2] + [20] * 3 + [1], "tanh", "Glorot normal")
model = dde.Model(data, net)

model.compile("adam", lr=1e-3)
model.train(epochs=15000)
model.compile("L-BFGS")
losshistory, train_state = model.train()
dde.saveplot(losshistory, train_state, issave=True, isplot=True)

X, y_true = gen_testdata()
y_pred = model.predict(X)
f = model.predict(X, operator=pde)
print("Mean residual:", np.mean(np.absolute(f)))
print("L2 relative error:", dde.metrics.l2_relative_error(y_true, y_pred))
np.savetxt("test.dat", np.hstack((X, y_true, y_pred)))

但是我运行完以后,报错了

ImportError: DLL load failed while importing _imaging: 找不到指定的模块。

卸载重新安装 Pillow 就好了, 重新安装了 几次 就成功了。

 类似资料: