二维网格的Python数据结构建议

2024-05-14 19:59:02 发布

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

我希望在Python中实现一个蚁群优化算法,虽然对于Python和面向对象编程都是新手,所以学习曲线相当陡峭。在这一点上,我要说的是:

  • 当蚂蚁在二维网格中行走时,它们会遇到障碍物、其他蚂蚁的信息素沉积、食物等。我用什么数据结构来表示这个二维世界和每个细胞的上述属性?在

我尝试了一个2D数组,认为array[x-coord][y-coord]可以指向具有适当属性(Obstacle: 'Yes / 'No', Pheromone Level: X %, etc.)的{}。不幸的是,尽管NumPy允许我创建一个2D数组,但我不能将dictionary对象分配给不同的坐标。在

from numpy import *

myArray = array([[1,2,3,4],
                 [5,6,7,8],
                 [9,10,11,12]])

myArray[2][2]={}

退货:

^{pr2}$

我不致力于字典或这个范例来实施这个项目,我当然会感谢这个团队的智慧。在


Tags: 算法信息网格数据结构属性数组array食物
3条回答

在纯Python中,我将使用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中的“正确”方式比非NumPy Python更接近于在Matlab中编写它的方式。不幸的是,我不熟悉蚁群优化的工作原理,所以我不能说什么更适合。在

我正在寻找与结构化二维网格相关的东西,谷歌把我带到了这个页面。在

我的问题是,我的解决方案并没有被问到,我的问题是,我不想在这里的二维网格结构和我的解决方案完全相关。我希望它能对搜索二维结构化网格的用户有所帮助,并被搜索引擎重定向到这里

注意:该方法只返回单元顶点和每个单元的顶点连通性。应用程序所需的其他量,如单元体积、单元质心、外接圆、内圆等,可以通过添加附加例程轻松生成

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

对函数的调用可以如下所示:

^{pr2}$

enter image description here

当然可以,如果你的数据类型是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)

虽然不确定在对象中使用numpy会有什么好处,但最好还是将其作为列表列表保留

相关问题 更多 >

    热门问题