Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Boltzmann wealth model: Use the new Mesa 2.2 API & some refactors #79

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 13 additions & 13 deletions examples/boltzmann_wealth_model_experimental/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@


def compute_gini(model):
agent_wealths = [agent.wealth for agent in model.schedule.agents]
agent_wealths = model.agents.get("wealth")
x = sorted(agent_wealths)
N = model.num_agents
B = sum(xi * (N - i) for i, xi in enumerate(x)) / (N * sum(x))
Expand All @@ -19,27 +19,26 @@ class BoltzmannWealthModel(mesa.Model):

def __init__(self, N=100, width=10, height=10):
super().__init__()
self.running = True # TODO remove this line when at Mesa 3.0
self.num_agents = N
self.grid = mesa.space.MultiGrid(width, height, True)
self.schedule = mesa.time.RandomActivation(self)
self.datacollector = mesa.DataCollector(
model_reporters={"Gini": compute_gini}, agent_reporters={"Wealth": "wealth"}
)
# 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))

self.running = True
self.datacollector.collect(self)

def step(self):
self.schedule.step()
# collect data
self.agents.shuffle().do("step")
# Must be before data collection.
self._advance_time() # Temporary API; will be finalized by Mesa 3.0 release
self.datacollector.collect(self)

def run_model(self, n):
Expand All @@ -55,17 +54,18 @@ def __init__(self, unique_id, model):
self.wealth = 1

def move(self):
possible_steps = self.model.grid.get_neighborhood(
possible_positions = self.model.grid.get_neighborhood(
self.pos, moore=True, include_center=False
)
new_position = self.random.choice(possible_steps)
self.model.grid.move_agent(self, new_position)
self.model.grid.move_agent_to_one_of(self, possible_positions)

def give_money(self):
cellmates = self.model.grid.get_cell_list_contents([self.pos])
cellmates.pop(
cellmates.index(self)
) # Ensure agent is not giving money to itself
cellmates = [
c
for c in self.model.grid.get_cell_list_contents([self.pos])
# Ensure agent is not giving money to itself
if c is not self
]
if len(cellmates) > 0:
other = self.random.choice(cellmates)
other.wealth += 1
Expand Down
Loading