我正在寻找与结构化 2D 网格相关的东西,谷歌将我带到了这个页面。
尽管我的解决方案与问题中所问的网格并不完全相关,而且我不想重复关于“结构化 2D 网格”数据结构的问题,但我在这里发布了我的解决方案。我希望它对搜索二维结构化网格并被搜索引擎重定向到这里的观众有用
注意:该方法只返回单元格顶点和每个单元格的顶点连通性。可以通过添加额外的例程轻松生成应用所需的其他量,如细胞体积、细胞质心、外接圆、内圆等
import numpy as np
import matplotlib.pyplot as plt
def create_structured_grid(corner1=None, corner2=None, nx=5, ny=5, plt_=True, annotate=True):
"""
creates a structured grid of rectangular lattice
input:
------
corner1 : [x_start, y_start]
corner2 : [x_end, y_end]
nx : numpts in x
ny : numpts in y
plt_ : boolean whether to plot or not
annotate: whether to annotate the grid points or not
output:
-------
vertex_array : numpy.array((numpts, dim),dtype=float) of vertices
connectivity : numpy.array((num_cells, 2**dim), dtyp=int) of
vertex connectivity for each cell
plots : additionally plots if boolean values are true
"""
#corner1 = np.array([0.0, 0.0])
#corner2 = np.array([1.0, 1.0])
dim = len(corner1) #currently only for 2D,
x_pts = np.linspace(corner1[0], corner2[0], nx)
y_pts = np.linspace(corner1[1], corner2[1], ny)
Xv, Yv = np.meshgrid(x_pts, y_pts)
numpts = nx*ny
vertex_array = np.zeros((numpts, 2), dtype=float)
vertex_array[:,0] = np.reshape(Xv, numpts)
vertex_array[:,1] = np.reshape(Yv, numpts)
num_cells = int(nx-1)*(ny-1)
connectivity = np.zeros((num_cells, int(2**dim)), dtype=int)
rows = ny-1
cols = nx-1
for row in range(rows):
for col in range(cols):
num = nx*row + col
connectivity[cols*row + col] = [num+0, num+1, num+nx, num+nx+1]
if plt_:
X,Y = vertex_array.T
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_aspect('equal')
plt.scatter(X,Y, marker='o', s=50, color='g', alpha=1.0)
plt.plot(Xv,Yv, linewidth=2, color='k')
plt.plot(Yv,Xv, linewidth=2, color='k')
if annotate:
for idx, cc in enumerate(vertex_array):
plt.text(cc[0], cc[1], str(idx), color='k', verticalalignment='bottom', horizontalalignment='right', fontsize='medium')
plt.show(block=False)
return vertex_array, connectivity
函数调用可以是这样的:
c1 = np.array([0.0, 0.0])
c2 = np.array([1.0, 1.0])
vertices, connctivity = create_structured_grid(corner1=c1, corner2=c2, nx=4, ny=4)
vertices = array([[ 0. , 0. ],
[ 0.33333333, 0. ],
[ 0.66666667, 0. ],
[ 1. , 0. ],
[ 0. , 0.33333333],
[ 0.33333333, 0.33333333],
[ 0.66666667, 0.33333333],
[ 1. , 0.33333333],
[ 0. , 0.66666667],
[ 0.33333333, 0.66666667],
[ 0.66666667, 0.66666667],
[ 1. , 0.66666667],
[ 0. , 1. ],
[ 0.33333333, 1. ],
[ 0.66666667, 1. ],
[ 1. , 1. ]])
connectivity = array([[ 0, 1, 5, 6],
[ 1, 2, 6, 7],
[ 2, 3, 7, 8],
[ 4, 5, 9, 10],
[ 5, 6, 10, 11],
[ 6, 7, 11, 12],
[ 8, 9, 13, 14],
[ 9, 10, 14, 15],
[10, 11, 15, 16]])