细胞自动机在Python中的高效模拟

2024-10-02 20:42:04 发布

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

我正在实现细胞自动机(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):
定义位置ID(x,y,z): id=int(x+(y-1)*网格大小+(z-1)*网格大小*网格大小) 返回id

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

TC[id] = [some_tumor_cell_properties]

函数neighbor generate(x,y,z)的所有26个相邻单元格,freespots为:

    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(tumorcell)的键并将它们转换为numpy.数组. 接下来,我将ndenumare应用于所有单元格的迭代。你知道吗

有什么方法可以提高代码的性能吗?事先谢谢你的帮助。你知道吗


Tags: 函数代码inidforifnpcell