"""
This script simply plots diode electrical pulse traces and computes thier time of arrival and widths based on a set-reset logic.
Jianwei Jan 2017
"""
import numpy as np
import matplotlib.pyplot as plt
import glob

import sys
sys.path.append('/workspace/projects/TES/scripts/TESPulseFitCode')
import lecroy
from pulse_discrimination import srlatch_full as sr
import peakutils as pku

def trace_extr(filename):
	"""extract relevant parameters from a trace stored in a file
	"""
	trc = lecroy.LecroyBinaryWaveform(filename)
	time = trc.mat[:, 0]*1e9
	signal = trc.mat[:, 1]
	return np.array(time), np.array(signal)

if __name__ == '__main__':

	# Export .trc as .txt for plotting - figures/lmfit_components_250ns/
	# time,signal = trace_extr('/home/jianwei/Posters/TESPulse/figures/fit_accuracy/diode_pulses/C1_diode_240ns_avg_100_00000.trc')
	# np.savetxt('diode_pulse_separated_240ns.dat',zip(time,signal),header='time(ns)\tsignal(V)',fmt=('%f','%f'))

	taus_vec=[]
	widths_vec=[]

	filelist = glob.glob('*.trc')
	for f in filelist:
		time,signal = trace_extr(f) 
		disc = sr(signal, -1, -1) # use discriminator to find edges
		edges = time[:-1][np.diff(disc)==1]
		tau = (edges[3]+edges[2])/2-(edges[0]+edges[1])/2
		widths = np.array([edges[1]-edges[0],edges[3]-edges[2]])
		taus_vec.append(tau)
		widths_vec.append(np.mean(widths))

		plt.cla()
		plt.plot(time,signal)
		np.set_printoptions(precision=3)
		plt.title('diode seperation = {:.2f}ns \t widths = {}ns \nedges at ={}ns'.format(tau,widths,edges))
		plt.show()
	results = zip(taus_vec,widths_vec)	
	np.savetxt('diode_pulses_separation_and_widths.dat', results, header='diode_separation\tdiode_widths')


