Skip to content

Commit 9d6533f

Browse files
committed
Boltzmann wealth model: Refactor code
1 parent 0bc6097 commit 9d6533f

File tree

1 file changed

+12
-11
lines changed
  • examples/boltzmann_wealth_model_experimental

1 file changed

+12
-11
lines changed

examples/boltzmann_wealth_model_experimental/model.py

+12-11
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ class BoltzmannWealthModel(mesa.Model):
1818
"""
1919

2020
def __init__(self, N=100, width=10, height=10):
21+
super().__init__()
2122
self.num_agents = N
2223
self.grid = mesa.space.MultiGrid(width, height, True)
2324
self.datacollector = mesa.DataCollector(
@@ -31,12 +32,10 @@ def __init__(self, N=100, width=10, height=10):
3132
y = self.random.randrange(self.grid.height)
3233
self.grid.place_agent(a, (x, y))
3334

34-
self.running = True
3535
self.datacollector.collect(self)
3636

3737
def step(self):
3838
self.agents.shuffle().do("step")
39-
# collect data
4039
self.datacollector.collect(self)
4140

4241
def run_model(self, n):
@@ -52,23 +51,25 @@ def __init__(self, unique_id, model):
5251
self.wealth = 1
5352

5453
def move(self):
55-
possible_steps = self.model.grid.get_neighborhood(
54+
possible_positions = self.model.grid.get_neighborhood(
5655
self.pos, moore=True, include_center=False
5756
)
58-
new_position = self.random.choice(possible_steps)
59-
self.model.grid.move_agent(self, new_position)
57+
self.model.grid.move_agent_to_one_of(self, possible_positions)
6058

6159
def give_money(self):
62-
cellmates = self.model.grid.get_cell_list_contents([self.pos])
63-
cellmates.pop(
64-
cellmates.index(self)
65-
) # Ensure agent is not giving money to itself
60+
if self.wealth <= 0:
61+
return
62+
cellmates = [
63+
c
64+
for c in self.model.grid.get_cell_list_contents([self.pos])
65+
# Ensure agent is not giving money to itself
66+
if c is not self
67+
]
6668
if len(cellmates) > 0:
6769
other = self.random.choice(cellmates)
6870
other.wealth += 1
6971
self.wealth -= 1
7072

7173
def step(self):
7274
self.move()
73-
if self.wealth > 0:
74-
self.give_money()
75+
self.give_money()

0 commit comments

Comments
 (0)