Exemple #1
0
    def realign_from_photodiode(self, debug=False, verbose=True):

        if verbose:
            print(
                '---> Realigning data with respect to photodiode signal [...] '
            )

        if debug:
            from datavyz import ges as ge

        success = True

        # extract parameters
        dt = 1. / self.metadata['NIdaq-acquisition-frequency']
        tlim, tnew = [0, self.Screen.photodiode.t[-1]], 0

        t0 = self.metadata['time_start'][0]
        length = self.metadata['presentation-duration'] + self.metadata[
            'presentation-interstim-period']
        npulses = int(self.metadata['presentation-duration'])
        self.metadata['time_start_realigned'] = []
        Nepisodes = np.sum(self.metadata['time_start'] < tlim[1])
        for i in range(Nepisodes):
            cond = (self.Screen.photodiode.t >=
                    t0 - .3) & (self.Screen.photodiode.t <= t0 + length)
            try:
                tnew, integral, threshold = find_onset_time(
                    self.Screen.photodiode.t[cond] - t0,
                    self.Screen.photodiode.val[cond], npulses)
                if debug and ((i < 3) or (i > Nepisodes - 3)):
                    ge.plot(self.Screen.photodiode.t[cond],
                            self.Screen.photodiode.val[cond])
                    ge.plot(self.Screen.photodiode.t[cond],
                            Y=[integral, integral * 0 + threshold])
                    ge.show()
            except Exception:
                success = False  # one exception is enough to make it fail
            t0 += tnew
            self.metadata['time_start_realigned'].append(t0)
            t0 += length

        if verbose:
            if success:
                print('[ok]          --> succesfully realigned')
            else:
                print('[X]          --> realignement failed')
        if success:
            self.metadata['time_start_realigned'] = np.array(
                self.metadata['time_start_realigned'])
            self.metadata['time_stop_realigned'] = self.metadata['time_start_realigned']+\
                self.metadata['presentation-duration']
        else:
            self.metadata['time_start_realigned'] = np.array([])
            self.metadata['time_stop_realigned'] = np.array([])
        return success
        # ge.title(AX[i], "a=%.2f, k=%.2f, $\gamma$=%.2f" % (residual.x[0], residual.x[1], residual.x[2]), color=getattr(ge, color), size='small')
        ge.title(AX[i],
                 "k=%.2f, $\gamma$=%.2f" % (residual.x[0], residual.x[1]),
                 color=getattr(ge, color),
                 size='small')
        ge.scatter(lum,
                   array,
                   ax=AX[i],
                   color=getattr(ge, color),
                   label='data',
                   ms=3)
        ge.plot(lum,
                func(lum, residual.x),
                ax=AX[i],
                lw=3,
                alpha=.5,
                color=getattr(ge, color),
                label='fit')
        ge.annotate(AX[i],
                    '$\lambda$=%s' % LAMBDA[color], (0.5, .1),
                    color=getattr(ge, color))
        ge.set_plot(AX[i],
                    xlabel='(computer) luminosity',
                    xticks=[0, 0.5, 1],
                    yticks=[0, 0.5, 1],
                    ylabel='measured I (norm.)')

        fig.savefig('doc/gamma-correction-%s.png' % correc)
ge.show()
Exemple #3
0
        ax.plot(np.arange(10) * 10,
                np.exp(np.random.randn(10)),
                'o',
                ms=2,
                label='line' + str(i + 1))
    for i in range(2):
        ax.plot(np.arange(10) * 10,
                np.exp(np.random.randn(10)),
                '-',
                label='line' + str(i + 1))

    ge.legend(ax, ncol=2)

    ge.plot(Y=Y,
            xlabel='time',
            ylabel='y-value',
            colormap=ge.copper,
            lw=1.,
            ax=ax)

    ge.bar_legend(fig,
                  X=np.arange(5),
                  inset={'rect': [.3, .8, .3, .05]},
                  colormap=ge.copper,
                  orientation='horizontal',
                  label='Trial ID',
                  no_ticks=True)

    ge.bar_legend(fig, bounds=[1e-3, 10], scale='log', label='scale')
    ge.show()
        
        ---> to be used with the "-Debug-" button of the GUI
        """

        from datavyz import ges as ge

        args.imgfolder = os.path.join(args.datafolder, 'FaceCamera-imgs')
        args.data = np.load(os.path.join(args.datafolder, 'facemotion.npy'),
                            allow_pickle=True).item()
        load_folder(args)
        set_ROI_area(args, roi_coords=args.data['ROI'])
        DATA = load_ROI_data(args, iframe1=0, iframe2=1000)
        frames, motion = compute_motion(args,
                                        time_subsampling=1,
                                        with_ProgressBar=True)
        ge.plot(frames, motion)
        ge.show()

    else:
        if os.path.isfile(os.path.join(args.datafolder, 'facemotion.npy')):
            print('Processing face motion for "%s" [...]' %
                  os.path.join(args.datafolder, 'facemotion.npy'))
            args.imgfolder = os.path.join(args.datafolder, 'FaceCamera-imgs')

            args.data = np.load(os.path.join(args.datafolder,
                                             'facemotion.npy'),
                                allow_pickle=True).item()
            load_folder(args)

            set_ROI_area(args, roi_coords=args.data['ROI'])
            frames, motion = compute_motion(
#                         'NSYN':np.array(NSYN)})

if __name__=='__main__':

    import sys, os
    from model import Model
    from analyz.workflow.batch_run import GridSimulation
    from analyz.IO.npz import load_dict
    
    if (len(sys.argv)>1) and (sys.argv[1]=='syn-input'):
        
        index = int(sys.argv[2])
        sim = GridSimulation(os.path.join('data', 'syn-input', 'spike-threshold-grid.npz'))
        sim.update_dict_from_GRID_and_index(index, Model) # update Model parameters

        if (Model['Fexc_bg']==0) and (Model['seed']>0):
            pass
        elif (Model['qNMDA']==0) and (Model['Deltax0']>0):
            pass # no NMDA and Zinc-modulation, meaningless ...
        else:
            print('Running:', sim.params_filename(index))
            t, v = run_single_trial(Model)
            np.savez(os.path.join('data', 'syn-input', sim.params_filename(index)), **{'t':t, 'v':v})
        
    else:
        Model['Fexc_bg'] = 2.
        t, v = run_single_trial(Model)
        from datavyz import ges as ge
        ge.plot(t, v)
        ge.show()
    'V0NMDA':1./0.08,# [mV]
    'Mg_NMDA':1.,# mM
}



if sys.argv[-1]=='plot':

    from analyz.IO.npz import load_dict
    from datavyz import ges as ge
    
    data = load_dict('data.npz')

    fig, AX = ge.figure(axes=(1,3), figsize=(2.,1.))
    ge.plot(data['t'], Y=[data['Vsoma'], data['Vdend']],
            LABELS=['soma', 'dend'], COLORS=['k', ge.blue], ax=AX[0],
            axes_args={'ylabel':'Vm (mV)', 'xlim':[0, data['t'][-1]]})
    ge.plot(data['t'], Y=[data['Casoma'], data['Cadend']],
            COLORS=['k', ge.blue], ax=AX[1],
            axes_args={'ylabel':'[Ca$^{2+}$] (nM)', 'xlabel':'time (ms)', 'xlim':[0, data['t'][-1]]})
    ge.scatter(data['Espike_times'], data['Espike_IDs'], color=ge.green,ax=AX[2],no_set=True,ms=3)
    ge.scatter(data['Ispike_times'], data['Espike_IDs'].max()*1.2+data['Ispike_IDs'], color=ge.red,
               ax=AX[2], no_set=True, ms=3)
    ge.set_plot(AX[2], [], xlim=[0, data['t'][-1]])
    fig.savefig('/home/yann/Desktop/trace.svg')
    ge.show()

else:
    
    nrn.defaultclock.dt = 0.025*nrn.ms
Exemple #7
0
    
    return pca

if __name__=='__main__':

    from sklearn.datasets import load_breast_cancer

    from datavyz import ges

    raw, data = load_breast_cancer(), {}
    for i, key in enumerate(raw['feature_names']):
        data[key] = np.log10(raw['data'][i])

    ges.features_plot(data, features=list(data.keys())[:6])
    ges.cross_correl_plot(data, features=list(data.keys())[:6])
    
    pca = PCA(data, n_components = len(data)) # desired_var_explained=0.9)
    
    ges.plot(100.*pca.explained_variance_ratio_,
              m='o', ms=4, xlabel='component #', ylabel='% var. expl.')

    ges.parallel_plot(pca.components_,
                      fig_args=dict(figsize=(3,1)))

    ges.show()

    

    
        
Exemple #8
0
        # recording and running
        if active:
            M = ntwk.StateMonitor(neuron, ('v', 'InternalCalcium'), record=[0, synapses_loc[0]])
        else:
            M = ntwk.StateMonitor(neuron, ('v'), record=[0, synapses_loc[0]])
            S = ntwk.StateMonitor(ES, ('X', 'gAMPA', 'gE_post', 'bZn'), record=[0])

        # # Run simulation
        print('running simulation [...]')
        ntwk.run(tstop*ntwk.ms)

        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()


    else:
        pass
    
    mf = FastMeanField(Model, tstop=6., dt=1e-2, tau=5e-2)

    if sys.argv[-1]=='sim':
        print('building the TF sim. (based on the COEFFS)')
        mf.simulate_TF_func(300,
                            coeffs_location='../configs/Network_Modulation_2020/COEFFS_pyrExc.npy',
                            tf_sim_file='tf_sim_points.npz',
                            Iinj_lim=[0, 200.], # in pA
                            Exc_lim=[0.01,50000],
                            Inh_lim=[0.01,50000],
                            with_Vm_functions=True,
                            sampling='log')

        
    mf.build_TF_func(tf_sim_file='tf_sim_points.npz')
    X, mVm, sVm = mf.run_single_connectivity_sim(mf.ecMatrix, verbose=True)

    from datavyz import ges as ge
    fig, AX = ge.figure(figsize=(3,1), axes=(1,5))
    COLORS=[ge.g, ge.b, ge.r, ge.purple]
    for i, label in enumerate(Model['REC_POPS']):
        AX[-1].plot(1e3*mf.t, 1e-2+X[i,:], lw=4, color=COLORS[i], alpha=.5)
        
        ge.plot(1e3*mf.t, 1e3*mVm[i,:], sy=1e3*sVm[i,:], ax=AX[i], color='k')
        AX[i].set_ylim([-72,-45])
        
    
    ge.show()
    # # benchmark