import numpy as np
from matplotlib import pyplot as plt
import scipy as sp
from scipy.stats import pearsonr
from matplotlib import markers
from sys import argv
blue = '#0984e3'
red = '#d63031'

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

def p2(e, rw, postfix, show=True, showline=True):
    # p2散点图
    fig = plt.figure(figsize=(4, 3))
    ax = fig.gca()
    if showline:
        fp1,residuals,rank,sv,rcond = sp.polyfit(e, rw, 1, full=True)
        print("残差：",residuals)
        print('Model parameter:',fp1)
        print("Other parameters: rank=%s, sv=%s, rcond=%s"%(str(rank), str(sv), str(rcond)))
        f1 = sp.poly1d(fp1)
        print("error= %f" % error(f1, e, rw))
        fx = sp.linspace(np.min(e), np.max(e), 2)
        plt.plot(fx,f1(fx),linewidth=2,color=red, ls='--', zorder=0)

    plt.scatter(e, rw, color='white', edgecolors=blue, linewidths=2, zorder=101)
    ax.set_xlabel(r'$TtD$', family='sans-serif', size=20)
    ax.set_ylabel(r'Breaking Rate', family='sans-serif', size=20)
    # ax.set_xlim(0, 1440)
    # ax.set_xticks(sp.linspace(int(min(e)*0.9), int(max(e)*1.1), 4))
    ax.tick_params(labelsize=14)
    ax.set_ylim(0, 0.6)
    ax.set_yticks(sp.linspace(0, 0.6, 5))
    plt.tight_layout()
    if show:
        plt.show()
    else:
        plt.savefig("graph/eid_co_sca_%s.eps" % postfix)

    # 皮尔逊相关系数
    print("pearson: %f, p-value: %f" % pearsonr(e, rw))

def p2c(e,c,m,s):
    p2(e,c,m,s,False)

def plot(mode, show):
    rw = np.loadtxt("outputs/BR_%s.csv" % mode, delimiter=',')
    e = np.loadtxt("outputs/EID_%s.csv" % mode, delimiter=',')

    p2(e[:-1], rw[1:], mode, show)

    # if mode == 'SURVIVE':
    #     p2(e[:-1], rw[1:], mode, show)
    # else:
    #     p2c(e[:-1], rw[1:], mode, show)

if __name__ == '__main__':
    # eid_plot c/s 1/2 t/f
    mode = 'CLASSIC' if argv[1] == 'c' else 'SURVIVE'
    show = argv[2] == 't'
    plot(mode, show)

    """
SURVIVE
残差： [ 0.06081364]
Model parameter: [ -3.54739130e-04   4.41956696e-01]
Other parameters: rank=2, sv=[ 1.40523958  0.15906514], rcond=3.10862446895e-15
error= 0.060814
pearson: -0.837958, p-value: 0.000183


CLASSIC
pearson: 0.384519, p-value: 0.174626
    """
