我正在使用 mesa(基于代理的建模)来实现景观模型。为了生成景观,我使用了几个 numpy 数组 (800 x 800),每个数组都包含特定信息(例如海拔、土壤湿度等)。为了初始化模型,Mesa 遍历用户指定的网格大小(在本例中为 800 x 800)并将“代理”分配给网格上的每个“补丁”:
def coord_iter(self):
""" An iterator that returns coordinates as well as cell contents. """
for row in range(self.width):
for col in range(self.height):
yield self.grid[row][col], row, col # agent, x, y
然后,使用此迭代器,我将 numpy 数组中的值分配给网格上的每个 x,y:
for agent, x, y in self.grid.coord_iter(self.landscape.elevation):
# check that patch is land
if self.landscape.elevation[x, y] != -9999:
self.agents_created += 1
self.create_landscape_patch(x, y)
# set landscape_classes (i.e. 0 = bracken) if 5 then this is a deposition area
if self.landscape.vegetation[x, y] != 5:
self.create_vegetation_patch(x, y)
# populate landscape patch with values
self.add_landscape_patch(x, y)
# if deposition site
if self.landscape.vegetation[x, y] == 5:
self.create_deposition_patch(x,y)
在 numpy 数组中,有一些我不需要分配给网格的 x、y 值,所以我目前使用一个简单的“if”语句来过滤掉这些值 ( if self.landscape.elevation[x, y] != -9999:
)。显然,通过使用 coord_iter 函数,我不可避免地会执行 800 x 800 次循环,而当 numpy 数组中的值 == -9999 时,我可以避免迭代。下面给出了如何创建每个“代理”然后将其分配给台面网格的示例(景观补丁)。
def create_landscape_patch(self, x, y):
self.elevation_xy = int(self.landscape.elevation[x, y])
# calculate burn probabilities based on soil and temp
self.burn_s_m_p = self.landscape.burn_s_m_p_array[x, y]
self.burn_s_t_p = self.landscape.burn_s_t_p_array[x, y]
# calculate succession probabilities based on soil and temp
self.succ_s_m_p = self.landscape.succ_s_m_p_array[x, y]
self.succ_s_t_p = self.landscape.succ_s_t_p_array[x, y]
self.time_colonised_xy = self.landscape.time_colonised[x, y]
self.is_patch_colonised_xy = self.landscape.colonised[x, y]
def add_landscape_patch(self, x, y):
patch = Landscape(self.unique_id, (x, y), self, self.elevation_xy, self.burn_s_m_p, self.burn_s_t_p, self.vegetation_typ_xy,
False, self.time_colonised_xy, self.is_patch_colonised_xy, self.succ_s_m_p, self.succ_s_t_p, self.veg_this_patch)
self.grid.place_agent(patch, (x, y))
self.schedule.add(patch)
self.unique_id += 1
目前我的代码有效,但我知道必须有更有效的方法来实现这个结果。“构建”景观所需的时间是几分钟,我希望能构建数千个!任何有关如何提高效率的帮助将不胜感激。谢谢