swdata/rewiring_rate.py
2018-07-15 12:22:05 +08:00

169 lines
5.4 KiB
Python

import json
from matplotlib import pyplot as plt
from island.match import Match
from island.matches import Matches
import numpy as np
import scipy as sp
from scipy.stats import pearsonr
from matplotlib import markers
def error(f,x,y):
return sp.sum((f(x)-y)**2)
def p1(x, rewires, tau, postfix, show):
fig = plt.figure(figsize=(6.4, 3.6))
ax = fig.gca()
ax.plot(x, rewires, color=green, linewidth=3)
ax.set_ylim(0, 0.5)
ax2 = ax.twinx()
ax2.plot(x, tau, color=red, linewidth=3)
ax2.set_ylim(0, 1440)
ax.set_xlim(1, 14)
ax.set_xlabel("Rounds")
ax.set_ylabel("Rewiring Rate", color=green)
ax.tick_params(axis='y', labelcolor=green)
ax2.set_ylabel("$\\tau_{p}$", family='sans-serif', color=red)
ax2.tick_params(axis='y', labelcolor=red)
plt.tight_layout()
if show:
plt.show()
else:
plt.savefig("graph/tau_p_rewire_plot_%s.eps" % postfix)
def p2(tau, rewires, postfix, show):
# # p2散点图
fig = plt.figure(figsize=(6.4, 3.6))
ax = fig.gca()
# ax.set_ylim(0.5, 1)
fp1,residuals,rank,sv,rcond = sp.polyfit(tau, rewires, 1, full=True)
print("残差:",residuals)
print('Model parameter:',fp1)
f1 = sp.poly1d(fp1)
print("error= %f" % error(f1, tau, rewires))
print("Other parameters: rank=%s, sv=%s, rcond=%s" % (str(rank), str(sv), str(rcond)))
# fx = sp.linspace(0,max(tau2),1000)
fx = sp.linspace(0,1440,2)
plt.plot(fx,f1(fx),linewidth=2,color=red, ls='--', zorder=0)
plt.scatter(tau, rewires, color=green, linewidths=2, zorder=100)
# plt.scatter(tau_r, coopr_r, color='white', edgecolors=green, linewidths=2, zorder=101)
ax.set_xlabel('$\\tau_{p}$', family='sans-serif')
ax.set_ylabel('Rewiring Rate')
ax.set_xlim(0, 1440)
ax.set_xticks(sp.linspace(0, 1440, 13))
ax.set_ylim(0, 0.6)
plt.tight_layout()
if show:
plt.show()
else:
plt.savefig("graph/tau_p_rewire_sca_%s.eps" % postfix)
# 皮尔逊相关系数
print("pearson: %f, p-value: %f" % pearsonr(tau, rewires))
if __name__ == '__main__':
mode = 'CLASSIC'
matches = Matches.from_profile_expr(lambda r: mode in r)
max_round = 15
survivals = {}
with open('survivals.json', 'r') as f:
survivals = json.load(f)
neighbors = {}
rewires = []
x = np.arange(1, max_round)
mwRe = {} # Match-wise frequency of rewiring
mwTau = {} # Match-wise Tau
tau = []
for i in range(len(matches.data)):
m = matches.data[i]
n = {}
for r in m.query('neighbor', 'create').raw_data:
if r['a'] in n:
n[r['a']].append(r['b'])
else:
n[r['a']] = [r['b']]
if r['b'] in n:
n[r['b']].append(r['a'])
else:
n[r['b']] = [r['a']]
neighbors[matches.names[i]] = n
for i in range(max_round-1):
re = []
for j in range(len(matches.data)):
rewire = 0
rows = matches.data[j].query('action', 'done').where(lambda x: x['rno']==i+1).raw_data
for r in rows:
if matches.data[j].query('action', 'done').where(lambda x: x['rno']==i and ((x['a']==r['a'] and x['b']==r['b']) or (x['a']==r['b'] and x['b']==r['a']))).count() == 0:
rewire += 1
if rows:
re.append(float(rewire) / float(len(rows)*2))
mwRe["%s-%d"%(j,i)] = re[-1]
if re:
rewires.append(np.average(re))
for i in range(max_round-1):
tp = []
for j in range(len(matches.data)):
if i == 0:
for r in matches.data[j].query('player', 'join').raw_data:
t = 0
k = r['pid']
if k not in neighbors[matches.names[j]]:
print("[%s(%d)] alone: %d" % (matches.names[j], i+1, k))
else:
t = 1440 * len(neighbors[matches.names[j]][k])
tp.append(t if t < 1440 else 1440)
mwTau["%s-%d"%(j,i)] = tp[-1]
else:
if str(i) not in survivals[matches.names[j]]:
continue
for k in survivals[matches.names[j]][str(i)]:
t = 0
if k not in neighbors[matches.names[j]]:
print("[%s(%d)] alone: %d" % (matches.names[j], i+1, k))
else:
trs = matches.data[j].get_tr(i, k, neighbors[matches.names[j]][k], survivals[matches.names[j]][str(i)])
for l in neighbors[matches.names[j]][k]:
if l in trs:
t += trs[l]
tp.append(t if t < 1440 else 1440)
mwTau["%s-%d"%(j,i)] = tp[-1]
if tp:
tau.append(np.average(tp))
else:
tau.append(0)
green = '#00b894'
red = '#d63031'
# p1折线图
# p1(x, rewires, tau, mode, False)
p2(tau, rewires, mode, False)
'''
classic
残差: [ 0.05873797]
Model parameter: [ 9.81549075e-04 -9.87729952e-01]
error= 0.058738
Other parameters: rank=2, sv=[ 1.41291267 0.06064473], rcond=3.10862446895e-15
pearson: 0.823000, p-value: 0.000300
survive
残差: [ 0.05788203]
Model parameter: [ 0.00033232 -0.06283898]
error= 0.057882
Other parameters: rank=2, sv=[ 1.3284034 0.48512309], rcond=3.10862446895e-15
pearson: 0.893237, p-value: 0.000017
'''