def plot_prefer_nonprefer(ax, prefer_pdf, nonprefer_pdf):
    '''

    Parameters
    ----------
    ax: ndarray
        Numpy array of axes objects with shape (6, ).
        ax[0] - Fraction of negative slope
        ax[1] - Prefer's precession
        ax[2] - Nonprefer's precession
        ax[3] - Difference in onsets for Prefer and Nonprefer
        ax[4] - Difference in slopes for Prefer and Nonprefer
        ax[5] - Difference in phases for Prefer and Nonprefer

    prefer_pdf: dataframe
        Pandas dataframe containing prefered passes (including non-precessing)
    nonprefer_pdf: dataframe
        Pandas dataframe containing nonprefered passes (including non-precessing)

    Returns
    -------
    '''
    pre_c = dict(prefer='r', nonprefer='b')
    prefer_allslope = prefer_pdf['slope'].to_numpy()
    nonprefer_allslope = nonprefer_pdf['slope'].to_numpy()
    prefer_slope = prefer_pdf[
        prefer_pdf['precess_exist']]['slope'].to_numpy() * np.pi
    nonprefer_slope = nonprefer_pdf[
        nonprefer_pdf['precess_exist']]['slope'].to_numpy() * np.pi
    prefer_onset = prefer_pdf[prefer_pdf['precess_exist']]['onset'].to_numpy()
    nonprefer_onset = nonprefer_pdf[
        nonprefer_pdf['precess_exist']]['onset'].to_numpy()
    prefer_dsp = np.concatenate(
        prefer_pdf[prefer_pdf['precess_exist']]['dsp'].to_list())
    nonprefer_dsp = np.concatenate(
        nonprefer_pdf[nonprefer_pdf['precess_exist']]['dsp'].to_list())
    prefer_phasesp = np.concatenate(
        prefer_pdf[prefer_pdf['precess_exist']]['phasesp'].to_list())
    nonprefer_phasesp = np.concatenate(
        nonprefer_pdf[nonprefer_pdf['precess_exist']]['phasesp'].to_list())

    # Precession fraction
    prefer_neg_n, prefer_pos_n = (prefer_allslope < 0).sum(), (prefer_allslope
                                                               > 0).sum()
    nonprefer_neg_n, nonprefer_pos_n = (nonprefer_allslope < 0).sum(), (
        nonprefer_allslope > 0).sum()
    table_arr = np.array([[prefer_neg_n, prefer_pos_n],
                          [nonprefer_neg_n, nonprefer_pos_n]])
    table_df = pd.DataFrame(table_arr,
                            columns=['-ve', '+ve'],
                            index=['Prefer', 'Nonprefer'])
    p_frac = fisherexact(table_arr)
    prefer_frac = prefer_neg_n / (prefer_pos_n + prefer_neg_n)
    nonprefer_frac = nonprefer_neg_n / (nonprefer_pos_n + nonprefer_neg_n)
    bar_w, bar_x, bar_y = 0.5, np.array([0, 1]), np.array(
        [prefer_frac, nonprefer_frac])
    ax[0].bar(bar_x, bar_y, width=bar_w)
    ax[0].errorbar(x=bar_x.mean(), y=0.8, xerr=1, c='k', capsize=2.5)
    ax[0].text(x=0, y=0.85, s='p%s' % (p2str(p_frac)), fontsize=legendsize)
    ax[0].set_xticks([0, 1])
    ax[0].set_xticklabels(['Prefer', 'Nonprefer'])
    ax[0].tick_params(labelsize=fontsize)

    # Prefer precession
    xdum = np.linspace(0, 1, 10)
    mean_phasesp = circmean(prefer_phasesp)
    regress = rcc(prefer_dsp, prefer_phasesp)
    ydum = regress['phi0'] + xdum * 2 * np.pi * regress['aopt']
    ax[1].scatter(prefer_dsp, prefer_phasesp, marker='.', c='gray', s=1)
    ax[1].scatter(prefer_dsp,
                  prefer_phasesp + 2 * np.pi,
                  marker='.',
                  c='gray',
                  s=1)
    ax[1].plot(xdum, ydum, c='k')
    ax[1].plot(xdum, ydum + 2 * np.pi, c='k')
    ax[1].plot(xdum, ydum + 2 * np.pi, c='k')
    ax[1].axhline(mean_phasesp, xmin=0, xmax=0.1, color='r')
    ax[1].set_ylim(-np.pi, 3 * np.pi)
    ax[1].set_xlim(0, 1)

    # Non-Prefer precession
    xdum = np.linspace(0, 1, 10)
    mean_phasesp = circmean(nonprefer_phasesp)
    regress = rcc(nonprefer_dsp, nonprefer_phasesp)
    ydum = regress['phi0'] + xdum * 2 * np.pi * regress['aopt']
    ax[2].scatter(nonprefer_dsp, nonprefer_phasesp, marker='.', c='gray', s=1)
    ax[2].scatter(nonprefer_dsp,
                  nonprefer_phasesp + 2 * np.pi,
                  marker='.',
                  c='gray',
                  s=1)
    ax[2].plot(xdum, ydum, c='k')
    ax[2].plot(xdum, ydum + 2 * np.pi, c='k')
    ax[2].plot(xdum, ydum + 2 * np.pi, c='k')
    ax[2].axhline(mean_phasesp, xmin=0, xmax=0.1, color='r')
    ax[2].set_ylim(-np.pi, 3 * np.pi)
    ax[2].set_xlim(0, 1)

    # Onset vs Slope
    p_onset, _ = watson_williams(prefer_onset, nonprefer_onset)
    _, p_slope = ranksums(prefer_slope, nonprefer_slope)
    ax[3].scatter(prefer_slope,
                  prefer_onset,
                  marker='o',
                  c=pre_c['prefer'],
                  label='prefer')
    ax[3].scatter(nonprefer_slope,
                  nonprefer_onset,
                  marker='x',
                  c=pre_c['nonprefer'],
                  label='nonprefer')
    ax[3].set_xlabel('Precession slope (rad)')
    ax[3].set_ylabel('Precession onset (rad)')
    customlegend(ax[3], fontsize=legendsize)

    # # Onset
    # p_onset, _ = watson_williams(prefer_onset, nonprefer_onset)
    # onset_bins = np.linspace(0, 2*np.pi, 20)
    # prefer_onsetbins, _ = np.histogram(prefer_onset, bins=onset_bins)
    # nonprefer_onsetbins, _ = np.histogram(nonprefer_onset, bins=onset_bins)
    # ax[3].step(onset_bins[:-1], prefer_onsetbins/prefer_onsetbins.sum(), where='pre', c=pre_c['prefer'], label='prefer')
    # ax[3].step(onset_bins[:-1], nonprefer_onsetbins/nonprefer_onsetbins.sum(), where='pre', c=pre_c['nonprefer'], label='nonprefer')
    # ax[3].annotate('Watson-William\np%s'%(p2str(p_onset)), xy=(0.6, 0.6), xycoords='axes fraction')
    # ax[3].set_xlabel('Precession onset (rad)')
    # customlegend(ax[3], fontsize=legendsize)
    #
    # # Slope
    # _, p_slope = ranksums(prefer_slope, nonprefer_slope)
    # slope_bins = np.linspace(-2*np.pi, 0, 20)
    # prefer_slopebins, _ = np.histogram(prefer_slope, bins=slope_bins)
    # nonprefer_slopebins, _ = np.histogram(nonprefer_slope, bins=slope_bins)
    # ax[4].step(slope_bins[:-1], prefer_slopebins/prefer_slopebins.sum(), where='pre', c=pre_c['prefer'], label='prefer')
    # ax[4].step(slope_bins[:-1], nonprefer_slopebins/nonprefer_slopebins.sum(), where='pre', c=pre_c['nonprefer'], label='nonprefer')
    # ax[4].annotate('Ranksums\np%s'%(p2str(p_slope)), xy=(0.6, 0.6), xycoords='axes fraction')
    # ax[4].set_xlabel('Precession slope (rad)')
    # customlegend(ax[4], fontsize=legendsize)

    # Spike phase
    prefer_phasesp_mean, nonprefer_phasesp_mean = circmean(
        prefer_phasesp), circmean(nonprefer_phasesp)
    p_phasesp, _ = watson_williams(prefer_phasesp, nonprefer_phasesp)
    phasesp_bins = np.linspace(-np.pi, np.pi, 20)
    prefer_phasespbins, _ = np.histogram(prefer_phasesp, bins=phasesp_bins)
    nonprefer_phasespbins, _ = np.histogram(nonprefer_phasesp,
                                            bins=phasesp_bins)
    norm_preferphasebins = prefer_phasespbins / prefer_phasespbins.sum()
    norm_nonpreferphasebins = nonprefer_phasespbins / nonprefer_phasespbins.sum(
    )
    maxl = max(norm_preferphasebins.max(), norm_nonpreferphasebins.max())
    ax[4].step(midedges(phasesp_bins),
               norm_preferphasebins,
               color='r',
               label='prefer')
    ax[4].step(midedges(phasesp_bins),
               norm_nonpreferphasebins,
               color='b',
               label='nonprefer')
    ax[4].scatter(prefer_phasesp_mean, maxl * 1.1, color='r', marker='|', s=64)
    ax[4].scatter(nonprefer_phasesp_mean,
                  maxl * 1.1,
                  color='b',
                  marker='|',
                  s=64)
    ax[4].annotate('Watson-William\np%s' % (p2str(p_phasesp)),
                   xy=(0.6, 0.2),
                   xycoords='axes fraction')
    ax[4].set_xlabel('Precession spike phase')
    customlegend(ax[4], fontsize=legendsize)

    return ax
Exemple #2
0
    def plot_average_precession(self, NShuffles=1000):

        fig_avercurve, ax_avercurve = plt.subplots(figsize=(figl, figl), sharey=True)
        fig_phasesp, ax_phasesp = plt.subplots(figsize=(figl, figl), sharey=True)

        anglediff, pass_nspikes = self.stack_anglediff(self.singlefield_df, precess_ref=True)

        anglediff = np.abs(anglediff)
        slopes = self.stack_key(self.singlefield_df, 'rcc_m')
        offsets = self.stack_key(self.singlefield_df, 'rcc_c')

        phasesp = np.concatenate(self.stack_key(self.singlefield_df, 'phasesp'))

        low_mask = anglediff < (np.pi / 6)
        high_mask = anglediff > (np.pi - np.pi / 6)

        sample_size = 500
        np.random.seed(1)
        high_ranvec = np.random.choice(high_mask.sum(), size=sample_size)
        low_ranvec = np.random.choice(low_mask.sum(), size=sample_size)

        anglediff_spikes = repeat_arr(anglediff, pass_nspikes)
        low_mask_sp = anglediff_spikes < (np.pi / 6)
        high_mask_sp = anglediff_spikes > (np.pi - np.pi / 6)
        phasesph = phasesp[high_mask_sp]
        phasespl = phasesp[low_mask_sp]

        slopes_high, offsets_high = slopes[high_mask][high_ranvec], offsets[high_mask][high_ranvec]
        slopes_low, offsets_low = slopes[low_mask][low_ranvec], offsets[low_mask][low_ranvec]

        regress_high, regress_low, pval_slope, pval_offset = permutation_test_average_slopeoffset(
            slopes_high, offsets_high, slopes_low, offsets_low, NShuffles=NShuffles)


        xdum = np.linspace(0, 1, 10)
        high_agg_ydum = 2 * np.pi * regress_high['aopt'] * xdum + regress_high['phi0']
        low_agg_ydum = 2 * np.pi * regress_low['aopt'] * xdum + regress_low['phi0']

        # Compare high vs low
        ax_avercurve.plot(xdum, high_agg_ydum, c='lime', label='$|d|>5\pi/6$')
        ax_avercurve.plot(xdum, low_agg_ydum, c='darkblue', label='$|d|<\pi/6$')
        ax_avercurve.text(0.05, -np.pi + 0.5, 'Slope\n  p%s\nOffset\n  p%s'% \
                          (p2str(pval_slope), p2str(pval_offset)), fontsize=legendsize)

        customlegend(ax_avercurve, fontsize=legendsize, loc='center right')

        #
        aedges = np.linspace(-np.pi, np.pi, 36)

        fstat, k_pval = circ_ktest(phasesph, phasespl)

        p_ww, ww_table = watson_williams(phasesph, phasespl)
        ax_phasesp.hist(phasesph, bins=aedges, density=True, histtype='step', color='lime')
        ax_phasesp.hist(phasespl, bins=aedges, density=True, histtype='step', color='darkblue')
        ax_phasesp.text(0.2, 0.15, 'Bartlett\'s\np%s'%(p2str(k_pval)), transform=ax_phasesp.transAxes, fontsize=fontsize)
        # ax_phasesp.legend(fontsize=legendsize-2, loc='lower center')
        ax_phasesp.set_xticks([-np.pi, 0, np.pi])
        ax_phasesp.set_xticklabels(['$-\pi$', '0', '$\pi$'])
        # ax_phasesp.set_yticks([0, 0.2])
        ax_phasesp.tick_params(labelsize=ticksize, direction='inout')
        ax_phasesp.set_xlabel('Phase (rad)', fontsize=fontsize)
        ax_phasesp.set_ylabel('Normalized frequency', fontsize=fontsize)
        ax_phasesp.set_xlim(-np.pi, np.pi)

        ax_avercurve.set_xlim(0, 1)
        ax_avercurve.set_ylim(-np.pi, np.pi + np.pi/2)
        ax_avercurve.set_yticks([-np.pi, 0, np.pi])
        ax_avercurve.set_yticklabels(['$-\pi$', '0', '$\pi$'])
        ax_avercurve.set_xlabel('Position', fontsize=fontsize)
        ax_avercurve.tick_params(labelsize=ticksize, direction='inout')

        ax_avercurve.set_ylabel('Phase (rad)', fontsize=fontsize)

        fig_avercurve.tight_layout()
        fig_avercurve.savefig(join(self.plot_dir, 'Networks_aver_precess_curve.png'), dpi=300)

        fig_phasesp.tight_layout()
        fig_phasesp.savefig(join(self.plot_dir, 'Networks_spike_phase_highlow.png'), dpi=300)

        plt.close()
def plot_correlogram(ax,
                     df,
                     tag,
                     direct='A->B',
                     overlap_key='overlap',
                     color='gray',
                     density=False,
                     regress=True,
                     x_dist=True,
                     y_dist=True,
                     ab_key='phaselag_AB',
                     ba_key='phaselag_BA',
                     alpha=0.2,
                     markersize=8,
                     linew=1):
    """

    Parameters
    ----------
    ax : matplotlib.axes._subplots.AxesSubplot
    df : Dataframe
    tag : str
    direct : str
        Either 'A->B', 'B->A' or 'combined'
    overlap_key : str
        Key of the overlap metric
    color : str
        Color of the scatter
    regress : bool
    x_dist : bool
    y_dist : bool
    ab_key : str
    ba_key : str
    alpha : float

    Returns
    -------

    """
    overlap = df[overlap_key].to_numpy()
    phaselag_AB = df[ab_key].to_numpy()
    phaselag_BA = df[ba_key].to_numpy()

    # Define x, y
    if direct == 'A->B':
        x = overlap
        y = phaselag_AB
    elif direct == 'B->A':
        x = overlap
        y = phaselag_BA
    elif direct == 'combined':
        x = np.concatenate([overlap, overlap])
        y = np.concatenate([phaselag_AB, -phaselag_BA])

    nan_mask = np.isnan(x) | np.isnan(y)
    x_nonan, y_nonan = x[~nan_mask], y[~nan_mask]

    # Scatter or density
    if density:
        xx, yy, zz = linear_circular_gauss_density(x_nonan,
                                                   y_nonan,
                                                   cir_kappa=3 * np.pi,
                                                   lin_std=0.05,
                                                   xbins=200,
                                                   ybins=800,
                                                   ybound=(-np.pi, 2 * np.pi))
        ax.pcolormesh(xx, yy, zz)
    else:
        ax.scatter(x, y, c=color, alpha=alpha, s=markersize, marker='.')
        ax.scatter(x,
                   y + (2 * np.pi),
                   c=color,
                   alpha=alpha,
                   s=markersize,
                   marker='.')

    # Plot marginal mean
    mean_y = circmean(y_nonan)
    ax.plot([0, 0.2], [mean_y, mean_y], c='k', linewidth=linew)

    # Regression
    regress_d = None
    if regress:
        regress_d = rcc(x_nonan, y_nonan, abound=[-2, 2])
        m, c, r, pval = regress_d['aopt'], regress_d['phi0'], regress_d[
            'rho'], regress_d['p']
        r_regress = np.linspace(0, 1, 20)
        lag_regress = 2 * np.pi * r_regress * m
        for tmpid, intercept in enumerate(
            [2 * mul_idx * np.pi + c for mul_idx in [-2, -1, 0, 1, 2]]):
            if tmpid == 0:
                ax.plot(r_regress,
                        lag_regress + intercept,
                        c='k',
                        linewidth=linew,
                        label='rho=%0.2f (p%s)' % (r, p2str(pval)))
            else:
                ax.plot(r_regress,
                        lag_regress + intercept,
                        c='k',
                        linewidth=linew)

    # X-axis
    ax.plot([0, 1], [0, 0], c='k', alpha=1, linewidth=linew)

    # (y-axis) Interpolation and Smoothened histrogram
    if y_dist:
        p, _ = rayleigh(y)
        yax, yden = circular_density_1d(y_nonan, 10 * np.pi, 60,
                                        (-np.pi, 3 * np.pi))

        ax.plot(yden / yden.max() * 0.2, yax, c='k', linewidth=linew)

    # (x-axis) Interpolation and Smoothened histrogram
    if x_dist:
        xax, xden = linear_density_1d(x_nonan,
                                      std=0.05,
                                      bins=100,
                                      bound=(0, 1))
        ax.plot(xax,
                xden / xden.max() * (np.pi / 2) - np.pi,
                c='k',
                linewidth=linew)

    # Set title

    # ax.set_title("%s %s (n=%d)" % (tag, direct, num_pairs), fontsize=fontsize)
    ax.set_ylim(-np.pi, 2 * np.pi)
    ax.set_yticks([-np.pi, 0, np.pi, np.pi * 2])
    _ = ax.set_yticklabels(['$-\pi$', '0', '$\pi$', '$2\pi$'])
    return ax, x, y, regress_d
Exemple #4
0
    def plot_field_bestprecession(self):

        fig_R, ax_R = plt.subplots(figsize=(figl, figl))

        fig_2Dscatter, ax_2Dscatter = plt.subplots(figsize=(figl, figl), sharey=True)

        fig_pishift = plt.figure(figsize=(figl*2, figl))
        ax_pishift = np.array(
            [fig_pishift.add_subplot(1, 2, i+1, polar=True) for i in range(2)]
        )

        fid = 0

        data = {'field': [], 'precess': [], 'precess_low':[], 'R':[], 'shufp':[]}

        # Re-organize & filter
        for i in range(self.singlefield_df.shape[0]):

            precess_info = self.singlefield_df.loc[i, 'precess_info']
            if precess_info is None:
                continue
            fieldangle_mlm, precess_angle = self.singlefield_df.loc[i, ['fieldangle_mlm', 'precess_angle']]
            precess_angle_low = self.singlefield_df.loc[i, 'precess_angle_low']
            data['field'].append(fieldangle_mlm)
            data['precess'].append(precess_angle)
            data['precess_low'].append(precess_angle_low)
            data['R'].append(precess_info['R'])
            data['shufp'].append(precess_info['pval'])


            fid += 1



        # Plot Scatter: field vs precess angles
        ax_2Dscatter.scatter(data['field'], data['precess'], alpha=0.2, s=8, c='gray')
        ax_2Dscatter.plot([0, np.pi], [np.pi, 2 * np.pi], c='k')
        ax_2Dscatter.plot([np.pi, 2 * np.pi], [0, np.pi], c='k')
        ax_2Dscatter.set_xlabel(r'$\theta_{rate}$', fontsize=fontsize)
        ax_2Dscatter.set_xticks([0, np.pi, 2 * np.pi])
        ax_2Dscatter.set_xticklabels(['$0$', '$\pi$', '$2\pi$'])
        ax_2Dscatter.set_yticks([0, np.pi, 2 * np.pi])
        ax_2Dscatter.set_yticklabels(['$0$', '$\pi$', '$2\pi$'])
        ax_2Dscatter.tick_params(labelsize=ticksize, direction='inout')
        ax_2Dscatter.set_ylabel(r'$\theta_{Precess}$', fontsize=fontsize)
        fig_2Dscatter.tight_layout()
        fig_2Dscatter.savefig(join(self.plot_dir, 'Networks_field_precess_2Dscatter.png'), dpi=300)


        # Plot Histogram: d(precess, rate)
        fieldangles = np.array(data['field'])
        precessangles = np.array(data['precess'])
        nanmask = (~np.isnan(fieldangles)) & (~np.isnan(precessangles))
        adiff = cdiff(precessangles[nanmask], fieldangles[nanmask])

        bins, edges = np.histogram(adiff, bins=np.linspace(-np.pi, np.pi, 36))
        bins_norm = bins / np.sum(bins)
        l = bins_norm.max()
        ax_pishift[0].bar(midedges(edges), bins_norm, width=edges[1] - edges[0],
                          alpha=0.5, color='gray')

        mean_angle = circmean(adiff)
        mean_angle = np.mod(mean_angle + np.pi, 2 * np.pi) - np.pi
        ax_pishift[0].plot([mean_angle, mean_angle], [0, l], c='k', linestyle='dashed')
        ax_pishift[0].plot([0, 0], [0, l], c='k')
        ax_pishift[0].scatter(0, 0, s=16, c='gray')
        ax_pishift[0].text(0.18, l * 0.4, r'$\theta_{rate}$', fontsize=fontsize+2)
        ax_pishift[0].spines['polar'].set_visible(False)
        ax_pishift[0].set_yticklabels([])
        ax_pishift[0].set_xticklabels([])
        ax_pishift[0].grid(False)
        ax_pishift[0].set_ylabel('All passes', fontsize=fontsize)
        # ax_pishift[0].yaxis.labelpad = 5

        v_pval, v_stat = vtest(adiff, mu=np.pi)
        ax_pishift[0].text(x=0.01, y=0.95, s='p%s'%(p2str(v_pval)), fontsize=legendsize,
                           transform=ax_pishift[0].transAxes)

        # Plot Histogram: d(precess_low, rate)
        fieldangles = np.array(data['field'])
        precessangles_low = np.array(data['precess_low'])
        nanmask = (~np.isnan(fieldangles)) & (~np.isnan(precessangles_low))
        adiff = cdiff(precessangles_low[nanmask], fieldangles[nanmask])
        bins, edges = np.histogram(adiff, bins=np.linspace(-np.pi, np.pi, 36))
        bins_norm = bins / np.sum(bins)
        l = bins_norm.max()
        ax_pishift[1].bar(midedges(edges), bins_norm, width=edges[1] - edges[0],
                          alpha=0.5, color='gray')
        mean_angle = circmean(adiff)
        mean_angle = np.mod(mean_angle + np.pi, 2 * np.pi) - np.pi
        ax_pishift[1].plot([mean_angle, mean_angle], [0, l], c='k', linestyle='dashed')
        ax_pishift[1].plot([0, 0], [0, l], c='k')
        ax_pishift[1].scatter(0, 0, s=16, c='gray')
        ax_pishift[1].text(0.18, l * 0.4, r'$\theta_{rate}$', fontsize=fontsize+2)

        ax_pishift[1].spines['polar'].set_visible(False)
        ax_pishift[1].set_yticklabels([])
        ax_pishift[1].set_xticklabels([])
        ax_pishift[1].grid(False)
        ax_pishift[1].set_ylabel('Low-spike passes', fontsize=fontsize)


        v_pval, v_stat = vtest(adiff, mu=np.pi)
        ax_pishift[1].text(x=0.01, y=0.95, s='p%s'%(p2str(v_pval)), fontsize=legendsize,
                           transform=ax_pishift[1].transAxes)
        fig_pishift.tight_layout()
        fig_pishift.savefig(join(self.plot_dir, 'Networks_field_precess_pishift.png'), dpi=300)




        # Plot R
        all_R = np.array(data['R'])
        rbins, redges = np.histogram(all_R, bins=50)
        rbinsnorm = np.cumsum(rbins) / rbins.sum()
        ax_R.plot(midedges(redges), rbinsnorm)

        ax_R.set_xlabel('R', fontsize=fontsize)
        ax_R.set_ylabel('Cumulative density', fontsize=fontsize)
        ax_R.tick_params(axis='both', which='major', labelsize=fontsize, direction='inout')
        ax_R.set_yticks([0, 0.5, 1])
        fig_R.tight_layout()
        fig_R.savefig(join(self.plot_dir, 'Networks_field_precess_R.png'), dpi=300)
Exemple #5
0
    def plot_both_slope_offset(self):

        density_figsize = (figl+0.5, figl*2)
        slice_figsize = (figl+0.5, figl*2)

        selected_adiff = np.linspace(0, np.pi, 6)  # 20
        adiff_ticks = [0, np.pi / 2, np.pi]
        adiff_ticksl = ['0', '$\pi$', '$2\pi$']
        adiff_label = r'$|d(\theta_{pass}, \theta_{precess})|$'

        offset_label = 'Onset phase (rad)'
        offset_slicerange = (0, 2*np.pi)
        offset_bound = (0, 2 * np.pi)
        offset_xticks = [0, np.pi, 2*np.pi]
        offset_xticksl = ['0', '$\pi$', '$2\pi$']
        offset_slicegap = 0.017  # 0.007

        slope_label = 'Slope ' + '$(rad)$'
        slope_slicerange = (-2 * np.pi, 0)
        slope_bound = (-2 * np.pi, 0)
        slope_xticks = [-2 * np.pi, -np.pi, 0]
        slope_xticksl = ['$-2\pi$', '$-\pi$', '0']
        slope_slicegap = 0.01  # 0.007

        adiff_edges = np.linspace(0, np.pi, 500)
        offset_edges = np.linspace(offset_bound[0], offset_bound[1], 500)
        slope_edges = np.linspace(slope_bound[0], slope_bound[1], 500)

        fig_density, ax_density = plt.subplots(2, 1, figsize=density_figsize, sharex='col', sharey='row')
        fig_slices, ax_slices = plt.subplots(2, 1, figsize=slice_figsize, sharex='row', sharey='row')

        anglediff, pass_nspikes = self.stack_anglediff(self.singlefield_df, precess_ref=True)
        anglediff = np.abs(anglediff)
        slope = self.stack_key(self.singlefield_df, 'rcc_m')
        slope = slope * 2 * np.pi
        offset = self.stack_key(self.singlefield_df, 'rcc_c')

        # Expand sample according to spikes
        anglediff_spikes = repeat_arr(anglediff, pass_nspikes)

        # 1D spike hisotgram
        spikes_bins, spikes_edges = np.histogram(anglediff_spikes, bins=adiff_edges)

        # 2D slope/offset histogram
        offset_bins, offset_xedges, offset_yedges = np.histogram2d(anglediff, offset,
                                                                   bins=(adiff_edges, offset_edges))
        slope_bins, slope_xedges, slope_yedges = np.histogram2d(anglediff, slope,
                                                                bins=(adiff_edges, slope_edges))

        offset_normbins = self.norm_div(offset_bins, spikes_bins)
        slope_normbins = self.norm_div(slope_bins, spikes_bins)

        # Unbinning
        offset_xedm, offset_yedm = midedges(offset_xedges), midedges(offset_yedges)
        slope_xedm, slope_yedm = midedges(slope_xedges), midedges(slope_yedges)
        offset_adiff, offset_norm = unfold_binning_2d(offset_normbins, offset_xedm, offset_yedm)
        slope_adiff, slope_norm = unfold_binning_2d(slope_normbins, slope_xedm, slope_yedm)

        # Linear-circular regression
        regress = rcc(offset_adiff, offset_norm)
        offset_m, offset_c, offset_rho, offset_p = regress['aopt'], regress['phi0'], regress['rho'], regress['p']
        regress = rcc(slope_adiff, slope_norm)
        slope_m, slope_c, slope_rho, slope_p = regress['aopt'], regress['phi0'], regress['rho'], regress['p']
        slope_c = slope_c - 2 * np.pi

        # Density

        offset_xx, offset_yy, offset_zz = linear_circular_gauss_density(offset_adiff, offset_norm,
                                                                        cir_kappa=4 * np.pi, lin_std=0.2, xbins=50,
                                                                        ybins=50, xbound=(0, np.pi),
                                                                        ybound=offset_bound)
        slope_xx, slope_yy, slope_zz = linear_circular_gauss_density(slope_adiff, slope_norm,
                                                                     cir_kappa=4 * np.pi, lin_std=0.2, xbins=50,
                                                                     ybins=50, xbound=(0, np.pi),
                                                                     ybound=slope_bound)
        # ax_density[0].pcolormesh(offset_xx, offset_yy, offset_zz)

        # Plot offset density
        cmap = 'Blues'
        ax_density[0].hist2d(offset_adiff, offset_norm,
                             bins=(np.linspace(0, np.pi, 36), np.linspace(0, 2 * np.pi, 36)), density=True,
                             cmap=cmap)
        regressed = (offset_c + offset_xedm * offset_m)
        ax_density[0].plot(offset_xedm, regressed, c='k')
        ax_density[0].text(np.pi/3, regressed.max() + 0.5, 'p%s'%p2str(offset_p), fontsize=legendsize)
        ax_density[0].set_xticks(adiff_ticks)
        ax_density[0].set_xticklabels(adiff_ticksl)
        ax_density[0].set_yticks(offset_xticks)
        ax_density[0].set_yticklabels(offset_xticksl)
        ax_density[0].tick_params(labelsize=ticksize, direction='inout')
        ax_density[0].set_ylabel(offset_label, fontsize=fontsize)

        # Plot slope density
        ax_density[1].hist2d(slope_adiff, slope_norm,
                             bins=(np.linspace(0, np.pi, 36), np.linspace(-2 * np.pi, 0, 36)), density=True,
                             cmap=cmap)
        regressed = (slope_c + slope_xedm * slope_m)
        # ax_density[1].pcolormesh(slope_xx, slope_yy, slope_zz)
        ax_density[1].plot(slope_xedm, regressed, c='k')
        ax_density[1].text(np.pi/3, regressed.max() + 0.5, 'p%s'%p2str(slope_p), fontsize=legendsize)
        ax_density[1].set_xticks(adiff_ticks)
        ax_density[1].set_xticklabels(adiff_ticksl)
        ax_density[1].set_yticks(slope_xticks)
        ax_density[1].set_yticklabels(slope_xticksl)
        ax_density[1].tick_params(labelsize=ticksize, direction='inout')
        ax_density[1].set_xlabel(adiff_label, fontsize=fontsize)
        ax_density[1].set_ylabel(slope_label, fontsize=fontsize)

        ax_slices[0], _ = plot_marginal_slices(ax_slices[0], offset_xx, offset_yy, offset_zz,
                                               selected_adiff,
                                               offset_slicerange, offset_slicegap)
        ax_slices[0].set_xticks(offset_xticks)
        ax_slices[0].set_xticklabels(offset_xticksl)
        ax_slices[0].set_xlabel(offset_label, fontsize=fontsize)
        ax_slices[0].tick_params(labelsize=ticksize, direction='inout')

        ax_slices[1], _ = plot_marginal_slices(ax_slices[1], slope_xx, slope_yy, slope_zz,
                                               selected_adiff, slope_slicerange, slope_slicegap)

        ax_slices[1].set_xticks(slope_xticks)
        ax_slices[1].set_xticklabels(slope_xticksl)
        ax_slices[1].tick_params(labelsize=ticksize, direction='inout')
        ax_slices[1].set_xlabel(slope_label, fontsize=fontsize)


        # Colorbar
        sm = plt.cm.ScalarMappable(cmap=cm.brg,
                                   norm=plt.Normalize(vmin=selected_adiff.min(), vmax=selected_adiff.max()))
        fig_colorbar = plt.figure(figsize=slice_figsize)
        fig_colorbar.subplots_adjust(right=0.8)
        cbar_ax = fig_colorbar.add_axes([0.7, 0.15, 0.03, 0.7])
        cb = fig_colorbar.colorbar(sm, cax=cbar_ax)
        cb.set_ticks(adiff_ticks)
        cb.set_ticklabels(adiff_ticksl)
        cb.set_label(adiff_label, fontsize=fontsize, rotation=90)




        for ax in ax_slices.flatten():
            ax.axes.get_yaxis().set_visible(False)
            ax.spines["top"].set_visible(False)
            ax.spines["right"].set_visible(False)
            ax.spines["left"].set_visible(False)


        # Others
        fig_density.tight_layout()
        fig_density.savefig(join(self.plot_dir, 'Networks_density.png'), dpi=300)
        fig_slices.tight_layout()
        fig_slices.savefig(join(self.plot_dir, 'Networks_slices.png'), dpi=300)
        # fig_colorbar.tight_layout()
        fig_colorbar.savefig(join(self.plot_dir, 'Networks_adiff_colorbar.png'), dpi=300)
        return None
Exemple #6
0
def plot_exintrinsic_Romani(simdf, ax):
    stat_fn = 'fig9_SIM_exintrinsic.txt'
    stat_record(stat_fn, True)

    ms = 0.2
    # Filtering
    smallerdf = simdf[(~simdf['overlap_ratio'].isna())]

    corr_overlap = smallerdf['overlap_plus'].to_numpy()
    corr_overlap_flip = smallerdf['overlap_minus'].to_numpy()
    corr_overlap_ratio = smallerdf['overlap_ratio'].to_numpy()

    # 1-sample chisquare test
    n_ex = np.sum(corr_overlap_ratio > 0)
    n_in = np.sum(corr_overlap_ratio <= 0)
    n_total = n_ex + n_in

    pchi, _, pchitxt = my_chi_1way([n_ex, n_in])
    stat_record(stat_fn, False, r'SIM, %d/%d=%0.2f, %s' % \
                (n_ex, n_in, n_ex/n_in, pchitxt))
    # 1-sample t test
    mean_ratio = np.mean(corr_overlap_ratio)
    p_1d1samp, _, p_1d1samptxt = my_ttest_1samp(corr_overlap_ratio, 0)
    stat_record(stat_fn, False, 'SIM, mean=%0.4f, %s' % \
                (mean_ratio, p_1d1samptxt))
    # Plot scatter 2d
    ax[0].scatter(corr_overlap_flip, corr_overlap, marker='.', s=ms, c='gray')
    ax[0].plot([0.3, 1], [0.3, 1], c='k', linewidth=0.75)
    ax[0].annotate('%0.2f' % (n_ex / n_in),
                   xy=(0.05, 0.17),
                   xycoords='axes fraction',
                   size=legendsize,
                   color='r')
    ax[0].annotate('p=%s' % (p2str(pchi)),
                   xy=(0.05, 0.025),
                   xycoords='axes fraction',
                   size=legendsize)
    ax[0].set_xlabel('Extrinsicity', fontsize=fontsize)
    ax[0].set_xticks([0, 1])
    ax[0].set_yticks([0, 1])
    ax[0].set_xlim(0, 1)
    ax[0].set_ylim(0, 1)
    ax[0].tick_params(axis='both', which='major', labelsize=ticksize)
    ax[0].spines['top'].set_visible(False)
    ax[0].spines['right'].set_visible(False)
    ax[0].set_ylabel('Intrinsicity', fontsize=fontsize)

    # Plot 1d histogram
    edges = np.linspace(-1, 1, 75)
    width = edges[1] - edges[0]
    (bins, _, _) = ax[1].hist(corr_overlap_ratio,
                              bins=edges,
                              color='gray',
                              density=True,
                              histtype='stepfilled')
    ax[1].plot([mean_ratio, mean_ratio], [0, bins.max()], c='k')
    ax[1].annotate('$\mu$' + '=%0.3f\np=%s' % (mean_ratio, p2str(p_1d1samp)),
                   xy=(0.2, 0.8),
                   xycoords='axes fraction',
                   fontsize=legendsize)
    ax[1].set_xticks([-0.5, 0, 0.5])
    ax[1].set_yticks([0, 0.1 / width])
    ax[1].set_yticklabels(['0', '0.1'])
    ax[1].set_ylim(0, 6.5)
    ax[1].set_xlabel('Extrinsicity - Intrinsicity', fontsize=fontsize)
    ax[1].tick_params(axis='both', which='major', labelsize=ticksize)
    ax[1].set_xlim(-0.5, 0.5)
    ax[1].set_ylabel('Normalized counts', fontsize=fontsize)
    ax[1].spines['top'].set_visible(False)
    ax[1].spines['right'].set_visible(False)
Exemple #7
0
def plot_pair_correlation_Romani(simdf, ax):
    stat_fn = 'fig9_SIM_paircorr.txt'
    stat_record(stat_fn, True)

    linew = 0.75
    markersize = 1

    # A->B
    ax[0], x, y, regress = plot_correlogram(ax=ax[0],
                                            df=simdf,
                                            tag='',
                                            direct='A->B',
                                            color='gray',
                                            alpha=1,
                                            markersize=markersize,
                                            linew=linew)

    nsamples = np.sum((~np.isnan(x)) & (~np.isnan(y)))
    stat_record(stat_fn, False, 'SIM A->B, y = %0.2fx + %0.2f, $r_{(%d)}=%0.2f, p=%s$' % \
                (regress['aopt'] * 2 * np.pi, regress['phi0'], nsamples, regress['rho'], p2str(regress['p'])))

    # B->A
    ax[1], x, y, regress = plot_correlogram(ax=ax[1],
                                            df=simdf,
                                            tag='',
                                            direct='B->A',
                                            color='gray',
                                            alpha=1,
                                            markersize=markersize,
                                            linew=linew)

    nsamples = np.sum((~np.isnan(x)) & (~np.isnan(y)))
    stat_record(stat_fn, False, 'SIM B->A, y = %0.2fx + %0.2f, $r_{(%d)}=%0.2f, p=%s$' % \
                (regress['aopt'] * 2 * np.pi, regress['phi0'], nsamples, regress['rho'], p2str(regress['p'])))

    ax[0].set_ylabel('Phase shift (rad)', fontsize=fontsize)
    ax[0].get_shared_y_axes().join(ax[0], ax[1])
    ax[1].set_yticklabels([''] * 4)

    for ax_each in [ax[0], ax[1]]:
        ax_each.spines['top'].set_visible(False)
        ax_each.spines['right'].set_visible(False)

    ax[0].set_title(r'$A\rightarrow B$', fontsize=fontsize)
    ax[1].set_title(r'$B\rightarrow A$', fontsize=fontsize)
Exemple #8
0
def omniplot_pairfields_Romani(simdf, ax):
    stat_fn = 'fig9_SIM_pair_directionality.txt'
    stat_record(stat_fn, True)

    linew = 0.75

    spike_threshs = np.arange(0, 420, 20)
    stats_getter = DirectionalityStatsByThresh('num_spikes_pair',
                                               'rate_R_pvalp', 'rate_Rp')
    linecolor = {'all': 'k', 'border': 'k', 'nonborder': 'k'}
    linestyle = {'all': 'solid', 'border': 'dotted', 'nonborder': 'dashed'}

    # Plot all
    all_dict = stats_getter.gen_directionality_stats_by_thresh(
        simdf, spike_threshs)
    ax[0].plot(spike_threshs,
               all_dict['medianR'],
               c=linecolor['all'],
               linestyle=linestyle['all'],
               label='All',
               linewidth=linew)
    ax[1].plot(spike_threshs,
               all_dict['sigfrac_shift'],
               c=linecolor['all'],
               linestyle=linestyle['all'],
               label='All',
               linewidth=linew)

    # Plot border
    simdf_b = simdf[simdf['border']].reset_index(drop=True)
    border_dict = stats_getter.gen_directionality_stats_by_thresh(
        simdf_b, spike_threshs)
    ax[0].plot(spike_threshs,
               border_dict['medianR'],
               c=linecolor['border'],
               linestyle=linestyle['border'],
               label='Border',
               linewidth=linew)
    ax[1].plot(spike_threshs,
               border_dict['sigfrac_shift'],
               c=linecolor['border'],
               linestyle=linestyle['border'],
               label='Border',
               linewidth=linew)

    # Plot non-border
    simdf_nb = simdf[~simdf['border']].reset_index(drop=True)
    nonborder_dict = stats_getter.gen_directionality_stats_by_thresh(
        simdf_nb, spike_threshs)
    ax[0].plot(spike_threshs,
               nonborder_dict['medianR'],
               c=linecolor['nonborder'],
               linestyle=linestyle['nonborder'],
               label='Non-border',
               linewidth=linew)
    ax[1].plot(spike_threshs,
               nonborder_dict['sigfrac_shift'],
               c=linecolor['nonborder'],
               linestyle=linestyle['nonborder'],
               label='Non-border',
               linewidth=linew)

    # Plot Fraction
    border_nfrac = border_dict['n'] / all_dict['n']
    ax[2].plot(spike_threshs,
               all_dict['datafrac'],
               c=linecolor['all'],
               linestyle=linestyle['all'],
               label='All',
               linewidth=linew)
    ax[2].plot(spike_threshs,
               border_nfrac,
               c=linecolor['border'],
               linestyle=linestyle['border'],
               label='Border',
               linewidth=linew)
    ax[2].plot(spike_threshs,
               1 - border_nfrac,
               c=linecolor['nonborder'],
               linestyle=linestyle['nonborder'],
               label='Non-border',
               linewidth=linew)

    # Binomial test for all fields
    signum_all, n_all = all_dict['shift_signum'][0], all_dict['n'][0]
    p_binom = binom_test(signum_all, n_all, p=0.05, alternative='greater')
    stat_txt = 'Binomial test, greater than p=0.05, %d/%d=%0.4f, p=%s' % (
        signum_all, n_all, signum_all / n_all, p2str(p_binom))
    stat_record(stat_fn, False, stat_txt)
    # ax[1].annotate('Sig. Frac. (All)\n%d/%d=%0.3f\np%s'%(signum_all, n_all, signum_all/n_all, p2str(p_binom)), xy=(0.1, 0.5), xycoords='axes fraction', fontsize=legendsize)

    # # Statistical test
    for idx, ntresh in enumerate(spike_threshs):
        stat_record(stat_fn, False, '======= Threshold=%d ======' % (ntresh))
        # KW test for border median R
        rs_bord_pR, (border_n, nonborder_n), mdns, rs_txt = my_kruskal_2samp(
            border_dict['allR'][idx], nonborder_dict['allR'][idx], 'border',
            'nonborder')
        stat_record(stat_fn, False,
                    "SIM, Median R, border vs non-border: %s" % (rs_txt))

        # Chisquared test for border fractions
        contin = pd.DataFrame({
            'border': [
                border_dict['shift_signum'][idx],
                border_dict['shift_nonsignum'][idx]
            ],
            'nonborder': [
                nonborder_dict['shift_signum'][idx],
                nonborder_dict['shift_nonsignum'][idx]
            ]
        }).to_numpy()

        chi_pborder, _, txt_chiborder = my_chi_2way(contin)
        _, _, fishtxt = my_fisher_2way(contin)
        stat_record(
            stat_fn, False,
            "SIM, Significant fraction, border vs non-border: %s, %s" %
            (txt_chiborder, fishtxt))

    # Plotting asthestic
    ax_ylabels = ['Median R', "Sig. Frac.", "Data Frac."]
    for axid in range(3):
        ax[axid].set_xticks([0, 200, 400])
        ax[axid].set_xticks(np.arange(0, 401, 100), minor=True)
        ax[axid].set_ylabel(ax_ylabels[axid], fontsize=fontsize)
        ax[axid].tick_params(axis='both', which='major', labelsize=ticksize)
        ax[axid].spines['top'].set_visible(False)
        ax[axid].spines['right'].set_visible(False)

    ax[1].set_xlabel('Spike-pair count threshold', fontsize=fontsize)

    customlegend(ax[0],
                 fontsize=legendsize,
                 loc='lower left',
                 bbox_to_anchor=(0.2, 0.5))

    ax[0].set_yticks([0, 0.2, 0.4, 0.6])
    ax[0].set_yticks(np.arange(0, 0.7, 0.1), minor=True)
    ax[1].set_yticks([0, 0.1, 0.2])
    ax[1].set_yticks(np.arange(0, 0.25, 0.05), minor=True)
    ax[2].set_yticks([0, 0.5, 1])
    ax[2].set_yticklabels(['0', '', '1'])
    ax[2].set_yticks(np.arange(0, 1.1, 0.1), minor=True)
    ax[3].axis('off')
Exemple #9
0
def plot_both_slope_offset_Romani(simdf, ax):
    def norm_div(target_hist, divider_hist):
        target_hist_norm = target_hist / divider_hist.reshape(-1, 1)
        target_hist_norm[np.isnan(target_hist_norm)] = 0
        target_hist_norm[np.isinf(target_hist_norm)] = 0
        target_hist_norm = target_hist_norm / np.sum(
            target_hist_norm) * np.sum(target_hist)
        return target_hist_norm

    nap_thresh = 1
    selected_adiff = np.linspace(0, np.pi, 6)  # 20
    offset_bound = (0, 2 * np.pi)
    slope_bound = (-2 * np.pi, 0)
    adiff_edges = np.linspace(0, np.pi, 100)
    offset_edges = np.linspace(offset_bound[0], offset_bound[1], 100)
    slope_edges = np.linspace(slope_bound[0], slope_bound[1], 100)

    stat_fn = 'fig8_SIM_slopeoffset.txt'
    stat_record(stat_fn, True, 'Average Phase precession')

    # Construct pass df
    refangle_key = 'rate_angle'
    passdf_dict = {
        'anglediff': [],
        'slope': [],
        'onset': [],
        'pass_nspikes': []
    }
    spikedf_dict = {'anglediff': [], 'phasesp': []}
    dftmp = simdf[(~simdf[refangle_key].isna())
                  & (simdf['numpass_at_precess'] >= nap_thresh)].reset_index()

    for i in range(dftmp.shape[0]):
        allprecess_df = dftmp.loc[i, 'precess_df']
        precessdf = allprecess_df[allprecess_df['precess_exist']].reset_index(
            drop=True)
        numprecess = precessdf.shape[0]
        if numprecess < 1:
            continue
        ref_angle = dftmp.loc[i, refangle_key]
        anglediff_tmp = cdiff(precessdf['mean_anglesp'].to_numpy(), ref_angle)
        phasesp_tmp = np.concatenate(precessdf['phasesp'].to_list())

        passdf_dict['anglediff'].extend(anglediff_tmp)
        passdf_dict['slope'].extend(precessdf['rcc_m'])
        passdf_dict['onset'].extend(precessdf['rcc_c'])
        passdf_dict['pass_nspikes'].extend(precessdf['pass_nspikes'])

        spikedf_dict['anglediff'].extend(
            repeat_arr(anglediff_tmp,
                       precessdf['pass_nspikes'].to_numpy().astype(int)))
        spikedf_dict['phasesp'].extend(phasesp_tmp)
    passdf = pd.DataFrame(passdf_dict)
    passdf['slope_piunit'] = passdf['slope'] * 2 * np.pi
    spikedf = pd.DataFrame(spikedf_dict)

    absadiff_pass = np.abs(passdf['anglediff'].to_numpy())
    offset = passdf['onset'].to_numpy()
    slope = passdf['slope_piunit'].to_numpy()

    absadiff_spike = np.abs(spikedf['anglediff'].to_numpy())
    phase_spike = spikedf['phasesp'].to_numpy()

    # 1D spike hisotgram
    spikes_bins, spikes_edges = np.histogram(absadiff_spike, bins=adiff_edges)

    # 2D slope/offset histogram
    offset_bins, offset_xedges, offset_yedges = np.histogram2d(
        absadiff_pass, offset, bins=(adiff_edges, offset_edges))
    slope_bins, slope_xedges, slope_yedges = np.histogram2d(absadiff_pass,
                                                            slope,
                                                            bins=(adiff_edges,
                                                                  slope_edges))
    offset_xedm, offset_yedm = midedges(offset_xedges), midedges(offset_yedges)
    slope_xedm, slope_yedm = midedges(slope_xedges), midedges(slope_yedges)
    offset_normbins = norm_div(offset_bins, spikes_bins)
    slope_normbins = norm_div(slope_bins, spikes_bins)

    # Unbinning
    offset_adiff, offset_norm = unfold_binning_2d(offset_normbins, offset_xedm,
                                                  offset_yedm)
    slope_adiff, slope_norm = unfold_binning_2d(slope_normbins, slope_xedm,
                                                slope_yedm)

    # Linear-circular regression
    regress = rcc(offset_adiff, offset_norm)
    offset_m, offset_c, offset_rho, offset_p = regress['aopt'], regress[
        'phi0'], regress['rho'], regress['p']
    regress = rcc(slope_adiff, slope_norm)
    slope_m, slope_c, slope_rho, slope_p = regress['aopt'], regress[
        'phi0'], regress['rho'], regress['p']
    slope_c = slope_c - 2 * np.pi
    stat_record(
        stat_fn, False, 'LC_Regression Onset-adiff $r_{(%d)}=%0.3f, p=%s$' %
        (offset_bins.sum(), offset_rho, p2str(offset_p)))
    stat_record(
        stat_fn, False, 'LC_Regression Slope-adiff $r_{(%d)}=%0.3f, p=%s$' %
        (slope_bins.sum(), slope_rho, p2str(slope_p)))

    # # Plot average precession curves
    low_mask = absadiff_pass < (np.pi / 6)
    high_mask = absadiff_pass > (np.pi - np.pi / 6)
    slopes_high_all, offsets_high_all = slope[high_mask], offset[high_mask]
    slopes_low_all, offsets_low_all = slope[low_mask], offset[low_mask]

    pval_slope, _, slope_descrips, slopetxt = my_kruskal_2samp(
        slopes_low_all, slopes_high_all, 'low-$|d|$', 'high-$|d|$')
    (mdn_slopel, lqr_slopel, hqr_slopel), (mdn_slopeh, lqr_slopeh,
                                           hqr_slopeh) = slope_descrips

    pval_offset, _, offset_descrips, offsettxt = my_ww_2samp(
        offsets_low_all, offsets_high_all, 'low-$|d|$', 'high-$|d|$')
    (cmean_offsetl, sem_offsetl), (cmean_offseth,
                                   sem_offseth) = offset_descrips

    xdum = np.linspace(0, 1, 10)
    high_agg_ydum = mdn_slopeh * xdum + cmean_offseth
    low_agg_ydum = mdn_slopel * xdum + cmean_offsetl
    slopel_valstr = r'low-$|d|=%0.2f$' % (mdn_slopel)
    slopeh_valstr = r'high-$|d|=%0.2f$' % (mdn_slopeh)
    offsetl_valstr = r'low-$|d|=%0.2f$' % (cmean_offsetl)
    offseth_valstr = r'high-$|d|=%0.2f$' % (cmean_offseth)
    stat_record(stat_fn, False, '===== Average precession curves ====')
    stat_record(stat_fn, False,
                'Slope, %s, %s, %s' % (slopel_valstr, slopeh_valstr, slopetxt))
    stat_record(
        stat_fn, False,
        'Onset, %s, %s, %s' % (offsetl_valstr, offseth_valstr, offsettxt))

    ax[0].plot(xdum, high_agg_ydum, c='lime', label='$|d|>5\pi/6$')
    ax[0].plot(xdum, low_agg_ydum, c='darkblue', label='$|d|<\pi/6$')

    ax[0].annotate('$p_s$' + '=%s' % (p2str(pval_slope)),
                   xy=(0.015, 0.2 + 0.03),
                   xycoords='axes fraction',
                   fontsize=legendsize)
    ax[0].annotate('$p_o$' + '=%s' % (p2str(pval_offset)),
                   xy=(0.015, 0.035 + 0.03),
                   xycoords='axes fraction',
                   fontsize=legendsize)
    ax[0].spines["top"].set_visible(False)
    ax[0].spines["right"].set_visible(False)
    ax[0].set_xticks([0, 1])
    ax[0].set_xlim(0, 1)
    ax[0].set_ylim(-np.pi - 1, np.pi + 0.3)
    ax[0].set_yticks([-np.pi, 0, np.pi])
    ax[0].set_yticklabels(['$-\pi$', '0', '$\pi$'])
    ax[0].tick_params(labelsize=ticksize)
    ax[0].set_xlabel('Position')
    customlegend(ax[0],
                 fontsize=legendsize,
                 loc='lower left',
                 handlelength=0.5,
                 bbox_to_anchor=(0.1, 0.7))
    ax[0].set_ylabel('Phase (rad)', fontsize=fontsize)

    # # Spike phases
    low_mask_sp = absadiff_spike < (np.pi / 6)
    high_mask_sp = absadiff_spike > (np.pi - np.pi / 6)
    phasesph = phase_spike[high_mask_sp]
    phasespl = phase_spike[low_mask_sp]
    fstat, k_pval = circ_ktest(phasesph, phasespl)
    p_ww, _, _, p_wwtxt = my_ww_2samp(phasesph, phasespl, r'$high-|d|$',
                                      r'$low-|d|$')
    mean_phasesph = circmean(phasesph)
    mean_phasespl = circmean(phasespl)
    nh, _, _ = ax[1].hist(phasesph,
                          bins=36,
                          density=True,
                          histtype='step',
                          color='lime')
    nl, _, _ = ax[1].hist(phasespl,
                          bins=36,
                          density=True,
                          histtype='step',
                          color='darkblue')
    ml = max(nh.max(), nl.max())
    ax[1].scatter(mean_phasesph,
                  ml * 1.1,
                  marker='|',
                  color='lime',
                  linewidth=0.75)
    ax[1].scatter(mean_phasespl,
                  ml * 1.1,
                  marker='|',
                  color='darkblue',
                  linewidth=0.75)
    ax[1].annotate(r'$p$=%s' % (p2str(p_ww)),
                   xy=(0.3, 0.1),
                   xycoords='axes fraction',
                   fontsize=legendsize)
    ax[1].set_xlim(-np.pi, np.pi)
    ax[1].set_xticks([-np.pi, 0, np.pi])
    ax[1].set_xticklabels(['$-\pi$', '0', '$\pi$'])
    ax[1].set_yticks([])
    ax[1].tick_params(labelsize=ticksize)
    ax[1].spines["top"].set_visible(False)
    ax[1].spines["right"].set_visible(False)
    ax[1].spines["left"].set_visible(False)
    ax[1].set_xlabel('Phase (rad)', fontsize=fontsize)
    ax[1].set_ylabel('Relative\nfrequency', fontsize=fontsize)

    stat_record(stat_fn, False,
                'SIM, difference of mean spike phases, %s' % (p_wwtxt))
    stat_record(stat_fn, False,
                r'SIM, difference of concentration Bartlett\'s test $F_{(%d, %d)}=%0.2f, p=%s$' % \
                (phasesph.shape[0], phasespl.shape[0], fstat, p2str(k_pval)))
Exemple #10
0
def plot_field_bestprecession_Romani(simdf, ax):

    print('Plot field best precession')
    stat_fn = 'fig8_SIM_field_precess.txt'
    stat_record(stat_fn, True)
    nap_thresh = 1

    # Stack data
    numpass_mask = simdf['numpass_at_precess'].to_numpy() >= nap_thresh
    numpass_low_mask = simdf['numpass_at_precess_low'].to_numpy() >= nap_thresh
    precess_adiff = []
    precess_nspikes = []
    all_adiff = []
    all_slopes = []

    # Density of Fraction, Spikes and Ratio
    df_this = simdf[numpass_mask
                    & (~simdf['rate_angle'].isna())].reset_index(drop=True)
    for i in range(df_this.shape[0]):
        numpass_at_precess = df_this.loc[i, 'numpass_at_precess']
        if numpass_at_precess < nap_thresh:
            continue
        refangle = df_this.loc[i, 'rate_angle']
        allprecess_df = df_this.loc[i, 'precess_df']
        if allprecess_df.shape[0] < 1:
            continue
        precess_df = allprecess_df[allprecess_df['precess_exist']]
        precess_counts = precess_df.shape[0]
        if precess_counts > 0:
            precess_adiff.append(
                cdiff(precess_df['mean_anglesp'].to_numpy(), refangle))
            precess_nspikes.append(precess_df['pass_nspikes'].to_numpy())
        if allprecess_df.shape[0] > 0:
            all_adiff.append(
                cdiff(allprecess_df['mean_anglesp'].to_numpy(), refangle))
            all_slopes.append(allprecess_df['rcc_m'].to_numpy())
    precess_adiff = np.abs(np.concatenate(precess_adiff))
    precess_nspikes = np.abs(np.concatenate(precess_nspikes))
    adiff_spikes_p = repeat_arr(precess_adiff, precess_nspikes.astype(int))
    adiff_bins = np.linspace(0, np.pi, 45)
    adm = midedges(adiff_bins)
    precess_bins, _ = np.histogram(precess_adiff, bins=adiff_bins)
    spike_bins_p, _ = np.histogram(adiff_spikes_p, bins=adiff_bins)
    spike_bins = spike_bins_p
    norm_bins = (precess_bins / spike_bins)
    norm_bins[np.isnan(norm_bins)] = 0
    norm_bins[np.isinf(norm_bins)] = 0
    precess_allcount = precess_bins.sum()
    rho, pval = spearmanr(adm, norm_bins)
    pm, pc, pr, ppval, _ = linregress(adm, norm_bins / norm_bins.sum())
    xdum = np.linspace(adm.min(), adm.max(), 10)
    linew_ax0 = 0.6
    ax[0].step(adm,
               precess_bins / precess_bins.sum(),
               color='navy',
               linewidth=linew_ax0,
               label='Precession')
    ax[0].step(adm,
               spike_bins / spike_bins.sum(),
               color='orange',
               linewidth=linew_ax0,
               label='Spike')
    ax[0].step(adm,
               norm_bins / norm_bins.sum(),
               color='green',
               linewidth=linew_ax0,
               label='Ratio')
    ax[0].plot(xdum, xdum * pm + pc, color='green', linewidth=linew_ax0)
    ax[0].set_xticks([0, np.pi / 2, np.pi])
    ax[0].set_xticklabels(['0', '$\pi/2$', '$\pi$'])
    # ax[0].set_ylim([0.01, 0.06])
    ax[0].set_yticks([0, 0.1])
    ax[0].tick_params(labelsize=ticksize)
    ax[0].spines["top"].set_visible(False)
    ax[0].spines["right"].set_visible(False)
    ax[0].set_xlabel(r'$|d(\theta_{pass}, \theta_{rate})|$' + ' (rad)',
                     fontsize=fontsize)
    ax[0].set_ylabel('Relative count', fontsize=fontsize, labelpad=5)
    customlegend(ax[0],
                 fontsize=legendsize,
                 bbox_to_anchor=[0, 0.5],
                 loc='lower left')
    ax[0].annotate('p=%s' % (p2str(pval)),
                   xy=(0.4, 0.5),
                   xycoords='axes fraction',
                   fontsize=legendsize,
                   color='green')
    stat_record(
        stat_fn, False,
        r"SIM Spearman's correlation: $r_{s(%d)}=%0.2f, p=%s$ " %
        (precess_allcount, rho, p2str(pval)))

    # Plot Rate angles vs Precess angles

    nprecessmask = simdf['precess_df'].apply(
        lambda x: x['precess_exist'].sum()) > 1
    numpass_mask = numpass_mask[nprecessmask]
    numpass_low_mask = numpass_low_mask[nprecessmask]
    simdf2 = simdf[nprecessmask].reset_index(drop=True)
    rateangles = simdf2['rate_angle'].to_numpy()
    precessangles = simdf2['precess_angle'].to_numpy()
    precessangles_low = simdf2['precess_angle_low'].to_numpy()

    ax[1].scatter(rateangles[numpass_mask],
                  precessangles[numpass_mask],
                  marker='.',
                  c='gray',
                  s=2)
    ax[1].plot([0, np.pi], [np.pi, 2 * np.pi], c='k')
    ax[1].plot([np.pi, 2 * np.pi], [0, np.pi], c='k')
    ax[1].set_xlabel(r'$\theta_{rate}$', fontsize=fontsize)
    ax[1].set_xticks([0, np.pi, 2 * np.pi])
    ax[1].set_xticklabels(['$0$', '$\pi$', '$2\pi$'], fontsize=fontsize)
    ax[1].set_yticks([0, np.pi, 2 * np.pi])
    ax[1].set_yticklabels(['$0$', '$\pi$', '$2\pi$'], fontsize=fontsize)
    ax[1].spines["top"].set_visible(False)
    ax[1].spines["right"].set_visible(False)
    ax[1].set_ylabel(r'$\theta_{Precess}$', fontsize=fontsize)

    # Plot Histogram: d(precess, rate)
    mask = (~np.isnan(rateangles)) & (~np.isnan(precessangles) & numpass_mask)
    adiff = cdiff(precessangles[mask], rateangles[mask])
    bins, edges = np.histogram(adiff, bins=np.linspace(-np.pi, np.pi, 36))
    bins_norm = bins / np.sum(bins)
    l = bins_norm.max()
    ax[2].bar(midedges(edges),
              bins_norm,
              width=edges[1] - edges[0],
              zorder=0,
              color='gray')
    linewidth = 1
    mean_angle = shiftcyc_full2half(circmean(adiff))
    ax[2].annotate("",
                   xy=(mean_angle, l),
                   xytext=(0, 0),
                   color='k',
                   zorder=3,
                   arrowprops=dict(arrowstyle="->"))
    ax[2].plot([0, 0], [0, l], c='k', linewidth=linewidth, zorder=3)
    ax[2].scatter(0, 0, s=16, c='gray')
    ax[2].spines['polar'].set_visible(False)
    ax[2].set_xticks([0, np.pi / 2, np.pi, 3 * np.pi / 2])
    ax[2].set_yticks([0, l / 2])
    ax[2].set_yticklabels([])
    ax[2].set_xticklabels([])
    v_pval, v_stat = vtest(adiff, mu=np.pi)
    ax[2].annotate('p=%s' % (p2str(v_pval)),
                   xy=(0.25, 0.95),
                   xycoords='axes fraction',
                   fontsize=legendsize)
    ax[2].annotate(r'$\theta_{rate}$',
                   xy=(0.95, 0.525),
                   xycoords='axes fraction',
                   fontsize=fontsize + 1)
    stat_record(
        stat_fn, False, r'SIM, d(precess, rate), $V_{(%d)}=%0.2f, p=%s$' %
        (bins.sum(), v_stat, p2str(v_pval)))
    ax[2].set_ylabel('All\npasses', fontsize=fontsize)

    # Plot Histogram: d(precess_low, rate)
    mask_low = (~np.isnan(rateangles)) & (~np.isnan(precessangles_low)
                                          & numpass_low_mask)
    adiff = cdiff(precessangles_low[mask_low], rateangles[mask_low])
    bins, edges = np.histogram(adiff, bins=np.linspace(-np.pi, np.pi, 36))
    bins_norm = bins / np.sum(bins)
    l = bins_norm.max()
    ax[3].bar(midedges(edges),
              bins_norm,
              width=edges[1] - edges[0],
              color='gray',
              zorder=0)
    mean_angle = shiftcyc_full2half(circmean(adiff))
    ax[3].annotate("",
                   xy=(mean_angle, l),
                   xytext=(0, 0),
                   color='k',
                   zorder=3,
                   arrowprops=dict(arrowstyle="->"))
    ax[3].plot([0, 0], [0, l], c='k', linewidth=linewidth, zorder=3)
    ax[3].scatter(0, 0, s=16, c='gray')
    ax[3].spines['polar'].set_visible(False)
    ax[3].set_xticks([0, np.pi / 2, np.pi, 3 * np.pi / 2])
    ax[3].set_yticks([0, l / 2])
    ax[3].set_yticklabels([])
    ax[3].set_xticklabels([])
    v_pval, v_stat = vtest(adiff, mu=np.pi)
    ax[3].annotate('p=%s' % (p2str(v_pval)),
                   xy=(0.25, 0.95),
                   xycoords='axes fraction',
                   fontsize=legendsize)
    ax[3].annotate(r'$\theta_{rate}$',
                   xy=(0.95, 0.525),
                   xycoords='axes fraction',
                   fontsize=fontsize + 1)
    stat_record(
        stat_fn, False, r'SIM, d(precess_low, rate), $V_{(%d)}=%0.2f, p=%s$' %
        (bins.sum(), v_stat, p2str(v_pval)))
    ax[3].set_ylabel('Low-spike\npasses', fontsize=fontsize)