def plot_overall_flu(exp_obj=exp_obj):
    dff = ao.normalize_dff(exp_obj.raw)
    dff_mean = np.mean(dff, axis=0)

    fig, ax = plt.subplots(figsize=(20, 4))
    color = 'black'
    ax.plot(dff_mean, color=color, alpha=0.4, linewidth=0.5)
    ax.tick_params(axis='y', labelcolor=color)
    if type(exp_obj.seizure_frames) == list:
        ax.axvline(x=exp_obj.seizure_frames[0], color='black')
        ax.axvline(x=exp_obj.seizure_frames[-1], color='black')
    # change x axis ticks to seconds
    labels = [item for item in ax.get_xticks()]
    for item in labels:
        labels[labels.index(item)] = int(round(item / exp_obj.fps))
    ax.set_xticklabels(labels)
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.spines['left'].set_visible(False)
    ax.set_xlabel('Time (seconds)')
    ax.set_title(experiment + ' - mean population Ca2+ signal of FOV',
                 horizontalalignment='center',
                 verticalalignment='top',
                 pad=20,
                 fontsize=15)
    plt.show()
Exemplo n.º 2
0
def _good_cells(exp_obj, min_radius_pix, max_radius_pix):
    good_cells = []
    radius_ = []
    for i in range(len(exp_obj.cell_id)):
        print('Processing cell #:', i)
        raw = list(exp_obj.raw[i])
        raw_dff = ao.normalize_dff(raw)
        std = np.std(raw_dff, axis=0)

        x = []
        y = []
        for j in np.arange(len(raw_dff), step=4):
            avg = np.mean(raw_dff[j:j+4])
            if avg > np.mean(raw_dff)+2.5*std:
              x.append(j)
              y.append(avg)

        radius = exp_obj.radius[i]
        radius_.append(radius)

        if len(x) > 0 and radius > min_radius_pix and radius < max_radius_pix:
            good_cells.append(exp_obj.cell_id[i])
    print('# of good cells found: %s (out of %s ROIs)'% (len(good_cells), len(exp_obj.cell_id)))
    exp_obj.good_cells = good_cells

    to_plot = radius_
    n, bins, patches = plt.hist(to_plot, 200)
    plt.axvline(min_radius_pix)
    plt.axvline(max_radius_pix)
    plt.suptitle('radius distribution', y=0.95)
    plt.show()
def plot_stim_responses_cells(title='', y_label=y_label, y_axis_range=[]):
    '''plot average stim response of each cell at each stim. timepoint, along with the average dFF across all cells at each frame'''
    dff = ao.normalize_dff(exp_obj.raw)
    dff_mean = np.mean(dff, axis=0)

    # keys = df.keys()[1:]
    # response = [df["%s" % stim].mean() for stim in df.keys()[1:]]
    # x = [int(i) for i in keys[pd.notna(response)]]
    # y = [a for a in response if str(a) != 'nan']

    fig, ax1 = plt.subplots(figsize=(20, 3))
    color = 'gray'
    ax1.plot(dff_mean, color=color, alpha=0.4, linewidth=0.5)
    ax1.tick_params(axis='y', labelcolor=color)
    if type(exp_obj.seizure_frames) == list:
        ax1.axvline(x=exp_obj.seizure_frames[0], color='black')
        ax1.axvline(x=exp_obj.seizure_frames[-1], color='black')

    ax2 = ax1.twinx()
    color = 'black'
    x_all = []
    y_all = []
    for cell in exp_obj.good_naparm_cells_all:
        stim_group = df.loc[cell, 'groups']
        x = exp_obj.stim_start_frames[0][stim_group::exp_obj.n_groups]
        y = [df.loc[cell, '%s' % i] for i in x]
        ax2.scatter(x, y, s=5)
        # ax2.plot(x, y, linewidth=0.5)
        x_all.extend(x)
        y_all.extend(y)

    # ax2.scatter(x_all, y_all, s=5)
    #ax2.plot(np.unique(x), np.poly1d(np.polyfit(x, y, 1))(np.unique(x))) # plot line of best fit through scatter plot  # this best fit line is linear so not useful

    ax2.tick_params(axis='y', labelcolor=color)
    ax2.set_ylabel(y_label)
    ax2.set_ylim(y_axis_range)

    ax1.set_title(title,
                  horizontalalignment='center',
                  verticalalignment='top',
                  pad=20,
                  fontsize=15)

    ax1.spines['top'].set_visible(False)
    ax1.spines['left'].set_visible(False)

    ax2.spines['top'].set_visible(False)
    ax2.spines['left'].set_visible(False)

    # change x axis ticks to seconds
    labels = [item for item in ax1.get_xticks()]
    for item in labels:
        labels[labels.index(item)] = int(round(item / exp_obj.fps))
    ax1.set_xticklabels(labels)
    ax1.set_xlabel('Time (seconds)')

    fig.show()
def plot_stim_responses_norm_cells(title='',
                                   norm_start=0,
                                   norm_end=exp_obj.n_frames,
                                   y_axis_range=[]):
    '''plot average stim response of each cell at each stim. timepoint, along with the average dFF across all cells at each frame'''
    dff = ao.normalize_dff(exp_obj.raw)
    dff_mean = np.mean(dff, axis=0)

    keys = df.keys()[1:]
    response = [df["%s" % stim].mean() for stim in df.keys()[1:]]
    x = [int(i) for i in keys[pd.notna(response)]]
    y = [a for a in response if str(a) != 'nan']

    fig, ax1 = plt.subplots(figsize=(20, 3))
    color = 'gray'
    ax1.plot(dff_mean, color=color, alpha=0.4, linewidth=0.5)
    ax1.tick_params(axis='y', labelcolor=color)
    if type(exp_obj.seizure_frames) == list:
        ax1.axvline(x=exp_obj.seizure_frames[0], color='black')
        ax1.axvline(x=exp_obj.seizure_frames[-1], color='black')

    ax2 = ax1.twinx()
    color = 'black'

    for cell in exp_obj.good_naparm_cells_all:
        stim_group = df.loc[cell, 'groups']
        x = exp_obj.stim_start_frames[0][stim_group::exp_obj.n_groups]
        y = [df.loc[cell, '%s' % i] for i in x]
        mean_ = np.mean(
            [y[i] for i in range(len(x)) if norm_end > x[i] > norm_start])

        y_ = [i / mean_ for i in y]  # normalized response of this cell

        ax2.scatter(x, y_, s=5)
        ax2.plot(x, y_, linewidth=0.5)

    ax2.set_ylim(y_axis_range)
    ax2.tick_params(axis='y', labelcolor=color)
    ax1.set_title((title),
                  horizontalalignment='center',
                  verticalalignment='top',
                  pad=20,
                  fontsize=15)
    fig.show()
def plot_flu_trace(exp_obj=exp_obj, idx=idx, slm_group=group, to_plot='raw'):
    raw = exp_obj.raw[idx]
    raw_ = np.delete(raw, exp_obj.photostim_frames)
    raw_dff = ao.normalize_dff(raw_)
    std_dff = np.std(raw_dff, axis=0)
    std = np.std(raw_, axis=0)

    if to_plot == 'raw':
        to_plot_ = raw
        to_thresh = std
    else:
        to_plot_ = raw_dff
        to_thresh = std_dff

    plt.figure(figsize=(20, 3))
    plt.plot(to_plot_, linewidth=0.1)
    # if to_plot == 'raw':
    #     plt.suptitle(('raw flu for cell #%s' % exp_obj.cell_id[idx]), horizontalalignment='center',
    #                  verticalalignment='top',
    #                  fontsize=15, y=1.00)
    # else:
    #     plt.scatter(x, y=[0] * len(x), c='r', linewidth=0.10)
    #     plt.axhline(y=np.mean(to_plot_) + 2.5 * to_thresh, c='green')
    #     plt.suptitle(('%s flu for cell #%s' % (to_plot, exp_obj.cell_id[idx])), horizontalalignment='center',
    #                  verticalalignment='top',
    #                  fontsize=15, y=1.00)

    for i in exp_obj.stim_start_frames[0][slm_group::exp_obj.n_groups]:
        plt.axvline(x=i - 1, c='gray', alpha=0.1)

    if exp_obj.seizure_frames:
        plt.scatter(exp_obj.seizure_frames,
                    y=[-20] * len(exp_obj.seizure_frames),
                    c='g',
                    linewidth=0.10)

    # plt.ylim(0, 300)
    plt.show()
def plot_stim_responses_stimgroups(title=''):
    '''plot average stim response of each cell at each stim. timepoint, along with the average dFF across all cells at each frame'''
    dff = ao.normalize_dff(exp_obj.raw)
    dff_mean = np.mean(dff, axis=0)

    # # use for troubleshooting gathering responses from pandas df
    # keys = df.keys()[1:]
    # response = [df["%s" % stim].mean() for stim in df.keys()[1:]]
    # x = [int(i) for i in keys[pd.notna(response)]]
    # y = [a for a in response if str(a) != 'nan']
    # #

    fig, ax1 = plt.subplots(figsize=(20, 3))
    color = 'gray'
    ax1.plot(dff_mean, color=color, alpha=0.4, linewidth=0.5)
    ax1.tick_params(axis='y', labelcolor=color)
    if type(exp_obj.seizure_frames) == list:
        ax1.axvline(x=exp_obj.seizure_frames[0], color='black')
        ax1.axvline(x=exp_obj.seizure_frames[-1], color='black')

    ax2 = ax1.twinx()
    color = 'black'
    for stim_group in range(exp_obj.n_groups):
        stims = exp_obj.stim_start_frames[0][stim_group::exp_obj.n_groups]
        response = [df["%s" % stim].mean() for stim in stims]
        x = [int(i) for i in stims[pd.notna(response)]]
        y = [a for a in response if str(a) != 'nan']
        ax2.scatter(x, y, s=5)
        ax2.plot(x, y, linewidth=0.5)

    ax2.tick_params(axis='y', labelcolor=color)
    ax1.set_title((title),
                  horizontalalignment='center',
                  verticalalignment='top',
                  pad=20,
                  fontsize=15)
    fig.show()
        expobj,
        background=expobj.meanFluImg_registered,
        title='SLM targets location w/ registered mean Flu img')

#%%#####################################################################################################################
########################################################################################################################
########################################################################################################################
########################################################################################################################
##### ------------------- processing for SLM targets Flu traces ########################################################
########################################################################################################################
########################################################################################################################
########################################################################################################################
########################################################################################################################

# collect SLM photostim individual targets -- individual, full traces, dff normalized
expobj.dff_SLMTargets = aoutils.normalize_dff(np.array(expobj.raw_SLMTargets))
expobj.save()

# collect and plot peri- photostim traces for individual SLM target, incl. individual traces for each stim
expobj.pre_stim = int(0.5 * expobj.fps)
expobj.post_stim = int(4 * expobj.fps)
expobj.SLMTargets_stims_dff, expobj.SLMTargets_stims_dffAvg, expobj.SLMTargets_stims_dfstdF, \
expobj.SLMTargets_stims_dfstdF_avg, expobj.SLMTargets_stims_raw, expobj.SLMTargets_stims_rawAvg = \
    expobj.get_alltargets_stim_traces_norm(pre_stim=expobj.pre_stim, post_stim=expobj.post_stim)

# %% photostim. SUCCESS RATE MEASUREMENTS and PLOT - SLM PHOTOSTIM TARGETED CELLS
# measure, for each cell, the pct of trials in which the dF_stdF > 20% post stim (normalized to pre-stim avgF for the trial and cell)
# can plot this as a bar plot for now showing the distribution of the reliability measurement

SLMtarget_ids = list(range(len(expobj.SLMTargets_stims_dfstdF)))
Exemplo n.º 8
0
        labels[labels.index(item)] = int(round(item / exp_obj.fps))
    ax.set_xticklabels(labels)
    ax.set_title(title, horizontalalignment='center', verticalalignment='top', pad=20, fontsize=15)

    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    # ax.spines['left'].set_visible(False)
    ax.set_xlabel(x_label)

    if save_path:
        plt.savefig(save_path)
    plt.show()

rois = [95, 16]

exp_obj.dff = ao.normalize_dff(exp_obj.raw[:10, :], threshold=50)
plot_flu_overlap_plots(dff_array=exp_obj.dff[:10, 10000:22000], title=(experiment + ' - flu of %s cells' % len(exp_obj.dff)), alpha=0.5)
                       # save_path="/Users/prajayshah/OneDrive - University of Toronto/UTPhD/Proposal/2020/Figures/%s: 10 cells.svg" % experiment)

#%% (quick) plot suite2p traces ###############################################################################
plt.figure(figsize=(50, 3))
for i in range(200,250):
    plt.plot(exp_obj.raw[i][exp_obj.good_frames], linewidth=0.2, alpha=0.2)
    plt.plot(exp_obj.spks[i][exp_obj.good_frames], linewidth=0.2, alpha=0.2)
# plt.xlim(0, exp_obj.spks.shape[1])
plt.xlim(0, len(exp_obj.good_frames))
plt.show()

#%% Gaussian filter of spks data and then plotting
def fwhm2sigma(fwhm):
    return fwhm / np.sqrt(8 * np.log(2))