Beispiel #1
0
def full_analysis(args):

    DATA = get_dataset()
    VC, ECR, TAU2, TAU1, SEXT, DUR = [], [], [], [], [], []
    for i in range(len(DATA)):
        try:
            X = np.load('../ring_model/data/fitted_data_' + str(i) + '.npy')
            for vec, VEC in zip(X, [VC, ECR, TAU2, TAU1, SEXT]):
                VEC.append(vec)
            DUR.append(DATA[i]['duration'])
        except IOError:
            pass

    fig, AX = plt.subplots(1, 4, figsize=(6., 2.3))
    plt.subplots_adjust(bottom=.3, left=.25, wspace=3.)
    for ax, vec, label, ylim in zip(
            AX, [VC, ECR, np.array(ECR) / 5., SEXT],
        ['$v_c$ (mm/s)', '$l_{exc}$ (mm)', '$l_{inh}$ (mm)', '$s_{ext}$ (mm)'],
        [[0, 500], [0, 6], [0, 6], [0, 4]]):
        ax.plot([0, 0], ylim, 'w.', ms=0.1)
        ax.bar([0], [np.array(vec).mean()],
               yerr=[np.array(vec).std()],
               color='lightgray',
               edgecolor='k',
               lw=3)
        set_plot(ax, ['left'], xticks=[], ylabel=label)

    fig2, AX = plt.subplots(1, 2, figsize=(3.2, 2.3))
    plt.subplots_adjust(bottom=.3, left=.3, wspace=1.8)
    AX[0].plot(DUR, 1e3 * np.array(TAU1), 'o')
    AX[0].plot(DUR, 1e3 * np.array(TAU2), 'o')
    plt.show()
Beispiel #2
0
def get_residual(args,
                 new_time,
                 space,
                 new_data,
                 Nsmooth=2,
                 fn='../ring_model/data/example_data.npy',
                 model_normalization_factor=None,
                 with_plot=False):

    new_time, space,\
        model_data_common_sampling,\
        exp_data_common_sampling =\
                reformat_model_data_for_comparison(fn,
                    new_time, space, new_data,
                    model_normalization_factor=model_normalization_factor,
                    with_global_normalization=True)

    if with_plot:

        fig, AX = plt.subplots(2, figsize=(4.5, 5))
        plt.subplots_adjust(bottom=.23, top=.97, right=.85, left=.3)
        plt.axes(AX[0])
        c = AX[0].contourf(new_time,
                           space,
                           exp_data_common_sampling,
                           np.linspace(exp_data_common_sampling.min(),
                                       exp_data_common_sampling.max(),
                                       args.Nlevels),
                           cmap=cm.viridis)
        plt.colorbar(c, label='norm. VSD', ticks=.5 * np.arange(3))
        set_plot(AX[0], xticks_labels=[], ylabel='space (mm)')
        plt.axes(AX[1])

        # to have the zero at the same color level
        factor = np.abs(exp_data_common_sampling.min() /
                        exp_data_common_sampling.max())
        model_data_common_sampling[
            -1, -1] = -factor * model_data_common_sampling.max()

        c2 = AX[1].contourf(new_time,
                            space,
                            model_data_common_sampling,
                            np.linspace(model_data_common_sampling.min(),
                                        model_data_common_sampling.max(),
                                        args.Nlevels),
                            cmap=cm.viridis)

        plt.colorbar(c2, label='norm. $\\delta V_N$', ticks=.5 * np.arange(3))
        set_plot(AX[1], xlabel='time (ms)', ylabel='space (mm)')

        if args.save:
            fig.savefig('/Users/yzerlaut/Desktop/temp.svg')
        else:
            show()

    return np.sum((exp_data_common_sampling - model_data_common_sampling)**2)
    def make_row_fig(cond, AX, with_top_label=False, fd=0):
        F1, Fe, Fi = data[col_key][cond], data[xkey][cond], data[ckey][cond]
        mFout, sFout = Fout_mean[cond], Fout_std[cond]
        for i, f1 in enumerate(np.unique(F1)[col_subsmpl]):
            i0 = np.argwhere(F1==f1).flatten()
            for j, fi in enumerate(np.unique(Fi[i0])):
                i1 = np.argwhere((Fi[i0]==fi)).flatten()
                cond2 =  (mFout[i0][i1]>=ylim[0]) & (mFout[i0][i1]<ylim[1])
                AX[i].errorbar(Fe[i0][i1][cond2],
                               Fout_mean[i0][i1][cond2],
                               yerr=Fout_std[i0][i1][cond2],
                               fmt='o', ms=4,
                               color=cmap(j/len(np.unique(Fi[i0]))))
                # # now analytical estimate
                if with_theory:
                    RATES = {xkey:np.concatenate([np.linspace(f1, f2, th_discret, endpoint=False)\
                                                       for f1, f2 in zip(Fe[i0][i1][:-1], Fe[i0][i1][1:])])}
                    for pop, f in zip([col_key, ckey, row_key],[f1, fi, fd]) :
                        RATES[pop] = f*np.ones(len(RATES[xkey]))
                    Fout_th = TF(RATES, data['Model'], data['Model']['NRN_KEY'])
                    th_cond = (Fout_th>ylim[0]) & (Fout_th<ylim[1])
                    AX[i].plot(RATES[xkey][th_cond],
                               Fout_th[th_cond], '-',
                               color=cmap(j/len(np.unique(Fi[i0]))), lw=5, alpha=.7)
            if with_top_label:
                AX[i].set_title(col_key_label+'='+str(round(f1,1))+col_key_unit)
            if logscale:
                AX[i].set_yscale('log')
                AX[i].set_xscale('log')
            ylabel2, yticks_labels2 = '', []
            if i==0: # if first column
                ylabel2, yticks_labels2 = ylabel, yticks_labels
            set_plot(AX[i], ylim=[.9*ylim[0], ylim[1]],
                     yticks=yticks, xticks=xticks, ylabel=ylabel2, xlabel=xlabel,
                     yticks_labels=yticks_labels2, xticks_labels=xticks_labels)

        Fi_log = np.log(Fi)/np.log(10)
        cax = inset_axes(AX[-1], width="20%", height="90%", loc=3)
        Fi_ticks, Fi_ticks_labels = [], []
        for k in np.arange(-2, 3):
            for l in range(1, 10):
                Fi_ticks.append(np.log(l)/np.log(10) +k)
                if l%10==1:
                    Fi_ticks_labels.append(str(l*np.exp(k*np.log(10))))
                else:
                    Fi_ticks_labels.append('')
        # Fi_ticks, Fi_ticks_labels = np.arange(-2,2), ['0.01','0.1','1', '10']
        cb = build_bar_legend(Fi_ticks, cax , cmap,
                              bounds = [np.log(Fi.min())/np.log(10),
                                        np.log(Fi.max())/np.log(10)],
                              ticks_labels=Fi_ticks_labels,
                              color_discretization=100,
                              label=ckey_label)
        AX[-1].axis('off')
Beispiel #4
0
def make_second_fig():
    DISTANCE, ERROR = find_minimum_with_distance()
    bins = np.logspace(np.log(ERROR.min())/np.log(10),np.log(ERROR.max())/np.log(10),10)
    hist, be = np.histogram(ERROR, bins=bins)
    
    from graphs.my_graph import set_plot
    fig, AX = plt.subplots(1, figsize=(5,4))
    plt.subplots_adjust(bottom=.3, left=.2)
    AX.bar(be[:-1], hist, width=np.diff(bins), edgecolor='k', color='lightgray', lw=2)
    AX.set_xscale('log')
    set_plot(AX, xticks=np.logspace(-2,1,4), xlabel='goodness to fit', ylabel='morphology number')
    return fig
Beispiel #5
0
def plot_response(args):

    fig, ax = plt.subplots(1, figsize=(4.7, 3))
    fig.suptitle(get_dataset()[args.data_index]['filename'])
    plt.subplots_adjust(bottom=.23, top=.9, right=.84, left=.25)

    print(get_dataset()[args.data_index])
    f = loadmat(get_dataset()[args.data_index]['filename'])
    data = 1e3 * f['matNL'][0]['stim1'][0]
    time = f['matNL'][0]['time'][0].flatten() + args.tshift
    print(time[-1] - time[0])
    space = f['matNL'][0]['space'][0].flatten()
    if args.Nsmooth > 0:
        smoothing = np.ones((args.Nsmooth, args.Nsmooth)) / args.Nsmooth**2
        smooth_data = convolve2d(data, smoothing, mode='same')
    else:
        smooth_data = data

    cond = (time > args.t0) & (time < args.t1)
    c = ax.contourf(time[cond], space, smooth_data[:,cond],\
             np.linspace(smooth_data.min(), smooth_data.max(), args.Nlevels), cmap=cm.viridis)
    plt.colorbar(c, label='VSD signal ($\perthousand$)', ticks=args.vsd_ticks)

    x1, x2 = ax.get_xlim()
    ax.plot([x1, x1], [0, 2], '-', color='gray', lw=4)
    ax.annotate('2mm', (x1, 2), rotation=90, fontsize=14)
    y1, y2 = ax.get_ylim()
    ax.plot([x1, x1 + 50], [y1, y1], '-', color='gray', lw=4)
    ax.annotate('50ms', (x1 + 20, y1 + .5), fontsize=14)

    if args.with_onset_propag:
        tt, xx = find_latencies_over_space_simple(time, space,
                                         smooth_data[:,cond],
                                         signal_criteria=args.signal_criteria,\
                                         amp_criteria=args.amp_criteria)
        plt.plot(tt + args.tshift, xx, 'o', lw=0, ms=1, color='k')

        # for intervals in [[0,2.3], [2.5,5.7], [5.9,8.5]]:
        #     cond = (xx>intervals[0]) & (xx<intervals[1]) & (tt<20)
        #     pol = np.polyfit(xx[cond], tt[cond]+100, 1)
        #     xxx = np.linspace(xx[cond][0], xx[cond][-1])
        #     plt.plot(np.polyval(pol, xxx), xxx, 'w--', lw=2)

    # set_plot(ax, ['bottom'], yticks=[], xlabel='time (ms)')
    set_plot(ax, xlabel='time (ms)', ylabel='space (mm)')
    if args.SAVE:
        fig.savefig('/Users/yzerlaut/Desktop/temp.svg')
    else:
        show()
def fig_with_average_trace(t_window, TEST_TRACES, CTRL_TRACES, delay, duration,\
                           threshold=-30, color='r'):
    # then fig with averages
    fig, ax = plt.subplots(1, figsize=(5, 3.5))
    ax.set_title('delay='+str(delay)+'ms, duration='+str(duration)+'ms, n='+\
                 str(len(TEST_TRACES))+' trials',fontsize=12)
    plt.subplots_adjust(left=.2, bottom=.25)
    CTRL_TRACES = np.array(CTRL_TRACES)
    CTRL_TRACES[CTRL_TRACES > threshold] = threshold
    TEST_TRACES = np.array(TEST_TRACES)
    TEST_TRACES[TEST_TRACES > threshold] = threshold
    ax.plot(t_window,
            CTRL_TRACES.mean(axis=0),
            'k',
            lw=2,
            label='blank trials')
    ax.fill_between(t_window,\
                    CTRL_TRACES.mean(axis=0)-CTRL_TRACES.std(axis=0),\
                    CTRL_TRACES.mean(axis=0)+CTRL_TRACES.std(axis=0),
                    color='lightgray')
    ax.plot(t_window,\
                    CTRL_TRACES.mean(axis=0)-CTRL_TRACES.std(axis=0),\
                    color='k', lw=.5)
    ax.plot(t_window,\
                    CTRL_TRACES.mean(axis=0)+CTRL_TRACES.std(axis=0),
                    color='k', lw=.5)
    ax.plot(t_window,
            TEST_TRACES.mean(axis=0),
            color,
            lw=2,
            label='test trials')
    ax.plot(t_window,\
            TEST_TRACES.mean(axis=0)+TEST_TRACES.std(axis=0),
            color=color, lw=.5)
    ax.plot(t_window,\
            TEST_TRACES.mean(axis=0)-TEST_TRACES.std(axis=0),\
            color=color, lw=.5)
    ax.fill_between(t_window,\
                    TEST_TRACES.mean(axis=0)-TEST_TRACES.std(axis=0),\
                    TEST_TRACES.mean(axis=0)+TEST_TRACES.std(axis=0),
                    color=color, alpha=.3)
    ax.legend(prop={'size': 'small'}, loc='best', frameon=False)
    set_plot(ax, ylabel='$V_m$ (mV)', xlabel='delay from state onset (ms)')
    ax.fill_between([delay, delay+duration],\
                    ax.get_ylim()[0]*np.ones(2), ax.get_ylim()[1]*np.ones(2),\
                    color=color, alpha=.2)
    return fig
Beispiel #7
0
def make_experimental_fig(index):
    
    fig, AX = plt.subplots(1, 2, figsize=(11,4))
    plt.subplots_adjust(bottom=.2)
    all_freq, all_psd, all_phase = np.load('full_data.npy')

    mymap = get_linear_colormap()
    X = 300+np.arange(3)*300

    HIGH_BOUND = 450 # higher nound for frequency
    f_bins = np.logspace(np.log(.1)/np.log(10), np.log(HIGH_BOUND)/np.log(10), 20)
    digitized = np.digitize(all_freq, f_bins)
    psd_means = np.array([all_psd[digitized == i].mean() for i in range(1, len(f_bins))])
    psd_std = np.array([all_psd[digitized == i].std() for i in range(1, len(f_bins))])
    phase_means = np.array([all_phase[digitized == i].mean() for i in range(1, len(f_bins))])
    phase_std = np.array([all_phase[digitized == i].std() for i in range(1, len(f_bins))])
    AX[0].errorbar(.5*(f_bins[1:]+f_bins[:-1]), psd_means, yerr=psd_std, color='gray', lw=3, label='data')
    AX[0].fill_between(.5*(f_bins[1:]+f_bins[:-1]), psd_means-psd_std, psd_means+psd_std, color='lightgray')
    AX[1].errorbar(.5*(f_bins[1:]+f_bins[:-1]), phase_means, yerr=phase_std, color='gray', lw=3, label='data')
    AX[1].fill_between(.5*(f_bins[1:]+f_bins[:-1]), phase_means-phase_std, phase_means+phase_std, color='lightgray')

    ### MEAN MODEL
    j=0
    for b, ls, ld, dd, g_pas, cm, ra in itertools.product(B, L_soma, L_dend, D_dend, G_PAS, CM, RA):
        if j==index:
            soma1, stick1, params1 = soma.copy(), stick.copy(), params.copy()
            soma1['L'] = ls
            stick1['B'], stick1['D'], stick1['L'] = b, dd, ld
            params1['g_pas'], params1['cm'], params1['Ra'] = g_pas, cm, ra
            psd, phase = get_input_imped(soma1, stick1, params1)
            fig.suptitle('B='+str(b)+', Ls='+str(1e6*ls)+'um, Ld='+str(1e6*ld)+'um, Dd='+\
                         str(1e6*dd)+'um, Gl='+str(1e2*g_pas)+'uS/cm2, Cm='+str(1e2*cm)+'uF/cm2, Ri='+str(1e2*ra)+'Ohm.m')
        j+=1

    AX[0].loglog(f, psd, 'k-', alpha=.8, lw=4)
    AX[1].semilogx(f, phase, 'k-', alpha=.8, lw=4, label='medium size \n   model')
    
    set_plot(AX[0], xlim=[.08,1000],\
                   xticks=[1,10,100,1000], yticks=[10,100,1000],yticks_labels=['10','100','1000'],\
                      xlabel='frequency (Hz)',ylabel='modulus ($\mathrm{M}\Omega$)')

    set_plot(AX[1], xlim=[.08,1000], ylim=[-.2,2.3],\
                   xticks=[1,10,100,1000], yticks=[0,np.pi/4.,np.pi/2.],\
                   yticks_labels=[0,'$\pi/4$', '$\pi/2$'],
             xlabel='frequency (Hz)', ylabel='phase shift (Rd)')

    return fig
def RASTER_PLOT(SPK_LIST,
                ID_LIST,
                tlim=None,
                ID_ZOOM_LIST=None,
                COLORS=None,
                with_fig=None,
                MS=1):

    if with_fig is not None:
        fig, ax = plt.gcf(), plt.gca()
    else:
        fig, ax = plt.subplots(1, figsize=(5, 3))
        plt.subplots_adjust(left=.25, bottom=.25)

    # time limit
    if tlim is None:
        tlim = np.ones(2)
        tlim[0] = np.min([np.min(spk) for spk in SPK_LIST])
        tlim[1] = np.max([np.max(spk) for spk in SPK_LIST])
    # neurons limit
    if ID_ZOOM_LIST is None:
        ID_ZOOM_LIST = []
        for ids in ID_LIST:
            ID_ZOOM_LIST.append([np.min(ids), np.max(ids)])
    # colors
    if COLORS is None:
        COLORS = ['g'] + ['r'] + ['k' for i in range(len(ID_LIST) - 2)]

    ii = 0  # index for plotting
    for spks, ids, id_zoom, col in zip(SPK_LIST, ID_LIST, ID_ZOOM_LIST,
                                       COLORS):
        spks2, ids2 = spks[(spks >= tlim[0]) & (spks <= tlim[1]) &
                           (ids >= id_zoom[0]) &
                           (ids <= id_zoom[1])], ids[(spks >= tlim[0])
                                                     & (spks <= tlim[1]) &
                                                     (ids >= id_zoom[0]) &
                                                     (ids <= id_zoom[1])]
        plt.plot(spks2, ii + ids2, '.', color=col, ms=MS)
        ii += id_zoom[1] - id_zoom[0]
    tot_neurons_num = int(
        round(np.sum([(I[1] - I[0]) for I in ID_ZOOM_LIST]) / 100., 0) * 100)
    ax.set_title(str(tot_neurons_num) + ' neurons sample', fontsize=14)
    my_graph.set_plot(ax, xlabel='time (ms)', yticks=[], ylabel='neuron index')
    return fig, ax
Beispiel #9
0
def plot_VC_episodes(main):
    t, VEC = BIN_load(main.filename, zoom=[main.args['x1'], main.args['x2']])
    y1, y2 = main.args['y1_min'], main.args['y1_max']
    fig = plt.figure(figsize=(10, 7))
    plt.subplots_adjust(left=.15, bottom=.15, top=.96, right=.96)
    ax = plt.subplot2grid((3, 1), (0, 0), rowspan=2)
    mymap = get_linear_colormap(color1='blue', color2='red')
    for i in range(VEC.shape[1]):
        ax.plot(1e3*t, VEC[0][i], '-',\
                color=mymap(np.linspace(0,1,VEC.shape[1])[i],1))
    set_plot(ax, ['left'], ylabel='$I_{amp}$ (pA)',\
             xlim=[main.args['x1'], main.args['x2']], xticks=[],\
             ylim=[y1, y2])
    ax2 = plt.subplot2grid((3, 1), (2, 0))
    for i in range(VEC.shape[1]):
        ax2.plot(1e3*t, VEC[1][i], '-', alpha=.5,\
                color=mymap(np.linspace(0,1,VEC.shape[1])[i],1))
    set_plot(ax2, xlabel='time (ms)', ylabel='$V_A$ (mV)',\
             xlim=[main.args['x1'], main.args['x2']])
    return [fig]
def fig_with_sample_traces(t_window, TEST_TRACES, CTRL_TRACES, delay, duration,\
                           threshold=-30, color='r', N=10):

    # then fig with all traces
    fig, ax = plt.subplots(1, figsize=(5, 3.5))
    ax.set_title('delay='+str(delay)+'ms, duration='+str(duration)+'ms, n='+\
                 str(len(TEST_TRACES))+' trials',fontsize=12)
    plt.subplots_adjust(left=.2, bottom=.25)
    for v in CTRL_TRACES[:N]:
        ax.plot(t_window, v, 'k', lw=.5)
    ax.plot(t_window, CTRL_TRACES[-1], 'k',\
            label='blank trials', lw=.5)
    for v in TEST_TRACES[:N]:
        plt.plot(t_window, v, color, lw=.5)
    ax.plot(t_window, TEST_TRACES[-1], color,\
            label='test trials', lw=.5)
    ax.legend(prop={'size': 'x-small'}, loc='best', frameon=False)
    set_plot(ax, ylabel='$V_m$ (mV)', xlabel='delay from state onset (ms)')
    ax.fill_between([delay, delay+duration],\
                    ax.get_ylim()[0]*np.ones(2), ax.get_ylim()[1]*np.ones(2),\
                    color=color, alpha=.2)
    return fig
Beispiel #11
0
def make_first_fig():
    DISTANCE, ERROR = find_minimum_with_distance()
    N = 40
    bins_positive = np.logspace(-9,np.log(DISTANCE.max())/np.log(10),N)
    bins_negative = np.logspace(-9,np.log(-DISTANCE.min())/np.log(10),N)
    i_positive = np.digitize(DISTANCE[DISTANCE>0], bins_positive)
    i_negative = np.digitize(-DISTANCE[DISTANCE<0], bins_negative)

    x_plus, val_plus, val_min = [], [], []
    x_min, val_plus_std, val_min_std = [], [], []
    for i in range(N):
        if len(ERROR[DISTANCE>0][i_positive==i])>0:
            val_plus.append(np.mean(ERROR[DISTANCE>0][i_positive==i]))
            val_plus_std.append(np.std(ERROR[DISTANCE>0][i_positive==i]))
            x_plus.append(bins_positive[i])
        if len(ERROR[DISTANCE>0][i_positive==i])>0:
            val_min.append(np.mean(ERROR[DISTANCE<0][i_negative==i]))
            val_min_std.append(np.std(ERROR[DISTANCE<0][i_negative==i]))
            x_min.append(bins_negative[i])

    sys.path.append('../../')
    from graphs.my_graph import set_plot
    fig, AX = plt.subplots(1,2, figsize=(10,4))
    AX[1].plot([DISTANCE[DISTANCE>0].min(),DISTANCE.max()],\
               [ERROR.min(),ERROR.min()], '-', color='lightgray', lw=5)
    AX[1].plot(DISTANCE[DISTANCE>0], ERROR[DISTANCE>0], 'k.', alpha=.05)
    AX[1].errorbar(x_plus, val_plus, yerr=val_plus_std, color='k', lw=3)
    AX[1].set_xscale('log');AX[1].set_yscale('log')
    set_plot(AX[1], yticks=np.logspace(-2,0,3), xticks=np.logspace(-2,0,3), ylabel='error (log)')
    
    AX[0].plot([DISTANCE[DISTANCE>0].min(),DISTANCE.max()],\
               [ERROR.min(),ERROR.min()], '-', color='lightgray', lw=5)
    AX[0].plot(-DISTANCE[DISTANCE<0], ERROR[DISTANCE<0], 'k.', alpha=.05)
    AX[0].errorbar(x_min, val_min, yerr=val_min_std, color='k', lw=3)
    AX[0].set_xscale('log');AX[0].set_yscale('log')
    set_plot(AX[0], yticks=np.logspace(-2,0,3), xticks=np.logspace(-2,0,3), ylabel='error (log)')

    return fig
Beispiel #12
0
def default_plot(main, xlabel='time (s)', ylabel=''):
    
    Nchannels = min([main.params['Nchannels'], 4]) # max 4 channels displayed
    
    fig, AX = plt.subplots(Nchannels, figsize=(30.,6.*Nchannels))
    plt.subplots_adjust(left=.15, bottom=.2, hspace=0.2, right=.95, top=.99)

    key_list = list(main.data.keys())
    key_list.remove("t")
    try:
        key_list.remove("params")
    except ValueError:
        pass
    
    cond = (main.data['t']>main.args['x1']) & (main.data['t']<=main.args['x2'])
    for i, key in enumerate(sorted(key_list)[:Nchannels]):
        AX[i].plot(main.data['t'][cond], main.data[key][cond])
        if i==Nchannels-1:
            set_plot(AX[i], xlabel=xlabel, ylabel=key, num_yticks=3)
        else:
            set_plot(AX[i], ['left'], ylabel=key, num_yticks=3, xticks=[])

    return fig
def fig_with_current_pulse_analysis(t_window, TEST_TRACES, CTRL_TRACES,\
                                    delay, duration, params,\
                                    threshold=-30, color='k'):
    CTRL_TRACES = np.array(CTRL_TRACES)
    CTRL_TRACES[CTRL_TRACES > threshold] = threshold
    # then fig with all traces
    fig, ax = plt.subplots(1, figsize=(6.5, 4.5))
    ax.set_title('n=' + str(len(CTRL_TRACES)) + ' trials', fontsize=12)
    plt.subplots_adjust(left=.2, bottom=.25)
    for v in CTRL_TRACES:
        plt.plot(t_window, v, color, lw=.2)
    ax.legend(prop={'size': 'x-small'}, loc='best', frameon=False)
    ax.plot(t_window,
            CTRL_TRACES.mean(axis=0),
            'k',
            lw=2,
            label='blank trials')
    ax.fill_between(t_window,\
                    CTRL_TRACES.mean(axis=0)-CTRL_TRACES.std(axis=0),\
                    CTRL_TRACES.mean(axis=0)+CTRL_TRACES.std(axis=0),
                    color='lightgray')
    ax.plot(t_window,\
                    CTRL_TRACES.mean(axis=0)-CTRL_TRACES.std(axis=0),\
                    color='k', lw=.5)
    ax.plot(t_window,\
                    CTRL_TRACES.mean(axis=0)+CTRL_TRACES.std(axis=0),
                    color='k', lw=.5)
    ## now fitting
    tcond = (t_window > float(params['CMD_delay']) - 10.) & (
        t_window < float(params['CMD_delay']) + float(params['CMD_dur']))
    El, Tm, Gl, func = fit_membrane_prop(t_window[tcond],\
                                         CTRL_TRACES.mean(axis=0)[tcond], params)
    ax.plot(t_window[tcond], func(t_window[tcond], El, Tm, Gl), 'r:', lw=3)
    ax.annotate('$V_0$='+str(np.round(El))+'mV, $\\tau_m$='+str(np.round(Tm))+\
                'ms, $g_L$='+str(np.round(Gl))+'nS', (0.1,.86), xycoords='axes fraction')
    set_plot(ax, ylabel='$V_m$ (mV)', xlabel='delay from state onset (ms)')
    return [fig]
Beispiel #14
0
    def __init__(self, data, dx, xlim, x_bar, x_units):

        self.addedData = []
        print(matplotlib.__version__)
        y0, y1 = data.min(), data.max()

        # The data
        self.xlim = min([len(data), int(xlim / dx)])
        self.n = np.linspace(0, self.xlim - 1, self.xlim)
        self.y = (self.n * 0.0) + data.mean()

        # The window
        self.fig = Figure(figsize=(5, 5), dpi=100)
        self.fig.subplots_adjust(bottom=.05, left=.1)
        self.ax1 = self.fig.add_subplot(111)

        # self.ax1 settings
        bar_lim = min([int(x_bar / dx), int(3. * self.xlim / 5)])
        self.xbar = self.ax1.plot([int(self.xlim/5), bar_lim+int(self.xlim/5)],\
                                  np.ones(2)*(y0+.1*(y1-y0)), 'k-', lw=5)
        self.ax1.plot([0, self.xlim - 1], [y0, y1], 'w.', ms=1e-4)
        self.xbar_legend = self.ax1.annotate(str(int(x_bar))+x_units,\
                                             (int(self.xlim/5),y0))
        self.line1 = Line2D([], [], color='blue')
        self.line1_tail = Line2D([], [], color='red', linewidth=2)
        self.line1_head = Line2D([], [],
                                 color='red',
                                 marker='o',
                                 markeredgecolor='r')
        self.ax1.add_line(self.line1)
        self.ax1.add_line(self.line1_tail)
        self.ax1.add_line(self.line1_head)

        set_plot(self.ax1, ['left'], xlim=[0, self.xlim - 1], xticks=[])
        FigureCanvas.__init__(self, self.fig)
        TimedAnimation.__init__(self, self.fig, interval=50, blit=True)
def POP_ACT_PLOT(t,
                 POP_ACT_LIST,
                 tlim=None,
                 pop_act_zoom=None,
                 COLORS=None,
                 with_fig=None):

    if with_fig is not None:
        fig, ax = plt.gcf(), plt.gca()
    else:
        fig, ax = plt.subplots(1, figsize=(5, 3))
        plt.subplots_adjust(left=.25, bottom=.25)

    # time limit
    if tlim is None:
        tlim = [t.min(), t.max()]
    # pop act lim
    if pop_act_zoom is None:
        pop_act_zoom = np.zeros(2)
        pop_act_zoom[0] = np.min([np.min(act) for act in POP_ACT_LIST])
        pop_act_zoom[1] = np.max([np.max(act) for act in POP_ACT_LIST])
        ID_ZOOM_LIST = []
    # colors
    if COLORS is None:
        COLORS = ['g'] + ['r'] + ['k' for i in range(len(POP_ACT_LIST) - 2)]

    for act, col in zip(POP_ACT_LIST[::-1], COLORS[::-1]):
        plt.plot(t[(t >= tlim[0]) & (t <= tlim[1])],
                 act[(t >= tlim[0]) & (t <= tlim[1])],
                 '-',
                 color=col)
    my_graph.set_plot(ax,
                      xlabel='time (ms)',
                      ylabel='pop. act. (Hz)',
                      ylim=pop_act_zoom)
    return fig, ax
def make_conversion_fig(Rm0=None):
    # we plot here the conversion between input resistance
    # and dendritic tree properties
    Rm_exp = get_Rm_range()[kept_cells]
    Rm = np.linspace(0.9 * Rm_exp.min(), 1.2 * Rm_exp.max(), 20)
    LS, LD, DD = 0 * Rm, 0 * Rm, 0 * Rm

    for i in range(len(Rm)):
        soma1, stick1, params1 = adjust_model_prop(Rm[i], soma, stick,\
                                                   precision=.01, maxiter=1e5)
        LS[i] = 1e6 * soma1['L']
        DD[i], LD[i] = 1e6 * stick1['D'], 1e6 * stick1['L']

    fig, AX = plt.subplots(4, figsize=(4.5, 8))
    plt.subplots_adjust(left=.4, bottom=.15, hspace=.3)

    AX[0].set_title('resizing rule')
    AX[0].hist(Rm_exp, bins=np.linspace(Rm.min(), Rm.max(), 10),\
               color='lightgray', edgecolor='k', lw=2)
    set_plot(AX[0], ['left'], ylabel='cell #', xticks=[])

    for ax, y, label in zip(AX[1:3], [LS, DD],\
         ['length of \n soma ($\mu$m)', 'root branch \n diameter ($\mu$m)']):
        ax.plot(Rm, y, 'k-', lw=2)
        set_plot(ax, ['left'], ylabel=label, xticks=[])
    AX[3].plot(Rm, LD, 'k-', lw=2)
    set_plot(AX[3], ylabel='tree length \n ($\mu$m)',\
                   xlabel='somatic input \n resistance (M$\Omega$)',\
                   xticks=[200,400,600])

    soma0, stick0, params0 = adjust_model_prop(Rm_exp.mean(),\
                                               soma, stick, precision=.1, maxiter=1e4)
    if Rm0 is not None:
        AX[1].plot([Rm_exp.mean()], [1e6 * soma0['L']], 'kD')
        AX[2].plot([Rm_exp.mean()], [1e6 * stick0['D']], 'kD')
        AX[3].plot([Rm_exp.mean()], [1e6 * stick0['L']], 'kD')

    return fig
Beispiel #17
0
        fig.suptitle('$f_{prox}$ = ' + str(new_ratio) + '%')
        for i in range(len(PROTOCOLS)):
            feG, fiG, feI, fiI, synch, muV, sV, TvN, muGn = get_fluct_var(i_nrn,\
                                          exp_type=PROTOCOLS[i], len_f=len_f, precision=precision)
            for ax, x in zip(AX, [1e3 * muV, 1e3 * sV, 1e2 * TvN, muGn]):
                ax.plot(F, x, lw=4, color=COLORS[i], label=PROTOCOLS[i])
            for ax, x in zip(AX2, [feG, fiG, feI, fiI, synch]):
                ax.plot(F, x, lw=4, color=COLORS[i], label=PROTOCOLS[i])
        plt.show(block=False)
        input('Hit Enter To Close')
        plt.close()

    if sys.argv[-1] != 'all':
        from graphs.my_graph import set_plot
        for ax, ylabel in zip(AX[:-1], LABELS[:-1]):
            set_plot(ax, ['left'], ylabel=ylabel, xticks=[], num_yticks=4)
        for ax, ylabel in zip(AX2[:-1], LABELS2[:-1]):
            set_plot(ax, ['left'], ylabel=ylabel, xticks=[], num_yticks=4)
        set_plot(AX[-2], ['left'], ylabel=LABELS[-2], xticks=[], num_yticks=4)
        set_plot(AX[-1], ['bottom','left'],\
                 ylabel=LABELS[-1], xticks=[], xlabel='increasing \n presynaptic quantity')
        set_plot(AX2[-2], ['left'],
                 ylabel=LABELS2[-2],
                 xticks=[],
                 num_yticks=4)  #, yticks=[0,1,2])
        set_plot(AX2[1], ['left'], ylabel=LABELS2[1], xticks=[],
                 num_yticks=4)  #, yticks=[0,2,4])
        set_plot(AX2[0], ['left'], ylabel=LABELS2[0], xticks=[],
                 num_yticks=4)  #, yticks=[0,0.3,0.6])
        set_plot(AX2[2], ['left'], ylabel=LABELS2[2], xticks=[],
                 num_yticks=4)  #, yticks=[0,0.15,0.3])
Beispiel #18
0
def full_plot(args):

    DATA = get_dataset()
    VC, SE, ECR, ICR, TAU2, TAU1, DUR, MONKEY = [], [], [], [], [], [], [], []
    for i in range(len(DATA)):
        args.data_index = i
        params = get_minimum_params(args)
        for vec, VEC in zip(params, [VC, SE, ECR, ICR, TAU2, TAU1]):
            VEC.append(vec)
        DUR.append(DATA[i]['duration'])
        MONKEY.append(DATA[i]['Monkey'])

    # vc
    fig1, ax1 = plt.subplots(1, figsize=(1.5, 2.3))
    plt.subplots_adjust(bottom=.4, left=.6)
    ax1.fill_between([-1., 1.],
                     np.ones(2) * args.vc[0],
                     np.ones(2) * args.vc[1],
                     color='lightgray',
                     alpha=.8,
                     label=r'$\mathcal{D}$ domain')
    ax1.bar([0], [np.array(VC).mean()],
            yerr=[np.array(VC).std()],
            color='lightgray',
            edgecolor='k',
            lw=3)
    ax1.legend(frameon=False)
    print('Vc = ', round(np.array(VC).mean()), '+/-',
          round(np.array(VC).std()), 'mm/s')
    set_plot(ax1, ['left'], xticks=[], ylabel='$v_c$ (mm/s)')
    # connectivity
    fig2, ax2 = plt.subplots(1, figsize=(2., 2.3))
    plt.subplots_adjust(bottom=.4, left=.6)
    ax2.bar([0], [np.array(ECR).mean()],
            yerr=[np.array(ECR).std()],
            color='lightgray',
            edgecolor='g',
            lw=3,
            label='$l_{exc}$')
    print('Ecr=', round(np.array(ECR).mean(), 1), '+/-',
          round(np.array(ECR).std(), 1), 'mm/s')
    ax2.bar([1.5], [np.array(ICR).mean()],
            yerr=[np.array(ICR).std()],
            color='lightgray',
            edgecolor='r',
            lw=3,
            label='$l_{inh}$')
    print('Icr=', round(np.array(ICR).mean(), 1), '+/-',
          round(np.array(ICR).std(), 1), 'mm/s')
    ax2.fill_between([-1., 2.5],
                     np.ones(2) * args.Econn_radius[0],
                     np.ones(2) * args.Econn_radius[1],
                     color='lightgray',
                     alpha=.8)
    ax2.legend(frameon=False)
    ax2.annotate("p=%.1e" % ttest_rel(ECR, ICR).pvalue, (0.1, .1),
                 xycoords='figure fraction')
    set_plot(ax2, ['left'], xticks=[], ylabel='extent (mm)')
    # stim extent
    fig3, ax3 = plt.subplots(1, figsize=(1.5, 2.3))
    plt.subplots_adjust(bottom=.4, left=.6)
    ax3.bar([0], [np.array(SE).mean()],
            yerr=[np.array(SE).std()],
            color='lightgray',
            edgecolor='k',
            lw=3)
    print('Ecr=', round(np.array(SE).mean(), 1), '+/-',
          round(np.array(SE).std(), 1), 'mm/s')
    ax3.fill_between([-1., 1.],
                     np.ones(2) * args.stim_extent[0],
                     np.ones(2) * args.stim_extent[1],
                     color='lightgray',
                     alpha=.8)
    set_plot(ax3, ['left'],
             xticks=[],
             ylabel='$l_{stim}$ (mm)',
             yticks=[0, 1, 2])

    DUR, TAU1, TAU2 = np.array(DUR), 1e3 * np.array(TAU1), 1e3 * np.array(TAU2)

    fig4, ax4 = plt.subplots(1, figsize=(2.5, 2.3))
    plt.subplots_adjust(bottom=.4, left=.6)
    for d in np.unique(DUR):
        ax4.errorbar([d], [TAU1[DUR == d].mean()],
                     yerr=[TAU1[DUR == d].std()],
                     marker='o',
                     color='k')
    ax4.plot([DUR.min(), DUR.max()],
             np.polyval(np.polyfit(DUR, TAU1, 1),
                        [DUR.min(), DUR.max()]),
             'k--',
             lw=0.5)
    ax4.fill_between([DUR.min(), DUR.max()],
                     1e3 * np.ones(2) * args.Tau1[0],
                     1e3 * np.ones(2) * args.Tau1[1],
                     color='lightgray',
                     alpha=.8)
    ax4.annotate("c=%.1e" % pearsonr(DUR, TAU1)[0], (0.1, .2),
                 xycoords='figure fraction')
    ax4.annotate("p=%.1e" % pearsonr(DUR, TAU1)[1], (0.1, .1),
                 xycoords='figure fraction')
    set_plot(ax4,
             xticks=[10, 50, 100],
             xlabel='$T_{stim}$ (ms)',
             ylabel='$\\tau_1$ (ms)',
             yticks=[0, 25, 50])

    fig5, ax5 = plt.subplots(1, figsize=(2.5, 2.3))
    plt.subplots_adjust(bottom=.4, left=.6)
    for d in np.unique(DUR):
        ax5.errorbar([d], [TAU2[DUR == d].mean()],
                     yerr=[TAU2[DUR == d].std()],
                     marker='o',
                     color='k')
    ax5.plot([DUR.min(), DUR.max()],
             np.polyval(np.polyfit(DUR, TAU2, 1),
                        [DUR.min(), DUR.max()]),
             'k--',
             lw=0.5)
    ax5.fill_between([DUR.min(), DUR.max()],
                     1e3 * np.ones(2) * args.Tau2[0],
                     1e3 * np.ones(2) * args.Tau2[1],
                     color='lightgray',
                     alpha=.8)
    ax5.annotate("c=%.1e" % pearsonr(DUR, TAU2)[0], (0.1, .2),
                 xycoords='figure fraction')
    ax5.annotate("p=%.1e" % pearsonr(DUR, TAU2)[1], (0.1, .1),
                 xycoords='figure fraction')
    set_plot(ax5,
             xticks=[10, 50, 100],
             xlabel='$T_{stim}$ (ms)',
             ylabel='$\\tau_2$ (ms)',
             yticks=[40, 120, 200])

    put_list_of_figs_to_svg_fig([fig1, fig2, fig3, fig4, fig5],
                                fig_name="/Users/yzerlaut/Desktop/temp.svg")
    show()
Beispiel #19
0
def plot_analysis(args):

    Residuals,\
        vcFull, seFull, ecrFull, icrFull,\
        t2Full, t1Full = np.load(\
            '../ring_model/data/residuals_data_'+str(args.data_index)+'.npy')

    i0 = np.argmin(Residuals)
    Residuals /= Residuals[i0]  # normalizing

    fig, AX = plt.subplots(1, 6, figsize=(9, 2.))
    plt.subplots_adjust(bottom=.3, left=.15)
    for ax, vec, label in zip(AX,
                              [vcFull, seFull, ecrFull, icrFull, t2Full, t1Full],\
                              ['$v_c (mm/s)$','$l_{stim}$ (mm)',
                               '$l_{exc}$ (mm)', '$l_{inh}$ (mm)',
                               '$\\tau_2$ (ms)', '$\\tau_1$ (ms)']):
        ax.plot(vec, Residuals, 'o')
        ax.plot([vec[i0]], [Residuals[i0]], 'ro')
        ax.set_yscale('log')
        if ax == AX[0]:
            set_plot(ax,
                     xlabel=label,
                     ylabel='Residual (norm.)',
                     yticks=[1, 2, 5, 10, 20],
                     yticks_labels=['1', '2', '5', '10', '20'])
        else:
            set_plot(ax, xlabel=label, yticks=[1, 5, 10, 20], yticks_labels=[])

    new_time, space, new_data = get_data(args.data_index,
                                         Nsmooth=args.Nsmooth,
                                         t0=args.t0,
                                         t1=args.t1)

    if args.force:
        fn = '../ring_model/data/model_data_' + str(args.data_index) + '.npy'
        t, X, Fe_aff, Fe, Fi, muVn =\
                                 Euler_method_for_ring_model(\
                                                             'RS-cell', 'FS-cell',\
                                                             'CONFIG1', 'RING1', 'CENTER',\
                                        custom_ring_params={\
                                                            'X_discretization':args.X_discretization,
                                                            'X_extent':args.X_extent,
                                                            'conduction_velocity_mm_s':vcFull[i0],
                                                            'exc_connect_extent':ecrFull[i0],
                                                            'inh_connect_extent':icrFull[i0]},
                                        custom_stim_params={\
                                                            'sX':seFull[i0], 'amp':15.,
                                                            'Tau1':t1Full[i0], 'Tau2':t2Full[i0]})
        np.save(fn, [args, t, X, Fe_aff, Fe, Fi, muVn])
    else:
        _, _, _, _, _, _, FILENAMES = np.load(
            '../ring_model/data/scan_data.npy')
        fn = FILENAMES[i0]

    res = get_residual(args,
                       new_time,
                       space,
                       new_data,
                       Nsmooth=args.Nsmooth,
                       fn=fn,
                       with_plot=True)
    show()
Rm_data = np.zeros(len(CELLS))

fig, ax = plt.subplots(figsize=(4, 3))
plt.subplots_adjust(bottom=.3, left=.3)

if sys.argv[-1] == 'all':
    for i in range(len(CELLS))[::5]:
        Rm_data[i] = 1e-6 / CELLS[i]['Gl']
        soma1, stick1, params1 = adjust_model_prop(Rm_data[i], soma, stick)
        Rtf_model, N_synapses = get_the_transfer_resistance_to_soma(soma1,\
                                                                    stick1, params1)

        ax.hist(1e-6 * Rtf_model, label='cell' + str(i))

    ax.legend(frameon=False, prop={'size': 'x-small'}, loc='best')
    set_plot(ax, xlabel='transfer resistance \n to soma $(M \Omega)$',\
             ylabel='synapses #')
else:
    for freq in [0., 2., 10.]:
        TF_model, Area = get_the_transfer_resistance_to_soma(soma,
                                                             stick,
                                                             params,
                                                             precision=1000,
                                                             with_area=True,
                                                             freq=freq)
        edges, bins = np.histogram(1e-6 * TF_model,
                                   bins=30,
                                   weights=Area,
                                   normed=True)
        bins = .5 * (bins[:-1] + bins[1:])
        plt.bar(bins,
                edges / edges.max(),
def make_experimental_fig():
    fig, AX = plt.subplots(2, 2, figsize=(11, 8))
    MICE, RATS = [], []

    psd_boundaries = [200, 900]
    all_freq, all_psd, all_phase = [np.empty(0, dtype=float) for i in range(3)]
    HIGH_BOUND = 450  # higher nound for frequency

    for file in os.listdir("./intracellular_data/"):
        if file.endswith("_rat.txt"):
            _ = 0
        elif file.endswith(".txt"):
            freq, psd, phase = np.loadtxt("./intracellular_data/" + file,
                                          unpack=True)
            MICE.append({
                'freq':
                freq[np.argsort(freq)],
                'psd':
                psd[np.argsort(freq)],
                'phase':
                (phase[np.argsort(freq)] %
                 (2. * np.pi) + np.pi / 2.) % (2. * np.pi) - np.pi / 2.
            })
            # print file, MICE[-1]['phase'].max()
            all_freq = np.concatenate([all_freq, MICE[-1]['freq']])
            all_psd = np.concatenate([all_psd, MICE[-1]['psd']])
            all_phase = np.concatenate([all_phase, MICE[-1]['phase']])

        psd_boundaries[0] = min([psd_boundaries[0], psd.max()])
        psd_boundaries[1] = max([psd_boundaries[1], psd.max()])

    np.save('full_data.npy',\
        [all_freq[all_freq<HIGH_BOUND], all_psd[all_freq<HIGH_BOUND], all_phase[all_freq<HIGH_BOUND]])
    all_freq, all_psd, all_phase = np.load('full_data.npy')

    mymap = get_linear_colormap()
    X = 300 + np.arange(3) * 300

    for m in MICE:
        rm = m['psd'][:3].mean()
        r = (rm - psd_boundaries[0]) / (psd_boundaries[1] - psd_boundaries[0])
        AX[0, 0].loglog(m['freq'][m['freq'] < HIGH_BOUND],
                        m['psd'][m['freq'] < HIGH_BOUND],
                        'o-',
                        color=mymap(r, 1),
                        ms=3)
        AX[0, 1].semilogx(m['freq'][m['freq'] < HIGH_BOUND],
                          m['phase'][m['freq'] < HIGH_BOUND],
                          'o-',
                          color=mymap(r, 1),
                          ms=3)

    AX[0, 0].annotate('n=' + str(len(MICE)) + ' cells', (.2, .2),
                      xycoords='axes fraction',
                      fontsize=18)

    ax2 = fig.add_axes([0.59, 0.7, 0.015, 0.18])
    cb = build_bar_legend(X, ax2, mymap, scale='linear', color_discretization=100,\
                                bounds=psd_boundaries,
                                label=r'$R_\mathrm{m}$ ($\mathrm{M}\Omega$)')

    f_bins = np.logspace(
        np.log(.1) / np.log(10),
        np.log(HIGH_BOUND) / np.log(10), 20)
    digitized = np.digitize(all_freq, f_bins)
    psd_means = np.array(
        [all_psd[digitized == i].mean() for i in range(1, len(f_bins))])
    psd_std = np.array(
        [all_psd[digitized == i].std() for i in range(1, len(f_bins))])
    phase_means = np.array(
        [all_phase[digitized == i].mean() for i in range(1, len(f_bins))])
    phase_std = np.array(
        [all_phase[digitized == i].std() for i in range(1, len(f_bins))])
    AX[1, 0].errorbar(.5 * (f_bins[1:] + f_bins[:-1]),
                      psd_means,
                      yerr=psd_std,
                      color='gray',
                      lw=3,
                      label='data')
    AX[1, 0].fill_between(.5 * (f_bins[1:] + f_bins[:-1]),
                          psd_means - psd_std,
                          psd_means + psd_std,
                          color='lightgray')
    AX[1, 1].errorbar(.5 * (f_bins[1:] + f_bins[:-1]),
                      phase_means,
                      yerr=phase_std,
                      color='gray',
                      lw=3,
                      label='data')
    AX[1, 1].fill_between(.5 * (f_bins[1:] + f_bins[:-1]),
                          phase_means - phase_std,
                          phase_means + phase_std,
                          color='lightgray')

    ## THEN MODEL

    from minimization import single_comp_imped
    try:
        Rm, Cm = np.load('single_comp_fit.npy')
        psd, phase = single_comp_imped(f, Rm, Cm)
        AX[1, 0].loglog(f, psd, 'k:', lw=2)
        AX[1, 1].semilogx(f, phase, 'k:', lw=2, label='single comp.')
    except IOError:
        print('no single compartment data available')

    ### MEAN MODEL
    psd, phase = get_input_imped(soma, stick, params)
    AX[1, 0].loglog(f, psd, 'k-', alpha=.8, lw=4)
    AX[1, 1].semilogx(f[:-1],
                      -phase[:-1],
                      'k-',
                      alpha=.8,
                      lw=4,
                      label='medium size \n   model')

    ### MODEL VARIATIONS
    base = np.linspace(0, 1, 4)
    for Rrm, b in zip([250, 350, 600, 800], base):
        soma1, stick1, params1 = adjust_model_prop(Rrm, soma, stick)
        psd, phase = get_input_imped(soma1, stick1, params1)
        AX[1, 0].loglog(f, psd, '-', color=mymap(b, 1), ms=5)
        AX[1, 1].semilogx(f[:-1], -phase[:-1], '-', color=mymap(b, 1), ms=5)

    ### ===================== FINAL graph settings

    ax3 = fig.add_axes([0.19, 0.125, 0.015, 0.18])
    cb = build_bar_legend([0,1], ax3, mymap, scale='linear', color_discretization=100,\
                                bounds=psd_boundaries,ticks_labels=['',''],
                                label='size variations')

    AX[1, 1].legend(frameon=False, prop={'size': 'x-small'})

    for ax, xlabel in zip([AX[0, 0], AX[1, 0]], ['', 'frequency (Hz)']):
        set_plot(ax, xlim=[.08,1000], ylim=[6., 1200],\
                   xticks=[1,10,100,1000], yticks=[10,100,1000],yticks_labels=['10','100','1000'],\
                       xlabel=xlabel,ylabel='modulus ($\mathrm{M}\Omega$)')

    for ax, xlabel in zip([AX[0, 1], AX[1, 1]], ['', 'frequency (Hz)']):
        set_plot(ax, xlim=[.08,1000], ylim=[-.2,2.3],\
                   xticks=[1,10,100,1000], yticks=[0,np.pi/4.,np.pi/2.],\
                   yticks_labels=[0,'$\pi/4$', '$\pi/2$'],
                   xlabel=xlabel, ylabel='phase shift (Rd)')

    fig2, ax = make_fig(np.linspace(0, 1, stick['B'] + 1) * stick['L'],
                        stick['D'],
                        xscale=1e-6,
                        yscale=50e-6)
    fig2.set_size_inches(3, 5, forward=True)

    fig3 = make_conversion_fig(Rm0=Rm)

    return fig, fig2, fig3
Beispiel #22
0
cond = (time > 70) & (time < 120)
mean_data = smooth_data[:, cond].mean(axis=1)

fig, AX = plt.subplots(1, 2, figsize=(8, 3))
plt.subplots_adjust(bottom=.23, top=.97, right=.85)


def to_minimize(x):
    return np.sum((mean_data - double_gaussian(space, *x))**2)


res = minimize(to_minimize, [3, 6, 2, .9])
print(res.x)
AX[0].plot(space, double_gaussian(space, *res.x), label='double gaussian')


def to_minimize(x):
    return np.sum((mean_data - gaussian(space, *x))**2)


res = minimize(to_minimize, [5, 2, .9])
AX[1].plot(space, gaussian(space, *res.x), label='simple gaussian')
for ax in AX:
    ax.plot(space, mean_data, label='data [70,120] ms')
    ax.legend()
set_plot(AX[0], xlabel='space (mm)', ylabel='VSDi signal ($\perthousand$)')
set_plot(AX[1], xlabel='space (mm)')
fig.savefig('/Users/yzerlaut/Desktop/1.png')
plt.show()
def make_experimental_fig():
    fig, AX = plt.subplots(1, 2, figsize=(8, 4))
    plt.subplots_adjust(bottom=.3, left=.25, wspace=.3)

    f, psd_means, phase_means = np.load(
        '../larkumEtAl2009/data/larkum_imped_data.npy')
    phase_means = -phase_means

    AX[0].plot(f,
               psd_means,
               color='gray',
               lw=3,
               label='Layer V pyr. cell \n Larkum et al. 2009')
    AX[1].plot(f,
               phase_means,
               color='gray',
               lw=3,
               label='Layer V pyr. cell \n Larkum et al. 2009')

    ## THEN MODEL

    from minimization import single_comp_imped
    try:
        Rm, Cm = np.load('single_comp_fit_larkum.npy')
        psd, phase = single_comp_imped(f, Rm, Cm)
        AX[0].loglog(f, psd, 'k:', lw=2)
        AX[1].semilogx(f, phase, 'k:', lw=2, label='single comp.')
    except IOError:
        print('no single compartment data available')

    ### MEAN MODEL
    psd, phase = get_input_imped(soma, stick, params)
    AX[0].loglog(f, psd, 'k-', alpha=.8, lw=3)
    AX[1].semilogx(f[:-1],
                   -phase[:-1],
                   'k-',
                   alpha=.8,
                   lw=3,
                   label='fitted \"reduced model\"')

    ### ===================== FINAL graph settings

    AX[1].legend(frameon=False, prop={'size': 'x-small'})

    set_plot(AX[0], xlim=[.08,1000], ylim=[.3, 200],\
           xticks=[1,10,100,1000], yticks=[1,10,100],yticks_labels=['1','10','100'],\
             xlabel='frequency (Hz)',ylabel='modulus ($\mathrm{M}\Omega$)')

    set_plot(AX[1], xlim=[.08,1000], ylim=[-.2,2.3],\
               xticks=[1,10,100,1000], yticks=[0,np.pi/4.,np.pi/2.],\
               yticks_labels=[0,'$\pi/4$', '$\pi/2$'],
               xlabel='frequency (Hz)', ylabel='phase shift (Rd)')

    # fig2, ax = make_fig(np.linspace(0, 1, stick['B']+1)*stick['L'],
    #          stick['D'], xscale=1e-6, yscale=50e-6)
    # fig2.set_size_inches(3, 5, forward=True)

    fig3, AX = plt.subplots(1, 2, figsize=(7, 2.5))
    plt.subplots_adjust(left=.3, bottom=.3)
    #### ================================================== ##
    #### COMPARING IT WITH Transfer Resistance DATA ##########
    #### ================================================== ##
    TFdata = np.load('../LarkumEtAl2009/data/larkum_Tf_Resist_data.npz')
    edges, bins = np.histogram(TFdata['R_transfer'],
                               bins=50,
                               weights=TFdata['Areas'],
                               normed=True)
    AX[0].bar(bins[:-1],
              edges / edges.max(),
              width=bins[1] - bins[0],
              color='gray',
              edgecolor='gray')
    precision = 1e4
    # params_for_cable_theory(stick, params) # setting cable membrane constants
    TF_model, Area = get_the_transfer_resistance_to_soma(soma,
                                                         stick,
                                                         params,
                                                         precision=precision,
                                                         with_area=True)
    edges, bins = np.histogram(1e-6 * TF_model,
                               bins=precision / 5,
                               weights=Area,
                               normed=True)
    # edges = np.concatenate([np.array([0,1]), np.real(edges)])
    # bins = np.concatenate([[bins.min()], bins])
    bins = .5 * (bins[:-1] + bins[1:])
    AX[0].plot(bins, edges / edges.max(), color='k', lw=1)
    set_plot(AX[0],
             ylabel='surfacic density \n (norm. by maximum)',
             xlabel='transfer resistance M$\Omega$',
             yticks=[0, 1])

    IRdata = np.load('../LarkumEtAl2009/data/larkum_Input_Resist_data.npz')
    edges, bins = np.histogram(IRdata['R_input'],
                               bins=50,
                               weights=IRdata['Areas'],
                               normed=True)
    AX[1].bar(bins[:-1],
              edges / edges.max(),
              width=bins[1] - bins[0],
              color='gray',
              edgecolor='gray')
    precision = 1e4
    # params_for_cable_theory(stick, params) # setting cable membrane constants
    TF_model, Area = get_the_input_resistance(soma,
                                              stick,
                                              params,
                                              precision=precision,
                                              with_area=True)
    edges, bins = np.histogram(1e-6 * TF_model,
                               bins=precision / 10,
                               weights=Area,
                               normed=True)
    # edges = np.concatenate([np.array([0,1]), np.real(edges)])
    # bins = np.concatenate([[bins.min()], bins])
    bins = .5 * (bins[:-1] + bins[1:])
    AX[1].plot(bins, edges / edges.max(), color='k', lw=1)
    set_plot(AX[1],
             ylabel='surfacic density \n (norm. by maximum)',
             xlabel='input resistance M$\Omega$',
             yticks=[0, 1])

    return fig, fig3
Beispiel #24
0
    import matplotlib.pylab as plt

    args2, t, X, Fe_aff1, Fe1, Fi1, muVn1,\
      Fe_aff2, Fe2, Fi2, muVn2, Fe_aff3, Fe3, Fi3, muVn3 = np.load(args.file)

    fig1, desambuigVSD = decode_stim(t,
                                     muVn1,
                                     muVn2,
                                     muVn3,
                                     stim_length=100e-3)
    fig2, desambuigFR = decode_stim(t,
                                    Fe1 - Fe1[0, :].mean(),
                                    Fe2 - Fe2[0, :].mean(),
                                    Fe3 - Fe3[0, :].mean(),
                                    stim_length=100e-3)

    # fig1.savefig('data/VSD.svg')
    # fig2.savefig('data/FR.svg')

    fig, ax = plt.subplots(1, figsize=(3.5, 2.5))
    plt.subplots_adjust(bottom=.3, left=.3)
    ax.plot(1e3 * t, desambuigFR, label='Firing Rate')
    ax.plot(1e3 * t, desambuigVSD, label='Vm')
    ax.legend(prop={'size': 'x-small'})
    set_plot(ax,
             ylabel='Desambuiguation \n $P^{AM}(2) - P^{LP}(2)$',
             xlabel='time (ms)')

    plt.show()
Beispiel #25
0
def decode_stim(t,
                S1,
                S2,
                AM,
                stim_length=100e-3,
                frame_norm=True,
                non_zero=1e-10):

    # extracting temporal quantities
    dt = t[1] - t[0]  # time step
    istim = int(stim_length /
                dt)  # duration in bins of response to determine cort. repres.
    # flatten over space S1 and S2 to extract onset times
    fS1, fS2 = S1.mean(axis=1), S2.mean(axis=1)
    iT1, iT2 = np.argmax(fS1), np.argmax(fS1)

    # mean cortical representations
    meanS1 = S1[iT1:iT1 + istim, :].mean(axis=0)
    meanS2 = S2[iT2:iT2 + istim, :].mean(axis=0)
    meanS12 = meanS1 + meanS2
    # then normalization
    meanS1 /= non_zero + np.linalg.norm(meanS1)
    meanS2 /= non_zero + np.linalg.norm(meanS2)
    meanS12 /= non_zero + np.linalg.norm(meanS12)
    Blank = np.zeros(len(meanS1))  # blank is zero

    LP = S1 + S2  # linear prediction

    dAM, dLP = {}, {
    }  # dictionaries that we will fill with the analysis values
    for key in [
            'Dev_vs_S1', 'Dev_vs_S2', 'Dev_vs_S12', 'Dev_vs_BL', 'P_S1',
            'P_S2', 'P_S12', 'P_BL'
    ]:
        dAM[key], dLP[key] = np.zeros(len(t)), np.zeros(
            len(t))  # initialized to zeros vectos

    # now loop over frames to get all the deviations to get an average deviation for the proba calc
    # for i in [500, 1100]:
    for i in range(len(t)):
        # --> Apparent Motion
        nAM = AM[i, :] / (non_zero + np.linalg.norm(AM[i, :]))
        # --> Linear Prediction
        nLP = LP[i, :] / (non_zero + np.linalg.norm(LP[i, :]))
        # computing deviations
        for key, stim in zip(\
                             ['Dev_vs_S1', 'Dev_vs_S2', 'Dev_vs_S12', 'Dev_vs_BL'],
                             [meanS1, meanS2, meanS12, Blank]):
            dAM[key][i] = np.std(nAM - stim)
            dLP[key][i] = np.std(nLP - stim)

    # now loop over frames to get all the deviations to get an average deviation for the proba calc
    for i in range(len(t)):

        # --> Apparent Motion
        nAM = AM[i, :] / (non_zero + np.linalg.norm(AM[i, :]))
        # --> Linear Prediction
        nLP = LP[i, :] / (non_zero + np.linalg.norm(LP[i, :]))
        # computing deviations
        Ptot_AM, Ptot_LP = 0, 0  # total proba
        for key1, key2, stim in zip(\
                             ['P_S1', 'P_S2', 'P_S12', 'P_BL'],
                             ['Dev_vs_S1', 'Dev_vs_S2', 'Dev_vs_S12', 'Dev_vs_BL'],
                             [meanS1, meanS2, meanS12, Blank]):
            dAM[key1][i] = np.exp(-0.5 * np.sum(
                (nAM - stim)**2 / (1e-9 + dAM[key2].std()))) + 1e-9
            Ptot_AM += dAM[key1][i]
            dLP[key1][i] = np.exp(-0.5 * np.sum(
                (nLP - stim)**2 / (1e-9 + dLP[key2].std()))) + 1e-9
            Ptot_LP += dLP[key1][i]

        for key in ['P_S1', 'P_S2', 'P_S12', 'P_BL']:
            dAM[key][i] /= Ptot_AM
            dLP[key][i] /= Ptot_LP

    fig, AX = plt.subplots(1, 2, figsize=(7, 2.5))
    AX[0].plot(nAM)
    AX[0].plot(meanS1)
    AX[1].plot(nLP)
    AX[1].plot(meanS12)
    AX[1].plot(meanS2)
    plt.show()

    # figure
    fig, AX = plt.subplots(1, 2, figsize=(7, 2.5))
    plt.subplots_adjust(bottom=.2, wspace=.3, hspace=.3)
    for key, label in zip(['P_S1', 'P_S2', 'P_S12', 'P_BL'],
                          ['P(1)', 'P(2)', 'P(1+2)', 'P(Blank)']):
        for ax, D in zip(AX[:2], [dAM, dLP]):
            ax.plot(1e3 * t, D[key], label=label)

    for ax, title in zip(AX, ['App. Motion', 'Linear Pred.']):
        ax.legend(prop={'size': 'x-small'})
        ax.set_title(title)
        set_plot(ax, yticks=[0, .5, 1], ylabel='Proba', xlabel='time (ms)')

    desambuig = dAM['P_S2'] - dLP['P_S2']
    return fig, desambuig
Beispiel #26
0
for i in range(len(CELLS)):
    Rm_data[i] = 1e-6 / CELLS[i]['Gl']
    soma1, stick1, params1 = adjust_model_prop(Rm_data[i], soma, stick)

    Rtf_model[i] = get_the_mean_transfer_resistance_to_soma(
        soma1, stick1, params1)

print('---------------------------------------------------')
print('Comparison between model and data for Tm')
print('MODEL, mean = ', 1e-6 * Rtf_model.mean(), 'ms +/-',
      1e-6 * Rtf_model.std())
print('---------------------------------------------------')

fig, [ax, ax2] = plt.subplots(1, 2, figsize=(8, 3))
plt.subplots_adjust(bottom=.3, wspace=.4)
# histogram
# ax.hist(1e3*Rtf_data, color='r', label='data')
ax.hist(1e-6 * Rtf_model, color='b', label='model')
ax.legend(frameon=False, prop={'size': 'x-small'}, loc='best')
set_plot(ax,
         xlabel='transfer resistance \n to soma $(M \Omega)$',
         ylabel='cell #')
# correl Rm-Tm
ax2.plot(Rm_data, 1e-6 * Rtf_model, 'ob', label='model')
ax2.legend(prop={'size': 'xx-small'}, loc='best')
set_plot(ax2,
         xlabel='somatic input \n resistance $(M \Omega)$',
         ylabel='transfer resistance \n to soma $(M \Omega)$')
plt.show()