import numpy as np
from IPython import embed


def zero_crossing(eod, time):
	threshold = 0
	shift_eod = np.roll(eod, 1)
	eod_times = time[(eod >= threshold) & (shift_eod < threshold)]
	sampling_rate = 40000.0
	eod_idx = eod_times*sampling_rate
	return eod_idx


def vector_strength(spike_times, eod_durations):
	n = len(spike_times)
	phase_times = np.zeros(len(spike_times))
	for i, idx in enumerate(spike_times):
		phase_times[i] = (spike_times[i] / eod_durations[i]) * 2 * np.pi
	vs = np.sqrt((1/n*sum(np.cos(phase_times)))**2 + (1/n*sum(np.sin(phase_times)))**2)
	return vs


def gaussian(x, sig):
	y = np.exp(-0.5 * (x/sig)**2) / np.sqrt(2*np.pi)/sig
	return y


def smooth(data, window, dt):
	sigma = window
	time_gauss = np.arange(-4 * sigma, 4 * sigma, dt)
	gauss = gaussian(time_gauss, sigma)
	smoothed_data = np.convolve(data, gauss, 'same')
	return smoothed_data


def map_keys(input):
	df_map = {} 
	for k in input.keys():
		freq = k[1]
		df = int(freq.strip('Hz'))
		if df in df_map.keys():
			df_map[df].append(k)
		else:
			df_map[df] = [k]
	return df_map
