Exemplo n.º 1
0
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()
Exemplo n.º 2
0
def plot_sim(filename, ge,
             omf_data=None,
             Umodel_data=None,
             mf_data=None):
    
    ## load file
    data = ntwk.load_dict_from_hdf5(filename)
    
    # ## plot
    fig, AX = ntwk.activity_plots(data,
                                  smooth_population_activity=10,
                                  COLORS=COLORS,
                                  pop_act_log_scale=True)

    if Umodel_data is not None:
        AX[2].plot(Umodel_data['t'],
                   Umodel_data['desired_Vm'], '-', lw=2, color='dimgrey', label='mean-field')

    if mf_data is None:

        mf = ntwk.FastMeanField(data, tstop=6., dt=2.5e-3, tau=20e-3)
        mf.build_TF_func(tf_sim_file='neural_network_dynamics/theory/tf_sim_points.npz')
        X, mVm, sVm = mf.run_single_connectivity_sim(mf.ecMatrix, verbose=True)
        t = np.linspace(0, data['tstop'], X.shape[1])
        for i, label in enumerate(data['REC_POPS']):
            AX[-1].plot(t, 1e-2+X[i,:], '--', lw=1, color=COLORS[i])
            ge.plot(t, 1e3*mVm[i,:], sy=1e3*sVm[i,:], color='k', lw=1, label='mean-field', ax=AX[2+i])
            AX[2+i].plot(t, 1e3*(mVm[i,:]-sVm[i,:]), 'k-', lw=0.5)
            AX[2+i].plot(t, 1e3*(mVm[i,:]+sVm[i,:]), 'k-', lw=0.5)
        # AX[2].plot(mf_data['t'], mf_data['desired_Vm'], 'k--', lw=2, label='U-model')
        # AX[2].legend(frameon=False, loc='best')

        
    if omf_data is None:
        try:
            omf_data = load_dict(filename.replace('ntwk.h5', 'mf.npz'))
        except FileNotFoundError:
            pass
    if omf_data is not None:
        t = np.linspace(0, data['tstop'], len(omf_data['pyrExc']))
        for i, label in enumerate(data['REC_POPS']):
            AX[-1].plot(t, 1e-2+omf_data[label], '-', lw=4, color=COLORS[i], alpha=.5)
            # AX[-1].plot(t, omf_data[label], 'k--')
        
    figM, _, _ = plot_matrix(data)
    
    ntwk.show()
Exemplo n.º 3
0
def read_file(filename):

    io = pynwb.NWBHDF5IO(filename, mode='r')
    nwbfile = io.read()

    from datavyz import ge
    #
    cond = (nwbfile.stimulus['protocol_id'].data[:] == 2)
    ge.plot(
        nwbfile.acquisition['episode_waveforms'].timestamps[:],
        nwbfile.acquisition['episode_waveforms'].data[cond, :].mean(axis=0))
    ge.show()

    cond = (nwbfile.acquisition['running-speed'].data[:] != 666)
    ge.hist(nwbfile.acquisition['running-speed'].data[:][cond])
    ge.show()

    io.close()
Exemplo n.º 4
0
        ge.annotate(ax,
                    '$\\gamma_{env}^{pyr}$', (1.1, .3),
                    color=COLORS[2],
                    ha='right',
                    size='large')

        ge.set_plot(ax,
                    ylabel='depol. (mV)',
                    xticks=[0, 5, 10, 15],
                    yticks=[0, 10, 20],
                    ylim=[-1, 22],
                    xlabel='modulatory\ninput (Hz)',
                    title='U-model of cortical states      ')
        ge.annotate(fig, 'a', (0, 1), va='top', bold=True, size='x-large')
        # ge.legend(ax)
        return fig, ax


if __name__ == '__main__':

    um = Umodel()
    from datavyz import ge

    fig, _ = um.illustration(ge)

    t = np.linspace(0, 10, 1000)
    Faff = 1.5 * t
    ge.plot(um.predict_Vm(t, Faff), fig_args={'figsize': (3, 1)})

    ge.show()
        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()


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
Exemplo n.º 7
0
        method='Nelder-Mead' # default method

    if (bounds is not None):
        res = minimize(to_minimize, coeffs,
                       method=method, bounds=bounds, options=options)
    else:
        res = minimize(to_minimize, coeffs,
                       method=method, options=options)
        
    if verbose:
        print(res)

    return res

if __name__=='__main__':


    import numpy as np
    from datavyz import ge

    def waveform(x, coeffs=[.3, .2, 2.]):
        return coeffs[2]*(np.sign(x-coeffs[0])+1.)*np.exp(-(x-coeffs[0])/coeffs[1])

    x = np.linspace(0, 1, 100)
    y = np.random.randn(100)+waveform(x, [0.5, .2, 4.])

    res = curve_fit(x, y, waveform)

    ge.plot(x, Y=[y, waveform(x, res.x)])
    ge.show()
Exemplo n.º 8
0
    parser.add_argument("--n_pulses", type=int, default=5)
    parser.add_argument("--Tdiscard0", type=float, default=200)
    parser.add_argument("--Tend", type=float, default=200)
    parser.add_argument("-NaZn", "--NalphaZn", type=int, default=30)

    parser.add_argument("-s", "--seed", help="#", type=int, default=1)

    args = parser.parse_args()

    if args.task=='demo':
    
        data = run_single_sim(Model, args)

        from datavyz import ge

        ge.plot(data['t'], 1e3*data['Ic'])

        ge.show()

    elif args.task=='run':

        Data = {'Current':[], 'alphaZn':np.linspace(0, args.alphaZnMax, args.NalphaZn)}

        for args.alphaZn in Data['alphaZn']:
            Data['Current'].append([])
            for args.syn_location in np.random.choice(np.arange(len(LOCs)), args.N_syn_location):
                data = run_single_sim(Model, args)
                print(Model['alphaZn'])
                Data['Current'][-1].append(data['Ic'])
        Data['t'] = data['t']
        np.save('data/pair_calib.npy', Data)
Exemplo n.º 9
0
import numpy as np

from datavyz import ge

fig, ax = ge.plot(Y=np.random.randn(4, 10),
                  sY=np.random.randn(4, 10),
                  xlabel='xlabel (xunit)',
                  ylabel='ylabel (yunit)',
                  title='datavyz demo plot')
ge.savefig(fig, 'docs/demo.png')
ge.show()
Exemplo n.º 10
0
#     width = box.width
#     height = box.height
#     inax_position  = ax.transAxes.transform(rect[0:2])
#     transFigure = fig.transFigure.inverted()
#     infig_position = transFigure.transform(inax_position)
#     x = infig_position[0]
#     y = infig_position[1]
#     width *= rect[2]
#     height *= rect[3]  # <= Typo was here
#     subax = fig.add_axes([x,y,width,height],facecolor=facecolor)
#     # x_labelsize = subax.get_xticklabels()[0].get_size()
#     # y_labelsize = subax.get_yticklabels()[0].get_size()
#     # x_labelsize *= rect[2]**0.5
#     # y_labelsize *= rect[3]**0.5
#     # subax.xaxis.set_tick_params(labelsize=x_labelsize)
#     # subax.yaxis.set_tick_params(labelsize=y_labelsize)
#     return subax

if __name__ == '__main__':

    from datavyz import ge

    y = np.exp(np.random.randn(100))
    fig, ax = ge.plot(y, xlabel='time', ylabel='y-value')
    sax = ge.inset(ax, [.5, .8, .5, .4])
    sax2 = ge.inset(fig, [0.1, 0.1, .3, .2])
    ge.hist(y, bins=10, ax=sax, axes_args={'spines': []}, xlabel='y-value')
    ge.hist(y, bins=10, ax=sax2, axes_args={'spines': []}, xlabel='y-value')
    ge.savefig(fig, 'docs/inset.png')
    ge.show()