def plot_signals(output, ge=None): fig, AX = ge.figure(axes_extents=[[[3,1]], [[3,1]], [[3,1]], [[3,1]]]) cond = output['t']>150 AX[0].plot(output['t'][cond], output['bZn_syn'][cond], '-', color=ge.colors[0]) AX[1].plot(output['t'][cond], output['Vm_syn'][cond], '-', color=ge.colors[1]) AX[2].plot(output['t'][cond], output['Vm_soma'][cond], '-', color=ge.colors[2]) return fig
def plot_sim(tdiscard=100, tend=1000): Data = np.load('data/pair_calib.npy', allow_pickle=True).item() cond = (Data['t']>tdiscard) & (Data['t']<tend) from datavyz import ge fig, ax= ge.figure(figsize=(2,2)) for i in range(len(Data['alphaZn'])): ge.plot(Data['t'][cond], np.array(Data['Current'][i]).mean(axis=0)[cond], color=ge.viridis(i/len(Data['alphaZn'])), ax=ax, no_set=True) ge.show()
def plot_matrix(Model, ge=None): REC_POPS, AFF_POPS = list(Model['REC_POPS']), list(Model['AFF_POPS']) pconnMatrix = np.zeros((len(REC_POPS)+len(AFF_POPS), len(REC_POPS))) for i, source_pop in enumerate(REC_POPS+AFF_POPS): for j, target_pop in enumerate(REC_POPS): pconnMatrix[i,j] = Model['p_%s_%s' % (source_pop, target_pop)] if ge is None: from datavyz import ge fig, ax = ge.figure(right=5.) Lims = [np.round(100*pconnMatrix.min(),1)-.1,np.round(100*pconnMatrix.max(),1)+.1] ge.matrix(100*pconnMatrix.T, origin='upper', ax=ax, vmin=Lims[0], vmax=Lims[1]) n, m = len(REC_POPS)+len(AFF_POPS), len(REC_POPS) for i, label in enumerate(REC_POPS+AFF_POPS): ge.annotate(ax, label, (-0.2, .9-i/n),\ ha='right', va='center', color=COLORS[i]) for i, label in enumerate(REC_POPS): ge.annotate(ax, label, (i/m+.25, -0.1),\ ha='right', va='top', color=COLORS[i], rotation=65) acb = ge.bar_legend(fig, inset=dict(rect=[.72,.3,.03,.5], facecolor=None), colormap=ge.viridis, bounds=[Lims[0], Lims[1]], label='$p_{conn}$ (%)') ge.set_plot(ax, ['left', 'bottom'], tck_outward=0, xticks=.75*np.arange(0,4)+.75/2., xticks_labels=[], xlim_enhancment=0, ylim_enhancment=0, yticks=.83*np.arange(0,6)+.85/2., yticks_labels=[]) return fig, ax, acb
ntwk.defaultclock.dt = 0.01*ntwk.ms else: ntwk.defaultclock.dt = 0.025*ntwk.ms ntwk.run(tstop*ntwk.ms) # if not active: # ntwk.run(tstop*ntwk.ms) # else: # adaptive_run(tstop, neuron, M) # ntwk.run(tstop*ntwk.ms) print('Runtime: %.2f s' % (time.time()-start)) from datavyz import ges as ge fig, AX = ge.figure(axes=(1,2),figsize=(2,1)) AX[0].plot(np.array(M.t/ntwk.ms), np.array(M.v/ntwk.mV)[0,:], label='soma') ge.plot(np.array(M.t/ntwk.ms), np.array(M.v/ntwk.mV)[1,:], label='dend', ax=AX[0]) if active: ge.plot(np.array(M.t/ntwk.ms), np.array(M.InternalCalcium/ntwk.nM)[1,:], label='dend', ax=AX[1], axes_args={'ylabel':'[Ca2+] (nM)', 'xlabel':'time (ms)'}) else: AX[1].plot(np.array(M.t/ntwk.ms), np.array(S.gAMPA/ntwk.nS)[0,:], ':', color=ge.orange, label='gAMPA') AX[1].plot(np.array(M.t/ntwk.ms), np.array(S.gE_post/ntwk.nS)[0,:]-np.array(S.gAMPA/ntwk.nS)[0,:], color=ge.orange, label='gNMDA') ge.legend(AX[0]) ge.legend(AX[1]) ge.show()
width='double-column', # can also be "single-column" or "one-and-a-half-column" fig_name='fig2.png', bg='gray', grid=True) ge.multipanel_figure([], width='one-and-a-half-column', # can also be "single-column" or "one-and-a-half-column" fig_name='fig3.png', bg='gray', grid=True) """ # generate some random data t = np.linspace(0, 10, 1e3) y = np.cos(5*t)+np.random.randn(len(t)) # Panel 'a' - schematic fig11 = 'docs/schematic.svg' # Panel 'b' - time series plot fig12, ax12 = ge.figure(axes_extents=(3,1)) # i.e. a wide plot ax12.plot(t, y) ge.set_plot(ax12, xlabel='xlabel (xunit)', ylabel='ylabel (yunit)') # Panel 'c' - more time series plot fig21, ax21 = ge.figure(axes_extents=(4,1)) # i.e. a very wide plot ax21.plot(t[t>9], y[t>9], label='raw') ax21.plot(t[t>9][1:], np.diff(y[t>9]), label='deriv.') ax21.plot(t[t>9][1:-1], np.diff(np.diff(y[t>9])), label='2nd deriv.') ge.set_plot(ax21, xlabel='xlabel (xunit)', ylabel='ylabel (yunit)') ge.legend(ax21, ncol=3, loc=(.3,1.)) # put a legend # Panel 'd' - scatter plot fig31, ax31 = ge.scatter(t[::10], t[::10]+np.random.randn(100), xlabel='ylabel (yunit)')
a = (1-SCALE['left']-SCALE['right'])/x_plots-SCALE['wspace'] a0 = (1-SCALE0['left']-SCALE0['right'])/x_plots-SCALE0['wspace'] b = (1-SCALE['top']-SCALE['bottom'])/y_plots-SCALE['hspace'] b0 = (1-SCALE0['top']-SCALE0['bottom'])/y_plots-SCALE0['hspace'] return { 'figsize':(\ A0_format['width']*A0_ratio*x_plots, A0_format['height']*A0_ratio*y_plots*height_to_width)} if __name__=='__main__': from datavyz import ge fig, ax = ge.figure(figsize=(1.2,1), left=1., right=4.) ax2 = ax.twinx() ax.plot(np.log10(np.logspace(-2.2,3,100)), np.exp(np.random.randn(100)), 'o', ms=2, color=ge.blue) ax2.plot(np.log10(np.logspace(-2,3,100)), np.exp(np.random.randn(100)), 'o', ms=1, color=ge.red) ge.set_plot(ax2, ['right'], yscale='log', ylabel='blabla', # yticks_rotation=20, size='x-small', tck_outward=2, ycolor=ge.red) ge.set_plot(ax, ycolor=ge.blue, xcolor='k', yscale='log', xscale='already-log10', ylabel='blabal', tck_outward=2, xlabel='trying', ylabelpad=-5) ge.savefig(fig, 'docs/twin-log-scale.png') ge.show()
'\$', '\#', '\%', '\S'] def getRandomMarker(): return "$" + markers[randint(0, len(markers), 1)] + "$" def getMarker(i): # Use modulus in order not to have the index exceeding the lenght of the list (markers) return "$" + markers[i % len(markers)] + "$" if __name__ == '__main__': from datavyz import ge fig, ax = ge.figure() for i, mi in enumerate(markers): # plt.plot(x[i], y[i], "b", alpha=0.5, marker=getRandomMarker(), markersize=randint(16,26,1)) ax.plot(x[i], y[i] + 50, "m", alpha=0.5, marker=getMarker(i), markersize=5) # Let's see if their "center" is located where we expect them to be... ax.plot(x[i], y[i] + 100, ge.red, alpha=0.5, marker=getMarker(i),
def show_trial_average_responses(RESP_PER_STIM, resp='', alphaZn=0., VLIM=None, ge=ge, syn_location='all', stimseed='all', annotate=True, window=[-200,400]): if resp=='ampa-only': cond = (RESP_PER_STIM['ampa_only']==True) else: cond = (RESP_PER_STIM['ampa_only']==False) & (RESP_PER_STIM['alphaZn']==alphaZn) resp = '$\\alpha_{Zn}$=%.2f' % alphaZn if syn_location!='all': cond = cond & (RESP_PER_STIM['syn_location']==syn_location) sloc = 'loc #%i' % syn_location else: sloc = 'Nloc=%i' % len(np.unique(RESP_PER_STIM['syn_location'])) if stimseed!='all': cond = cond & (RESP_PER_STIM['stimseed']==stimseed) stim = 'stim-seed #%i' % (1+np.argwhere(np.unique(RESP_PER_STIM['stimseed'])==stimseed)[0][0]) else: stim = 'n=%i stim-seeds' % len(np.unique(RESP_PER_STIM['stimseed'])) bg_levels = np.unique(RESP_PER_STIM['bg_level']) fig, AX = ge.figure(figsize=(.85,.9), axes=(len(bg_levels),1), wspace=0.1, right=1.3) ge.annotate(AX[-1], '%s, n=%i bg seeds, %s, %s' % (resp, len(np.unique(RESP_PER_STIM['seed'])), stim, sloc), (1., 1), ha='right', size='small') t = RESP_PER_STIM['t'] ylim, ylim2 = [np.inf, -np.inf], [np.inf, -np.inf] for ibg, bg in enumerate(bg_levels): for istim, nstim in enumerate(np.unique(RESP_PER_STIM['nstim'])[::-1]): # raw responses scond = cond &\ (RESP_PER_STIM['nstim']==nstim) & (RESP_PER_STIM['bg_level']==bg) tcond = (t>=RESP_PER_STIM['stim_delay']+window[0]) & (t<RESP_PER_STIM['stim_delay']+window[1]) y0 = np.mean([RESP_PER_STIM['Vm'][i] for i, s in enumerate(scond) if s], axis=0) AX[ibg].plot(t[tcond], y0[tcond],lw=1, color=cmap(1-istim/len(np.unique(RESP_PER_STIM['nstim'])))) ylim = [-76, max([ylim[1],y0.max()])] AX[ibg].plot([t[tcond][0],t[tcond][-1]], -75*np.ones(2), 'k:', lw=0.5) if annotate: ge.annotate(AX[ibg],'%.1fHz'%bg,(1,.7), color=ge.purple,ha='right',va='top') for ibg, bg in enumerate(bg_levels): if VLIM is not None: ylim = VLIM ge.set_plot(AX[ibg], [], ylim=ylim) ge.draw_bar_scales(AX[0], Xbar = 100, Xbar_label='100ms', Ybar = 10, Ybar_label='10mV', loc=(0.05,.8), orientation='right-bottom') ge.bar_legend(fig, X=np.unique(RESP_PER_STIM['nstim']), bounds=[0, np.unique(RESP_PER_STIM['nstim'])[-1]], ticks_labels=['%i' % x if i%4==0 else '' for i, x in enumerate(np.unique(RESP_PER_STIM['nstim']))], inset=dict(rect=[.999,.4,.016, .5]), colormap=cmap, label='$N_{syn}$') return fig
def show_response_bg_dep(FREE, CHELATED, AMPA=None, ge=ge, method='Integral', BG_levels=None, crossing=None, xlim=None, ylim=None, yscale='lin'): if BG_levels is None: BG_levels = [R['bg_level'] for R in FREE] CS = [CHELATED, FREE] if AMPA is not None: CS.append(AMPA) fig, AX = ge.figure(axes=(1,3), figsize=(1,1.), hspace=0.3, right=1.5) else: fig, AX = ge.figure(axes=(1,2), figsize=(1,1.), hspace=0.3, right=1.5) #fig2, ax2 = ge.figure(axes=(1,1), figsize=(1,1.), hspace=0.3, right=1.5) for ibg, bg in enumerate(BG_levels): if method[:5]=='delta': AX[0].plot(FREE[ibg]['nstims'], FREE[ibg][method[5:]]-FREE[ibg][method[5:]][0], lw=1, color=cmap(ibg/(len(BG_levels)-1))) AX[1].plot(CHELATED[ibg]['nstims'], CHELATED[ibg][method[5:]]-CHELATED[ibg][method[5:]][0], lw=1, color=cmap(ibg/(len(BG_levels)-1))) else: for C, ax in zip(CS, AX): # data try: ge.scatter(C[ibg]['nstims'], C[ibg][method], ax=ax, color=cmap(ibg/(len(BG_levels)-1)), no_set=True, lw=0.5, ms=2) # fit x, coefs = np.linspace(C[ibg]['nstims'][0], C[ibg]['nstims'][-1], 100), C[ibg][method+'-coeffs'] y = coefs[0]*sigmoid_func(x, coefs[1], coefs[2]) ge.plot(x, y, ax=ax, color=cmap(ibg/(len(BG_levels)-1)), no_set=True, lw=3, alpha=0.5) except IndexError: pass # ADDING THE c50 position: if crossing is not None: try: ix0 = min(np.argwhere(y>crossing).flatten()) ax.plot(np.ones(2)*x[ix0], [0,crossing], ':', lw=1, color=cmap(ibg/(len(BG_levels)-1))) except ValueError: pass if crossing is not None: for ax in AX[:2]: ax.plot([x[0], x[-1]], crossing*np.ones(2), ':', lw=0.5, color=ge.dimgrey) ge.annotate(AX[1], 'L23-L23\nprops', (0., .9), size='small', color='dimgrey', bold=True, va='top') ge.annotate(AX[0], 'L4-L23\nprops', (0., .9), size='small', color=ge.green, bold=True, va='top') if method=='Integral': ylabel='PSP integral (mV.s)'+10*' ' if method=='Peak': ylabel='max. $\delta$ $V_m$ (mV)'+10*' ' if method=='Freq': ylabel='Spike Freq. (Hz) '+10*' ' if method=='Proba': ylabel='Spike Probability '+20*' ' if method=='deltaFreq': ylabel='$\delta$ Spike Freq. (Hz) '+10*' ' ge.set_plot(AX[0], ['left'], ylabel=ylabel, ylim=ylim) if AMPA is None: ge.set_plot(AX[0], ['left'], ylabel=ylabel, ylim=ylim, xlim=xlim, yscale=yscale) ge.set_plot(AX[1], xlabel='$N_{syn}$', ylim=ylim, xlim=xlim, yscale=yscale) else: ge.set_plot(AX[0], ['left'], ylim=ylim, xlim=xlim, yscale=yscale) ge.set_plot(AX[1], ['left'], ylabel=ylabel, ylim=ylim, xlim=xlim, yscale=yscale) ge.set_plot(AX[2], xlabel='$N_{syn}$', ylim=ylim, xlim=xlim, yscale=yscale) ge.annotate(AX[2], 'AMPA\nonly', (0., .9), size='small', color=ge.blue, bold=True, va='top') #ge.set_plot(ax2, xlabel='$\\nu_{bg}$ (Hz)', ylabel='$c_{50}$ ($N_{syn}$)') ge.bar_legend(fig, X=[0]+BG_levels, bounds=[-BG_levels[1]/2., BG_levels[-1]+BG_levels[1]/2], inset=dict(rect=[.9,.3,.05, .5]), label='$\\nu_{bg}$ (Hz)', colormap=cmap) return fig #, fig2
# # we reintroduce the data limits # ax.set_ylim(ylim) # ax.set_xlim(xlim) if __name__ == '__main__': x = 32.23545345e-5 print(sci_str(x, rounding=2)) print(from_pval_to_star(x)) for i in range(20): print(int_to_roman(i)) from datavyz import ge fig, AX = ge.figure(axes=(10, 1), figsize=(.7, .7), bottom=1.5) for i, ax in enumerate(AX): ge.top_left_letter(ax, ge.int_to_roman(i + 1)) ge.matrix(np.random.randn(10, 10), ax=ax) sax = ge.arrow(fig, [0.04, .2, .93, 0.]) ge.annotate(fig, 'time', (.5, .17), ha='center') ge.savefig(fig, 'docs/annotations1.png') ge.show() # from datavyz..graphs import * # fig, ax = figure() # ax.plot(np.random.randn(30), np.random.randn(30), 'o') # bar_scales(ax, xbar=2, ybar=2, location='bottom left', # ybar_label=r'10$\mu$V', xbar_label='200ms')
def plot_single_sim_bg_data(RESP, ge=ge, alphaZn=[0, 0.45], view=[-200, 600], shift=20, Vm_shift=1., with_ampa_only=False, NSTIMs=None, bg_levels=[0.], with_nsyn_annot=False, syn_location=0, seeds=[0], stimseeds=[0], LABELS=[], COLORS=[ge.green, 'k'], LWS=[1.5, 1, 1, 2], bar_scale_args=dict(Xbar=200, Xbar_label='200ms', Ybar=15, Ybar_label='15mV ', loc=(0.1, .8), orientation='right-bottom'), ampa_color=ge.blue, figsize=(2.1, .15), VLIM=[-85, 30]): """ Show raw simulation data """ AE = [] for _ in range(len(bg_levels)): AE += [[[1, 6]]] AE += [[[1, 3]]] AE += [[[1, 1]]] fig, AX = ge.figure(axes_extents=AE, figsize=figsize, hspace=0., left=.2, right=.3, top=1.2) if len(stimseeds) < len(bg_levels): stimseeds = [stimseeds[0] for _ in range(len(bg_levels))] if len(seeds) < len(bg_levels): seeds = [seeds[0] for _ in range(len(bg_levels))] for bg_level, stimseed, seed, ax, ax2, ax3 in zip(bg_levels, stimseeds, seeds, AX[::3], AX[1::3], AX[2::3]): cond = np.zeros(len(RESP['bg_level']), dtype=bool) CONDS = [((RESP['alphaZn'] == aZn) & (RESP['ampa_only'] == False)) for aZn in alphaZn] # adding the alpha levels for acond in CONDS: cond = cond | acond cond0 = (RESP['bg_level'] == bg_level) & (RESP['syn_location'] == syn_location) cond = cond & cond0 # adding the same bg-seed and stim-seed condition AVAILABLE_BG_SEEDS, AVAILABLE_STIM_SEEDS = [], [] for acond in CONDS: AVAILABLE_BG_SEEDS.append(np.unique(RESP['seed'][cond & acond])) AVAILABLE_STIM_SEEDS.append( np.unique(RESP['stimseed'][cond & acond])) available_bg_seeds = np.intersect1d(*AVAILABLE_BG_SEEDS) available_stim_seeds = np.intersect1d(*AVAILABLE_STIM_SEEDS) if (len(available_bg_seeds) < 1) or (len(available_stim_seeds) < 1): raise BaseException print(available_bg_seeds, available_stim_seeds) print('---> No available seeds for this configuration:') if with_ampa_only: CONDS.append((RESP['ampa_only'] == True)) COLORS.append(ampa_color) for i in range(len(CONDS)): CONDS[i] = CONDS[i] & cond0 &\ (RESP['seed']==available_bg_seeds[seed]) &\ (RESP['stimseed']==available_stim_seeds[stimseed]) ax3.axis('off') for ic, cond, color, lw in zip(range(len(CONDS)), CONDS, COLORS, LWS): icond = np.argwhere(cond) # icond = np.argwhere(cond & acond) if len(icond) > 0: i0 = icond[0][0] if NSTIMs is None: NSTIMs = RESP['NSTIMs'][i0] iplot = 0 data = np.load(RESP['filename'][i0], allow_pickle=True).item() tt, Vm = data['t'], data['Vm_soma'] BG_raster, STIM_raster = data['BG_raster'], data['STIM_raster'] for istim, nstim in enumerate(RESP['NSTIMs'][i0]): if nstim in NSTIMs: t0 = istim * RESP['duration_per_bg_level'][i0] + view[ 0] + RESP['stim_delay'][i0] t1 = t0 + view[1] - view[0] tcond = (tt >= t0) & (tt < t1) t, v = tt[tcond], Vm[tcond] ax.plot(t - t0 + iplot * (shift + view[1] - view[0]), v + ic * Vm_shift, color=color, lw=lw) if color == COLORS[0]: for i, sp0 in enumerate(BG_raster): sp = np.array(sp0) spcond = (sp >= t0) & (sp < t1) ax2.scatter(sp[spcond] - t0 + iplot * (shift + view[1] - view[0]), i * np.ones(len(sp[spcond])), color=ge.purple, s=1) for i, sp0 in enumerate(STIM_raster): sp = np.array(sp0) spcond = (sp >= t0) & (sp < t1) ax2.scatter(sp[spcond] - t0 + iplot * (shift + view[1] - view[0]), i * np.ones(len(sp[spcond])), color=ge.orange, s=1) if bg_level == 0. or with_nsyn_annot: ge.annotate( ax2, '$N_{syn}$=%i' % nstim, (iplot * (shift + view[1] - view[0]) - view[0], i), va='top', clip_on=False, xycoords='data', rotation=90, color=ge.orange, ha='right', size='x-small') # ge.annotate(ax3, ' $N_{syn}$=%i' % nstim, # (iplot*(shift+view[1]-view[0])-view[0], 0), clip_on=False, # xycoords='data', color=ge.orange, size='x-small') iplot += 1 else: print('data not found for color:', color) # fig.suptitle('loc-ID=%i, bg-seed=%i, stim-seed=%i' % (syn_location, available_bg_seeds[seed], # available_stim_seeds[stimseed])) ge.annotate(ax2, '$\\nu_{bg}$=%.0fHz' % bg_level, (0, 0), color=ge.purple, rotation=90, ha='right', size='small') ge.set_plot(ax, [], xlim=[0, iplot * (shift + view[1] - view[0])], ylim=VLIM) ge.set_plot(ax2, [], xlim=[0, iplot * (shift + view[1] - view[0])], ylim=[-1, i + 1]) ge.set_plot(ax3, [], xlim=[0, iplot * (shift + view[1] - view[0])], ylim=[-1, i + 1]) if bg_level == 0.: for i, label, color in zip(range(4), LABELS, COLORS): ge.annotate(ax, label, (i / 5. + .2, 1.), color=color, va='top') ge.draw_bar_scales(ax, **bar_scale_args) return fig
from datavyz import ge X, y = make_moons(n_samples=400, noise=0.30, random_state=42) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42) # Single Decision Tree Classifier tree = DecisionTreeClassifier() tree.fit(X_train, y_train) # Bagging Classifier bag_clf = BaggingClassifier(\ DecisionTreeClassifier(), n_estimators=500, max_samples=0.5, bootstrap=True) bag_clf.fit(X_train, y_train) fig, AX = ge.figure(axes=(1, 2)) for ax in AX: ge.scatter( X=[X_train[:, 0][y_train == 1], X_train[:, 0][y_train == 0]], Y=[X_train[:, 1][y_train == 1], X_train[:, 1][y_train == 0]], xlabel='x1', ylabel='x2', COLORS=[ge.blue, ge.orange], LABELS=['y=1', 'y=0'], ax=ax) x1, x2 = np.meshgrid( np.linspace(X_train[:, 0].min(), X_train[:, 0].max(), 200), np.linspace(X_train[:, 1].min(), X_train[:, 1].max(), 200)) y_pred_full = tree.predict(np.array([x1.flatten(), x2.flatten()]).T) ge.twoD_plot(x1.flatten(), x2.flatten(), y_pred_full, alpha=0.3, ax=AX[0])
# scale for that cell ax.plot([0, 0], [ncells-i, ncells-i+bar_fraction], color=graph.default_color) if 100.*norm_factor<1: graph.annotate(ax, '%.1f%%' % (100.*norm_factor), (0, ncells-i), xycoords='data', ha='right', size='small') else: graph.annotate(ax, '%i%%' % int(100.*norm_factor), (0, ncells-i), xycoords='data', ha='right', size='small') ax.plot([0, Tbar], [ncells+1, ncells+1], color=graph.default_color) if Tbar_label is None: Tbar_label = '%is' % Tbar graph.annotate(ax, Tbar_label, (0, ncells+1), xycoords='data', size='small') if title!='': graph.annotate(ax, title, (.5, 1.), ha='center', va='top') return fig, ax if __name__=='__main__': from datavyz import ge data = {} for i in range(30): data['cell%i' % (i+1)] = np.random.randn(1000) fig, ax = ge.figure(axes_extents=(5,5), top=0., bottom=0., right=0.5, left=0.1) ge.Ca_trace_plot(data, Tbar_label='X-s', title='Ca activity', ax=ax) ge.show()