import numpy as np
import matplotlib.pyplot as plt
from . import ardice
from stardice import keithley

nt = np.load('ardice_caracteristics_0001.npy')

def solve(p, target):
    a, b, c = p
    c -= target
    delta = b*b - 4 * a * c
    x1 = (-b + np.sqrt(delta))/(2*a)
    return x1

target = 1e-5
curr = nt[0,:]
workpoint = []
for led in range(16):
    y = nt[1+2*led, :]
    e = nt[2+2*led, :]
    goods = (y < 1e35) & (curr > 100)
    p = np.polyfit(curr[goods], y[goods], 2)
    plt.subplot(4,4,led+1)
    plt.errorbar(curr[goods], -2.5 * np.log10(y[goods]/np.polyval(p, curr[goods])), e[goods]/np.polyval(p, curr[goods]), marker='.', ls='none')
    plt.axis([curr.min(), curr.max(), -0.1, 0.1])
    workpoint.append(solve(p, target))

print(workpoint)

print('testing workpoint')
ar = ardice.Ardice()
k = keithley.Keithley6514('/dev/ttyUSB1')
nsamples = 10

k.setup(krange=2e-5, samples=nsamples)

testres = []
for led in range(16):
    ar.all_led_off()
    ar.led_on(led, workpoint[led])
    on = k.read()
    print((workpoint[led], np.mean(on[0])))
    testres.append((led, workpoint[led], np.mean(on[0]), np.median(on[0]), np.std(on[0])))
ar.all_led_off()
del ar
testres = np.rec.fromrecords(testres, names=['led', 'curr', 'mean', 'median', 'std'])
plt.show()
             
    
