Skip to content

Commit

Permalink
Schelling: Use new API and simplify
Browse files Browse the repository at this point in the history
  • Loading branch information
rht authored and tpike3 committed Jan 9, 2024
1 parent 8f6e043 commit dc8989e
Showing 1 changed file with 9 additions and 19 deletions.
28 changes: 9 additions & 19 deletions examples/schelling_experimental/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ def __init__(self, pos, model, agent_type):
Args:
unique_id: Unique identifier for the agent.
x, y: Agent initial location.
pos: Agent initial location.
agent_type: Indicator for the agent's type (minority=1, majority=0)
"""
super().__init__(pos, model)
Expand All @@ -38,48 +38,38 @@ class Schelling(mesa.Model):
"""

def __init__(self, width=20, height=20, density=0.8, minority_pc=0.2, homophily=3):
""" """

super().__init__()
self.width = width
self.height = height
self.density = density
self.minority_pc = minority_pc
self.homophily = homophily

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

self.happy = 0
self.datacollector = mesa.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, y = cell[1]
if self.random.random() < self.density:
agent_type = 1 if self.random.random() < self.minority_pc else 0

agent = SchellingAgent((x, y), self, agent_type)
self.grid.place_agent(agent, (x, y))
self.schedule.add(agent)
for _, pos in self.grid.coord_iter():
if self.random.random() < density:
agent_type = 1 if self.random.random() < minority_pc else 0
agent = SchellingAgent(pos, self, agent_type)
self.grid.place_agent(agent, pos)

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()
self.agents.shuffle().do("step")
# collect data
self.datacollector.collect(self)

if self.happy == self.schedule.get_agent_count():
if self.happy == len(self.agents):
self.running = False

0 comments on commit dc8989e

Please sign in to comment.