Skip to content

Commit dc8989e

Browse files
rhttpike3
authored andcommitted
Schelling: Use new API and simplify
1 parent 8f6e043 commit dc8989e

File tree

1 file changed

+9
-19
lines changed

1 file changed

+9
-19
lines changed

examples/schelling_experimental/model.py

Lines changed: 9 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ def __init__(self, pos, model, agent_type):
1212
1313
Args:
1414
unique_id: Unique identifier for the agent.
15-
x, y: Agent initial location.
15+
pos: Agent initial location.
1616
agent_type: Indicator for the agent's type (minority=1, majority=0)
1717
"""
1818
super().__init__(pos, model)
@@ -38,48 +38,38 @@ class Schelling(mesa.Model):
3838
"""
3939

4040
def __init__(self, width=20, height=20, density=0.8, minority_pc=0.2, homophily=3):
41-
""" """
42-
41+
super().__init__()
4342
self.width = width
4443
self.height = height
45-
self.density = density
46-
self.minority_pc = minority_pc
4744
self.homophily = homophily
4845

49-
self.schedule = mesa.time.RandomActivation(self)
5046
self.grid = mesa.space.SingleGrid(width, height, torus=True)
5147

5248
self.happy = 0
5349
self.datacollector = mesa.DataCollector(
5450
{"happy": "happy"}, # Model-level count of happy agents
55-
# For testing purposes, agent's individual x and y
56-
{"x": lambda a: a.pos[0], "y": lambda a: a.pos[1]},
5751
)
5852

5953
# Set up agents
6054
# We use a grid iterator that returns
6155
# the coordinates of a cell as well as
6256
# its contents. (coord_iter)
63-
for cell in self.grid.coord_iter():
64-
x, y = cell[1]
65-
if self.random.random() < self.density:
66-
agent_type = 1 if self.random.random() < self.minority_pc else 0
67-
68-
agent = SchellingAgent((x, y), self, agent_type)
69-
self.grid.place_agent(agent, (x, y))
70-
self.schedule.add(agent)
57+
for _, pos in self.grid.coord_iter():
58+
if self.random.random() < density:
59+
agent_type = 1 if self.random.random() < minority_pc else 0
60+
agent = SchellingAgent(pos, self, agent_type)
61+
self.grid.place_agent(agent, pos)
7162

72-
self.running = True
7363
self.datacollector.collect(self)
7464

7565
def step(self):
7666
"""
7767
Run one step of the model. If All agents are happy, halt the model.
7868
"""
7969
self.happy = 0 # Reset counter of happy agents
80-
self.schedule.step()
70+
self.agents.shuffle().do("step")
8171
# collect data
8272
self.datacollector.collect(self)
8373

84-
if self.happy == self.schedule.get_agent_count():
74+
if self.happy == len(self.agents):
8575
self.running = False

0 commit comments

Comments
 (0)