def plot_coding_direction(units, time_period=None, label=None, axs=None):
    # get event start times: sample, delay, response
    period_names, period_starts = _get_trial_event_times(['sample', 'delay', 'go'], units, 'good_noearlylick_hit')

    _, proj_contra_trial, proj_ipsi_trial, time_stamps, _ = psth.compute_CD_projected_psth(
        units.fetch('KEY'), time_period=time_period)

    fig = None
    if axs is None:
        fig, axs = plt.subplots(1, 1, figsize=(8, 6))

    # plot
    _plot_with_sem(proj_contra_trial, time_stamps, ax=axs, c='b')
    _plot_with_sem(proj_ipsi_trial, time_stamps, ax=axs, c='r')

    for x in period_starts:
        axs.axvline(x=x, linestyle = '--', color = 'k')
    # cosmetic
    axs.spines['right'].set_visible(False)
    axs.spines['top'].set_visible(False)
    axs.set_ylabel('CD projection (a.u.)')
    axs.set_xlabel('Time (s)')
    if label:
        axs.set_title(label)

    return fig
def plot_coding_direction(units, time_period=None, axs=None):
    _, proj_contra_trial, proj_ipsi_trial, time_stamps = psth.compute_CD_projected_psth(
        units.fetch('KEY'), time_period=time_period)

    period_starts = (
        experiment.Period
        & 'period in ("sample", "delay", "response")').fetch('period_start')

    if axs is None:
        fig, axs = plt.subplots(1, 1, figsize=(8, 6))

    # plot
    _plot_with_sem(proj_contra_trial, time_stamps, ax=axs, c='b')
    _plot_with_sem(proj_ipsi_trial, time_stamps, ax=axs, c='r')

    for x in period_starts:
        axs.axvline(x=x, linestyle='--', color='k')
    # cosmetic
    axs.spines['right'].set_visible(False)
    axs.spines['top'].set_visible(False)
    axs.set_ylabel('CD projection (a.u.)')
    axs.set_xlabel('Time (s)')
예제 #3
0
    def make(self, key):
        water_res_num, sess_date = get_wr_sessdate(key)
        sess_dir = store_stage / water_res_num / sess_date
        sess_dir.mkdir(parents=True, exist_ok=True)

        # ---- Setup ----
        time_period = (-0.4, 0)
        probe_keys = (ephys.ProbeInsertion & key).fetch(
            'KEY', order_by='insertion_number')

        fig1, axs = plt.subplots(len(probe_keys),
                                 len(probe_keys),
                                 figsize=(16, 16))

        if len(probe_keys) > 1:
            [a.axis('off') for a in axs.flatten()]

            # ---- Plot Coding Direction per probe ----
            probe_proj = {}
            for pid, probe in enumerate(probe_keys):
                units = ephys.Unit & probe
                label = (ephys.ProbeInsertion & probe).aggr(
                    ephys.ProbeInsertion.RecordableBrainRegion.proj(
                        brain_region='CONCAT(hemisphere, " ", brain_area)'),
                    brain_regions='GROUP_CONCAT(brain_region SEPARATOR", ")'
                ).fetch1('brain_regions')
                label = '({}) {}'.format(probe['insertion_number'], label)

                _, period_starts = _get_trial_event_times(
                    ['sample', 'delay', 'go'], units, 'good_noearlylick_hit')

                # ---- compute CD projected PSTH ----
                _, proj_contra_trial, proj_ipsi_trial, time_stamps, hemi = psth.compute_CD_projected_psth(
                    units.fetch('KEY'), time_period=time_period)

                # ---- save projection results ----
                probe_proj[pid] = (proj_contra_trial, proj_ipsi_trial,
                                   time_stamps, label, hemi)

                # ---- generate fig with CD plot for this probe ----
                fig, ax = plt.subplots(1, 1, figsize=(6, 6))
                _plot_with_sem(proj_contra_trial, time_stamps, ax=ax, c='b')
                _plot_with_sem(proj_ipsi_trial, time_stamps, ax=ax, c='r')
                # cosmetic
                for x in period_starts:
                    ax.axvline(x=x, linestyle='--', color='k')
                ax.spines['right'].set_visible(False)
                ax.spines['top'].set_visible(False)
                ax.set_ylabel('CD projection (a.u.)')
                ax.set_xlabel('Time (s)')
                ax.set_title(label)
                fig.tight_layout()

                # ---- plot this fig into the main figure ----
                buf = io.BytesIO()
                fig.savefig(buf, format='png')
                buf.seek(0)
                axs[pid, pid].imshow(Image.open(buf))
                buf.close()
                plt.close(fig)

            # ---- Plot probe-pair correlation ----
            for p1, p2 in itertools.combinations(probe_proj.keys(), r=2):
                proj_contra_trial_g1, proj_ipsi_trial_g1, time_stamps, label_g1, p1_hemi = probe_proj[
                    p1]
                proj_contra_trial_g2, proj_ipsi_trial_g2, time_stamps, label_g2, p2_hemi = probe_proj[
                    p2]
                labels = [label_g1, label_g2]

                # plot trial CD-endpoint correlation
                p_start, p_end = time_period
                contra_cdend_1 = proj_contra_trial_g1[:,
                                                      np.logical_and(
                                                          time_stamps >=
                                                          p_start, time_stamps
                                                          < p_end)].mean(
                                                              axis=1)
                ipsi_cdend_1 = proj_ipsi_trial_g1[:,
                                                  np.logical_and(
                                                      time_stamps >= p_start,
                                                      time_stamps < p_end
                                                  )].mean(axis=1)
                if p1_hemi == p2_hemi:
                    contra_cdend_2 = proj_contra_trial_g2[:,
                                                          np.logical_and(
                                                              time_stamps >=
                                                              p_start,
                                                              time_stamps <
                                                              p_end)].mean(
                                                                  axis=1)
                    ipsi_cdend_2 = proj_ipsi_trial_g2[:,
                                                      np.logical_and(
                                                          time_stamps >=
                                                          p_start, time_stamps
                                                          < p_end)].mean(
                                                              axis=1)
                else:
                    contra_cdend_2 = proj_ipsi_trial_g2[:,
                                                        np.logical_and(
                                                            time_stamps >=
                                                            p_start,
                                                            time_stamps < p_end
                                                        )].mean(axis=1)
                    ipsi_cdend_2 = proj_contra_trial_g2[:,
                                                        np.logical_and(
                                                            time_stamps >=
                                                            p_start,
                                                            time_stamps < p_end
                                                        )].mean(axis=1)

                c_df = pd.DataFrame([contra_cdend_1, contra_cdend_2]).T
                c_df.columns = labels
                c_df['trial-type'] = 'contra'
                i_df = pd.DataFrame([ipsi_cdend_1, ipsi_cdend_2]).T
                i_df.columns = labels
                i_df['trial-type'] = 'ipsi'
                df = c_df.append(i_df)

                # remove NaN trial - could be due to some trials having no spikes
                non_nan = ~np.logical_or(
                    np.isnan(df[labels[0]]).values,
                    np.isnan(df[labels[1]]).values)
                df = df[non_nan]

                fig = plt.figure(figsize=(6, 6))
                jplot = _jointplot_w_hue(data=df,
                                         x=labels[0],
                                         y=labels[1],
                                         hue='trial-type',
                                         colormap=['b', 'r'],
                                         figsize=(8, 6),
                                         fig=fig,
                                         scatter_kws=None)

                # ---- plot this fig into the main figure ----
                buf = io.BytesIO()
                fig.savefig(buf, format='png')
                buf.seek(0)
                axs[p1, p2].imshow(Image.open(buf))
                buf.close()
                plt.close(fig)

        else:
            # ---- Plot Single-Probe Coding Direction ----
            probe = probe_keys[0]
            units = ephys.Unit & probe
            label = (ephys.ProbeInsertion & probe).aggr(
                ephys.ProbeInsertion.RecordableBrainRegion.proj(
                    brain_region='CONCAT(hemisphere, " ", brain_area)'),
                brain_regions='GROUP_CONCAT(brain_region SEPARATOR", ")'
            ).fetch1('brain_regions')

            unit_characteristic_plot.plot_coding_direction(
                units, time_period=time_period, label=label, axs=axs)

        # ---- Save fig and insert ----
        fn_prefix = f'{water_res_num}_{sess_date}_'
        fig_dict = save_figs((fig1, ), ('coding_direction', ), sess_dir,
                             fn_prefix)

        plt.close('all')
        self.insert1({**key, **fig_dict, 'cd_probe_count': len(probe_keys)})
def plot_paired_coding_direction(unit_g1, unit_g2, labels=None, time_period=None):
    """
    Plot trial-to-trial CD-endpoint correlation between CD-projected trial-psth from two unit-groups (e.g. two brain regions)
    Note: coding direction is calculated on selective units, contra vs. ipsi, within the specified time_period
    """
    _, proj_contra_trial_g1, proj_ipsi_trial_g1, time_stamps, unit_g1_hemi = psth.compute_CD_projected_psth(
        unit_g1.fetch('KEY'), time_period=time_period)
    _, proj_contra_trial_g2, proj_ipsi_trial_g2, time_stamps, unit_g2_hemi = psth.compute_CD_projected_psth(
        unit_g2.fetch('KEY'), time_period=time_period)

    # get event start times: sample, delay, response
    period_names, period_starts = _get_trial_event_times(['sample', 'delay', 'go'], unit_g1, 'good_noearlylick_hit')

    if labels:
        assert len(labels) == 2
    else:
        labels = ('unit group 1', 'unit group 2')

    # plot projected trial-psth
    fig, axs = plt.subplots(1, 2, figsize=(16, 6))

    _plot_with_sem(proj_contra_trial_g1, time_stamps, ax=axs[0], c='b')
    _plot_with_sem(proj_ipsi_trial_g1, time_stamps, ax=axs[0], c='r')
    _plot_with_sem(proj_contra_trial_g2, time_stamps, ax=axs[1], c='b')
    _plot_with_sem(proj_ipsi_trial_g2, time_stamps, ax=axs[1], c='r')

    # cosmetic
    for ax, label in zip(axs, labels):
        for x in period_starts:
            ax.axvline(x=x, linestyle = '--', color = 'k')
        ax.spines['right'].set_visible(False)
        ax.spines['top'].set_visible(False)
        ax.set_ylabel('CD projection (a.u.)')
        ax.set_xlabel('Time (s)')
        ax.set_title(label)

    # plot trial CD-endpoint correlation - if 2 unit-groups are from 2 hemispheres,
    #   then contra-ipsi definition is based on the first group
    p_start, p_end = time_period
    contra_cdend_1 = proj_contra_trial_g1[:, np.logical_and(time_stamps >= p_start, time_stamps < p_end)].mean(axis=1)
    ipsi_cdend_1 = proj_ipsi_trial_g1[:, np.logical_and(time_stamps >= p_start, time_stamps < p_end)].mean(axis=1)
    if unit_g1_hemi == unit_g1_hemi:
        contra_cdend_2 = proj_contra_trial_g2[:, np.logical_and(time_stamps >= p_start, time_stamps < p_end)].mean(axis=1)
        ipsi_cdend_2 = proj_ipsi_trial_g2[:, np.logical_and(time_stamps >= p_start, time_stamps < p_end)].mean(axis=1)
    else:
        contra_cdend_2 = proj_ipsi_trial_g2[:, np.logical_and(time_stamps >= p_start, time_stamps < p_end)].mean(axis=1)
        ipsi_cdend_2 = proj_contra_trial_g2[:, np.logical_and(time_stamps >= p_start, time_stamps < p_end)].mean(axis=1)

    c_df = pd.DataFrame([contra_cdend_1, contra_cdend_2]).T
    c_df.columns = labels
    c_df['trial-type'] = 'contra'
    i_df = pd.DataFrame([ipsi_cdend_1, ipsi_cdend_2]).T
    i_df.columns = labels
    i_df['trial-type'] = 'ipsi'
    df = c_df.append(i_df)

    jplot = _jointplot_w_hue(data=df, x=labels[0], y=labels[1], hue= 'trial-type', colormap=['b', 'r'],
                             figsize=(8, 6), fig=None, scatter_kws=None)
    jplot['fig'].show()

    return fig
예제 #5
0
파일: report.py 프로젝트: rozmar/map-ephys
    def make(self, key):
        water_res_num, sess_date = get_wr_sessdate(key)
        sess_dir = store_stage / water_res_num / sess_date
        sess_dir.mkdir(parents=True, exist_ok=True)

        # ---- Setup ----
        time_period = (-0.4, 0)
        probe_keys = (ephys.ProbeInsertion & key).fetch(
            'KEY', order_by='insertion_number')
        period_starts = (experiment.Period
                         & 'period in ("sample", "delay", "response")'
                         ).fetch('period_start')

        fig1, axs = plt.subplots(len(probe_keys),
                                 len(probe_keys),
                                 figsize=(16, 16))
        [a.axis('off') for a in axs.flatten()]

        # ---- Plot Coding Direction per probe ----
        probe_proj = {}
        for pid, probe in enumerate(probe_keys):
            units = ephys.Unit & probe
            label = (ephys.ProbeInsertion.InsertionLocation
                     & probe).fetch1('brain_location_name').replace(
                         '_', ' ').upper()

            # ---- compute CD projected PSTH ----
            _, proj_contra_trial, proj_ipsi_trial, time_stamps, hemi = psth.compute_CD_projected_psth(
                units.fetch('KEY'), time_period=time_period)

            # ---- save projection results ----
            probe_proj[pid] = (proj_contra_trial, proj_ipsi_trial, time_stamps,
                               label, hemi)

            # ---- generate fig with CD plot for this probe ----
            fig, ax = plt.subplots(1, 1, figsize=(6, 6))
            _plot_with_sem(proj_contra_trial, time_stamps, ax=ax, c='b')
            _plot_with_sem(proj_ipsi_trial, time_stamps, ax=ax, c='r')
            # cosmetic
            for x in period_starts:
                ax.axvline(x=x, linestyle='--', color='k')
            ax.spines['right'].set_visible(False)
            ax.spines['top'].set_visible(False)
            ax.set_ylabel('CD projection (a.u.)')
            ax.set_xlabel('Time (s)')
            ax.set_title(label)
            fig.tight_layout()

            # ---- plot this fig into the main figure ----
            buf = io.BytesIO()
            fig.savefig(buf, format='png')
            buf.seek(0)
            axs[pid, pid].imshow(Image.open(buf))
            buf.close()
            plt.close(fig)

        # ---- Plot probe-pair correlation ----
        for p1, p2 in itertools.combinations(probe_proj.keys(), r=2):
            proj_contra_trial_g1, proj_ipsi_trial_g1, time_stamps, label_g1, p1_hemi = probe_proj[
                p1]
            proj_contra_trial_g2, proj_ipsi_trial_g2, time_stamps, label_g2, p2_hemi = probe_proj[
                p2]
            labels = [label_g1, label_g2]

            # plot trial CD-endpoint correlation
            p_start, p_end = time_period
            contra_cdend_1 = proj_contra_trial_g1[:,
                                                  np.logical_and(
                                                      time_stamps >= p_start,
                                                      time_stamps < p_end
                                                  )].mean(axis=1)
            ipsi_cdend_1 = proj_ipsi_trial_g1[:,
                                              np.logical_and(
                                                  time_stamps >= p_start,
                                                  time_stamps < p_end)].mean(
                                                      axis=1)
            if p1_hemi == p2_hemi:
                contra_cdend_2 = proj_contra_trial_g2[:,
                                                      np.logical_and(
                                                          time_stamps >=
                                                          p_start, time_stamps
                                                          < p_end)].mean(
                                                              axis=1)
                ipsi_cdend_2 = proj_ipsi_trial_g2[:,
                                                  np.logical_and(
                                                      time_stamps >= p_start,
                                                      time_stamps < p_end
                                                  )].mean(axis=1)
            else:
                contra_cdend_2 = proj_ipsi_trial_g2[:,
                                                    np.logical_and(
                                                        time_stamps >= p_start,
                                                        time_stamps < p_end
                                                    )].mean(axis=1)
                ipsi_cdend_2 = proj_contra_trial_g2[:,
                                                    np.logical_and(
                                                        time_stamps >= p_start,
                                                        time_stamps < p_end
                                                    )].mean(axis=1)

            c_df = pd.DataFrame([contra_cdend_1, contra_cdend_2]).T
            c_df.columns = labels
            c_df['trial-type'] = 'contra'
            i_df = pd.DataFrame([ipsi_cdend_1, ipsi_cdend_2]).T
            i_df.columns = labels
            i_df['trial-type'] = 'ipsi'
            df = c_df.append(i_df)

            # remove NaN trial - could be due to some trials having no spikes
            non_nan = ~np.logical_or(
                np.isnan(df[labels[0]]).values,
                np.isnan(df[labels[1]]).values)
            df = df[non_nan]

            fig = plt.figure(figsize=(6, 6))
            jplot = jointplot_w_hue(data=df,
                                    x=labels[0],
                                    y=labels[1],
                                    hue='trial-type',
                                    colormap=['b', 'r'],
                                    figsize=(8, 6),
                                    fig=fig,
                                    scatter_kws=None)

            # ---- plot this fig into the main figure ----
            buf = io.BytesIO()
            fig.savefig(buf, format='png')
            buf.seek(0)
            axs[p1, p2].imshow(Image.open(buf))
            buf.close()
            plt.close(fig)

        # ---- Save fig and insert ----
        fn_prefix = f'{water_res_num}_{sess_date}_'

        fig_dict = {}
        for fig, figname in zip((fig1, ), ('coding_direction', )):
            fig_fp = sess_dir / (fn_prefix + figname + '.png')
            fig.tight_layout()
            fig.savefig(fig_fp)
            print(f'Generated {fig_fp}')
            fig_dict[figname] = fig_fp.as_posix()

        plt.close('all')
        self.insert1({**key, **fig_dict})