matplotlib 在FiPy中定义多元高斯初始条件

e1xvtsh3  于 2023-08-06  发布在  其他
关注(0)|答案(2)|浏览(103)

我在尝试用多元高斯初始条件进行Fipy积分。
我目前使用的代码如下:

from fipy import CellVariable, Grid2D, Viewer
from scipy.stats import multivariate_normal
import numpy as np
import matplotlib.pyplot as plt
plt.close('all')
# Define the grid and cell variable
nx = 40
ny = 100
dx = 1.0
dy = 1.90
mesh = Grid2D(dx=dx, dy=dy, nx=nx, ny=ny)
phi = CellVariable(name="phi", mesh=mesh)

# Set the Gaussian initial condition
mean = [nx * dx / 2, ny * dy / 2]  # Center of the Gaussian surface
covariance = [[10, 0], [0, 5]]  # Covariance matrix

# Generate coordinates for the grid
X, Y = mesh.cellCenters[0], mesh.cellCenters[1]

# Evaluate the Gaussian surface
gaussian_surface = multivariate_normal(mean=mean, cov=covariance)
Z = np.zeros_like(X)
Xm=X.value.reshape([nx,ny])
Ym=Y.value.reshape([nx,ny])

Z = gaussian_surface.pdf(np.column_stack((X.value.flat, Y.value.flat)))

# Assign the Gaussian surface to the cell variable
phi.setValue(Z)

plt.pcolor(Xm,Ym,phi.value.reshape((nx, ny)), cmap='plasma')

plt.colorbar(label='phi')
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Gaussian Initial Condition')
plt.show()

字符串
我的代码适用于正方形网格:

的数据
但它不适用于矩形的:



我该怎么解决?

n3ipq98p

n3ipq98p1#

OP的代码给出以下警告:

/tmp/ipykernel_9302/2008401024.py:32: UserWarning: The input coordinates to 
pcolor are interpreted as cell centers, but are not monotonically 
increasing or decreasing. This may lead to incorrectly calculated 
cell edges, in which case, please supply explicit cell edges to 
pcolor.  plt.pcolor(Xm,Ym,phi.value.reshape((nx, ny)), cmap='plasma')

字符串
这暗示了一个整形问题,因为行为主的矩阵存储被视为列为主(反之亦然)。因此,要修复它,我们可以在最后的步骤中使用nx, ny = ny, nx简单地反转(nx, ny)。正如预期的那样,OP的原始代码在nx=ny时工作正常。更正后的版本完整性如下所示:

from fipy import CellVariable, Grid2D, Viewer
from scipy.stats import multivariate_normal
import numpy as np
import matplotlib.pyplot as plt
plt.close('all')
# Define the grid and cell variable
nx = 40
ny = 100
dx = 1.0
dy = 1.90
mesh = Grid2D(dx=dx, dy=dy, nx=nx, ny=ny)
phi = CellVariable(name="phi", mesh=mesh)

# Set the Gaussian initial condition
mean = [nx * dx / 2, ny * dy / 2]  # Center of the Gaussian surface
covariance = [[10, 0], [0, 5]]  # Covariance matrix

# Generate coordinates for the grid
X, Y = mesh.cellCenters[0], mesh.cellCenters[1]

# Evaluate the Gaussian surface
gaussian_surface = multivariate_normal(mean=mean, cov=covariance)
Z = np.zeros_like(X)

nx, ny = ny, nx

Xm=X.value.reshape([nx,ny])
Ym=Y.value.reshape([nx,ny])

Z = gaussian_surface.pdf(np.column_stack((X.value.flat, Y.value.flat)))

# Assign the Gaussian surface to the cell variable
phi.setValue(Z)

plt.pcolor(Xm,Ym,phi.value.reshape((nx, ny)), cmap='plasma')

plt.colorbar(label='phi')
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Gaussian Initial Condition')
plt.show()


输出量:


的数据

ruyhziif

ruyhziif2#

通过调用Viewer(vars=phi).plot()可以看出,phi中的内容没有任何问题,因此我认为问题出在对plt.pcolor()的调用上。我不使用它,所以我不能建议,但我猜它与XmYmphi.value.reshape((nx, ny))之间不一致的数据形状有关。


的数据

相关问题