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

Python中细胞自动机的高效模拟,python,performance,numpy,cellular-automata,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

我正在实现细胞自动机(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位置ID(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应用于所有单元的迭代


有什么方法可以提高代码的性能吗?提前感谢您的帮助。

选择其他语言?您可以尝试timit模块查找代码速度较慢的地方。乍一看,它可能与您正在创建的所有阵列相关,但我需要进一步研究。停止使用numpy。像这样使用它很慢。例如,
freeSpots=np.append(freeSpots,np.array(currenighbor))
是二次时间非常好的点,我对freeSpots函数进行了大量修改。更改后,我的10^4个单元格的代码大约在20秒内运行。在10^6的时间内,代码运行6分钟。这是最好的办法吗?