from nrn_wrapper import Cell, complete_mechanismdir
from optimization.simulate import iclamp, extract_simulation_params

__author__ = 'caro'

data_real_dir = '../2015_08_11d/ramp/ramp.csv'
data_new_dir = './ramp.csv'
model_dir = '../../model/cells/dapmodel0.json'
mechanism_dir = '../../model/channels/schmidthieber'

data_real = pd.read_csv(data_real_dir)

# create cell and run simulation
cell = Cell.from_modeldir(model_dir, complete_mechanismdir(mechanism_dir))
simulation_params = extract_simulation_params(data_real)
v, t = iclamp(cell, **simulation_params)
i = data_real.i.values
sec = data_real.sec.values

data = pd.DataFrame({'v': v, 't': t, 'i': i, 'sec': sec})
data.to_csv(data_new_dir, index=None)

pl.figure()
pl.plot(t, v)
pl.show()

pl.figure()
pl.plot(t, i)
pl.show()
prng = Random()
prng.seed(seed)

# initialize data
t = np.arange(0, problem.simulation_params['tstop']+dt, dt)
i_inj = problem.simulation_params['i_amp']
data = np.zeros((n_data, len(t)/subsample, 2))  # inputs are the trace of v and i_inj
labels = np.zeros(n_data)

for i in range(n_data):
    # modify parameter
    candidate = problem.generator(prng, None)

    # run simulation
    problem.update_cell(candidate)
    v, t = iclamp(problem.cell, **problem.simulation_params)
    data[i, :, 0] = v[:-1:subsample]
    data[i, :, 1] = i_inj[:-1:subsample]
    labels[i] = candidate[0]

# store data
if not os.path.exists(save_dir):
    os.makedirs(save_dir)
with open(save_dir+'/problem.json', 'w') as f:
    json.dump(params, f, indent=4)
with open(save_dir+'/cell.json', 'w') as f:
    json.dump(Cell.from_modeldir(params['model_dir']).get_dict(), f, indent=4)
np.savetxt(save_dir+'/seed.txt', np.array([seed]))
with open(save_dir+'data.npy', 'w') as f:
    np.save(f, data)
with open(save_dir+'labels.npy', 'w') as f: