[英]Python Data Structure Recommendations for a 2D Grid
我希望在Python中實現一個蟻群優化算法,雖然它是Python和面向對象編程的新手,所以學習曲線相當陡峭。 在這一點上,我被困在如何解決以下情況:
我曾嘗試過2D數組,認為array[x-coord][y-coord]
可以指向具有適當屬性的{} (dictionary)
(Obstacle: 'Yes / 'No', Pheromone Level: X %, etc.)
不幸的是,盡管NumPy允許我創建一個2D數組,但我無法將字典對象分配給各種坐標。
from numpy import *
myArray = array([[1,2,3,4],
[5,6,7,8],
[9,10,11,12]])
myArray[2][2]={}
返回:
Traceback (most recent call last):
File "/Users/amormachine/Desktop/PythonTest.py", line 7, in <module>
myArray[2][2]={}
TypeError: long() argument must be a string or a number, not 'dict'
[Finished in 0.6s with exit code 1]
我不是致力於字典或這個實施這個項目的范例,並且肯定會欣賞該集團的智慧。
確定你可以,你只是不知道你的dtype是否為int ...所以使用對象制作你的數組,你可以使用對象......
In [43]: a = [[{},{},{}],[{},{},{}]]
In [44]: a = numpy.array(a)
In [45]: a[1][1] = {'hello':'world','something':5}
In [46]: a
Out[46]:
array([[{}, {}, {}],
[{}, {'hello': 'world', 'something': 5}, {}]], dtype=object)
雖然不確定whay你會使用numpy與對象,你可能最好把它留作列表列表
在普通的Python中,我會選擇list-of-dicts方法,但是對於NumPy,我發現使用不同屬性的單獨數組更自然,而不是試圖將事物保存在一個結構中。
import numpy as np
grid_shape = (120,80)
# example of random initialization with this grid shape
pheremone_level = np.random.rand(*grid_shape)
obstacle = np.random.rand(*grid_shape) > 0.8
正如@bitwise所說,它完全取決於你想要執行的操作。 通常,NumPy中的“正確”方式將更接近於在Matlab中編寫它而不是非NumPy Python。 不幸的是我不熟悉Ant Colony Optimization的工作方式,所以我不能說什么更合適。
我正在尋找與結構化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]])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.