具有时间依赖性Dirichlet边界条件的非平稳扩散对流方程

时间:2019-05-21 11:39:01

标签: python fipy

我想建立fipy来求解具有正弦边界的一维扩散对流方程。

我最终得到了以下代码:

from fipy import *
import numpy as np 
import matplotlib.pylab as plt

def boundary(t):
    return 1 + 0.1 * np.sin(6*np.pi*t)

nx = 50
dx = 1./nx
mesh = Grid1D(nx=nx, dx=dx)
n_model = CellVariable(name="density",mesh=mesh,value=1., hasOld=True)
D_model = CellVariable(name="D",mesh=mesh,value=mesh.x[::-1]*5.+3)
v_model = FaceVariable(name="v",mesh=mesh,value=1. )
v_model = (-1*mesh.x) * [[1.]]
n_model.constrain(boundary(0.), mesh.facesRight)
equation = (TransientTerm(var=n_model) == DiffusionTerm(coeff=D_model,var=n_model) \
                + ExponentialConvectionTerm(coeff=v_model,var=n_model))
timeStepDuration = 0.9 * dx**2 / (2 * 1)  * 1e2
time_length = 2
steps = np.int(time_length/timeStepDuration)
t = 0
n_out = np.zeros((steps,nx))
import time
t1 = time.time()
for step in xrange(steps):
    t += timeStepDuration
    n_model.updateOld()
    n_out[step] = n_model.globalValue
    n_model.constrain(boundary(t), mesh.facesRight)
    equation.solve(dt=timeStepDuration)
print "Execution time: %.3f"%(time.time()-t1)

plt.figure()
plt.imshow(n_out.T)
plt.colorbar()
plt.show()

代码运行正常,我得到了合理的结果。但是,它也相当慢,整个周期大约需要3.5秒。有没有更好的方法来实现这一目标?或如何加快系统速度?

1 个答案:

答案 0 :(得分:2)

您不想继续约束n_model。约束不会被替换;他们都被相继申请。而是执行我们在examples.diffusion.mesh1D中演示的内容。将t声明为Variable,就此n_model约束Variable,并在每个时间步更新t的值。对我来说这快了4倍。

from fipy import *
import numpy as np 
import matplotlib.pylab as plt

def boundary(t):
    return 1 + 0.1 * np.sin(6*np.pi*t)

nx = 50
dx = 1./nx
mesh = Grid1D(nx=nx, dx=dx)
n_model = CellVariable(name="density",mesh=mesh,value=1., hasOld=True)
D_model = CellVariable(name="D",mesh=mesh,value=mesh.x[::-1]*5.+3)
v_model = FaceVariable(name="v",mesh=mesh,value=1. )
v_model = (-1*mesh.x) * [[1.]]
t = Variable(value=0.)
n_model.constrain(boundary(t), mesh.facesRight)
equation = (TransientTerm(var=n_model) == DiffusionTerm(coeff=D_model,var=n_model) \
                + ExponentialConvectionTerm(coeff=v_model,var=n_model))
timeStepDuration = 0.9 * dx**2 / (2 * 1)  * 1e2
time_length = 2
steps = np.int(time_length/timeStepDuration)
n_out = np.zeros((steps,nx))
import time
t1 = time.time()
for step in xrange(steps):
    t.setValue(t() + timeStepDuration)
    n_model.updateOld()
    n_out[step] = n_model.globalValue
    equation.solve(dt=timeStepDuration)
print "Execution time: %.3f"%(time.time()-t1)

plt.figure()
plt.imshow(n_out.T)
plt.colorbar()
plt.show()