含时Dirichlet边界条件的非定常扩散方程

2024-04-19 10:10:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我想建立一个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秒的周期。有没有更好的方法来实现这一点?或者我如何加速系统?你知道吗


Tags: nameimportmodeltimevaluevarnpplt
1条回答
网友
1楼 · 发布于 2024-04-19 10:10:30

您不想继续重新约束n_model。约束不会被替换;它们都会连续应用。相反,按照我们在^{}中演示的做。将t声明为Variable,根据该Variable约束n_model,并在每个时间步更新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()

相关问题 更多 >