1
0
mirror of https://github.com/gsi-upm/soil synced 2024-11-22 11:12:29 +00:00
soil/tests/test_mesa.py

72 lines
1.9 KiB
Python
Raw Normal View History

"""
2021-10-14 15:37:06 +00:00
Mesa-SOIL integration tests
We have to test that:
- Mesa agents can be used in SOIL
- Simplified soil agents can be used in mesa simulations
- Mesa and soil agents can interact in a simulation
- Mesa visualizations work with SOIL simulations
"""
2021-10-14 15:37:06 +00:00
from mesa import Agent, Model
from mesa.time import RandomActivation
from mesa.space import MultiGrid
2021-10-14 15:37:06 +00:00
class MoneyAgent(Agent):
"""An agent with fixed initial wealth."""
2021-10-14 15:37:06 +00:00
def __init__(self, unique_id, model):
super().__init__(unique_id, model)
self.wealth = 1
def step(self):
self.move()
if self.wealth > 0:
self.give_money()
def give_money(self):
cellmates = self.model.grid.get_cell_list_contents([self.pos])
if len(cellmates) > 1:
other = self.random.choice(cellmates)
other.wealth += 1
self.wealth -= 1
def move(self):
possible_steps = self.model.grid.get_neighborhood(
self.pos, moore=True, include_center=False
)
2021-10-14 15:37:06 +00:00
new_position = self.random.choice(possible_steps)
self.model.grid.move_agent(self, new_position)
class MoneyModel(Model):
"""A model with some number of agents."""
2021-10-14 15:37:06 +00:00
def __init__(self, N, width, height):
self.num_agents = N
self.grid = MultiGrid(width, height, True)
self.schedule = RandomActivation(self)
# Create agents
for i in range(self.num_agents):
a = MoneyAgent(i, self)
self.schedule.add(a)
# Add the agent to a random grid cell
x = self.random.randrange(self.grid.width)
y = self.random.randrange(self.grid.height)
self.grid.place_agent(a, (x, y))
def step(self):
"""Advance the model by one step."""
2021-10-14 15:37:06 +00:00
self.schedule.step()
# model = MoneyModel(10)
# for i in range(10):
# model.step()
# agent_wealth = [a.wealth for a in model.schedule.agents]