-
Notifications
You must be signed in to change notification settings - Fork 0
/
simulation1.py
80 lines (51 loc) · 1.54 KB
/
simulation1.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
# Tutorial on evolutionary game theory part 2
from bird import Bird
import random
import numpy as np
import pandas as pd
import matplotlib
def initialise():
"""
Create a population of birds - all dove to begin
"""
birds = []
for _ in range(1000):
birds.append(Bird("dove"))
return (birds)
def timestep(birds, value, cost):
"""
Pair up the birds, make them compete
Then produce next generation, weighted by fitness
"""
next_generation = []
random.shuffle(birds)
for _ in range(1000):
# pair up random birds to contest
a, b = random.sample(birds, 2)
a.contest(b, value, cost)
# generate next generation
fitnesses = [bird.fitness for bird in birds]
draw = random.choices(birds, k=1000, weights=fitnesses)
next_generation = [bird.spawn() for bird in draw]
return next_generation
def main():
birds = initialise()
rows = []
V = 4 ; C = 6
for _ in range(1000):
# add the counts to a new row
strategy = [bird.strategy for bird in birds]
n_hawks = strategy.count("hawk")
n_doves = strategy.count("dove")
row = {'n_hawks': n_hawks, 'n_doves': n_doves}
rows.append(row)
# run the timestep function
birds = timestep(birds, V, C)
# create dataframe and save output
df = pd.DataFrame(rows)
df.to_csv('simulation.csv')
fig = df.plot(y=["n_hawks", "n_doves"]).get_figure()
fig.savefig('simulation.pdf')
if __name__ == "__main__":
main()
main()