Пример #1
0
def _plot_power_each_mouse(res, figure_path, excitatory, valence):
    res[ykey_b] /= 100
    ax_lim = {'yticks': [0, .5, 1], 'ylim': [0, 1.05]}
    name_str = '_E' if excitatory else '_I'
    name_str += '_' + valence
    for mouse in np.unique(res['mouse']):
        path, name = plot.plot_results(res,
                                       x_key=xkey_b,
                                       y_key=ykey_b,
                                       loop_keys='mouse',
                                       select_dict={'mouse': mouse},
                                       plot_args=trace_args_bhv,
                                       path=figure_path,
                                       save=False,
                                       colors=['k'],
                                       ax_args=ax_lim)

        plot.plot_results(res,
                          x_key='trials',
                          y_key='power',
                          loop_keys='mouse',
                          select_dict={'mouse': mouse},
                          plot_args=trace_args,
                          path=figure_path,
                          reuse=True,
                          save=False,
                          colors=['k'],
                          ax_args=ax_lim)
        plt.gca().set_xlim(left=0)
        plt.gca().set_ylim(bottom=-0.05)
        plt.legend(['neural', 'behavior'], frameon=False, loc=0)
        plot._easy_save(path, name + name_str)
Пример #2
0
def _plot_power_statistics(res_, figure_path, excitatory, valence):
    name_str = '_E' if excitatory else '_I'
    name_str += '_' + valence

    _ = reduce.new_filter_reduce(res_,
                                 filter_keys=['mouse', 'odor_valence'],
                                 reduce_key='half_lick')
    res = reduce.new_filter_reduce(res_,
                                   filter_keys=['mouse', 'odor_valence'],
                                   reduce_key='half_power')
    res['half_lick'] = _['half_lick']
    from sklearn import linear_model
    from sklearn.metrics import mean_squared_error, r2_score
    regr = linear_model.LinearRegression()
    regr.fit(res['half_lick'].reshape(-1, 1), res['half_power'].reshape(-1, 1))

    y_pred = regr.predict(res['half_lick'].reshape(-1, 1))
    score = regr.score(res['half_lick'].reshape(-1, 1),
                       res['half_power'].reshape(-1, 1))

    lim = [10, 50]
    ax_lim = {'xlim': lim, 'ylim': lim}
    a, b = plot.plot_results(res,
                             x_key='half_lick',
                             y_key='half_power',
                             plot_args=scatter_args,
                             plot_function=plt.scatter,
                             path=figure_path,
                             save=False,
                             ax_args=ax_lim)

    plt.plot(lim, lim, '--', color='red', alpha=.5, linewidth=1)
    plt.text(25, lim[1], 'R = {:.2f}'.format(score), fontsize=5)
    plot._easy_save(a, b + name_str, pdf=True)
Пример #3
0
def _hist(res, save_path):
    ## distribution
    def histogram(real, label, bin, range, ax):
        density, bins = np.histogram(real, bins=bin, density=True, range=range)
        unity_density = density / density.sum()
        widths = bins[:-1] - bins[1:]
        ax.bar(bins[1:], unity_density, width=widths, alpha=.5, label=label)

    for mouse in np.unique(res['mouse']):
        pt_csp = filter.filter(res, {'mouse': mouse, 'odor_valence': 'PT CS+'})
        csp = filter.filter(res, {'mouse': mouse})
        csm = filter.filter(res, {'mouse': mouse})

        data = pt_csp['velocity']
        start = pt_csp['on'][0]
        end = pt_csp['end'][0]
        data_before = data[:, :start].flatten()
        data_during = data[:, start:end].flatten()
        data_after = data[:, end:].flatten()

        bins = 50
        range = [-70, 70]
        fig = plt.figure(figsize=(2, 1.5))
        ax = fig.add_axes([0.2, 0.2, 0.7, 0.7])
        histogram(data_before, 'before', bin=bins, range=range, ax=ax)
        histogram(data_during, 'during', bin=bins, range=range, ax=ax)
        plt.xlim([range[0] - 0.5, range[1] + .5])
        ax.spines["right"].set_visible(False)
        ax.spines["top"].set_visible(False)
        ax.xaxis.set_ticks_position('bottom')
        ax.yaxis.set_ticks_position('left')
        rs = ranksums(data_before, data_during)[-1]
        xlim = plt.xlim()
        ylim = plt.ylim()
        x = xlim[0] + .7 * (xlim[1] - xlim[0])
        y = ylim[0] + .7 * (ylim[1] - ylim[0])
        plot.significance_str(x, y, rs)
        name = 'before_during_mouse_{}'.format(mouse)
        plot._easy_save(save_path, name=name)

        fig = plt.figure(figsize=(2, 1.5))
        ax = fig.add_axes([0.2, 0.2, 0.7, 0.7])
        histogram(data_during, 'before', bin=bins, range=range, ax=ax)
        histogram(data_after, 'during', bin=bins, range=range, ax=ax)
        plt.xlim([range[0] - 0.5, range[1] + .5])
        ax.spines["right"].set_visible(False)
        ax.spines["top"].set_visible(False)
        ax.xaxis.set_ticks_position('bottom')
        ax.yaxis.set_ticks_position('left')
        rs = ranksums(data_during, data_after)[-1]
        xlim = plt.xlim()
        ylim = plt.ylim()
        x = xlim[0] + .7 * (xlim[1] - xlim[0])
        y = ylim[0] + .7 * (ylim[1] - ylim[0])
        plot.significance_str(x, y, rs)
        name = 'during_after_mouse_{}'.format(mouse)
        plot._easy_save(save_path, name=name)
Пример #4
0
def distribution_dff(res,
                     start_days,
                     end_days,
                     arg,
                     valence,
                     figure_path,
                     hist_range=(-.05, 1.2)):
    list_of_days = list(zip(start_days, end_days))
    res = filter.filter_days_per_mouse(res, days_per_mouse=list_of_days)
    res = filter.filter(res, {'odor_valence': valence})
    new = _compare_dff(res, loop_keys=['mouse', 'odor'], arg=arg)

    #
    def _helper(real, label, bin=20):
        density, bins = np.histogram(real,
                                     bins=bin,
                                     density=True,
                                     range=hist_range)
        unity_density = density / density.sum()
        widths = bins[:-1] - bins[1:]
        ax.bar(bins[1:], unity_density, width=widths, alpha=.5, label=label)

    fig = plt.figure(figsize=(2, 1.5))
    ax = fig.add_axes([0.2, 0.2, 0.7, 0.7])

    x = np.concatenate(new['day_0'])
    y = np.concatenate(new['day_1'])
    sr = wilcoxon(x, y)[-1]
    _helper(x, 'Before')
    _helper(y, 'After')

    ax.set_xlabel('Amplitude')
    ax.set_ylabel('Density')
    ax.spines["right"].set_visible(False)
    ax.spines["top"].set_visible(False)
    ax.xaxis.set_ticks_position('bottom')
    ax.yaxis.set_ticks_position('left')
    plt.legend(frameon=False)
    ylim = plt.ylim()
    xlim = plt.xlim()
    sig_str = plot.significance_str(x=(xlim[-1] - ylim[0]) * .7,
                                    y=.7 * (ylim[-1] - ylim[0]),
                                    val=sr)
    _easy_save(os.path.join(figure_path, 'dff_distribution'),
               valence,
               dpi=300,
               pdf=True)

    print('Before mean: {}'.format(np.mean(x)))
    print('After mean: {}'.format(np.mean(y)))
    print('wilcoxon: {}'.format(sr))
def _plot(x, y, z, xlim, ylim, xticks, yticks, name, color=True):
    fig = plt.figure(figsize=(3, 2))
    ax = fig.add_axes((.2, .2, .6, .6))
    if not color:
        z = np.ones_like(x)
    plt.scatter(x, y, c=z, s=3, edgecolor='')
    plt.xlabel(xname)
    plt.ylabel(yname)
    plt.xlim(xlim)
    plt.ylim(ylim)
    plt.xticks(xticks)
    plt.yticks(yticks)
    ax = plt.gca()
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.xaxis.set_ticks_position('bottom')
    ax.yaxis.set_ticks_position('left')
    folder = yname + '_vs_' + xname
    name = name

    #first method
    from sklearn.linear_model import LinearRegression
    x = x.reshape(-1, 1)
    y = y.reshape(-1, 1)
    model = LinearRegression().fit(x, y)
    r2 = model.score(x, y)
    slope = model.coef_[0][0]
    intercept = model.intercept_[0]
    y_pred = model.predict(x)

    # second method
    # slope, residual, _, _ = np.linalg.lstsq(x, y, rcond=-1)
    # slope = slope[0][0]
    # r2= 1 - residual[0] / (x.size * y.var())
    # intercept = 0
    # y_pred = slope * x

    plt.plot(x, y_pred, 'r-', linewidth=1, alpha=.7)

    xlim = plt.xlim()
    ylim = plt.ylim()
    plt.text(x=.1 * (xlim[-1] - xlim[0]),
             y=.8 * (ylim[-1] - ylim[0]),
             s='R = {0:.3f}'.format(r2))
    plt.title('$y= {0:.3f} x+{1:.2f}$'.format(slope, intercept))
    plot._easy_save(os.path.join(save_path, folder), name)
def _raw_plot(res, i):
    res = filter.filter(res, {'condition': 'Y'})
    print(res['mouse'][i])
    print(res['session'][i])
    a = res['bin_ir_raw'][i]
    b = res['bin_samp_raw'][i]
    x = res['bin_ant_raw'][i]

    data = np.concatenate([a, b, x], axis=1)

    fig = plt.figure(figsize=(3, 3))
    ax = fig.add_axes((.25, .25, .6, .6))
    plt.imshow(data, cmap='gray')
    xticks = [0, 120, 220, 300]
    xticklabels = ['Nosepoke', 'Odor', '1 S', 'US']
    plt.xticks(xticks, xticklabels)
    plt.xlim([120, 300])
    plt.xlabel('Time')
    plt.ylabel('Trial')
    plot._easy_save(path=os.path.join(save_path, 'example_licks'),
                    name='Y_{}'.format(i))
Пример #7
0
def behavior_vs_neural_onset(neural_res, behavior_res, start, end, figure_path, neural_arg ='onset', behavior_arg ='onset'):
    neural_key = 'neural'
    behavior_key = 'behavior'
    
    if behavior_arg == 'onset':
        behavior_data_key = 'time_first_lick_raw'
    elif behavior_arg == 'magnitude':
        behavior_data_key = 'lick_5s'
    elif behavior_arg == 'com':
        behavior_data_key = 'lick_com_raw'
    else:
        raise ValueError('bad key')
    
    if neural_arg == 'onset':
        neural_data_key = 'onset'
    elif neural_arg == 'magnitude':
        neural_data_key = 'dff'
    else:
        raise ValueError('bad key')
    
    list_of_days = [np.arange(s, e+1) for s, e in zip(start,end)]
    neural_res_filtered = filter.filter_days_per_mouse(neural_res, days_per_mouse=list_of_days)
    neural_res_filtered = filter.filter(neural_res_filtered, filter_dict={'odor_valence':'CS+'})
    behavior_res_filtered = filter.filter(behavior_res, filter_dict={'odor_valence':'CS+'})

    names_neu, ixs_neu = filter.retrieve_unique_entries(neural_res_filtered, ['mouse','day','odor_standard'])
    out = defaultdict(list)
    for ix, names in zip(ixs_neu, names_neu):
        mouse = names[0]
        day = names[1]
        odor_standard = names[2]

        assert len(ix) == 1
        neural = neural_res_filtered[neural_data_key][ix[0]]

        #test
        ixs = np.where(neural > -1)[0]
        for a in ixs:
            plt.plot(np.transpose(neural_res_filtered['data'][ix[0]][a]))
            plt.title(neural[a])
            plt.show()

        neural = neural[neural > -1] * .229



        temp = filter.filter(behavior_res_filtered, {'mouse': mouse, 'odor_standard': odor_standard})
        assert len(temp[behavior_data_key]) == 1
        ix_day = [x == day for x in temp['day'][0]]
        lick = temp[behavior_data_key][0][ix_day]
        lick = lick[lick>-1]

        out['mouse'].append(mouse)
        out['day'].append(day)
        out['odor_standard'].append(odor_standard)
        out[neural_key + neural_arg].append(np.mean(neural))
        out[behavior_key + behavior_arg].append(np.mean(lick))
        out['neural_raw'].append(neural)
        out['lick_raw'].append(lick)

    for k, v in out.items():
        out[k] = np.array(v)

    ## distribution
    def _helper(real, label, bin, range, ax):
        density, bins = np.histogram(real, bins=bin, density=True, range= range)
        unity_density = density / density.sum()
        widths = bins[:-1] - bins[1:]
        ax.bar(bins[1:], unity_density, width=widths, alpha=.5, label=label)

    all_neural = np.concatenate(out['neural_raw'])
    all_licks = np.concatenate(out['lick_raw'])
    bins = 20
    range = [0, 5]
    xticks = [0, 2, 5]
    xticklabels = ['Odor ON', 'Odor OFF', 'US']
    fig = plt.figure(figsize=(2, 1.5))
    ax = fig.add_axes([0.2, 0.2, 0.7, 0.7])
    _helper(all_neural, neural_key + neural_arg, bins, range, ax)
    _helper(all_licks, behavior_key + behavior_arg, bins, range, ax)
    plt.xticks(xticks, xticklabels)
    plt.xlim([range[0]-0.5, range[1] + .5])
    plt.ylabel('Density')
    ax.spines["right"].set_visible(False)
    ax.spines["top"].set_visible(False)
    ax.xaxis.set_ticks_position('bottom')
    ax.yaxis.set_ticks_position('left')
    folder = 'onset_distribution_lick_neural_'
    name = behavior_arg + '_' + ','.join([str(x) for x in start]) + '_' + ','.join([str(x) for x in end])
    plt.legend(frameon=False)
    _easy_save(os.path.join(figure_path, folder), name, dpi=300, pdf=True)

    print('lick mean: {}'.format(np.mean(all_licks)))
    print('neural mean: {}'.format(np.mean(all_neural)))

    ## versus
    if behavior_arg in ['onset', 'com']:
        xlim = [0, 5]
        xticks = [0, 2, 5]
        xticklabels = ['ON','OFF', 'US']
    else:
        xlim = [0, 35]
        xticks = [0, 10, 20, 30]
        xticklabels = [0, 10, 20, 30]

    ax_args = {'xlim':xlim, 'ylim':[0, 3.5], 'xticks':xticks, 'yticks':[0, 2, 5],
               'xticklabels':xticklabels, 'yticklabels': ['ON','OFF','US']}
    path, name = plot.plot_results(out, x_key=behavior_key + behavior_arg, y_key=neural_key + neural_arg, loop_keys='mouse',
                      plot_function=plt.scatter,
                      plot_args= scatter_args,
                                   ax_args=ax_args,
                                   colormap='jet',
                      path = figure_path,
                      save=False)

    from sklearn import linear_model
    from sklearn.metrics import mean_squared_error, r2_score
    scores = []
    for mouse in np.unique(out['mouse']):
        res = filter.filter(out, {'mouse':mouse})
        regr = linear_model.LinearRegression()
        x = res[behavior_key + behavior_arg].reshape(-1,1)
        y = res[neural_key + neural_arg].reshape(-1,1)
        regr.fit(x, y)

        y_pred = regr.predict(x)
        score = regr.score(x, y)
        scores.append(score)

    print('average regression: {}'.format(np.mean(scores)))

    xlim = plt.xlim()
    ylim = plt.ylim()
    plt.text((xlim[1] - xlim[0])/2, ylim[1]-.5, 'Average R = {:.2f}'.format(np.mean(scores)))
    name += '_' + behavior_arg
    plot._easy_save(path, name)
Пример #8
0
            if condition == 'H':
                color = color_dict[phase]

            fp = plot.plot_results(res, x_key='trials', y_key=y_key_bool,
                              select_dict={'phase_odor_valence': phase, 'condition':'H'},
                              ax_args=ax_args_bool_cur, plot_args=trace_args_copy,
                              colors=color,
                              save=False,
                              path=save_path)


            c = behavior.behavior_config.behaviorConfig()
            y = c.fully_learned_threshold_up / 100.
            plt.plot(plt.xlim(), [y, y], '--', color='gray', linewidth=.5)

            plot._easy_save(fp[0],fp[1],pdf=True)


            fp = plot.plot_results(res, x_key='trials', y_key=y_key,
                              select_dict={'phase_odor_valence': phase, 'condition':'H'},
                              ax_args=ax_args_cur, plot_args=trace_args_copy,
                              colors=color,
                              save=False,
                              path=save_path)

            c = behavior.behavior_config.behaviorConfig()
            y = c.fully_learned_threshold_up / 100.
            plt.plot(plt.xlim(), [y, y], '--', color='gray', linewidth=.5)

            plot._easy_save(fp[0], fp[1], pdf=True)
                                       ax_args=ax_args_pt_,
                                       plot_function= sns.stripplot,
                                       plot_args= swarm_args_copy,
                                       sort=True,
                                       fig_size=[1.5, 1.5], rect=(.3, .2, .6, .6),
                                       path=save_path_all, reuse=False, save=False)

        plot.plot_results(mean_std_res, x_key=collapse_arg, y_key= reduce_key, error_key= reduce_key + '_sem',
                          select_dict={'condition': 'CHANNEL'},
                          ax_args=ax_args_pt_,
                          plot_function= plt.errorbar,
                          plot_args= error_args,
                          fig_size=[2, 1.5],
                          path=save_path_all, reuse=True, save=False)
        plt.xlim(-.1, .1)
        plot._easy_save(path, name, pdf=True)

    #stats
    print(mean_std_res[x_key])
    print(mean_std_res[reduce_key])
    print(mean_std_res[reduce_key + '_sem'])

if 'summary' in experiments:
    all_res = filter.filter(all_res, {'odor_valence':['CS+','CS-', 'PT CS+']})
    all_res_lick = reduce.new_filter_reduce(all_res, filter_keys=['condition', 'odor_valence','mouse'],
                                            reduce_key=lick_smoothed)
    all_res_bool = reduce.new_filter_reduce(all_res, filter_keys=['condition', 'odor_valence','mouse'],
                                            reduce_key=boolean_smoothed)

    line_args_copy = line_args.copy()
    line_args_copy.update({'marker': None, 'linewidth':.75})
Пример #10
0
def compare_to_shuffle(res, start, end, data_arg, figure_path):
    '''

    :param res:
    :param start:
    :param end:
    :param data_arg: 'onset', 'duration', 'amplitude'
    :param figure_path:
    :return:
    '''
    n_shuffle = 1000

    list_of_days = [np.arange(s, e+1) for s, e in zip(start,end)]
    res_ = filter.filter_days_per_mouse(res, days_per_mouse=list_of_days)
    res_ = filter.filter(res_, filter_dict={'odor_valence':'CS+'})
    mice = np.unique(res_['mouse'])

    real = []
    shuffled = []
    for mouse in mice:
        res_mouse_ = filter.filter(res_, {'mouse': mouse})
        days = np.unique(res_mouse_['day'])
        for day in days:
            res_mouse_day = filter.filter(res_mouse_, {'day': day})

            assert res_mouse_day['onset'].size == 2, 'should be two entries corresponding to two CS+ per mouse'
            a = res_mouse_day[data_arg][0]
            b = res_mouse_day[data_arg][1]
            responsive_to_both = np.array([x>-1 and y>-1 for x, y in zip(a,b)])
            a_ = a[responsive_to_both]
            b_ = b[responsive_to_both]
            real_diff = np.abs(a_ - b_)
            real.append(real_diff)

            for n in range(n_shuffle):
                a_shuffled = np.random.permutation(a_)
                b_shuffled = np.random.permutation(b_)
                shuffled_diff = np.abs(a_shuffled - b_shuffled)
                shuffled.append(shuffled_diff)

    flatten = lambda l: [item for sublist in l for item in sublist]
    real = np.array(flatten(real), dtype=float)
    shuffled = np.array(flatten(shuffled), dtype=float)

    bin = 20
    if data_arg == 'amplitude':
        xlim = 1
        hist_range = 1
    else:
        period = .229
        xlim = np.ceil(bin * period)
        hist_range = bin * period
        real *= period
        shuffled *= period

    p = scipy.stats.ranksums(real, shuffled)[1]

    fig = plt.figure(figsize=(2, 1.5))
    ax = fig.add_axes([0.25, 0.25, 0.7, 0.7])

    def _helper(real, label):
        density, bins = np.histogram(real, bins=bin, density=True, range=[0, hist_range])
        unity_density = density / density.sum()
        widths = bins[:-1] - bins[1:]
        ax.bar(bins[1:], unity_density, width=widths, alpha = .5, label=label)

    _helper(real, 'Within Neurons')
    _helper(shuffled, 'Shuffled')

    ax.legend(frameon=False)
    ax.set_xlabel((r'$\Delta$' + ' ' + data_arg.capitalize()))
    ax.set_ylabel('Density')
    plt.xlim([0, xlim])

    # xticks = np.arange(xlim)
    # ax.set_xticks(xticks)
    # ax.set_xticklabels(xticks)
    # yticks = np.array([0, .5, 1])
    # ax.set_yticks(yticks)
    # plt.ylim([0, 1])

    ylim = ax.get_ylim()
    xlim = ax.get_xlim()
    x = (xlim[1] - xlim[0])/2
    y = (ylim[1] - ylim[0])/2
    t = 'P = {:.3e}'.format(p)
    plt.text(x, y, t)

    ax.spines["right"].set_visible(False)
    ax.spines["top"].set_visible(False)
    ax.xaxis.set_ticks_position('bottom')
    ax.yaxis.set_ticks_position('left')
    _easy_save(os.path.join(figure_path, data_arg), 'difference_' + data_arg, dpi=300, pdf=True)

    print('real mean: {}'.format(np.mean(real)))
    print('shuffled mean: {}'.format(np.mean(shuffled)))
    print('ranksum: {}'.format(t))
Пример #11
0
    ax.spines[loc].set_visible(False)
ax.tick_params('both', length=0)
xticks = np.arange(0, im.shape[1]) + .5
yticks = np.arange(0, im.shape[0]) + .5
ax.set_xticks(xticks)
ax.set_yticks(yticks[::-1])
ax.set_xticklabels((xticks + .5).astype(int), fontsize=7)
ax.set_yticklabels((yticks + .5).astype(int), fontsize=7)

ax = fig.add_axes(rect_cb)
cb = plt.colorbar(cax=ax, ticks=np.arange(vmin, vmax + 0.01, 0.1))
cb.outline.set_linewidth(0.5)
cb.set_label('Correlation', fontsize=7, labelpad=2)
plt.tick_params(axis='both', which='major', labelsize=7)
plt.axis('tight')
plot._easy_save(os.path.join(save_path, 'matrix', mouse), 'across_correlation_matrix')

res = filter.exclude(res, {'mouse':'M241_ofc'})
list = ['PIR','OFC','OFC_LONGTERM','OFC_COMPOSITE','MPFC_COMPOSITE']
scatter_args = {'marker':'.', 's':8, 'alpha': .5}
error_args = {'fmt': '', 'capsize': 2, 'elinewidth': 1, 'markersize': 2, 'alpha': .5}
reduce_keys = ['within_day_crisp_average', 'across_day_mean_corrs_average']
xkey = 'experiment'
for reduce_key in reduce_keys:
    res_reduce = reduce.new_filter_reduce(res, filter_keys=['experiment'], reduce_key= reduce_key)

    for i, element in enumerate(list):
        reuse = True if i > 0 else False
        save = False if i != len(list)-1 else True
        plot.plot_results(res, x_key=xkey, y_key= reduce_key,
                          select_dict={xkey:element},
Пример #12
0
def plot_compare_dff(res,
                     start_days,
                     end_days,
                     arg,
                     valence,
                     more_stats,
                     figure_path,
                     lim=(-.05, 1.2),
                     ticks=(0, .5, 1)):
    list_of_days = list(zip(start_days, end_days))
    res = filter.filter_days_per_mouse(res, days_per_mouse=list_of_days)
    res = filter.filter(res, {'odor_valence': valence})
    new = _compare_dff(res, loop_keys=['mouse', 'odor'], arg=arg)

    #analysis
    xs, ys = new['day_0'], new['day_1']
    a, b = [], []
    for x, y in zip(xs, ys):
        a.append(np.sum(x > y))
        b.append(np.sum(y > x))
    fraction = np.sum(a) / (np.sum(a) + np.sum(b))

    ax_args_copy = {}
    ax_args_copy.update({
        'ylim': lim,
        'xlim': lim,
        'yticks': ticks,
        'xticks': ticks
    })
    scatter_args_copy = scatter_args.copy()
    scatter_args_copy.update({
        'marker': ',',
        's': 1,
        'alpha': .2,
        'facecolors': 'none'
    })

    colors = ['Black']
    # if valence == 'CS+':
    #     colors = ['Green']
    # if valence == 'CS-':
    #     colors = ['darkred']
    colors *= 300
    path, name = plot.plot_results(new,
                                   select_dict={'odor_valence': valence},
                                   x_key='day_0',
                                   y_key='day_1',
                                   loop_keys=['mouse', 'odor'],
                                   path=figure_path,
                                   plot_args=scatter_args_copy,
                                   ax_args=ax_args_copy,
                                   plot_function=plt.scatter,
                                   colors=colors,
                                   legend=False,
                                   fig_size=(2, 1.5),
                                   rect=(.25, .25, .6, .6),
                                   save=False)
    plt.xlim(lim)
    plt.ylim(lim)
    plt.plot(lim, lim, '--', color='red', alpha=.5, linewidth=1)
    plt.title(valence)
    if valence == 'CS+':
        plt.text(0,
                 lim[1] - .1,
                 '{:.1f}% diminished'.format(fraction * 100),
                 fontsize=5)
    if valence == 'CS-':
        plt.text(0,
                 lim[1] - .1,
                 '{:.1f}% increased'.format(100 - fraction * 100),
                 fontsize=5)

    if more_stats:
        new = _compare_dff(res, loop_keys=['mouse', 'odor'], arg='first')
        new = filter.filter(new, {'odor_valence': valence})
        xs, ys = new['day_0'], new['day_1']
        a, b, c = [], [], []
        for x, y in zip(xs, ys):
            a.append(np.sum(x > y))
            b.append(np.sum(y > x))
            c.append(np.sum(y < 0.1))
        lost_fraction = np.sum(c) / (np.sum(a) + np.sum(b))
        plt.text(0,
                 lim[1] - .2,
                 'Of those, {:.1f}% are unresponsive'.format(100 *
                                                             lost_fraction),
                 fontsize=5)
    _easy_save(path, name, pdf=True)
Пример #13
0
    plt.xticks(xticks, '')
    plt.yticks([])
    plt.tick_params(direction='out', length=2, width=.5, grid_alpha=0.5)

    for line in condition_lines:
        plt.plot([line, line], plt.ylim(), '--', color='grey', linewidth=.5)

    for line in xticks:
        plt.plot([line, line], plt.ylim(), '--', color='grey', linewidth=.25, alpha=0.5)


    titles = ['Naive','Learned']
    for j, x in enumerate(odor_on_lines):
        plt.text(x, -1, titles[j])
    plt.title(odor.upper())

    ax = fig.add_axes(rect_cb)
    cb = plt.colorbar(cax=ax, ticks=[-condition_config.vlim, condition_config.vlim])
    cb.outline.set_linewidth(0.5)
    cb.set_label(r'$\Delta$ F/F', fontsize=7, labelpad=-10)
    plt.tick_params(axis='both', which='major', labelsize=7)

    plot._easy_save(save_path,
                    'mouse_' + str(mouse) +
                    '_day_' + str(days) +
                    '_odor_' + str(odor))



Пример #14
0
def plotter(image,
            odor_on,
            water_on,
            odor_names,
            condition_config,
            save_path,
            name_str=''):
    if black:
        plt.style.use('dark_background')

    frames_per_trial = 75

    titles = odor_names
    n_plots = int(image.shape[1] / frames_per_trial)

    fig = plt.figure(figsize=(3.5, 3))
    fig_width = .14 * n_plots
    rect = [.1, .1, fig_width, .7]
    rect_cb = [fig_width + .1 + .02, 0.1, 0.02, .7]
    ax = fig.add_axes(rect)

    if black:
        from matplotlib.colors import LinearSegmentedColormap
        cdict1 = {
            'red': ((0.0, 0.0, 0.0), (0.5, 0.0, 0.1), (1.0, 1.0, 1.0)),
            'green': ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0)),
            'blue': ((0.0, 0.0, 0.55), (0.5, 0.1, 0.0), (1.0, 0.0, 0.0))
        }
        cmap = LinearSegmentedColormap('BlueRed1', cdict1)
        cmap = LinearSegmentedColormap.from_list("",
                                                 ["turquoise", "black", "red"])

        ax.spines['top'].set_visible(False)
        ax.spines['right'].set_visible(False)
        ax.spines['bottom'].set_visible(False)
        ax.spines['left'].set_visible(False)
        ax.tick_params(axis=u'both', which=u'both', length=0)
    else:
        cmap = 'bwr'
        plt.tick_params(direction='out', length=2, width=.5, grid_alpha=0.5)

    plt.imshow(image,
               vmin=-condition_config.vlim,
               vmax=condition_config.vlim,
               cmap=cmap)
    plt.axis('tight')

    ax.xaxis.set_ticks_position('bottom')
    ax.yaxis.set_ticks_position('left')

    condition_lines = np.cumsum([frames_per_trial] * n_plots)[:-1]
    odor_on_lines_raw = np.arange(odor_on, frames_per_trial * n_plots,
                                  frames_per_trial)
    water_on_lines = np.arange(water_on, frames_per_trial * n_plots,
                               frames_per_trial)
    if 'water' in titles:
        water_on_lines = water_on_lines[[0, 1, 4]]
        # water_on_lines = water_on_lines[[2, 3, 4]]
        odor_on_lines = odor_on_lines_raw[:-1]
    else:
        if condition_config.period == 'pt':
            odor_on_lines = odor_on_lines_raw
        else:
            if condition_config.filter_ix is None:
                water_on_lines = water_on_lines[:2]
                # water_on_lines = water_on_lines[2:]
            else:
                water_on_lines = water_on_lines[[0]]
            odor_on_lines = odor_on_lines_raw

    if not naive:
        xticks = np.concatenate(
            (odor_on_lines, odor_on_lines + 8, water_on_lines))
        xticklabels = ['ON'] * len(odor_on_lines) + ['OFF'] * len(
            odor_on_lines) + ['US'] * len(water_on_lines)
    else:
        xticks = np.concatenate((odor_on_lines, odor_on_lines + 8))
        xticklabels = ['ON'] * len(odor_on_lines) + ['OFF'
                                                     ] * len(odor_on_lines)

    plt.xticks(xticks, xticklabels, fontsize=5)
    range = image.shape[0]
    if range > 100:
        interval = 50
    else:
        interval = 25
    plt.yticks(np.arange(0, range, interval))

    for line in xticks:
        plt.plot([line, line],
                 plt.ylim(),
                 '--',
                 color='grey',
                 linewidth=.5,
                 alpha=0.5)

    for line in condition_lines:
        plt.plot([line, line],
                 plt.ylim(),
                 '--',
                 color='grey',
                 linewidth=.75,
                 alpha=1)

    for j, x in enumerate(odor_on_lines_raw):
        plt.text(x, -1, titles[j].upper())

    axcb = fig.add_axes(rect_cb)
    cb = plt.colorbar(cax=axcb,
                      ticks=[-condition_config.vlim, condition_config.vlim])

    if black:
        cb.outline.set_visible(False)
        cb.set_ticks([])
    else:
        cb.outline.set_linewidth(0.5)
        cb.set_label(r'$\Delta$ F/F', fontsize=7, labelpad=-10)

    plt.tick_params(axis='both', which='major', labelsize=7)

    name_black = '_black' if black else ''
    if condition_config.plot_big:
        name = 'big_mouse_' + ','.join(
            [str(x) for x in condition_config.plot_big_days])
        name += '_sorted_to_' + ','.join(
            [str(x) for x in condition_config.sort_days])
        name += name_black
    else:
        name = 'mouse_' + str(mouse) + name_str
        if not condition_config.independent_sort:
            name += '_sorted_to_' + str(condition_config.sort_days)

    if condition_config.filter_ix is not None:
        name += '_odor_' + str(condition_config.filter_ix)

    plt.sca(ax)
    # plt.title(name)
    plot._easy_save(save_path, name)
                                       plot_args=scatter_args_copy,
                                       ax_args=ax_args_local,
                                       colors=color,
                                       save=False,
                                       path=save_path)
        plt.plot([0, 5], [0, 5], '--', color='gray')

        try:
            stat_res = filter.filter(res_use, {'odor_valence': valence})
            a, b = stat_res[before_key], stat_res[after_key]
            stat = wilcoxon(a, b)
            ylim = plt.gca().get_ylim()
            sig_str = plot.significance_str(x=.4,
                                            y=.7 * (ylim[-1] - ylim[0]),
                                            val=stat[-1])
            plot._easy_save(path, name)
            print('Before: {}, After: {}'.format(np.mean(a), np.mean(b)))
            print(stat)
        except:
            print('no stats')

if 'summary_mouse_line' in experiments:
    _collapse_conditions(all_res, control_condition='YFP', str=collapse_arg)
    ykey = reduce_key_raw + '_mean'
    for i, v in enumerate(all_res[reduce_key_raw]):
        all_res[ykey].append(np.mean(v[v > 0]))
    all_res[ykey] = np.array(all_res[ykey])

    res_modified = reduce.new_filter_reduce(
        all_res,
        filter_keys=['condition', 'mouse', 'odor_valence'],
Пример #16
0
def plot_stability_across_days(res, start_days_per_mouse, learned_days_per_mouse, figure_path):
    strengthen_starting_threshold = .1
    strengthen_absolute_threshold = .2
    strengthen_relative_threshold = 2
    weaken_starting_threshold = .3
    weaken_absolute_threshold = .15
    weaken_relative_threshold = .5

    res = copy.copy(res)
    res = filter.filter(res, {'odor_valence':['CS+', 'CS-']})
    list_odor_on = res['DAQ_O_ON_F']
    list_water_on = res['DAQ_W_ON_F']
    for i in range(len(list_odor_on)):
        dff_list = res['dff'][i]
        dff_max = np.max(dff_list[:,list_odor_on[i]: list_water_on[i]],axis=1)
        res['dff_max'].append(dff_max)
    res['dff_max'] = np.array(res['dff_max'])

    out = defaultdict(list)
    combinations, ixs = filter.retrieve_unique_entries(res, ['mouse','odor'])
    for combination, ix in zip(combinations, ixs):
        odor_valence = np.unique(res['odor_valence'][ix])
        mouse = np.unique(res['mouse'][ix])
        days = res['day'][ix]
        assert len(days) == len(np.unique(days))
        assert len(mouse) == 1
        sort_ix = np.argsort(days)
        list_of_dff_max = res['dff_max'][ix][sort_ix]
        list_of_ssig = res['sig'][ix][sort_ix]
        data = [x * y for x, y in zip(list_of_ssig, list_of_dff_max)]
        data = np.array(data)

        strengthen_mask = data[0,:] > strengthen_starting_threshold
        strengthen_overall_threshold = np.max((data[0,:] * strengthen_relative_threshold, data[0,:] + strengthen_absolute_threshold), axis=0)
        strengthen_passed_mask = strengthen_overall_threshold < data
        strengthen_any = np.any(strengthen_passed_mask[1:,:], axis=0)
        n_strengthen_passed = np.sum(strengthen_any * strengthen_mask)
        n_strengthen_denom = np.sum(strengthen_mask)

        new_mask = np.invert(strengthen_mask)
        n_new_passed = np.sum(strengthen_any * new_mask)
        n_new_denom = np.sum(new_mask)

        weaken_mask = data[0,:] > weaken_starting_threshold
        weaken_overall_threshold = np.min((data[0,:] * weaken_relative_threshold, data[0,:] - weaken_absolute_threshold), axis=0)
        weaken_passed_mask = weaken_overall_threshold > data
        weaken_any = np.any(weaken_passed_mask[1:,:], axis=0)
        n_weaken_passed = np.sum(weaken_any * weaken_mask)
        n_weaken_denom = np.sum(weaken_mask)

        strs = ['strengthen_denom', 'strengthen_pass', 'new_denom', 'new_pass','weaken_denom','weaken_pass']
        vals = [n_strengthen_denom, n_strengthen_passed, n_new_denom, n_new_passed, n_weaken_denom, n_weaken_passed]

        for k, v in zip(strs,vals):
            out['Type'].append(k)
            out['Count'].append(v)
            out['mouse'].append(mouse[0])
            out['odor_valence'].append(odor_valence[0])
    for k, v in out.items():
        out[k] = np.array(v)

    def _helper(res):
        out = defaultdict(list)
        strs = [['strengthen_denom', 'strengthen_pass'], ['new_denom', 'new_pass'], ['weaken_denom', 'weaken_pass']]
        out_strs = ['up', 'new', 'down']
        for i, keys in enumerate(strs):
            ix_denom = res['Type'] == keys[0]
            ix_numer = res['Type'] == keys[1]
            numer = np.sum(res['Count'][ix_numer])
            denom = np.sum(res['Count'][ix_denom])
            fraction =  numer/ denom
            out['Type'].append(out_strs[i])
            out['Fraction'].append(fraction)
            out['numer'].append(numer)
            out['denom'].append(denom)
        for k, v in out.items():
            out[k] = np.array(v)
        return out

    ax_args_copy = ax_args.copy()
    ax_args_copy.update({'ylim':[0, 0.5], 'yticks':[0, .1, .2, .3, .4, .5]})
    overall = copy.copy(out)
    csm_res = filter.filter(overall, {'odor_valence':'CS-'})
    csp_res = filter.filter(overall, {'odor_valence':'CS+'})

    csp_stats = _helper(csp_res)
    csp_stats['Condition'] = np.array(['CS+'] * len(csp_stats['Type']))
    csm_stats = _helper(csm_res)
    csm_stats['Condition'] = np.array(['CS-'] * len(csm_stats['Type']))
    overall_stats = reduce.chain_defaultdicts(csp_stats, csm_stats, copy_dict=True)
    filter.assign_composite(overall_stats, ['Type', 'Condition'])

    bar_args = {'alpha': 1, 'edgecolor':'black','linewidth':1}
    colors = ['Green','Red']
    save_path, name = plot.plot_results(overall_stats, x_key='Type_Condition', y_key='Fraction', sort=True,
                                        colors=colors,
                                        path=figure_path,
                                        plot_function=plt.bar, plot_args=bar_args, ax_args=ax_args_copy,
                                        save=False, reuse=False)

    strs = ['down','new','up']
    fontsize = 4
    for i in range(3):
        ix = csp_stats['Type'] == strs[i]
        numer = csp_stats['numer'][ix][0]
        denom = csp_stats['denom'][ix][0]

        x = i * 2
        y = numer/denom
        y_offset = .025
        plt.text(x, y + y_offset, str(numer) + '/' + str(denom), horizontalalignment = 'center', fontsize= fontsize)

    strs = ['down','new','up']
    for i in range(3):
        ix = csm_stats['Type'] == strs[i]
        numer = csm_stats['numer'][ix][0]
        denom = csm_stats['denom'][ix][0]

        x = i * 2 + 1
        y = numer/denom
        y_offset = .025
        plt.text(x, y + y_offset, str(numer) + '/' + str(denom), horizontalalignment = 'center', fontsize= fontsize)
    plot._easy_save(save_path, name, pdf=True)

    overall_stats_no_distinction = _helper(overall)
    save_path, name = plot.plot_results(overall_stats_no_distinction, x_key='Type', y_key='Fraction', sort=True,
                      colors=['Grey']*10,
                      path=figure_path,
                      plot_function=plt.bar, plot_args=bar_args, ax_args=ax_args_copy,
                      save=False, reuse=False)
    strs = ['down','new','up']
    for i in range(3):
        ix = overall_stats_no_distinction['Type'] == strs[i]
        numer = overall_stats_no_distinction['numer'][ix][0]
        denom = overall_stats_no_distinction['denom'][ix][0]

        x = i
        y = numer/denom
        y_offset = .025
        plt.text(x, y + y_offset, str(numer) + '/' + str(denom), horizontalalignment = 'center', fontsize= fontsize)
    plot._easy_save(save_path, name, pdf=True)
Пример #17
0
plt.axis('tight')
for loc in ['top', 'right']:
    ax.spines[loc].set_visible(False)
ax.tick_params('in', length=0.25)

cmap = mpl.cm.cool
norm = mpl.colors.Normalize(vmin=min, vmax=max)
cb = mpl.colorbar.ColorbarBase(ax1, cmap=cmap, norm=norm)
cb.set_ticks(np.arange(min, max + .01, .1))
cb.outline.set_linewidth(0.5)
cb.set_label('AP', fontsize=7, labelpad=5)
plt.tick_params(axis='both', which='major', labelsize=7)
plt.axis('tight')

save_path = os.path.join(Config.LOCAL_FIGURE_PATH, 'MISC', 'HISTOLOGY')
plot._easy_save(save_path, arg_type + '_' + arg)

if arg == 'OUTPUT':
    min, max = 1.0, 1.8
    ylim = [-5, -3]
    yticks = [-3, -4, -5]
    xlim = [0, 4]
    xticks = [0, 1, 2, 3, 4]

    for i, d in enumerate(res['coordinates virus (AP, ML, DV)']):
        try:
            numbers = _string_splitter(d, length=length)
            res['ap_r_v'].append(numbers[0])
            res['ml_r_v'].append(numbers[1])
            res['dv_r_v'].append(numbers[2])
        except:
                     color='turquoise')
            xticks = [water_on]
            xticklabels = ['US']
        else:
            raise ValueError('unrecognized odor valence for plotting')

        if valence != 'US':
            color = odor_dict[odor_standard_names[i]]
            plt.fill_between([odor_on, odor_off],
                             cumsum[i] - .5,
                             cumsum[i + 1] - .5,
                             alpha=.7,
                             facecolor=color)
            plt.text(0, (cumsum[i + 1] - cumsum[i]) / 2 + cumsum[i],
                     odor_standard_names[i])
    # plt.xticks(xticks, xticklabels)
    plt.title('Day {}'.format(day))
    plt.xticks([])
    plt.yticks([])
    ax = plt.gca()
    ax.spines['top'].set_visible(False)
    ax.spines['bottom'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.spines['left'].set_visible(False)
    ax.xaxis.set_ticks_position('bottom')
    ax.yaxis.set_ticks_position('left')

    plot._easy_save(save_path,
                    'across_day_mouse_{}_day_{}'.format(mouse, day),
                    dpi=1000)
Пример #19
0
def behavior_vs_neural_power(neural_res, behavior_res, start, end, figure_path, neural_arg ='power', behavior_arg ='onset'):
    neural_res = copy.copy(neural_res)

    neural_key = 'neural'
    behavior_key = 'behavior'
    if behavior_arg == 'onset':
        behavior_data_key = 'time_first_lick_raw'
    elif behavior_arg == 'magnitude':
        behavior_data_key = 'lick_5s'
    elif behavior_arg == 'com':
        behavior_data_key = 'lick_com_raw'
    else:
        raise ValueError('bad key')
    neural_data_key = 'max_power'

    _power(neural_res, excitatory=True)
    for i, p in enumerate(neural_res['Power']):
        s, e = neural_res['DAQ_O_ON_F'][i], neural_res['DAQ_W_ON_F'][i]
        mp = np.max(p[s:e]) - np.mean(p[:s])
        neural_res[neural_data_key].append(mp)
    neural_res[neural_data_key] = np.array(neural_res[neural_data_key])

    list_of_days = [np.arange(s, e+1) for s, e in zip(start,end)]
    print(list_of_days)
    neural_res_filtered = filter.filter_days_per_mouse(neural_res, days_per_mouse=list_of_days)
    neural_res_filtered = filter.filter(neural_res_filtered, filter_dict={'odor_valence':'CS+'})
    behavior_res_filtered = filter.filter(behavior_res, filter_dict={'odor_valence':'CS+'})

    names_neu, ixs_neu = filter.retrieve_unique_entries(neural_res_filtered, ['mouse','day','odor_standard'])
    out = defaultdict(list)
    for ix, names in zip(ixs_neu, names_neu):
        mouse = names[0]
        day = names[1]
        odor_standard = names[2]

        assert len(ix) == 1
        neural = neural_res_filtered[neural_data_key][ix[0]]

        temp = filter.filter(behavior_res_filtered, {'mouse': mouse, 'odor_standard': odor_standard})
        assert len(temp[behavior_data_key]) == 1
        ix_day = [x == day for x in temp['day'][0]]
        lick = temp[behavior_data_key][0][ix_day]
        lick = lick[lick>-1]

        out['mouse'].append(mouse)
        out['day'].append(day)
        out['odor_standard'].append(odor_standard)
        out[neural_key + neural_arg].append(np.mean(neural))
        out[behavior_key + behavior_arg].append(np.mean(lick))
        out['neural_raw'].append(neural)
        out['lick_raw'].append(lick)

    for k, v in out.items():
        out[k] = np.array(v)

    ## versus
    if behavior_arg in ['onset', 'com']:
        xlim = [0, 5]
        xticks = [0, 2, 5]
        xticklabels = ['ON', 'OFF', 'US']
    else:
        xlim = [0, 35]
        xticks = [0, 10, 20, 30]
        xticklabels = [0, 10, 20, 30]

    ax_args = {'xlim': xlim, 'ylim': [0, .1], 'xticks': xticks, 'yticks': [0, .05, .1],
               'xticklabels': xticklabels}
    path, name = plot.plot_results(out, x_key=behavior_key + behavior_arg, y_key=neural_key + neural_arg,
                                   loop_keys='mouse',
                                   plot_function=plt.scatter,
                                   plot_args=scatter_args,
                                   ax_args=ax_args,
                                   colormap='jet',
                                   path=figure_path,
                                   save=False)

    from sklearn import linear_model
    from sklearn.metrics import mean_squared_error, r2_score
    scores = []
    for mouse in np.unique(out['mouse']):
        res = filter.filter(out, {'mouse':mouse})
        regr = linear_model.LinearRegression()
        x = res[behavior_key + behavior_arg].reshape(-1,1)
        y = res[neural_key + neural_arg].reshape(-1,1)
        regr.fit(x, y)

        y_pred = regr.predict(x)
        score = regr.score(x, y)
        scores.append(score)

    print('regression: {}'.format(scores))

    xlim = plt.xlim()
    ylim = plt.ylim()
    plt.text((xlim[1] - xlim[0])/2, ylim[1]-.01, 'Average R = {:.2f}'.format(np.mean(scores)))
    name += '_' + behavior_arg
    plot._easy_save(path, name)
Пример #20
0
        plt.plot([water_on, water_on],
                 ylim,
                 '-',
                 linewidth=1,
                 color='turquoise')
        xticks = [water_on]
        xticklabels = ['US']
    else:
        raise ValueError('unrecognized odor valence for plotting')

    if odor_res['odor_valence'][0] != 'US':
        plt.fill_between([odor_on, odor_off],
                         ylim[0],
                         ylim[1],
                         alpha=.7,
                         facecolor=color)

    # plt.xticks(xticks, xticklabels)
    plt.xticks([])
    plt.yticks([])
    plt.title(odor_name.upper())

    ax = plt.gca()
    ax.spines['top'].set_visible(False)
    ax.spines['bottom'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.spines['left'].set_visible(False)
    ax.xaxis.set_ticks_position('bottom')
    ax.yaxis.set_ticks_position('left')
    plot._easy_save(save_path, str(mouse) + '_' + odor_standard)
Пример #21
0
def distribution(res, start, end, data_arg, figure_path, save):
    list_of_days = [np.arange(s, e+1) for s, e in zip(start,end)]
    res_ = filter.filter_days_per_mouse(res, days_per_mouse=list_of_days)
    res_ = filter.filter(res_, filter_dict={'odor_valence':'CS+'})
    mice = np.unique(res_['mouse'])

    real = []
    for mouse in mice:
        res_mouse_ = filter.filter(res_, {'mouse': mouse})
        days = np.unique(res_mouse_['day'])
        for day in days:
            res_mouse_day = filter.filter(res_mouse_, {'day': day})
            assert res_mouse_day['onset'].size == 2, 'should be two entries corresponding to two CS+ per mouse'
            a = res_mouse_day[data_arg][0]
            b = res_mouse_day[data_arg][1]
            a = a[a>-1]
            b = b[b>-1]
            real.append(a)
            real.append(b)

    flatten = lambda l: [item for sublist in l for item in sublist]
    real = np.array(flatten(real), dtype=float)
    print('Number of points: {}'.format(real.shape))

    bin = 20
    if data_arg == 'amplitude':
        xlim = 1.5
        hist_range = 1.5
    else:
        period = .229
        xlim = np.ceil(bin * period)
        hist_range = bin * period
        real *= period

    if not save:
        fig = plt.figure(figsize=(2, 1.5))
        ax = fig.add_axes([0.2, 0.2, 0.7, 0.7])
    else:
        ax = plt.gca()

    def _helper(real, label):
        density, bins = np.histogram(real, bins=bin, density=True, range=[0, hist_range])
        unity_density = density / density.sum()
        widths = bins[:-1] - bins[1:]
        ax.bar(bins[1:], unity_density, width=widths, alpha=.5, label=label)

    _helper(real, 'Data')
    ax.set_xlabel((data_arg.capitalize()))
    ax.set_ylabel('Density')

    if data_arg != 'amplitude':
        plt.xticks([0, 2, 5], ['Odor On', 'Off', 'US'])
        plt.xlim([-0.5, 5.5])
    else:
        plt.xlim([0, xlim])

    # xticks = np.arange(xlim)
    # ax.set_xticks(xticks)
    # ax.set_xticklabels(xticks)
    # yticks = np.array([0, .5, 1])
    # ax.set_yticks(yticks)
    # plt.ylim([0, 1])

    mean = np.mean(real)
    median = np.median(real)
    ylim = ax.get_ylim()
    xlim = ax.get_xlim()
    x = (xlim[1] - xlim[0]) / 2
    y = (ylim[1] - ylim[0]) / 2
    if save:
        y -= .05
    t = 'Median = {:.3f}, mean = {:.3f}'.format(median, mean)
    # plt.text(x, y, t)

    ax.spines["right"].set_visible(False)
    ax.spines["top"].set_visible(False)
    ax.xaxis.set_ticks_position('bottom')
    ax.yaxis.set_ticks_position('left')

    name = 'distribution ' + data_arg + '_' + ','.join([str(x) for x in start]) + '_' + ','.join([str(x) for x in end])

    if save:
        plt.legend(frameon=False)
        _easy_save(os.path.join(figure_path, data_arg), name, dpi=300, pdf=True)

    #statistics
    if data_arg == 'onset':
        odor = np.sum(real < 2) / real.size
        delay = np.sum(real > 2) / real.size
        print('mean, median: {}, {}'.format(mean, median))
        print('Fraction of cells with onset during odor presentation: {}'.format(odor))
    return real
Пример #22
0
                              condition.name)
load_path = os.path.join(data_directory, str(mouse) + '.npy')
save_path = os.path.join(config.Config().LOCAL_FIGURE_PATH, 'MISC',
                         'COUNTING_CELLS')

rois = file_io.load_numpy(load_path)
#ROIT has dimensions YDIM, XDIM, NROI, DAYS
roiT = np.transpose(rois, (1, 2, 3, 0)).astype('float32')

ydim, xdim, nroi, ndays = roiT.shape

for r in range(nroi):
    fig, axs = plt.subplots(1, ndays, figsize=(6, 1))
    for d in range(ndays):
        roi = roiT[:, :, r, d]
        comy, comx = np.round(center_of_mass(roi)).astype(int)
        subset = roi[comy - pad:comy + pad, comx - pad:comx + pad]
        im = axs[d].imshow(subset)
        axs[d].set_title('Day {}'.format(1 + d * 2), fontsize=7)
        axs[d].axis('off')

        cm = im.get_cmap()
        cm.colors[0] = [0, 0, 0]
        im = axs[d].imshow(subset, cmap=cm)
        fig.suptitle(str(r))

    try:
        plot._easy_save(path=save_path, name=str(r))
    except:
        plt.close()
Пример #23
0
                            mean - err,
                            mean + err,
                            zorder=0,
                            lw=0,
                            alpha=config.fill_alpha,
                            color=condition_config.colors[j])

        # plt.xticks([time_odor_on, time_odor_off, time_water_on], labels=['ON', 'OFF', 'US'])
        plt.xticks([time_odor_on, time_odor_off, time_water_on],
                   labels=['', '', ''])
        plt.yticks([])
        plt.ylim(condition_config.ylim)
        # if condition_config.name == 'standard':
        #     legends = ['CS+1','CS+2','CS-1','CS-2']
        # else:
        #     legends = [odor.upper() for odor in odors]
        # plt.legend(legends, frameon=False)
        # ax.set_xlabel('Time (s)')
        # ax.set_ylabel(r'$\Delta$ F/F')
        # draw_scale_line_xy(ax, length=[5, .5], offset=[0, 0], linewidth= config.scale_linewidth)
        ax.spines['top'].set_visible(False)
        ax.spines['bottom'].set_visible(False)
        ax.spines['right'].set_visible(False)
        ax.spines['left'].set_visible(False)
        ax.xaxis.set_ticks_position('bottom')
        ax.yaxis.set_ticks_position('left')

        plot._easy_save(
            save_path,
            'mouse_' + str(mouse) + '_cell_' + str(cell) + '_day_' + str(i))
Пример #24
0
    water_on_lines = np.arange(water_on, frames_per_trial * len(odors), frames_per_trial)
    if 'water' in odors:
        water_on_lines = water_on_lines[[0,1,4]]
    else:
        water_on_lines = water_on_lines[[0,1]]

    if cell_days[i] >= condition.training_start_day[mouse]:
        xticks = np.append(odor_on_lines, water_on_lines)
    else:
        xticks = odor_on_lines

    plt.xticks(xticks, '')
    plt.yticks([])
    plt.tick_params(direction='out', length=2, width=.5, grid_alpha=0.5)
    plt.ylabel(condition_config.title[i])
    for line in condition_lines:
        plt.plot([line, line], plt.ylim(), '--', color='grey', linewidth=.5)

    for j, x in enumerate(odor_on_lines):
        plt.text(x, -1, odors[j].upper())

    ax = fig.add_axes(rect_cb)
    cb = plt.colorbar(cax=ax, ticks=[-condition_config.vlim, condition_config.vlim])
    cb.outline.set_linewidth(0.5)
    cb.set_label(r'$\Delta$ F/F', fontsize=7, labelpad=-10)
    plt.tick_params(axis='both', which='major', labelsize=7)

    plot._easy_save(save_path,
                    'mouse_' + str(mouse) +
                    '_cell_' + str(cell) +
                    '_day_' + str(res_mouse['day'][i]))
Пример #25
0
        xticks = np.concatenate((odor_on_lines, odor_on_lines + 8))

    plt.xticks(xticks, '')
    plt.yticks([])

    for line in condition_lines:
        plt.plot([line, line], plt.ylim(), '--', color='grey', linewidth=.5)

    for j, x in enumerate(odor_on_lines_raw):
        plt.text(x, -1, titles[j].upper())

    ax = fig.add_axes(rect_cb)
    cb = plt.colorbar(cax=ax,
                      ticks=[-condition_config.vlim, condition_config.vlim])

    if black:
        cb.outline.set_visible(False)
        cb.set_ticks([])
    else:
        cb.outline.set_linewidth(0.5)
        cb.set_label(r'$\Delta$ F/F', fontsize=7, labelpad=-10)

    plt.tick_params(axis='both', which='major', labelsize=7)

    name_black = '_black' if black else ''
    name = 'mouse_' + str(mouse) + '_day_' + str(days[i]) + name_black
    if condition_config.plot_big:
        name += '_big' + ','.join(
            [str(x) for x in condition_config.plot_big_days])
    plot._easy_save(save_path, name)
Пример #26
0
        for ims in imData:
            ims = np.stack(ims, axis=0)
            ims = ims[i]
            mean_ims.append(ims.mean(axis=0))
        mean_ims = np.stack(mean_ims, axis=0)
        across_day_mean_corrs = across_corr_metric(mean_ims)
        across_day_mean_corrs_average = across_day_mean_corrs[
            ~np.eye(across_day_mean_corrs.shape[0], dtype=bool)].mean()

    imdir = os.path.join(d, 'python_reg.tif')
    fi.imsave(imdir, mean_ims.astype('uint16'), photometric='minisblack')
    for i, im in enumerate(mean_ims):
        plt.imshow(im, cmap='gray')
        plt.xticks([])
        plt.yticks([])
        plot._easy_save(d, str(i))

    #saving
    p, experiment = os.path.split(d)
    p, mouse = os.path.split(p)
    save_dir = os.path.join(data_directory, condition.name)
    res = defaultdict(list)

    res['within_day_corrs'].append(within_day_corrs)
    res['within_day_corrs_average'].append(within_day_corr_average)
    res['within_day_crisp'].append(within_day_crisp)
    res['within_day_crisp_average'].append(np.mean(within_day_crisp))
    res['across_day_mean_corrs'].append(across_day_mean_corrs)
    res['across_day_mean_corrs_average'].append(across_day_mean_corrs_average)
    # res['within_day_mean_corrs'].append(within_day_mean_corrs)
    res['mouse'].append(mouse)