PINN求解PDE代码
时间: 2023-12-20 17:56:51 浏览: 224
以下是使用PINN求解PDE的Python代码示例:
```python
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
# 定义PINN模型
class PINN(tf.keras.Model):
def __init__(self):
super(PINN, self).__init__()
self.dense1 = tf.keras.layers.Dense(50, activation=tf.nn.tanh)
self.dense2 = tf.keras.layers.Dense(50, activation=tf.nn.tanh)
self.dense3 = tf.keras.layers.Dense(1, activation=None)
def call(self, inputs):
x = inputs[:, 0:1]
t = inputs[:, 1:2]
u = self.dense1(tf.concat([x, t], 1))
u = self.dense2(u)
u = self.dense3(u)
return u
# 定义PDE的边界条件和初始条件
def initial_condition(x):
return np.sin(np.pi * x)
def boundary_condition(x, t):
return np.exp(-np.pi**2 * t) * np.sin(np.pi * x)
# 定义PINN模型的损失函数
def loss(model, x, t, u, x_bc, t_bc, u_bc):
with tf.GradientTape(persistent=True) as tape:
tape.watch(x)
tape.watch(t)
u_pred = model(tf.concat([x, t], 1))
u_x = tape.gradient(u_pred, x)
u_t = tape.gradient(u_pred, t)
u_xx = tape.gradient(u_x, x)
f = u_t + u_pred * u_x - 0.01 * u_xx
f_bc = model(tf.concat([x_bc, t_bc], 1)) - u_bc
loss = tf.reduce_mean(tf.square(f)) + tf.reduce_mean(tf.square(f_bc))
return loss
# 定义训练函数
def train(model, x, t, u, x_bc, t_bc, u_bc, epochs):
optimizer = tf.keras.optimizers.Adam()
for epoch in range(epochs):
with tf.GradientTape() as tape:
loss_value = loss(model, x, t, u, x_bc, t_bc, u_bc)
grads = tape.gradient(loss_value, model.trainable_variables)
optimizer.apply_gradients(zip(grads, model.trainable_variables))
if epoch % 100 == 0:
print("Epoch {}: Loss = {}".format(epoch, loss_value.numpy()))
# 生成训练数据和边界数据
N = 1000
M = 100
x = np.linspace(0, 1, N)
t = np.linspace(0, 1, M)
x, t = np.meshgrid(x, t)
x, t = x.flatten()[:, None], t.flatten()[:, None]
u = initial_condition(x)
x_bc = np.concatenate((x[0:N], x[N*(M-1):N*M]), axis=0)
t_bc = np.concatenate((t[0:N], t[N*(M-1):N*M]), axis=0)
u_bc = np.concatenate((boundary_condition(x[0:N], t[0:N]), boundary_condition(x[N*(M-1):N*M], t[N*(M-1):N*M])), axis=0)
# 训练PINN模型
model = PINN()
train(model, x, t, u, x_bc, t_bc, u_bc, epochs=1000)
# 绘制预测结果
u_pred = model(tf.concat([x, t], 1))
u_pred = np.reshape(u_pred, (M, N))
plt.imshow(u_pred, cmap='jet', extent=[0, 1, 0, 1], origin='lower')
plt.colorbar()
plt.show()
```
该代码使用PINN求解了一个一维热方程,其中包括了初始条件和边界条件。在训练模型后,可以使用模型预测每个时间和空间点的温度值,并绘制成图像。
阅读全文