
from Baseline import get_baseline_class
from CellData import CellData, icelldata_of_dir
from models.LIFACnoise import LifacNoiseModel
from Baseline import BaselineCellData, BaselineModel
from os import listdir
import numpy as np
from IPython import embed
import pyrelacs.DataLoader as Dl
from ModelFit import ModelFit, get_best_fit
from FiCurve import FICurveModel, FICurveCellData
import os
import matplotlib.pyplot as plt
import functions as fu
from scipy.optimize import curve_fit
from scipy.signal import find_peaks
from thunderfish.eventdetection import threshold_crossing_times, threshold_crossings, detect_peaks
import helperFunctions as hF
import models.smallModels as sM
from stimuli.SinusoidalStepStimulus import SinusoidalStepStimulus
from matplotlib import gridspec
# from plottools.axes import labelaxes_params





# sp = self.spikes(index)
# binary = np.zeros(t.shape)
# spike_indices = ((sp - t[0]) / dt).astype(int)
# binary[spike_indices[(spike_indices >= 0) & (spike_indices < len(binary))]] = 1
# g = gaussian_kernel(kernel_width, dt)
# rate = np.convolve(binary, g, mode='same')

fit = ModelFit("results/final_2/2012-07-12-ag-invivo-1/start_parameter_4_err_6.11/")
model = fit.get_model()
print(model.parameters)
eodf = fit.get_cell_data().get_eod_frequency()
baseline = BaselineModel(model, eod_frequency=eodf)
print("model BF: {:.2f}".format(baseline.get_baseline_frequency()))

model_no_dend = LifacNoiseModel({'step_size': 5e-05, 'mem_tau': 0.0018888888888888887, 'v_base': 0, 'v_zero': 0, 'threshold': 1, 'v_offset': -175.9718894958496, 'input_scaling': 364.44444444444446, 'delta_a': 0.03, 'tau_a': 0.1511111111111111, 'a_zero': 4.402004449113477, 'noise_strength': 0, 'dend_tau': 5e-05, 'refractory_period': 0.0007944444444444448}
)

baseline = BaselineModel(model_no_dend, eod_frequency=eodf)

print("no dend BF: {:.2f}".format(baseline.get_baseline_frequency()))
# baseline.plot_interspike_interval_histogram()

for i in range(10):
    v1, spikes = model.simulate(SinusoidalStepStimulus(eodf, 0, 0), 30)
    print("last spikes:", max(spikes))
    print(len(spikes) / 30)
    time, freq = hF.calculate_time_and_frequency_trace(spikes, 5e-05)
    plt.plot(time, freq)
    plt.show()