def plot_output(cls, ts, i_inj, states, y_states=None, suffix="", show=True, save=False, l=1, lt=1, targstyle='-'): """ Plot voltage and ion concentrations, potentially compared to a target model Args: ts(ndarray of dimension [time]): time steps of the measurements i_inj(ndarray of dimension [time]): input current states(ndarray of dimension [time, state_var, nb_neuron]): y_states(list of ndarray [time, nb_neuron], optional): list of values for the target model, each element is an ndarray containing the recordings of one state variable (Default value = None) suffix(str): suffix for the name of the saved file (Default value = "") show(bool): If True, show the figure (Default value = True) save(bool): If True, save the figure (Default value = False) l(float): width of the main lines (Default value = 1) lt(float): width of the target lines (Default value = 1) targstyle(str): style of the target lines (Default value = '-') """ plt.figure() nb_plots = len(cls._ions) + 2 custom_cycler = None if (states.ndim > 3): # circuit in parallel states = np.reshape(np.swapaxes(states,-2,-1), (states.shape[0], states.shape[1], -1)) custom_cycler = cycler('color', utils.COLORS.repeat(y_states[cls.V_pos].shape[1])) y_states = [np.reshape(y, (y.shape[0], -1)) if y is not None else None for y in y_states] # Plot voltage p = plt.subplot(nb_plots, 1, 1) if custom_cycler is not None: p.set_prop_cycle(custom_cycler) plt.plot(ts, states[:, cls.V_pos], linewidth=l) if y_states is not None: if y_states[cls.V_pos] is not None: plt.plot(ts, y_states[cls.V_pos], 'r', linestyle=targstyle, linewidth=lt, label='target model') plt.legend() plt.ylabel('Voltage (mV)') for i, (ion, pos) in enumerate(cls._ions.items()): p = plt.subplot(nb_plots, 1, 2+i) if custom_cycler is not None: p.set_prop_cycle(custom_cycler) plt.plot(ts, states[:, pos], linewidth=l) if y_states is not None: if y_states[pos] is not None: plt.plot(ts, y_states[pos], 'r', linestyle=targstyle, linewidth=lt, label='target model') plt.legend() plt.ylabel('[{}]'.format(ion)) plt.subplot(nb_plots, 1, nb_plots) plt.plot(ts, i_inj, 'b') plt.xlabel('t (ms)') plt.ylabel('$I_{inj}$ ($\\mu{A}/cm^2$)') utils.save_show(show, save, utils.IMG_DIR + 'output_%s' % suffix)
def hhsimp_box(df): utils.box(df, ['b', 'g', 'm', 'g', 'm'], ['C_m', 'g_L', 'g_K', 'E_L', 'E_K']) plt.title('Membrane') utils.save_show(True, True, 'boxmemb', dpi=300) plt.subplot(3, 1, 1) utils.box(df, ['m', '#610395'], ['a__mdp', 'b__mdp']) plt.title('Midpoint') plt.subplot(3, 1, 2) utils.box(df, ['m', '#610395'], ['a__scale', 'b__scale']) plt.title('Scale') plt.subplot(3, 1, 3) utils.box(df, ['m', '#610395'], ['a__tau', 'b__tau']) plt.yscale('log') plt.title('Time constant') plt.tight_layout() utils.save_show(True, True, 'boxrates', dpi=300)
def plot_results(self, ts, i_inj_values, results, ca_true=None, suffix="", show=True, save=False): V = results[:, 0] a = results[:, 1] b = results[:, 2] il = self._i_L(V) ik = self._i_K(a, b, V) plt.figure() plt.subplot(4, 1, 1) plt.plot(ts, V, 'k') plt.title('Leaky Integrator Neuron') plt.ylabel('V (mV)') plt.subplot(4, 1, 2) plt.plot(ts, il, 'g', label='$I_{L}$') plt.plot(ts, ik, 'c', label='$I_{K}$') plt.ylabel('Current') plt.legend() plt.subplot(4, 1, 3) plt.plot(ts, a, 'c', label='a') plt.plot(ts, b, 'b', label='b') plt.ylabel('Gating Value') plt.legend() plt.subplot(4, 1, 4) plt.plot(ts, i_inj_values, 'b') plt.xlabel('t (ms)') plt.ylabel('$I_{inj}$ ($\\mu{A}/cm^2$)') # plt.ylim(-1, 40) utils.save_show(show, save, name='Results_{}'.format(suffix), dpi=300)
def boxplot_vars(var_dic, suffix="", show=False, save=True): df = pd.DataFrame.from_dict(var_dic) plt.figure() plt.subplot(121) cols = [RATE_COLORS['n'], RATE_COLORS['n'], RATE_COLORS['f'], 'k'] box(df, cols, CONDS) plt.title('Conductances') plt.subplot(122) cols = ['b', RATE_COLORS['n'], RATE_COLORS['f'], 'k'] box(df, cols, MEMB) # plt.plot([DEFAULT[m] for m in MEMB], 'r', marker='*', linestyle='', markersize=10) plt.title('Membrane') utils.save_show(show, save, name='{}MEmbrane_{}'.format(utils.NEUR_DIR, suffix).format(suffix), dpi=300) plt.figure() plt.subplot(211) box(df, ['#666666'], ['rho_ca']) plt.title('Rho_ca') plt.yscale('log') plt.subplot(212) box(df, ['#0000ff'], ['decay_ca']) # , 'b') plt.title('Decay_ca') plt.tight_layout() utils.save_show(show, save, name='{}CalciumPump_{}'.format(utils.NEUR_DIR, suffix), dpi=300) plt.figure() for i, type in enumerate(['mdp', 'scale', 'tau']): plt.subplot(3, 1, i + 1) plt.title(type) labels = [ '{}__{}'.format(rate, type) for rate in RATE_COLORS.keys() ] cols = RATE_COLORS.values() if (type == 'tau'): labels = ['h__alpha' if x == 'h__tau' else x for x in labels] plt.yscale('log') box(df, cols, labels) utils.save_show(show, save, name='{}Rates_{}'.format(utils.NEUR_DIR, suffix), dpi=300)
if __name__ == '__main__': show_res('Forward_celeggrouprealeq0.2', -1) get_data() get_curr() with open('forward_input', 'rb') as f: cur = pickle.load(f) df = pd.DataFrame(cur.transpose(), index=labels.values()) sns.heatmap(df, cmap='jet') plt.title('Membrane potentials (mV)') plt.xlabel('Time (ms)') plt.ylabel('Neuron') utils.save_show(False, False, 'Input Current', dpi=300) suffix = sys.argv[1] for i, m in enumerate(cfg_model.models): if cfg_model.NEURON_MODEL == m: suffix = cfg_model.models_name[i] + suffix break if fake: suffix = suffix + 'fake' else: suffix = suffix + 'real' if eq_cost: suffix = suffix + 'eqcost' else: suffix = suffix + 'difcost' suffix = suffix + str(dt)
def study_vars(cls, p, suffix='', target=None, show=False, save=True): cls.plot_vars(p, func=utils.bar, suffix='compared_%s' % suffix, show=show, save=save) cls.boxplot_vars(p, suffix='boxes_%s' % suffix, show=show, save=save) if p['C_m'].shape != (1, ): corr = pd.DataFrame(p).corr() plt.subplots(figsize=(11, 9)) # Generate a custom diverging colormap cmap = sns.diverging_palette(220, 10, as_cmap=True) # Draw the heatmap with the mask and correct aspect ratio sns.heatmap(corr, cmap=cmap, center=0, square=True, linewidths=.5, cbar_kws={"shrink": .5}) utils.save_show(show=show, save=save, name='{}Correlation_{}'.format( utils.NEUR_DIR, suffix)) # def comp(toto, curs): # import time # st = time.time() # v = toto.calculate_exc(curs)[:, 0] # print('explicit', time.time() - st) # plt.subplot(2, 1, 1) # plt.plot(np.arange(0, len(v) * toto.dt, toto.dt), v, 'r') # plt.xlabel('Time (ms)') # plt.ylabel('Voltage (mV)') # plt.title('Explicit solver, dt=%sms' % toto.dt) # st = time.time() # v = toto.calculate(curs)[:, 0] # print('implicit', time.time() - st) # plt.subplot(2, 1, 2) # plt.plot(np.arange(0, len(v) * toto.dt, toto.dt), v, 'g') # plt.xlabel('Time (ms)') # plt.ylabel('Voltage (mV)') # plt.title('Implicit-explicit solver, dt=%sms' % toto.dt) # plt.tight_layout() # plt.savefig('/home/marcus/Pictures/thesisreport/solversdt%s' % toto.dt, dpi=250) # plt.close() # # def step_exc(self, X, i_inj): # """Integrate and update voltage after one time step # # Args: # X(np.array or tensor): state vector # i_inj(np.array or tensor): input current # # """ # V = X[self.V_pos] # p = X[1] # q = X[2] # n = X[3] # e = X[4] # f = X[5] # cac = X[-1] # # h = self._h(cac) # V = V + ((i_inj - self._i_ca(V, e, f, h) - self._i_ks(V, n) - self._i_kf(V, p, q) - self._i_leak(V)) / # self._param[ # 'C_m']) * self.dt # # cac = cac + (-self._i_ca(V, e, f, h) * self._param['rho_ca'] - ( # (cac - self.REST_CA) / self._param['decay_ca'])) * self.dt # p = self._update_gate(p, 'p', V) # q = self._update_gate(q, 'q', V) # n = self._update_gate(n, 'n', V) # e = self._update_gate(e, 'e', V) # f = self._update_gate(f, 'f', V) # # if self._tensors: # return tf.stack([V, p, q, n, e, f, cac], 0) # else: # return np.array([V, p, q, n, e, f, cac]) # @staticmethod # def ica_from_v(X, v_fix, self): # e = X[1] # f = X[2] # cac = X[-1] # # h = self._h(cac) # tau = self._param['e__tau'] # e = ((tau * self.dt) / (tau + self.dt)) * ((e / self.dt) + (self._inf(v_fix, 'e') / tau)) # tau = self._param['f__tau'] # f = ((tau * self.dt) / (tau + self.dt)) * ((f / self.dt) + (self._inf(v_fix, 'f') / tau)) # ica = self._i_ca(v_fix, e, f, h) # cac += (-self._i_ca(v_fix, e, f, h) * self._param['rho_ca'] - ( # (cac - self.REST_CA) / self._param['decay_ca'])) * self.dt # # if self._tensors: # return tf.stack([ica, e, f, h, cac], 0) # else: # return [ica, e, f, h, cac] # # @staticmethod # def ik_from_v(X, v_fix, self): # p = X[1] # q = X[2] # n = X[3] # # tau = self._param['p__tau'] # p = ((tau * self.dt) / (tau + self.dt)) * ((p / self.dt) + (self._inf(v_fix, 'p') / tau)) # tau = self._param['q__tau'] # q = ((tau * self.dt) / (tau + self.dt)) * ((q / self.dt) + (self._inf(v_fix, 'q') / tau)) # tau = self._param['n__tau'] # n = ((tau * self.dt) / (tau + self.dt)) * ((n / self.dt) + (self._inf(v_fix, 'n') / tau)) # ik = self._i_kf(v_fix, p, q) + self._i_ks(v_fix, n) # # if self._tensors: # return tf.stack([ik, p, q, n], 0) # else: # return [ik, p, q, n] # # # def plots_ica_from_v(ts, V, results, name="ica", show=False, save=True): # """plot i_ca and Ca conc depending on the voltage # # Args: # ts: # V: # results: # name: (Default value = "ica") # show(bool): If True, show the figure (Default value = True) # save(bool): If True, save the figure (Default value = False) # # Returns: # # """ # ica = results[:, 0] # e = results[:, 1] # f = results[:, 2] # h = results[:, 3] # cac = results[:, -1] # # plt.figure() # # plt.subplot(4, 1, 1) # plt.title('Hodgkin-Huxley Neuron : I_ca from a fixed V') # plt.plot(ts, ica, 'b') # plt.ylabel('I_ca') # # plt.subplot(4, 1, 2) # plt.plot(ts, cac, 'r') # plt.ylabel('$Ca^{2+}$ concentration') # # plt.subplot(4, 1, 3) # plt.plot(ts, e, RATE_COLORS['e'], label='e') # plt.plot(ts, f, RATE_COLORS['f'], label='f') # plt.plot(ts, h, RATE_COLORS['h'], label='h') # plt.ylabel('Gating Value') # plt.legend() # # plt.subplot(4, 1, 4) # plt.plot(ts, V, 'k') # plt.ylabel('V (input) (mV)') # plt.xlabel('t (ms)') # # utils.save_show(show, save, name) # # # def plots_ik_from_v(ts, V, results, name="ik", show=True, save=False): # """plot i_k depending on the voltage # # Args: # ts: # V: # results: # name: (Default value = "ik") # show(bool): If True, show the figure (Default value = True) # save(bool): If True, save the figure (Default value = False) # # Returns: # # """ # ik = results[:, 0] # p = results[:, 1] # q = results[:, 2] # n = results[:, 3] # # plt.figure() # # plt.subplot(3, 1, 1) # plt.title('Hodgkin-Huxley Neuron : I_ca from a fixed V') # plt.plot(ts, ik, 'b') # plt.ylabel('I_k') # # plt.subplot(3, 1, 2) # plt.plot(ts, p, RATE_COLORS['p'], label='p') # plt.plot(ts, q, RATE_COLORS['q'], label='q') # plt.plot(ts, n, RATE_COLORS['n'], label='n') # plt.ylabel('Gating Value') # plt.legend() # # plt.subplot(3, 1, 3) # plt.plot(ts, V, 'k') # plt.ylabel('V (input) (mV)') # plt.xlabel('t (ms)') # # utils.save_show(show, save, name) # plt.close()
def plot_vars(cls, var_dic, suffix="evolution", show=False, save=True, func=utils.plot): """plot variation/comparison/boxplots of all variables organized by categories Args: var_dic: suffix: (Default value = "") show(bool): If True, show the figure (Default value = True) save(bool): If True, save the figure (Default value = False) func: (Default value = plot) Returns: """ fig = plt.figure() grid = plt.GridSpec(2, 3) for nb in range(len(GATES)): gate = GATES[nb] cls.plot_vars_gate(gate, var_dic['{}__mdp'.format(gate)], var_dic['{}__scale'.format(gate)], var_dic['{}__tau'.format(gate)], fig, grid[nb], (nb % 3 == 0), func=func) cls.plot_vars_gate('h', var_dic['h__mdp'], var_dic['h__scale'], var_dic['h__alpha'], fig, grid[5], False, func=func) plt.tight_layout() utils.save_show(show, save, name='{}Rates_{}'.format(utils.NEUR_DIR, suffix), dpi=300) fig = plt.figure() grid = plt.GridSpec(1, 2) subgrid = gridspec.GridSpecFromSubplotSpec(4, 1, grid[0], hspace=0.1) for i, var in enumerate(CONDS): ax = plt.Subplot(fig, subgrid[i]) func(ax, var_dic[var]) # ) ax.set_ylabel(var) if (i == 0): ax.set_title('Conductances') fig.add_subplot(ax) subgrid = gridspec.GridSpecFromSubplotSpec(4, 1, grid[1], hspace=0.1) for i, var in enumerate(MEMB): ax = plt.Subplot(fig, subgrid[i]) func(ax, var_dic[var]) # ) ax.set_ylabel(var) if (i == 0): ax.set_title('Membrane') ax.yaxis.tick_right() fig.add_subplot(ax) plt.tight_layout() utils.save_show(show, save, name='{}Membrane_{}'.format(utils.NEUR_DIR, suffix), dpi=300) plt.figure() ax = plt.subplot(211) func(ax, var_dic['rho_ca']) # , 'r') plt.ylabel('Rho_ca') plt.yscale('log') ax = plt.subplot(212) func(ax, var_dic['decay_ca']) # , 'b') plt.ylabel('Decay_ca') utils.save_show(show, save, name='{}CalciumPump_{}'.format(utils.NEUR_DIR, suffix), dpi=300)
def plot_results(self, ts, i_inj_values, results, ca_true=None, suffix="", show=True, save=False): """plot all dynamics Args: ts: i_inj_values: results: ca_true: (Default value = None) suffix: (Default value = "") show(bool): If True, show the figure (Default value = True) save(bool): If True, save the figure (Default value = False) Returns: """ V = results[:, 0] p = results[:, 1] q = results[:, 2] n = results[:, 3] e = results[:, 4] f = results[:, 5] cac = results[:, 6] h = self._h(cac) ica = self._i_ca(V, e, f, h) ik = self._i_ks(V, n) + self._i_kf(V, p, q) il = self._i_leak(V) plt.figure() plt.subplot(5, 1, 1) plt.title('C.elegans Hodgkin-Huxley Neuron') if (V.ndim == 1): plt.plot(ts, V, 'k') else: plt.plot(ts, V) plt.ylabel('V (mV)') plt.subplot(5, 1, 2) if (ca_true is not None): plt.plot(ts, ca_true, 'Navy', linestyle='-.', label='real data') plt.legend() if (V.ndim == 1): plt.plot(ts, cac, 'r') else: plt.plot(ts, cac) plt.ylabel('[$Ca^{2+}$]') plt.subplot(5, 1, 3) plt.plot(ts, ica, RATE_COLORS['f'], label='$I_{Ca}$') plt.plot(ts, ik, 'm', label='$I_{K}$') plt.plot(ts, il, 'g', label='$I_{L}$') plt.ylabel('Current') plt.legend() plt.subplot(5, 1, 4) plt.plot(ts, p, RATE_COLORS['p'], label='p') plt.plot(ts, q, RATE_COLORS['q'], label='q') plt.plot(ts, n, RATE_COLORS['n'], label='n') plt.plot(ts, e, RATE_COLORS['e'], label='e') plt.plot(ts, f, RATE_COLORS['f'], label='f') plt.plot(ts, h, RATE_COLORS['h'], label='h') plt.ylabel('Gating Value') plt.legend() plt.subplot(5, 1, 5) plt.plot(ts, i_inj_values, 'b') plt.xlabel('t (ms)') plt.ylabel('$I_{inj}$ ($\\mu{A}/cm^2$)') # plt.ylim(-1, 40) utils.save_show(show, save, name='Results_{}'.format(suffix), dpi=300)
def leak_box(df): utils.box(df, ['b', 'g', 'Gold'], ['C_m', 'g_L', 'E_L']) plt.title('Membrane') utils.save_show(True, True, 'box1', dpi=300)
# utils.save_show(True, True, 'dispreal', dpi=300) dd = optim.get_vars_all(dir, losses=True) optim.plot_loss_rate(dd['loss'], dd['rates'], dd['loss_test'], 50, show=True) from odynn import datas dic = optim.get_vars(dir, loss=True) train, test = optim.get_data(dir) print(dic['loss']) df = pd.DataFrame(dic['loss'], columns=['loss']) # df = pd.DataFrame.from_dict(dic)#.head(4) df = df.sort_values('loss').reset_index(drop=True) # df = df.dropna() sns.barplot(x=df.index, y='loss', data=df) # df.plot.bar(y='loss') utils.save_show(True, True, 'lossfin_virt', dpi=300);exit() # df = df[df['loss'] <= np.min(df['loss'])] # hhsimp_box(df) # cfg_model.NEURON_MODEL.boxplot_vars(dic, show=True, save=True) dic = df.to_dict('list') # dic = collections.OrderedDict(sorted(dic.items(), key=lambda t: t[0])) # obj = circuit.CircuitTf.create_random(n_neuron=9, syn_keys={(i,i+1):True for i in range(8)}, gap_keys={}, n_rand=50, dt=0.1) p = optim.get_best_result(dir) print(p) # p = {k: v[0] for k,v in p.items()} for i in range(train[1].shape[-1]): ns.comp_pars_targ(p, cfg_model.NEURON_MODEL.default_params, dt=train[0][1] - train[0][0], i_inj=train[1][:,i], suffix='virtrain%s'%i, show=True, save=True) for i in range(test[1].shape[-1]): ns.comp_pars_targ(p, cfg_model.NEURON_MODEL.default_params, dt=test[0][1] - test[0][0], i_inj=test[1][:,i], suffix='virtest%s'%i, show=True, save=True)