def show_residuals_over_trials(self, graph=None, ax=None, threshold=100):

        if graph is None:
            from datavyz import ges as graph
        if ax is None:
            # fig, ax = graph.figure(axes=(1,3), wspace=.2,
            #                        left=.7, bottom=.7, figsize=(.7,1.))
            fig, ax = graph.figure(left=.7, bottom=.7, figsize=(.7,1.))
        else:
            fig = None

        result = self.result
        if self.new_result is not None:
            RESULTS = [self.result, self.new_result]
        else:
            RESULTS = [self.result]
        for res in RESULTS:
            indices = np.argsort(res['residuals'])
            x = res['residuals'][indices]
            full_x = np.concatenate([np.arange(1, len(indices)+1)[x<=threshold],
                                     [len(indices)+1, res['Ntot']]])
            full_y = np.concatenate([x[x<=threshold], [threshold, threshold]])
            ax.plot(np.log10(full_x), np.log10(full_y), clip_on=False)

        graph.set_plot(ax,
                       # yticks=np.log10([1, 2, 5, 10, 20]),
                       # yticks_labels=['1', '2', '5', '10', '>20'],
                       # yminor_ticks=np.log10([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20]),
                       # ylim=[1, np.log10(threshold)],
                       xminor_ticks=np.log10(np.concatenate([[i*10**k for i in range(1,10)]\
                                                             for k in range(0,7)])),
                       xlim=[np.log10(result['Ntot']), -1.],
                       xticks=np.arange(7),
                       xticks_labels=['1','','','$10^3$','','','$10^6$'],
                       xlabel='config #',
                       ylabel=r'fit $\chi^2$ (norm.)       ', ylabelpad=-7)
        graph.annotate(ax, '4 pop. model', (.4, 1.2), ha='center')

        return fig, ax
        'green': ga,
        'red': ra,
        'blue': ba
    }
}

lum = np.linspace(0, 1, len(gb))


def func(lum, coefs):
    # return coefs[0]+coefs[1]*lum**coefs[2]
    return coefs[0] * lum**coefs[1]


for correc in ['before', 'after']:
    fig, AX = ge.figure(axes=(3, 1))
    for i, color in enumerate(['blue', 'green', 'red']):

        array = calib[correc][color]
        array = (array - np.min(array)) / (np.max(array) - np.min(array))

        def to_minimize(coefs):
            return np.sum(np.abs(array - func(lum, coefs))**2)

        residual = minimize(to_minimize, [1, 1], bounds=[(0.5, 2), (0.1, 3.)])

        print('For %s and %s, gamma=' % (correc, color), residual.x[1])

        # 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]),
示例#3
0
    from neural_network_dynamics import main as ntwk  # based on Brian2

    if (args.filename == '') and (args.directory == ''):
        print("""
        please provide as arguments either a filename of a morphology or a directory containing some
        FOR EXAMPLE:
        python nrn_morpho.py --filename ./neural_network_dynamics/single_cell_integration/morphologies/Jiang_et_al_2015/L5pyr-j140408b.CNG.swc
        OR:
        python nrn_morpho.py --directory ./neural_network_dynamics/single_cell_integration/morphologies/Jiang_et_al_2015/
        """)
    elif args.directory != '':
        file_list = [
            fn for fn in os.listdir(args.directory) if fn.endswith('.swc')
        ]

        fig, AX = ge.figure(figsize=(.6, .6),
                            axes=(int(len(file_list) / 8) + 1, 8))

        n = 0
        for fn, ax in zip(file_list, ge.flat(AX)):
            morpho = ntwk.Morphology.from_swc_file(
                os.path.join(args.directory, fn))
            SEGMENTS = ntwk.morpho_analysis.compute_segments(morpho)
            colors = [
                ge.green if comp_type == 'axon' else ge.red
                for comp_type in SEGMENTS['comp_type']
            ]
            plot_nrn_shape(ge, SEGMENTS, colors=colors, ax=ax)
            ge.title(ax, fn.split('-')[0], bold=True, style='italic', size='')
            n += 1
        while n < len(ge.flat(AX)):
            ge.flat(AX)[n].axis('off')
示例#4
0
#                ncol=ncol,
#                # numpoints=1,
#                # scatterpoints=1,
#                columnspacing=columnspacing,
#                handletextpad=handletextpad,
#                handlelength=handlelength,
#                title=title,
#                fontsize=fontsize)

if __name__ == '__main__':

    from datavyz import ges as ge

    Y = [np.exp(np.random.randn(100)) for i in range(4)]

    fig, ax = ge.figure(right=5.)  # with extended right space

    for i in range(2):
        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)
示例#5
0
            os.path.join(args.imgfolder, args.FILES[0])),
                                k=3)
        init_fit_area(args,
                      ellipse=args.data['ROIellipse'],
                      reflectors=(args.data['reflectors']
                                  if 'reflectors' in args.data else None))

        args.cframe = 10000

        preprocess(args, with_reinit=False)

        fit = perform_fit(args,
                          saturation=args.data['ROIsaturation'],
                          verbose=True,
                          N_iterations=0)[0]
        fig, ax = ge.figure(figsize=(1.4, 2), left=0, bottom=0, right=0, top=0)
        ax.plot(*ellipse_coords(*fit), 'r')
        ax.plot([fit[0]], [fit[1]], 'ro')
        ge.image(args.img_fit, ax=ax)
        ge.show()

        fit = perform_fit(args,
                          saturation=args.data['ROIsaturation'],
                          verbose=True,
                          N_iterations=8,
                          do_xy=True)[0]
        fig, ax = ge.figure(figsize=(1.4, 2), left=0, bottom=0, right=0, top=0)
        ax.plot(*ellipse_coords(*fit), 'r')
        ax.plot([fit[0]], [fit[1]], 'ro')
        ax.plot(*args.xy.T, 'r')
        ge.image(args.img_fit, ax=ax)
示例#6
0
        loc_syn0 = LOCs[1]
    except BaseException:
        pass
    NSYNs = [2, 4, 6, 8, 10, 12, 14]

    if sys.argv[-1] == 'syn-demo':

        from datavyz import nrnvyz, ges as ge

        _, neuron, SEGMENTS = initialize_sim(Model)
        vis = nrnvyz(SEGMENTS, ge=ge)

        fig, AX = ge.figure(axes=(len(NSYNs), 1),
                            figsize=(.8, 1.2),
                            wspace=0,
                            left=0,
                            top=0.3,
                            bottom=0,
                            right=0)
        for nsyn, ax in zip(NSYNs, AX):
            ge.title(ax, '$N_{syn}$=%i' % nsyn, size='xx-small')
            vis.plot_segments(SEGMENTS['comp_type'] != 'axon',
                              bar_scale_args=dict(Ybar=50,
                                                  Xbar_label='50um',
                                                  Xbar=50,
                                                  Ybar_label='',
                                                  loc='top-right',
                                                  xyLoc=(-110, 90),
                                                  size='xx-small'),
                              ax=ax)
            vis.add_dots(ax, loc_syn0 + np.arange(nsyn), 10, ge.orange)
示例#7
0
            viridis, viridis_r, copper, copper_r, cool, jet, PiYG, binary,
            binary_r, bone, Pastel1, Pastel2, Paired, Accent, Dark2, Set1,
            Set2, Set3, tab10, tab20, tab20b, tab20c
    ]:
        setattr(cls, color.name, color)
        cls.cmaps.append(color)

    # then some linear colormaps
    for (c1, c2) in zip(
        ['blue', 'red', 'blue', 'green', 'red', 'green', 'orange'],
        ['red', 'blue', 'orange', 'red', 'green', 'orange', 'green']):
        setattr(cls, '%s_to_%s' % (c1, c2),
                get_linear_colormap(getattr(cls, c1), getattr(cls, c2)))

    cls.get_linear_colormap = get_linear_colormap


if __name__ == '__main__':

    import numpy as np
    from datavyz import ges as ge

    colors = ['tab:blue', 'tab:red']
    fig, ax = ge.figure()
    for i, c in enumerate(ge.colors[:3]):
        ge.scatter([i], [i], color=c, ax=ax, no_set=True)
    fig, ax = ge.figure()
    for i, x in enumerate(np.linspace(0, 1, 50)):
        ax.scatter([i], [x], color=ge.get_linear_colormap(ge.blue, ge.red)(x))
    ge.show()
    'cMg': 1., # mM
    'etaMg': 0.33, # 1/mM
    '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:
    
示例#9
0
    return data


if __name__ == '__main__':

    import sys
    if len(sys.argv) > 1:
        fn = sys.argv[1]
    else:
        fn = '/home/yann/DATA/2020_09_11/13-40-10/pupil-data.npy'

    from datavyz import ges as ge

    data = np.load(fn, allow_pickle=True).item()

    fig, AX = ge.figure(axes=(1, 6), figsize=(3, 1), hspace=0.1)

    for i, key in enumerate(['cx', 'cy', 'sx', 'sy', 'residual']):
        AX[i].plot(data['times'], data[key], label='fit')

    data = replace_outliers(data)

    for i, key in enumerate(['cx', 'cy', 'sx', 'sy', 'residual']):
        AX[i].plot(data['times'], data[key + '-corrected'], label='corrected')
        ge.set_plot(AX[i],
                    xlim=[data['times'][0], data['times'][-1]],
                    ylabel=key)

    ge.show()
示例#10
0
                                                               ON_EXC_EVENT.format(**Model))


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

示例#11
0
                                                   top=0,
                                                   right=0))
        vis.add_dots(ax, PROX, 50, ge.orange)
        vis.add_dots(ax, DIST, 50, ge.orange)
        ge.show()

    elif args.protocol == 'syn-number':

        tstop, t0_stim = 300, 20
        if args.plot:
            data = load_dict(
                os.path.join('data', 'branco-syn-number-%s.npz' % suffix))

            fig, AX = ge.figure(axes=(1, 2),
                                figsize=(.7, 1),
                                right=4.,
                                hspace=0.1,
                                bottom=0.1)
            ge.title(AX[0],
                     '%i to %i synapses (by 2)' % (N_PULSES[0], N_PULSES[-1]))
            for synapses_loc, label, ax in zip([PROX, DIST], ['prox', 'dist'],
                                               AX):
                for i in range(len(data['v-%s' % label])):
                    ax.plot(data['t'],
                            data['v-%s' % label][i],
                            label=label,
                            color='k',
                            lw=1)

                ge.set_plot(ax, [], ylim=[-76, -45], xlim=[0, tstop])
                ge.draw_bar_scales(ax,
示例#12
0
文件: main.py 项目: yzerlaut/datavyz
    #               axes_args={'spines':['left', 'bottom'], 'xlabel':'my-x value', 'ylabel':'my-y value'})
    # save_on_desktop(fig, figname='2.svg')
    # show()

    # mg = graphs('ggplot_npotebook')
    # mg = graphs()
    # mg.hist(np.random.randn(100), xlabel='ksjdfh')

    from datavyz import ges as ge

    # ge.boxplot(np.exp(np.random.randn(100)),
    #            axes_args=dict(xticks=[1],
    #                           xticks_labels=['data']))

    fig_lf, AX = ge.figure(axes_extents=[[[3, 1]], [[1, 2], [1, 2], [1, 2]]],
                           figsize=(1., .5),
                           wspace=3.,
                           hspace=2.)
    for ax in [item for sublist in AX for item in sublist]:
        ge.top_left_letter(ax, 'a')
    # _, ax, _ = ge.figure(with_bar_legend=True)
    AX[1][0].hist(np.random.randn(100))
    fig, ax = ge.figure()
    ax.hist(np.random.randn(100))
    ge.panel_label(ax, 'a')
    ge.annotate(ax, 'blabla', (0.7, 0.8), italic=True)
    ge.set_plot(ax)
    ge.show()

    ge.show()
示例#13
0
    
    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