import matplotlib.pyplot as plt
import numpy as np
from IPython import embed
import matplotlib as matplotlib
import math
import scipy.integrate as integrate
from scipy import signal
from scipy.interpolate import interp1d
from scipy.interpolate import CubicSpline
import scipy as sp
import pickle
from scipy.spatial import distance
from myfunctions import *
import time
from matplotlib import gridspec
#from matplotlib_scalebar.scalebar import ScaleBar
import matplotlib.mlab as ml
import scipy.integrate as si
import pandas as pd
from plot_eod_chirp import find_dev, find_beats, find_times, find_periods


def singlemodulation(beat_corr, deviation_s, a_fe, a_fr):
    bef_c = 0
    aft_c = 1
    sampling = 100000
    i = 0
    fig = plt.figure(figsize = (6,4))
    ax = {}
    pp_max = []
    add = 1
    nfft = 4096
    e = 0
    left_c = [bef_c * sampling] * len(beat_corr)
    right_c = [aft_c * sampling] * len(beat_corr)
    p = 0
    s = 0
    d = 0
    eod_fe = [0]
    eod_fr = 200
    time, time_cut, cut = find_times(left_c[e], right_c[e], sampling, deviation_s[d])
    eod_fish_e, eod_fish_r, period_fish_r, period_fish_e = find_periods(a_fe, time, eod_fr, a_fr, eod_fe, e)
    eod_overlayed_chirp = eod_fish_r+1
    nfft = int(4096*2*2)
    ax[1] = fig.add_subplot(1,2,1)#sharey=ax['third'+str(i)], sharex=ax['third'+str(i)]
    plt.plot(time, eod_overlayed_chirp )
    plt.xlim([0,0.05])
    ax[1].set_ylabel('mv')
    ax[1].set_xlabel('Time [ms]')
    ax[2] = fig.add_subplot(1,2,2)
    pp, f = ml.psd(eod_overlayed_chirp, Fs=sampling, NFFT=nfft,
                   noverlap=nfft / 2)
    ax[2].set_ylabel('psd')
    ax[2].set_xlabel('Frequency [Hz]')
    plt.plot(f, pp)
    plt.xlim([-50, 2000])
    plt.subplots_adjust(wspace = 0.45)
    plt.legend()
    plt.savefig('singlemodulation.pdf')
    plt.show()


if __name__ == "__main__":
    delta_t = 0.014  # ms
    interest_interval = delta_t * 1.2
    bef_c = interest_interval / 2
    aft_c = interest_interval / 2
    sigma = delta_t / math.sqrt((2 * math.log(10)))  # width of the chirp
    phase_zero = [0]  # phase when the chirp occured (vary later) / zero at the peak o a beat cycle
    phase_zero = np.arange(0,2*np.pi,2*np.pi/10)
    eod_fr = 500 # eod fish reciever
    eod_fr = 537# eod fish reciever
    factor = 200
    sampling_fish = 500
    sampling = 100000
    d = 1
    x = [ 1.5, 2.5,0.5,]
    x = [ 1.5]
    time_range = 200 * delta_t
    deviation_ms, deviation_s, deviation_dp = find_dev(x, sampling)
    a_fe = 0.5
    a_fr = 1
    start = 5
    end = 3500
    step = 250
    eod_fe, beat_corr, beats = find_beats(start,end,step,eod_fr)
    singlemodulation(beat_corr, deviation_s, a_fe, a_fr)
