本文整理汇总了Python中mesa.space.SingleGrid类的典型用法代码示例。如果您正苦于以下问题:Python SingleGrid类的具体用法?Python SingleGrid怎么用?Python SingleGrid使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了SingleGrid类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: WorldModel
class WorldModel(Model):
def __init__(self, N, width, height):
self.grid = SingleGrid(height, width, True)
self.schedule = RandomActivation(self)
self.num_agents = N
self.running = True
for i in range(self.num_agents):
ethnicity = random.choice(Ethnicities)
a = PersonAgent(unique_id=i,
model=self,
ethnicity=int(ethnicity)
)
self.schedule.add(a)
# Add the agent to a random grid cell
self.grid.position_agent(a)
self.datacollector = DataCollector(
agent_reporters={
"Nationalism": lambda a: a.nationalism,
"X": lambda a: a.pos[0],
"Y": lambda a: a.pos[1]
}
)
def step(self):
self.datacollector.collect(self)
self.schedule.step()
示例2: ShapesModel
class ShapesModel(Model):
def __init__(self, N, width=20, height=10):
self.running = True
self.N = N # num of agents
self.headings = ((1, 0), (0, 1), (-1, 0), (0, -1)) # tuples are fast
self.grid = SingleGrid(width, height, torus=False)
self.schedule = RandomActivation(self)
self.make_walker_agents()
def make_walker_agents(self):
unique_id = 0
while True:
if unique_id == self.N:
break
x = random.randrange(self.grid.width)
y = random.randrange(self.grid.height)
pos = (x, y)
heading = random.choice(self.headings)
# heading = (1, 0)
if self.grid.is_cell_empty(pos):
print("Creating agent {2} at ({0}, {1})"
.format(x, y, unique_id))
a = Walker(unique_id, self, pos, heading)
self.schedule.add(a)
self.grid.place_agent(a, pos)
unique_id += 1
def step(self):
self.schedule.step()
示例3: Schelling
class Schelling(Model):
'''
Model class for the Schelling segregation model.
'''
def __init__(self, height=20, width=20, density=0.8, minority_pc=0.2, homophily=3):
'''
'''
self.height = height
self.width = width
self.density = density
self.minority_pc = minority_pc
self.homophily = homophily
self.schedule = RandomActivation(self)
self.grid = SingleGrid(height, width, torus=True)
self.happy = 0
self.datacollector = DataCollector(
{"happy": "happy"}, # Model-level count of happy agents
# For testing purposes, agent's individual x and y
{"x": lambda a: a.pos[0], "y": lambda a: a.pos[1]})
# Set up agents
# We use a grid iterator that returns
# the coordinates of a cell as well as
# its contents. (coord_iter)
for cell in self.grid.coord_iter():
x = cell[1]
y = cell[2]
if self.random.random() < self.density:
if self.random.random() < self.minority_pc:
agent_type = 1
else:
agent_type = 0
agent = SchellingAgent((x, y), self, agent_type)
self.grid.position_agent(agent, (x, y))
self.schedule.add(agent)
self.running = True
self.datacollector.collect(self)
def step(self):
'''
Run one step of the model. If All agents are happy, halt the model.
'''
self.happy = 0 # Reset counter of happy agents
self.schedule.step()
# collect data
self.datacollector.collect(self)
if self.happy == self.schedule.get_agent_count():
self.running = False
示例4: SchellingModel
class SchellingModel(Model):
"""
Model class for the Schelling segregation model.
"""
def __init__(self, height, width, density, minority_pc, homophily):
"""
"""
self.height = height
self.width = width
self.density = density
self.minority_pc = minority_pc
self.homophily = homophily
self.schedule = RandomActivation(self)
self.grid = SingleGrid(height, width, torus=True)
self.happy = 0
self.total_agents = 0
self.datacollector = DataCollector(
{"unhappy": lambda m: m.total_agents - m.happy},
# For testing purposes, agent's individual x and y
{"x": lambda a: a.pos[X], "y": lambda a: a.pos[Y]},
)
self.running = True
# Set up agents
# We use a grid iterator that returns
# the coordinates of a cell as well as
# its contents. (coord_iter)
for cell, x, y in self.grid.coord_iter():
if random.random() < self.density:
if random.random() < self.minority_pc:
agent_type = 1
else:
agent_type = 0
agent = SchellingAgent(self.total_agents, agent_type)
self.grid.position_agent(agent, x, y)
self.schedule.add(agent)
self.total_agents += 1
def step(self):
"""
Run one step of the model. If All agents are happy, halt the model.
"""
self.happy = 0 # Reset counter of happy agents
self.schedule.step()
self.datacollector.collect(self)
if self.happy == self.total_agents:
self.running = False
示例5: PD_Model
class PD_Model(Model):
'''
Model class for iterated, spatial prisoner's dilemma model.
'''
schedule_types = {"Sequential": BaseScheduler,
"Random": RandomActivation,
"Simultaneous": SimultaneousActivation}
# This dictionary holds the payoff for this agent,
# keyed on: (my_move, other_move)
payoff = {("C", "C"): 1,
("C", "D"): 0,
("D", "C"): 1.6,
("D", "D"): 0}
def __init__(self, height, width, schedule_type, payoffs=None):
'''
Create a new Spatial Prisoners' Dilemma Model.
Args:
height, width: Grid size. There will be one agent per grid cell.
schedule_type: Can be "Sequential", "Random", or "Simultaneous".
Determines the agent activation regime.
payoffs: (optional) Dictionary of (move, neighbor_move) payoffs.
'''
self.running = True
self.grid = SingleGrid(height, width, torus=True)
self.schedule_type = schedule_type
self.schedule = self.schedule_types[self.schedule_type](self)
# Create agents
for x in range(width):
for y in range(height):
agent = PD_Agent((x, y), self)
self.grid.place_agent(agent, (x, y))
self.schedule.add(agent)
self.datacollector = DataCollector({
"Cooperating_Agents":
lambda m: len([a for a in m.schedule.agents if a.move == "C"])
})
def step(self):
self.datacollector.collect(self)
self.schedule.step()
def run(self, n):
'''
Run the model for a certain number of steps.
'''
for _ in range(n):
self.step()
示例6: SchellingModel
class SchellingModel(Model):
'''
Model class for the Schelling segregation model.
'''
def __init__(self, height, width, density, type_pcs=[.2, .2, .2, .2, .2]):
'''
'''
self.height = height
self.width = width
self.density = density
self.type_pcs = type_pcs
self.schedule = RandomActivation(self)
self.grid = SingleGrid(height, width, torus=False)
self.happy = 0
self.datacollector = DataCollector(
{"happy": lambda m: m.happy}, # Model-level count of happy agents
# For testing purposes, agent's individual x and y
{"x": lambda a: a.pos[0], "y": lambda a: a.pos[1]})
self.running = True
# Set up agents
# We use a grid iterator that returns
# the coordinates of a cell as well as
# its contents. (coord_iter)
total_agents = self.height * self.width * self.density
agents_by_type = [total_agents*val for val in self.type_pcs]
for loc, types in enumerate(agents_by_type):
for i in range(int(types)):
pos = self.grid.find_empty()
agent = SchellingAgent(pos, self, loc)
self.grid.position_agent(agent, pos)
self.schedule.add(agent)
def step(self):
'''
Run one step of the model. If All agents are happy, halt the model.
'''
self.happy = 0 # Reset counter of happy agents
self.schedule.step()
self.datacollector.collect(self)
if self.happy == self.schedule.get_agent_count():
self.running = False
示例7: __init__
def __init__(self, N, width=20, height=10):
self.running = True
self.N = N # num of agents
self.headings = ((1, 0), (0, 1), (-1, 0), (0, -1)) # tuples are fast
self.grid = SingleGrid(width, height, torus=False)
self.schedule = RandomActivation(self)
self.make_walker_agents()
示例8: __init__
def __init__(self, height, width, schedule_type, payoffs=None):
"""
Create a new Spatial Prisoners' Dilemma Model.
Args:
height, width: Grid size. There will be one agent per grid cell.
schedule_type: Can be "Sequential", "Random", or "Simultaneous".
Determines the agent activation regime.
payoffs: (optional) Dictionary of (move, neighbor_move) payoffs.
"""
self.running = True
self.grid = SingleGrid(height, width, torus=True)
self.schedule_type = schedule_type
self.schedule = self.schedule_types[self.schedule_type](self)
# Create agents
for x in range(width):
for y in range(height):
agent = PD_Agent((x, y))
self.grid.place_agent(agent, (x, y))
self.schedule.add(agent)
self.datacollector = DataCollector(
{"Cooperating_Agents": lambda m: len([a for a in m.schedule.agents if a.move == "C"])}
)
示例9: setUp
def setUp(self):
self.space = SingleGrid(50, 50, False)
self.agents = []
for i, pos in enumerate(TEST_AGENTS_GRID):
a = MockAgent(i, None)
self.agents.append(a)
self.space.place_agent(a, pos)
示例10: __init__
def __init__(self, width=50, height=50, torus=True, num_bug=50, seed=42, strategy=None):
super().__init__(seed=seed)
self.number_of_bug = num_bug
if not(strategy in ["stick", "switch"]):
raise TypeError("'strategy' must be one of {stick, switch}")
self.strategy = strategy
self.grid = SingleGrid(width, height, torus)
self.schedule = RandomActivation(self)
data = {"Bean": lambda m: m.number_of_bean,
"Corn": lambda m: m.number_of_corn,
"Soy": lambda m: m.number_of_soy,
"Bug": lambda m: m.number_of_bug,
}
self.datacollector = DataCollector(data)
# create foods
self._populate(Bean)
self._populate(Corn)
self._populate(Soy)
# create bugs
for i in range(self.number_of_bug):
pos = self.grid.find_empty()
bug = Bug(i, self)
bug.strategy = self.strategy
self.grid.place_agent(bug, pos)
self.schedule.add(bug)
示例11: Foraging
class Foraging(Model):
number_of_bean = 0
number_of_corn = 0
number_of_soy = 0
def __init__(self, width=50, height=50, torus=True, num_bug=50, seed=42, strategy=None):
super().__init__(seed=seed)
self.number_of_bug = num_bug
if not(strategy in ["stick", "switch"]):
raise TypeError("'strategy' must be one of {stick, switch}")
self.strategy = strategy
self.grid = SingleGrid(width, height, torus)
self.schedule = RandomActivation(self)
data = {"Bean": lambda m: m.number_of_bean,
"Corn": lambda m: m.number_of_corn,
"Soy": lambda m: m.number_of_soy,
"Bug": lambda m: m.number_of_bug,
}
self.datacollector = DataCollector(data)
# create foods
self._populate(Bean)
self._populate(Corn)
self._populate(Soy)
# create bugs
for i in range(self.number_of_bug):
pos = self.grid.find_empty()
bug = Bug(i, self)
bug.strategy = self.strategy
self.grid.place_agent(bug, pos)
self.schedule.add(bug)
def step(self):
self.schedule.step()
self.datacollector.collect(self)
if not(self.grid.exists_empty_cells()):
self.running = False
def _populate(self, food_type):
prefix = "number_of_{}"
counter = 0
while counter < food_type.density * (self.grid.width * self.grid.height):
pos = self.grid.find_empty()
food = food_type(counter, self)
self.grid.place_agent(food, pos)
self.schedule.add(food)
food_name = food_type.__name__.lower()
attr_name = prefix.format(food_name)
val = getattr(self, attr_name)
val += 1
setattr(self, attr_name, val)
counter += 1
示例12: __init__
def __init__(self, height, width, palestinian_density, settlement_density,
settlers_violence_rate, settlers_growth_rate, suicide_rate, greed_level,
settler_vision=1, palestinian_vision=1,
movement=True, max_iters=1000):
super(SeparationBarrierModel, self).__init__()
self.height = height
self.width = width
self.palestinian_density = palestinian_density
self.settler_vision = settler_vision
self.palestinian_vision = palestinian_vision
self.settlement_density = settlement_density
self.movement = movement
self.running = True
self.max_iters = max_iters
self.iteration = 0
self.schedule = RandomActivation(self)
self.settlers_violence_rate = settlers_violence_rate
self.settlers_growth_rate = settlers_growth_rate
self.suicide_rate = suicide_rate
self.greed_level = greed_level
self.total_violence = 0
self.grid = SingleGrid(height, width, torus=False)
model_reporters = {
}
agent_reporters = {
# "x": lambda a: a.pos[0],
# "y": lambda a: a.pos[1],
}
self.dc = DataCollector(model_reporters=model_reporters,
agent_reporters=agent_reporters)
self.unique_id = 0
# Israelis and palestinans split the region in half
for (contents, x, y) in self.grid.coord_iter():
if random.random() < self.palestinian_density:
palestinian = Palestinian(self.unique_id, (x, y), vision=self.palestinian_vision, breed="Palestinian",
model=self)
self.unique_id += 1
self.grid.position_agent(palestinian, x,y)
self.schedule.add(palestinian)
elif ((y > (self.grid.height) * (1-self.settlement_density)) and random.random() < self.settlement_density):
settler = Settler(self.unique_id, (x, y),
vision=self.settler_vision, model=self, breed="Settler")
self.unique_id += 1
self.grid.position_agent(settler, x,y)
self.schedule.add(settler)
示例13: setUp
def setUp(self):
'''
Create a test non-toroidal grid and populate it with Mock Agents
'''
self.grid = SingleGrid(3, 5, True)
self.agents = []
counter = 0
for y in range(3):
for x in range(5):
if TEST_GRID[y][x] == 0:
continue
counter += 1
# Create and place the mock agent
a = MockAgent(counter, None)
self.agents.append(a)
self.grid.place_agent(a, (x, y))
示例14: __init__
def __init__(self, height=20, width=20, density=.8, group_ratio=.66, minority_ratio=.5, homophily=3):
self.height = height
self.width = width
self.density = density
self.group_ratio = group_ratio
self.minority_ratio = minority_ratio
self.homophily = homophily
self.happy = 0
self.segregated = 0
self.schedule = RandomActivation(self)
self.grid = SingleGrid(height, width, torus=False)
self.place_agents()
self.datacollector = DataCollector( {'happy': (lambda m: m.happy), 'segregated': (lambda m: m.segregated)})
self.running = True
示例15: setUp
def setUp(self):
'''
Create a test non-toroidal grid and populate it with Mock Agents
'''
width = 3
height = 5
self.grid = SingleGrid(width, height, True)
self.agents = []
counter = 0
for x in range(width):
for y in range(height):
if TEST_GRID[x][y] == 0:
continue
counter += 1
# Create and place the mock agent
a = MockAgent(counter, None)
self.agents.append(a)
self.grid.place_agent(a, (x, y))