import matplotlib.pyplot as pl
import numpy as np
import pandas as pd
import json
from optimization.errfuns import rms
from new_optimization.fitter.hodgkinhuxleyfitter import HodgkinHuxleyFitter

__author__ = 'caro'


save_dir = '../../results/new_optimization/V_18_10_16/'
method = 'L-BFGS-B'

candidates = pd.read_csv(save_dir + method + '/candidates.csv')
best_candidate = candidates.candidate[np.argmin(candidates.fitness)]
best_candidate = np.array([float(x) for x in best_candidate.split()])

with open(save_dir + 'optimization_settings.json', 'r') as f:
    optimization_settings = json.load(f)

fitter = HodgkinHuxleyFitter(**optimization_settings['fitter'])

v_model, t, i_inj = fitter.simulate_cell(best_candidate)

pl.figure()
pl.plot(t, fitter.data.v, 'k', label='data')
pl.plot(t, v_model, 'r', label='model')
pl.legend()
pl.show()
                    [['soma', '0.5', 'km', 'gbar']],
                    [['soma', '0.5', 'ih_fast', 'gbar']],
                    [['soma', '0.5', 'ih_slow', 'gbar']],
                    [['soma', '0.5', 'nap', 'gbar']],
                    [['soma', '0.5', 'kdr', 'gbar']],
                    [['soma', '0.5', 'kap', 'gbar']],
                    [['soma', '0.5', 'na8st', 'gbar']]
                 ]
errfun = 'rms'
fitfun = 'get_v'
fitnessweights = [1]
model_dir = '../../../model/cells/dapmodel0.json'
mechanism_dir = '../../../model/channels/schmidthieber'
data_dir = '../../../data/2015_08_26b/rampIV/3.0(nA).csv'

fitter = HodgkinHuxleyFitter(variable_keys, errfun, fitfun, fitnessweights,
                 model_dir, mechanism_dir, data_dir, simulation_params={'celsius': 35})

# create cell
candidate = np.ones(len(variable_keys))  # gbars should be 1
fitter.update_cell(candidate)

# extract parameter
channel_list = get_channel_list(fitter.cell, 'soma')
ion_list = get_ionlist(channel_list)

v_exp = fitter.data.v.values
t_exp = fitter.data.t.values
i_exp = fitter.data.i.values
dt_exp = t_exp[1] - t_exp[0]

dvdt_exp = np.concatenate((np.array([(v_exp[1]-v_exp[0])/dt_exp]), np.diff(v_exp)/dt_exp))