Пример #1
0
def analysis_pdf(datafile, iprotocol=0, Nmax=1000000):

    data = Data(datafile)

    pdf_filename = os.path.join(
        summary_pdf_folder(datafile),
        '%s-behavioral-modulation.pdf' % data.protocols[iprotocol])

    full_resp = compute_population_resp(datafile,
                                        protocol_id=iprotocol,
                                        Nmax=Nmax)

    with PdfPages(pdf_filename) as pdf:
        # print('   - behavioral-modulation analysis for ROI #%i / %i' % (roi+1, data.iscell.sum()))
        fig = population_tuning_fig(full_resp)
        pdf.savefig(fig)  # saves the current figure into a pdf page
        plt.close()
        fig1, fig2 = behavior_mod_population_tuning_fig(
            full_resp, running_speed_threshold=0.1, pupil_threshold=2.5)

        pdf.savefig(fig1)  # saves the current figure into a pdf page
        plt.close(fig1)
        pdf.savefig(fig2)  # saves the current figure into a pdf page
        plt.close(fig2)

    print('[ok] behavioral-modulation analysis saved as: "%s" ' % pdf_filename)
Пример #2
0
    YLIM = (np.min([ax.get_ylim()[0] for ax in AX]), np.max([ax.get_ylim()[1] for ax in AX]))
    for ax in AX:
        ax.set_ylim(YLIM)
        data.add_stim(ax)
        ax.axis('off')
    add_bar(AX[0], Xbar=2, Ybar=1)
    ax = plt.axes([0.84,0.25,0.13,0.6])
    responsive = responsiveness(data)
    SI = orientation_selectivity_plot(*data.compute_integral_responses('angle'), ax=ax, color=('k' if responsive else 'lightgray'))
    ax.annotate('SI=%.2f ' % SI, (1, 0.97), va='top', ha='right', xycoords='figure fraction',
                weight='bold', fontsize=9, color=('k' if responsive else 'lightgray'))
    ax.annotate(('responsive' if responsive else 'unresponsive'), (0.85, 0.97), ha='left', va='top',
                xycoords='figure fraction', weight='bold', fontsize=9, color=(plt.cm.tab10(2) if responsive else plt.cm.tab10(3)))
    AX[0].annotate(' ROI#%i' % (roiIndex+1), (0, 0.1), xycoords='figure fraction', weight='bold', fontsize=9)
    return fig, SI, responsive

if __name__=='__main__':
    
    filename = os.path.join(os.path.expanduser('~'), 'DATA', 'Wild_Type', '2021_03_11-17-13-03.nwb')
    FullData= Data(filename)
    print('the datafile has %i validated ROIs (over %i from the full suite2p output) ' % (np.sum(FullData.iscell),
                                                                                          len(FullData.iscell)))
    # for i in [2, 6, 9, 10, 13, 15, 16, 17, 21, 38, 41, 136]: # for 2021_03_11-17-13-03.nwb
    # # for i in range(np.sum(FullData.iscell))[:5]:
    #     # fig1, _, _ = orientation_selectivity_analysis(FullData, roiIndex=i)
    #     fig2, _, _ = direction_selectivity_analysis(FullData, roiIndex=i)
    #     # fig1.savefig(os.path.join(os.path.expanduser('~'), 'Desktop', 'data3', 'ROI#%i.svg' % (i+1)))
    #     plt.show()


def analysis_pdf(datafile,
                 iprotocol=0,
                 stat_test_props=dict(interval_pre=[-2, 0],
                                      interval_post=[1, 3],
                                      test='wilcoxon',
                                      positive=True),
                 response_significance_threshold=0.05,
                 quantity='dFoF',
                 verbose=True,
                 Nmax=1000000):

    data = Data(datafile, metadata_only=True)

    print('   - computing episodes [...]')
    EPISODES = EpisodeResponse(datafile,
                               protocol_id=iprotocol,
                               quantities=['dFoF'])

    pdf_filename = os.path.join(
        summary_pdf_folder(datafile),
        '%s-spatial_selectivity.pdf' % data.protocols[iprotocol])

    results = {'Ntot': EPISODES.data.nROIs, 'significant': []}

    fig, AX = ge.figure(axes=(3, 1))

    with PdfPages(pdf_filename) as pdf:

        print(
            '   - spatial-selectivity analysis for summed ROI fluo (n=%i rois)'
            % EPISODES.data.nROIs)

        fig, AX = EPISODES.plot_trial_average(
            quantity=quantity,
            roiIndices='all',
            roiIndex=None,
            column_key='x-center',
            row_key='y-center',  # color_key='angle',
            ybar=0.2,
            ybarlabel='0.2dF/F',
            xbar=1.,
            xbarlabel='1s',
            with_annotation=True,
            with_std=True,
            with_stat_test=True,
            stat_test_props=stat_test_props,
            with_screen_inset=True,
            verbose=verbose)
        pdf.savefig(fig)
        plt.close(fig)  # Add figure to pdf and close

        for roi in np.arange(EPISODES.data.nROIs)[:Nmax]:

            print('   - spatial-selectivity analysis for ROI #%i / %i' %
                  (roi + 1, EPISODES.data.nROIs))

            resp = EPISODES.compute_summary_data(
                stat_test_props,
                exclude_keys=['repeat'],
                response_args=dict(roiIndex=roi),
                response_significance_threshold=response_significance_threshold
            )

            fig, AX = EPISODES.plot_trial_average(
                quantity=quantity,
                roiIndex=roi,
                column_key='x-center',
                row_key='y-center',
                color_key='angle',
                ybar=0.2,
                ybarlabel='0.2dF/F',
                xbar=1.,
                xbarlabel='1s',
                with_annotation=True,
                with_std=False,
                with_stat_test=True,
                stat_test_props=stat_test_props,
                with_screen_inset=True,
                verbose=verbose)
            pdf.savefig(fig)
            plt.close(fig)  # Add figure to pdf and close

            significant_cond, label = (
                resp['significant'] == True), '  -> max resp.: '
            if np.sum(significant_cond) > 0:
                imax = np.argmax(resp['value'][significant_cond])
                for key in resp:
                    if ('-bins' not in key):
                        if (key not in results):
                            results[key] = []  # initialize if not done
                        results[key].append(resp[key][significant_cond][imax])
                        label += format_key_value(
                            key, resp[key][significant_cond]
                            [imax]) + ', '  # should have a unique value
                        print(label)
                ge.annotate(
                    fig, label + '\n\n', (0, 0),
                    size='x-small')  #, ha='right', va='top'), rotation=90)
            else:
                ge.annotate(
                    fig,
                    label + ' N/A (no significant resp.)\n\n', (0, 0),
                    size='x-small')  #, ha='right', va='top', rotation=90)

        # the adding the bins
        for key in resp:
            if ('-bins' in key):
                results[key] = resp[key]

        fig = summary_fig(results)
        pdf.savefig(fig)  # saves the current figure into a pdf page
        plt.close(fig)

    print('[ok] spatial-selectivity analysis saved as: "%s" ' % pdf_filename)
Пример #4
0
def compute_DS_population_resp(filename,
                               options,
                               protocol_id=0,
                               Nmax=100000,
                               stat_test_props=dict(interval_pre=[-2, 0],
                                                    interval_post=[1, 3],
                                                    test='ttest',
                                                    positive=True),
                               significance_threshold=0.01):

    # load datafile
    data = Data(filename)

    full_resp = {
        'roi': [],
        'angle_from_pref': [],
        'Nroi_tot': data.iscell.sum(),
        'post_level': [],
        'evoked_level': []
    }

    # get levels of pupil and running-speed in the episodes (i.e. after realignement)
    if 'Pupil' in data.nwbfile.processing:
        Pupil_episodes = EpisodeResponse(data,
                                         protocol_id=protocol_id,
                                         quantity='Pupil',
                                         **options)
        full_resp['pupil_level'] = []
    else:
        Pupil_episodes = None
    if 'Running-Speed' in data.nwbfile.acquisition:
        Running_episodes = EpisodeResponse(data,
                                           protocol_id=protocol_id,
                                           quantity='Running-Speed',
                                           **options)
        full_resp['speed_level'] = []
    else:
        Running_episodes = None

    if Running_episodes is not None:
        for key in Running_episodes.varied_parameters.keys():
            full_resp[key] = []
    elif Pupil_episodes is not None:
        for key in Pupil_episodes.varied_parameters.keys():
            full_resp[key] = []
    else:
        print(
            100 * '-' +
            '\n /!\ Need at least one of the Pupil or Running modalities /!\ \n  '
            + 100 * '-')

    for roi in np.arange(data.iscell.sum())[:Nmax]:
        ROI_EPISODES = EpisodeResponse(data,
                                       protocol_id=protocol_id,
                                       quantity='CaImaging',
                                       baseline_substraction=True,
                                       roiIndex=roi,
                                       **options)
        # check if significant response in at least one direction and compute mean evoked resp
        resp = {'significant': [], 'pre': [], 'post': []}
        for ia, angle in enumerate(ROI_EPISODES.varied_parameters['angle']):

            stats = ROI_EPISODES.stat_test_for_evoked_responses(
                episode_cond=ROI_EPISODES.find_episode_cond('angle', ia),
                **stat_test_props)
            resp['significant'].append(
                stats.significant(threshold=significance_threshold))
            resp['pre'].append(np.mean(stats.x))
            resp['post'].append(np.mean(stats.y))

        if np.sum(resp['significant']) > 0:
            # if significant in at least one
            imax = np.argmax(np.array(resp['post']) - np.array(resp['pre']))
            amax = ROI_EPISODES.varied_parameters['angle'][imax]
            # we compute the post response relative to the preferred orientation for all episodes
            post_interval_cond = ROI_EPISODES.compute_interval_cond(
                stat_test_props['interval_post'])
            pre_interval_cond = ROI_EPISODES.compute_interval_cond(
                stat_test_props['interval_pre'])
            for iep, r in enumerate(ROI_EPISODES.resp):
                full_resp['angle_from_pref'].append(
                    shift_orientation_according_to_pref(
                        ROI_EPISODES.angle[iep], amax))
                full_resp['post_level'].append(
                    ROI_EPISODES.resp[iep, post_interval_cond].mean())
                full_resp['evoked_level'].append(
                    full_resp['post_level'][-1] -
                    ROI_EPISODES.resp[iep, pre_interval_cond].mean())
                full_resp['roi'].append(roi)
                # adding running and speed level in the "post" interval:
                if Pupil_episodes is not None:
                    full_resp['pupil_level'].append(
                        Pupil_episodes.resp[iep, post_interval_cond].mean())
                if Running_episodes is not None:
                    full_resp['speed_level'].append(
                        Running_episodes.resp[iep, post_interval_cond].mean())

    # transform to numpy array for convenience
    for key in full_resp:
        full_resp[key] = np.array(full_resp[key])

    #########################################################
    ############ per cell analysis ##########################
    #########################################################

    angles = np.unique(full_resp['angle_from_pref'])

    full_resp['per_cell'], full_resp['per_cell_post'] = [], []

    for roi in np.unique(full_resp['roi']):

        roi_cond = (full_resp['roi'] == roi)

        full_resp['per_cell'].append([])
        full_resp['per_cell_post'].append([])

        for ia, angle in enumerate(angles):
            cond = (full_resp['angle_from_pref'] == angle) & roi_cond
            full_resp['per_cell'][-1].append(
                full_resp['evoked_level'][cond].mean())
            full_resp['per_cell_post'][-1].append(
                full_resp['post_level'][cond].mean())

    full_resp['per_cell'] = np.array(full_resp['per_cell'])
    full_resp['per_cell_post'] = np.array(full_resp['per_cell_post'])

    return full_resp
Пример #5
0
    # ax = plt.axes([0.88, 0.2, 0.11, 0.6], projection='polar')
    # responsive = responsiveness(data)
    # SI = direction_selectivity_plot(*data.compute_integral_responses('angle'), ax=ax, color=('k' if responsive else 'lightgray'))
    # ax.annotate('SI=%.2f ' % SI, (1, 0.97), va='top', ha='right', xycoords='figure fraction',
    #             weight='bold', fontsize=9, color=('k' if responsive else 'lightgray'))
    # ax.annotate(('responsive' if responsive else 'unresponsive'), (0.85, 0.97), ha='left', va='top',
    #             xycoords='figure fraction', weight='bold', fontsize=9, color=(plt.cm.tab10(2) if responsive else plt.cm.tab10(3)))
    ax.annotate(' ROI#%i' % (roiIndex + 1), (0, 0.1),
                xycoords='figure fraction',
                weight='bold',
                fontsize=9)
    SI, responsive = 0, False
    return fig, SI, responsive


if __name__ == '__main__':

    filename = os.path.join(os.path.expanduser('~'), 'DATA', 'Wild_Type',
                            '2021_03_11-17-32-34.nwb')
    FullData = Data(filename, with_visual_stim=True)
    print(FullData.protocols)

    for i in range(np.sum(FullData.iscell))[:1]:
        print('ROI#', i + 1)
        fig1, _, _ = RF_analysis(FullData, roiIndex=i)

    # ax.axis('off')
    # fig.savefig(os.path.join(os.path.expanduser('~'), 'Desktop', 'RF', 'ROI#%i.png' % (i+1)))
    plt.show()
    plt.close()