Beispiel #1
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)
Beispiel #2
0
def get_time_max(t, data, debug=False, Nsmooth=1):
    spatial_average = np.mean(data, axis=0)
    smoothed = gaussian_smoothing(spatial_average, Nsmooth)[:-int(Nsmooth)]
    i0 = np.argmax(smoothed)
    t0 = t[:-int(Nsmooth)][i0]
    if debug:
        plt.plot(t, spatial_average)
        plt.plot(t[:-int(Nsmooth)], smoothed)
        plt.plot([t0], [smoothed[i0]], 'D')
        show()
    return t0
Beispiel #3
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()
Beispiel #4
0
def get_stim_center(time,
                    space,
                    data,
                    Nsmooth=4,
                    debug=False,
                    tmax=0.,
                    window=100.):
    """ we smoothe the average over time and take the x position of max signal"""
    temporal_average = np.mean(\
                data[:,(time>tmax-window) & (time<tmax+window)], axis=1)
    smoothed = gaussian_smoothing(temporal_average, Nsmooth)[:-int(Nsmooth)]
    i0 = np.argmax(smoothed)
    x0 = space[:-int(Nsmooth)][i0]
    if debug:
        plt.plot(space, temporal_average)
        plt.plot(space[:-int(Nsmooth)], smoothed)
        plt.plot([x0], [smoothed[i0]], 'D')
        show()
    return x0
Beispiel #5
0
        description=""" 
     By default the scripts runs the single neuron response to a current step
     """,
        formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument('-n', "--NRN", help="NEURON TYPE", default='LIF')
    parser.add_argument('-a', "--amp",help="Amplitude of the current in pA",\
                        type=float, default=200.)
    parser.add_argument('-d', "--duration",help="Duration of the current step in ms",\
                        type=float, default=400.)
    parser.add_argument('-as', "--amplitudes",
                        help="ARRAY of Amplitude of different steps in pA",\
                        type=float, default=[], nargs='*')
    parser.add_argument('-ds', "--durations",
                        help="ARRAY of durations of different steps in ms",\
                        type=float, default=[], nargs='*')
    parser.add_argument('-dl', "--delay",help="Duration of the current step in ms",\
                        type=float, default=150.)
    parser.add_argument('-p', "--post",help="After-Pulse duration of the step (ms)",\
                        type=float, default=400.)
    parser.add_argument("-c", "--color", help="color of the plot", default='k')
    parser.add_argument("--save",
                        default='',
                        help="save the figures with a given string")
    parser.add_argument("-v", "--verbose", help="", action="store_true")
    args = parser.parse_args()

    from graphs.my_graph import set_plot, show
    from neural_network_dynamics.cells.pulse_protocols import current_pulse_sim
    current_pulse_sim(vars(args))
    show()
Beispiel #6
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 #7
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()