#! /usr/bin/python4

#import scipy.optimize as opt
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import VisTools.plotting as vt
import VisTools.tex as vtt
import sys
#import uncertainties as unc
#import uncertainties.unumpy as unp

append = str(sys.argv[1])

plt.ioff()
plt.style.use('bmh')
fig, axarr = plt.subplots(
    2,
    1,
    figsize=(10, 8),
    gridspec_kw={'height_ratios':[4, 1]}
)
plt.subplots_adjust(hspace=.5)
data = pd.read_csv("./" + __file__[:-3].split("_")[1] + append + ".csv", comment="#")

fits = np.array([])
errs = np.array([])
colors = np.array([])

data['dv_pit48'] /= 2
data['Dv'] = data['v_pit48'] - data['v_set']
data['Dvk'] = data['v_keith'] - data['v_set']
print(data)
# fit to abs dist
linfnc = lambda x, m, c: x*m+c

def plot_and_linfit(col: str, fil, l: str):
    plot = axarr[0].errorbar(
        data[fil]['v_set'],
        data[fil][col],
        alpha=0.3,
        label=None,
        fmt='.',
        antialiased=True
    )

    vals = vt.lm_plot(
        data[fil],
        'v_set',
        col,
        None,
        'dv_pit48',
        l,
        fig=axarr[0],
        color=plot[0].get_color()
    )

    return vals, plot

for i in range(8):
    val, p = plot_and_linfit(
        'Dv',
        data.cycles == i,
        '$f_{}={{m:.3f}}\\cdot x{{c:+.3f}}V$'.format(i))
    fits = np.append(fits, val[0])
    #errs = np.append(errs, np.sqrt(pcov[0][0]))
    colors = np.append(colors, p[0].get_color() )

plot_and_linfit('Dvk', data.cycles == 0, 'reference measurement')

print(fits[0].n)
for i in range(8):
    axarr[1].errorbar(
        i,
        fits[i].n,
        yerr=fits[i].s,
        fmt='.',
        #c = colors[i],
    )

axarr[0].set_xlabel('V$_{set}$')
#axarr[0].set_title("PowerIt ADC Calibration: dependency on measurement cycles")
axarr[0].set_ylabel(r'$\Delta$V$_{IN}$ / V')

axarr[1].set_xlabel('scaler value')
axarr[1].set_ylabel(r'$m = \Delta$Gain')
axarr[0].legend(
    bbox_to_anchor=(0, -.29, 1, 1),
    loc="lower left",
    mode="expand",
    borderaxespad=0,
    ncol=3)
plt.savefig(
    "./" + __file__[:-3].split("_")[1] + append + ".pdf",
    dpi=1000,
    bbox_inches='tight')

vtt.unc_tolatex(fits[0], "0")
