#! /usr/bin/python3

import scipy.optimize as opt
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import VisTools.plotting as vt

plt.ioff()
plt.style.use('bmh')
fig, axarr = plt.subplots(
    2,
    1,
    figsize=(10, 8),
    gridspec_kw={'height_ratios':[2, 1]},
    sharex="col"
)
data = pd.read_csv("./adccalib_v48.csv", comment="#")

data['Dv'] = data['v_pit48'] / data['v_keith']
print(data)

axarr[0].errorbar(
    data['v_keith'],
    data['v_pit48'],
    yerr=data['dv_pit48'],
    label="V$_{MONITOR\_48V}$",
    fmt='.'
)
p =axarr[1].errorbar(
    data['v_keith'],
    data['Dv'],
    yerr=data['dv_pit48'],
    label=" absolute Error of ADC",
    fmt='.',
    alpha=.3
)

# fit to abs dist
linfnc = lambda x,m,c: x*m+c

pfinal = vt.fit_linear(
    data.v_keith,
    data.Dv,
    (0,0)
)

axarr[1].plot(
    data.v_set,
    linfnc(data.v_keith, pfinal[0].n, pfinal[1].n),
    color=p[0].get_color()
)

print( pfinal )


vt.annotate_unc(
    plt, 
    pfinal[1], 
    name="\Delta V48[1]", 
    data_pos=(47, 1.1),
    formatting='f')

plt.xlabel('V$_{IN,EXT} / V$')
axarr[0].set_ylabel('V$_{IN,PIT} / V$')
axarr[0].set_title("PowerIt ADC Calibration: 48V Input")
axarr[1].set_ylabel('($V_{IN,PIT} / V_{IN,EXT}$) / V')
#-plt.savefig("2kw_direct.png")

plt.tight_layout()
plt.savefig("adccalib_v48.pdf", dpi=1000)
