使用Python对元胞自动机进行高效仿真

时间:2019-12-23 15:21:55

标签: python performance numpy cellular-automata

我正在实施细胞自动机(CA)以模拟肿瘤的生长。我的目标是在三个维度上模拟CA。但是,我的代码非常慢。我希望在合理的时间内(1小时内)模拟10 ^ 6个细胞。有什么方法可以加快我的代码速度吗?我很难找到我的代码的瓶颈。

我的代码是:

   for generation in np.arange(100):
        print(len(TC.keys()))
        keys = list(TC.keys())
        keys = np.array(keys)
        for cell in np.ndenumerate(keys): # for each tumor cell
            cell_id = cell[1]
            division, migration, death = TC[cell_id].action(TC_pdivision, TC_pmigration, TC_pdeath)
            if death:
                del TC[cell_id] # remove tumor cell from dictionary
            else:  
                # find free spot
                ngh = TC[cell_id].freeSpots(cells,TC[cell_id].neighbors(TC[cell_id].x,TC[cell_id].y,TC[cell_id].z))      
               if np.size(ngh)>0:
                   ngh = np.reshape(ngh,[int(np.shape(ngh)[0]/3),3])
                   x,y,z = spot(ngh)
                  cell_id_new = positionToID(x,y,z)
                  if migration:
                     TC[cell_id_new] = TC.pop(cell_id)
                  elif division:
                     TC[cell_id_new] = TumorCell(x, y, z)

也就是说,每个肿瘤的位置在三个维度(x,y,z)中定义。每个肿瘤细胞是词典中的一个条目。我正在使用PositionToID函数转换(x,y,z):
    def positionToID(x,y,z):            id = int(x +(y-1)* gridSize +(z-1)* gridSize * gridSize)            返回ID

因此,肿瘤细胞的定义如下:

TC[id] = [some_tumor_cell_properties]

函数邻居在所有26个相邻单元格中生成(x,y,z),并且自由点为:

    def freeSpots(self, cells, ngh):
    freeSpots = np.array([])
    for neighbor in ngh:
        currNeighbor = tuple(neighbor)
        if currNeighbor not in cells:
            freeSpots = np.append(freeSpots, np.array(currNeighbor))
    return freeSpots

负责检查每个相邻的电池是否被占用。 Freespots速度很快,因此此功能不是问题。

我想,问题出在迭代器上。我试图通过提取字典TC(肿瘤细胞)的键并将其转换为numpy.array来遍历所有肿瘤细胞。接下来,我将ndenumare应用于所有单元的迭代。

有什么办法可以提高代码的性能?预先感谢您的帮助。

0 个答案:

没有答案