#! /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"
)

for f in ["ana", "digi"]:
    axarr[0].cla()
    axarr[1].cla()
    data = pd.read_csv("./adccalib_v18" + f + ".csv", comment="#")

    data['Dv'] = data['v_pit18'+f] / data['v_keith']
    print(data)

    axarr[0].errorbar(
        data['v_keith'],
        data['v_pit18'+f],
        yerr=data['dv_pit18'+f],
        label="V$_{MONITOR\_48V}$",
        fmt='.'
    )
    axarr[0].plot(
        data['v_keith'],
        data['v_keith'],
        c='#555555',
        alpha=.3
    )
    p =axarr[1].errorbar(
        data['v_keith'],
        data['Dv'],
        yerr=data['dv_pit18'+f],
        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_keith'],
        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 1V8"+f+"[1]", 
        data_pos=(np.mean(data.adcval), 1.1),
        formatting='f')

    plt.xlabel('V$_{OUT,EXT} / V$')
    axarr[0].set_ylabel('V$_{OUT,PIT} / V$')
    axarr[0].set_title("PowerIt ADC Calibration: 1V8 {} Output".format("Analog" if f == 'ana' else "Digital"))
    axarr[1].set_ylabel('($V_{OUT,PIT} / V_{OUT,EXT}$) / V')
    #-plt.savefig("2kw_direct.png")

    plt.tight_layout()
    plt.savefig("adccalib_v18" + f + ".pdf", dpi=1000)
