# -*- coding: UTF-8 -*-
import json
from matplotlib import pyplot as plt
import scipy as sp
from island.match import Match
from island.matches import Matches

def error(f,x,y):
    return sp.sum((f(x)-y)**2)

matches = Matches('wos-data-new-2')
max_round = 17

coopr = []
data = {}
x = []
_x = []

survivals = {}
with open('winner.json','r') as f:
    survivals = json.load(f)

for j in range(len(matches.data)):
    coop = 0
    rows = matches.data[j].query('action', 'done').raw_data
    info = matches.data[j].query('game', 'created').select('info').raw_data[0]['info']
    ns = int(info['next_start'])
    for row in rows:
        if row['act_a'] == 'C':
            coop += 1
        if row['act_b'] == 'C':
            coop += 1

    if rows:
        data[ns] = float(coop) / len(rows) / 2
        x.append(ns)

x = sorted(x)
for i in range(len(x)):
    _x.append(i)
    coopr.append(data[x[i]])

fig = plt.figure()
plt.scatter(_x, coopr)
ax = fig.gca()
plt.ylim(0,1)
fp1,residuals,rank,sv,rcond = sp.polyfit(_x, coopr, 1, full=True)
print("残差：",residuals)
print('Model parameter:',fp1)
f1 = sp.poly1d(fp1)
print(error(f1, _x, coopr))
fx = sp.linspace(0,_x[-1],1000)

plt.plot(fx,f1(fx),linewidth=1,color='red')


plt.show()
# plt.savefig('graph/co_per_game.png')