-
Notifications
You must be signed in to change notification settings - Fork 5
/
egt.py
executable file
·288 lines (256 loc) · 7.83 KB
/
egt.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
# -*- coding: utf-8 -*-
# -*- Author: shaodan -*-
# -*- 2015.06.28 -*-
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
from evolution import Evolution, CoEvolution, StaticStrategyEvolution
from population import Population, DynamicPopulation
import game
import rule
import adapter
# 生成网络
# G = ba(N, 5, 3, 1)
# G = nx.davis_southern_women_graph()
# G = nx.random_regular_graph(4, 1000)
# G = nx.convert_node_labels_to_integers(nx.grid_2d_graph(100, 100, periodic=True))
# G = nx.star_graph(10)
# G = nx.watts_strogatz_graph(1000, 5, 0.2)
G = nx.barabasi_albert_graph(1000, 3)
# G = nx.powerlaw_cluster_graph(1000, 10, 0.2)
# G = nx.convert_node_labels_to_integers(nx.davis_southern_women_graph())
# G = ["/../../DataSet/ASU/Douban-dataset/data/edges.csv", ',']
# G = {"path":"/../wechat/barabasi_albert_graph(5000,100)_adj.txt", "fmt":"adj"}
# G = "/../wechat/facebook.txt"
# 网络结构
p = Population(G)
# print nx.info(p)
# p.degree_distribution()
# 博弈类型
g = game.PDG(b=5)
# g = game.PGG(3)
# g = game.PGG2(3)
# 学习策略
# u = rule.BirthDeath()
u = rule.DeathBirth()
# u = rule.Fermi()
# u = rule.HeteroFermi(g.delta)
# 连接策略
a = adapter.Preference(3)
# 绘图参数
colors = 'bgrcmykw'
markers = '.,ov^v<>1234sp*hH+xDd|-'
lines = ['-', '--', '-.', ':']
fmt = ['bd-', 'ro--', 'g^-.', 'c+:', 'mx--', 'y*-.']
def once():
e = Evolution(has_mut=True)
e.set_population(p).set_game(g).set_rule(u)
e.evolve(1000)
e.show()
# 分析节点最终fit和结构参数的关系
# p.show_degree()
# p.degree_distribution()
def lattice():
l = 100
def observe(s, f):
plt.imshow(s.reshape((l, l)), interpolation='sinc', cmap='bwr')
plt.show()
G = nx.grid_2d_graph(l, l)
# nx.draw(G, node_size=200, with_labels=True)
# plt.show()
p = Population(G)
e = Evolution()
e.set_population(p).set_game(g).set_rule(u)
# e.evolve(1)
observe(p.strategy, p.fitness)
def cora():
G = nx.barabasi_albert_graph(1000, 3)
# G = nx.watts_strogatz_graph(1000, 5, 0.3)
# G = nx.random_regular_graph(4, 1000)
p = Population(G)
e = Evolution()
g = game.PDG(2)
e.set_population(p).set_game(g)
# p.strategy = np.ones(len(p), np.int)
f, axs = plt.subplots(3, 4)
axs = axs.reshape(12)
for r in range(11):
if r > 5:
r_ = 10-r
p.strategy = np.zeros(len(p), dtype=np.int)
s = 1
else:
r_ = r
p.strategy = np.ones(len(p), dtype=np.int)
s = 0
n = int(round(len(p)/10.0 * r_))
selected_list = np.random.choice(range(len(p)), n)
p.strategy[selected_list] = s
# print p.strategy
g.strategy = p.strategy
g.play()
p.show_degree(axs[r])
plt.show()
def once_co():
dp = DynamicPopulation(G)
c = CoEvolution(has_mut=False)
c.set_population(dp).set_game(g).set_rule(u)
c.set_adapter(a)
c.evolve(50000)
c.show()
def repeat2d():
e = Evolution()
bs = np.linspace(1, 10, 3)
# fig, axes = plt.subplots()
colors = 'brgcmykwa'
symbs = '.ox+*sdph-'
for i in range(1, 10):
i = 4
G = nx.random_regular_graph(i + 1, 1000)
p = Population(G)
a = [0] * len(bs)
for j, b in enumerate(bs):
g = game.PDG(b)
e.set_population(p).set_game(g).set_rule(u)
e.evolve(10000)
a[j] = e.cooperate[-1]
plt.plot(bs, a, colors[j]+symbs[j], label='b=%f' % b)
break
plt.show()
def repeat_k():
# 网络平均度不同,合作率曲线
e = Evolution(has_mut=False)
k = 5
a = [0] * k
for i in range(k):
G = nx.random_regular_graph(i*2+2, 1000)
p = Population(G)
e.set_population(p).set_game(g).set_rule(u)
print('Control Variable k: %d' % (i*2+2))
e.evolve(100000, restart=True, quiet=True)
# TODO: if e is CoEvolution, population need re-copy
# a[i] = e.cooperate[-1]
e.show(fmt[i], label="k=%d" % (i*2+2))
# plt.plot(range(2, k+1), a[1:], 'r-')
# plt.plot([400+i*i for i in range(20)], 'ro--', label='k=4')
# plt.plot([400 + i for i in range(20)], 'g^-.', label='k=6')
# plt.plot([400 - i for i in range(20)], 'cx:', label='k=8')
plt.legend(loc='lower right')
plt.show()
def repeat_b():
# 博弈收益参数不同,合作率曲线
e = Evolution(has_mut=False)
G = nx.random_regular_graph(4, 1000)
p = Population(G)
b = 5
for i in range(b):
g = game.PDG(i*2+2)
e.set_population(p).set_game(g).set_rule(u)
print('Control Variable b: %d' % (i*2+2))
e.evolve(100000, restart=True, quiet=True, autostop=False)
e.show(fmt[i], label="b=%d" % (i*2+2))
plt.legend(loc='lower right')
plt.show()
def repeat_start_pc():
# 初始Pc不同的合作变化曲线
# G = nx.watts_strogatz_graph(1000, 4, 0.2)
G = nx.barabasi_albert_graph(1000, 3)
p = Population(G)
g = game.PDG(b=10)
u = rule.DeathBirth()
e = Evolution(has_mut=False)
e.set_population(p).set_game(g).set_rule(u)
for i in range(5):
pc = (2*i+1)/10.0
p.init_strategies(g, [pc, 1-pc])
print('Initial P(C) is %.2f' % pc)
e.evolve(100000, restart=True, quiet=True, autostop=False)
e.show(fmt[i], label=r'start $P_C$=%.2f' % pc)
plt.legend(loc='lower right')
plt.title(r'Evolution under Different Start $P_C$')
plt.xlabel('Number of generations')
plt.ylabel(r'Fraction of cooperations, $\rho_c$')
plt.show()
def repeat_ss_rewire():
# 策略固定,连接倾向进行演化
from network import LatticeWithLongTie
p = LatticeWithLongTie(30)
g = game.PDG(b=8)
# u = rule.DeathBirth()
u = rule.Fermi(0.1)
a = adapter.Preference(3)
e = StaticStrategyEvolution()
e.set_game(g).set_rule(u).set_adapter(a)
e.set_population(p)
e.bind_process()
p.init_longtie()
# p.degree_distribution(loglog=False)
p_copy1 = p.copy()
plt.figure()
for i in range(6):
i = 5
pc = i/5.0
# 复制演化前的状态
p_copy = p.copy()
e.set_population(p)
a.dynamic = p.dynamics
a.bind(p)
# if i > 0:
# p.is_equal(p_copy1)
# break
p.init_strategies(g, [pc, 1-pc])
# p.check_cache()
# 重置网络连接,重置节点的连接策略
p = p_copy
print('static P(C) is %.2f' % pc)
e.evolve(100, restart=True, quiet=True, autostop=False)
e.show(fmt[i], label=r'static $P_C$=%.2f ' % pc)
break
plt.legend(loc='upper left')
plt.title('Static Strategy Evolution')
plt.xlabel('Number of generations')
plt.ylabel('Rewire Strategies')
plt.ylim(0, len(p))
plt.show()
# p.degree_distribution(loglog=False)
def repeat_ll_rewire():
# 策略固定,连接倾向进行演化
from network import LatticeWithLongTie
# G = nx.random_regular_graph(5, 1000)
p = LatticeWithLongTie(30)
g = game.PDG(b=8)
u = rule.DeathBirth()
# u = rule.Fermi(.1)
a = adapter.Preference(3)
e = CoEvolution()
e.set_game(g).set_rule(u).set_adapter(a)
e.set_population(p)
e.bind_process()
p.degree_distribution()
print('start evolving')
e.evolve(10000, restart=True, quiet=True, autostop=False)
plt.figure()
e.show(fmt[0], label='LLN Co-Evolution')
plt.legend(loc='upper left')
plt.title('LLN Co-Evolution')
plt.xlabel('Number of generations')
plt.ylabel('Rewire Strategies')
plt.show()
p.degree_distribution()
# lattice()
# cora()
# once()
# once_co()
# repeat2d()
repeat_k()
# repeat_b()
# repeat_start_pc()
# repeat_ss_rewire()
# repeat_ll_rewire()
# import cProfile
# import pstats
#
# cProfile.run("repeat_ss_rewire()", "timeit")
# p = pstats.Stats('timeit')
# p.sort_stats('time')
# p.print_stats(20)