-
Notifications
You must be signed in to change notification settings - Fork 929
/
Copy pathschelling.py
88 lines (71 loc) · 2.42 KB
/
schelling.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
from mesa import Agent, Model
from mesa.space import SingleGrid
from mesa.time import RandomActivation
class SchellingAgent(Agent):
"""
Schelling segregation agent
"""
def __init__(self, unique_id, model, agent_type):
"""
Create a new Schelling agent.
Args:
unique_id: Unique identifier for the agent.
x, y: Agent initial location.
agent_type: Indicator for the agent's type (minority=1, majority=0)
"""
super().__init__(unique_id, model)
self.type = agent_type
def step(self):
similar = 0
for neighbor in self.model.grid.iter_neighbors(
self.pos, moore=True, radius=self.model.radius
):
if neighbor.type == self.type:
similar += 1
# If unhappy, move:
if similar < self.model.homophily:
self.model.grid.move_to_empty(self)
else:
self.model.happy += 1
class Schelling(Model):
"""
Model class for the Schelling segregation model.
"""
def __init__(
self, seed, height, width, homophily, radius, density, minority_pc=0.5
):
""" """
super().__init__(seed=seed)
self.height = height
self.width = width
self.density = density
self.minority_pc = minority_pc
self.homophily = homophily
self.radius = radius
self.schedule = RandomActivation(self)
self.grid = SingleGrid(height, width, torus=True)
self.happy = 0
# Set up agents
# We use a grid iterator that returns
# the coordinates of a cell as well as
# its contents. (coord_iter)
for _cont, pos in self.grid.coord_iter():
if self.random.random() < self.density:
agent_type = 1 if self.random.random() < self.minority_pc else 0
agent = SchellingAgent(self.next_id(), self, agent_type)
self.grid.place_agent(agent, pos)
self.schedule.add(agent)
def step(self):
"""
Run one step of the model.
"""
self.happy = 0 # Reset counter of happy agents
self.schedule.step()
if __name__ == "__main__":
import time
# model = Schelling(15, 40, 40, 3, 1, 0.625)
model = Schelling(15, 100, 100, 8, 2, 0.8)
start_time = time.perf_counter()
for _ in range(100):
model.step()
print(time.perf_counter() - start_time)