from . import ardice
from stardice import keithley
import numpy as np
from glob import glob

template = 'ardice_caracteristics_'
existing_files = glob(template +'*.npy')
existing_files = [int(f.replace('.npy', '').replace(template, '')) for f in existing_files]
if not existing_files:
    print('Warning: first file in the seri')
    odometer = 0
else:
    odometer = np.max(existing_files) + 1

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

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

result = []
curr = np.arange(10, 2000, 10)
result.append(curr)
for led in range(16):
    ar.all_led_off()
    dark = k.read()
    res = np.full(len(curr), np.nan)
    std = np.full(len(curr), np.nan)
    for _c, c in enumerate(curr):
        ar.led_on(led, c)
        on = k.read()
        res[_c] = np.mean(on[0]) - np.mean(dark[0])
        std[_c] = np.std(on[0])/np.sqrt(nsamples)
        if res[_c] > 1e37:
            break
    result.append(res)
    result.append(std)
ar.all_led_off()
del ar
#result = np.rec.fromrecords(result, names=['led', 'dark', 'on'])
result = np.array(result)
import matplotlib.pyplot as plt
np.save(template+'%04d.npy' % odometer, result)
