-
Notifications
You must be signed in to change notification settings - Fork 81
/
abm-segregation-continuous.py
42 lines (36 loc) · 1.06 KB
/
abm-segregation-continuous.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
import pycxsimulator
from pylab import *
n = 1000 # number of agents
r = 0.1 # neighborhood radius
th = 0.5 # threshold for moving
class agent:
pass
def initialize():
global agents
agents = []
for i in range(n):
ag = agent()
ag.type = randint(2)
ag.x = random()
ag.y = random()
agents.append(ag)
def observe():
global agents
cla()
red = [ag for ag in agents if ag.type == 0]
blue = [ag for ag in agents if ag.type == 1]
plot([ag.x for ag in red], [ag.y for ag in red], 'ro')
plot([ag.x for ag in blue], [ag.y for ag in blue], 'bo')
axis('image')
axis([0, 1, 0, 1])
def update():
global agents
ag = choice(agents)
neighbors = [nb for nb in agents
if (ag.x - nb.x)**2 + (ag.y - nb.y)**2 < r**2 and nb != ag]
if len(neighbors) > 0:
q = len([nb for nb in neighbors if nb.type == ag.type]) \
/ float(len(neighbors))
if q < th:
ag.x, ag.y = random(), random()
pycxsimulator.GUI().start(func=[initialize, observe, update])