Exemplo n.º 1
0
def psthcorr(rec, nids=None, ssnids=None, ssseps=None, natexps=False, strange=None, plot=True):
    if nids == None:
        nids = sorted(rec.n) # use active neurons
    if ssnids == None:
        ssnids = nids # use nids as the superset
    nn = len(nids)
    nnss = len(ssnids)
    # note that using norm=True or norm='ntrials' doesn't seem to make a difference to the
    # results, probably doesn't matter for calculating corrs:
    midbins, psths, spikets = rec.psth(nids=nids, natexps=natexps, strange=strange, plot=False,
                                       binw=0.02, tres=0.005, norm=True)
    rho = np.corrcoef(psths) # defaults to bias=1
    rho[np.diag_indices(nn)] = np.nan # nan the diagonal, which imshow plots as white
    ssrho = np.zeros((nnss, nnss)) # superset rho matrix
    ssrho.fill(np.nan) # init with nans
    # load up values into appropriate spots in superset rho matrix:
    for i in range(nn):
        for j in range(nn):
            ssi, ssj = ssnids.searchsorted([nids[i], nids[j]])
            ssrho[ssi, ssj] = rho[i, j]

    if plot == False:
        return ssrho

    # plot superset rho matrix:
    figure(figsize=FIGSIZE)
    imshow(ssrho, vmin=-1, vmax=1, cmap='jet') # cmap='gray' is too bland
    ssnidticks = np.arange(0, nnss, 10)
    xticks(ssnidticks)
    yticks(ssnidticks)
    if SHOWCOLORBAR:
        colorbar()
    basetitle = rec.absname
    if strange != None:
        strange_sec = tuple(np.array(strange)/1e6) # convert to sec for display
        basetitle += '_strange=(%.f, %.f)' % strange_sec
    gcfm().window.setWindowTitle(basetitle + '_rho_mat')
    tight_layout(pad=0.3)

    # plot rho histogram:
    lti = np.tril_indices(nnss, -1) # lower triangle (below diagonal) indices of ssrho
    ssrhol = ssrho[lti]
    notnanis = np.logical_not(np.isnan(ssrhol)) # indices of non-nan values
    fssrhol = ssrhol[notnanis] # ssrhol filtered out for nans
    fssrholmean = fssrhol.mean()
    t, p = ttest_1samp(fssrhol, 0) # 2-sided ttest relative to 0
    print('mean=%g, t=%g, p=%g' % (fssrholmean, t, p))
    if p < ALPHA0:
        pstring = '$p<%g$' % ceilsigfig(p)
    else:
        pstring = '$p>%g$' % floorsigfig(p)
    figure(figsize=FIGSIZE)
    rhobins = np.arange(RHOMIN, RHOMAX+0.0333, 0.0333) # left edges + rightmost edge
    n = hist(fssrhol, bins=rhobins, color='k')[0]
    axvline(x=fssrholmean, c='r', ls='--') # draw vertical red line at mean fssrhol
    axvline(x=0, c='e', ls='--') # draw vertical grey line at x=0
    xlim(xmin=RHOMIN, xmax=RHOMAX)
    ylim(ymax=n.max()) # effectively normalizes the histogram
    rhoticks = np.arange(-0.2, 1+0.2, 0.2) # excluding the final 1
    xticks(rhoticks)
    yticks([n.max()]) # turn off y ticks to save space
    #yticks([0, n.max()])
    text(0.98, 0.98, '$\mu$=%.2g\n%s' % (fssrholmean, pstring), color='k',
         transform=gca().transAxes, horizontalalignment='right', verticalalignment='top')
    gcfm().window.setWindowTitle(basetitle + '_rho_hist')
    tight_layout(pad=0.3)

    # plot rho vs separation:
    fssseps = ssseps[notnanis] # ssseps filtered out for nans
    figure(figsize=FIGSIZE)
    # scatter plot:
    pl.plot(fssseps, fssrhol, 'k.')
    # bin seps and plot mean rho in each bin:
    sepbins = np.arange(0, fssseps.max()+SEPBINW, SEPBINW) # left edges
    sepmeans, rhomeans, rhostds = scatterbin(fssseps, fssrhol, sepbins)
    #pl.plot(sepmeans, rhomeans, 'r.-', ms=10, lw=2)
    errorbar(sepmeans, rhomeans, yerr=rhostds, fmt='r.-', ms=10, lw=2, zorder=9999)
    xlim(xmin=0, xmax=SEPMAX)
    ylim(ymin=RHOMIN, ymax=RHOMAX)
    septicks = np.arange(0, fssseps.max()+100, 500)
    xticks(septicks)
    yticks(rhoticks)
    gcfm().window.setWindowTitle(basetitle + '_rho_sep')
    tight_layout(pad=0.3)
    return ssrho
for recname in sorted(mot):
    rec = eval(recname)
    mviname = os.path.basename(rec.e0.s.fname)
    framei0, framei1 = rec.e0.d.framei[0], rec.e0.d.framei[-1]
    print('%s: %s, frameis %d:%d' % (recname, mviname, framei0, framei1))
    mvi2mot[(mviname, framei0)] = mot[recname]
allmotion = np.hstack(list(mvi2mot.values()))
allmotion = np.hstack([allmotion, -allmotion]) # make it symmetric around 0
motionbins = np.arange(-300, 300+MOTIONBINW, MOTIONBINW) # deg/s, symmetric around 0
midbins = motionbins[:-1] + MOTIONBINW / 2
motioncount = np.histogram(allmotion, bins=motionbins)[0]
k = kurtosis(allmotion)
# kurtosistest() seems to use the method of Anscombe & Glynn (1983),
# http://biomet.oxfordjournals.org/content/70/1/227
z, p = kurtosistest(allmotion)
pstring = 'p < %g' % ceilsigfig(p)
# normally distributed signal with same std as data, to check that its kurtosis is 0:
#nsamples = 10000000
#normal = scipy.random.normal(0, allmotion.std(), nsamples)
#normalcount = np.histogram(normal, bins=motionbins)[0]
normalcount = core.g(0, allmotion.std(), midbins) # generate normal distrib directly
# normalize to get same probability mass:
normalcount = normalcount / normalcount.sum() * motioncount.sum()
plot(midbins, normalcount, marker=None, ls='-', c='0.7', lw=2)
plot(midbins, motioncount, marker=None, ls='-', c='k', lw=2)
text(0.98, 0.98, 'k = %.1f' % k, # kurtosis
     horizontalalignment='right', verticalalignment='top',
     transform=gca().transAxes, color='k')
text(0.98, 0.90, '%s' % pstring, # p-value of null (normal) hypothesis of kurtosis test
     horizontalalignment='right', verticalalignment='top',
     transform=gca().transAxes, color='k')
Exemplo n.º 3
0
u, p = mannwhitneyu(rpsths[0], rpsths[1]) # 1-sided
dfiltrpsths = rpsths[1][rpsths[1] != 0] # filter out 0 values
sfiltrpsths = rpsths[0][rpsths[0] != 0]
smean = 10**(log10(dfiltrpsths).mean()) # geometric mean, excluding 0 values
dmean = 10**(log10(sfiltrpsths).mean())
logu, logp = mannwhitneyu(log10(dfiltrpsths), log10(sfiltrpsths)) # 1-sided, filtered log values
print('u, p:', u, p)
print('logu, logp:', logu, logp)
# display means and p value:
text(0.02, 0.18, '$\mu$ = %.1f Hz' % smean, # synched
                 horizontalalignment='left', verticalalignment='bottom',
                 transform=gca().transAxes, color='r')
text(0.02, 0.10, '$\mu$ = %.1f Hz' % dmean, # desynched
                 horizontalalignment='left', verticalalignment='bottom',
                 transform=gca().transAxes, color='b')
text(0.02, 0.02, 'p < %.1g' % ceilsigfig(p, 1),
                 horizontalalignment='left', verticalalignment='bottom',
                 transform=gca().transAxes, color='k')
# arrow doesn't display correctly on log axis, use annotate instead:
ymin, ymax = ylim()
logymin, logymax = log10(ymin), log10(ymax)
logyrange = logymax - logymin
annotate('', xy=(smean, 10**(logymin+(6/7)*logyrange)), xycoords='data', # synched
             xytext=(smean, ymax), textcoords='data',
             arrowprops=dict(fc='r', ec='none', width=1.3, headwidth=7, frac=0.5))
annotate('', xy=(dmean, 10**(logymin+(6/7)*logyrange)), xycoords='data', # desynched
             xytext=(dmean, ymax), textcoords='data',
             arrowprops=dict(fc='b', ec='none', width=1.3, headwidth=7, frac=0.5))
titlestr = 'PSTH distribution %s' % urecnames
gcfm().window.setWindowTitle(titlestr)
tight_layout(pad=0.3)
Exemplo n.º 4
0
def psthcorrdiff(rhos, seps, basetitle):
    """Plot difference of a pair of rho matrices (rhos[0] - rhos[1]). seps is the
    corresponding distance matrix"""
    assert len(rhos) == 2

    # calc rho difference matrix:
    rhod = rhos[0] - rhos[1]
    assert rhod.shape[0] == rhod.shape[1] # square
    nn = rhod.shape[0]
    
    # plot rho diff matrix:
    figure(figsize=FIGSIZE)
    imshow(rhod, vmin=-1, vmax=1, cmap='jet') # cmap='gray' is too bland
    ssnidticks = np.arange(0, nn, 10)
    xticks(ssnidticks)
    yticks(ssnidticks)
    if SHOWCOLORBAR:
        colorbar()
    gcfm().window.setWindowTitle(basetitle + '_rhod_mat')
    tight_layout(pad=0.3)

    # plot rho difference histogram:
    lti = np.tril_indices(nn, -1) # lower triangle (below diagonal) indices
    rhol = rhod[lti]
    notnanis = np.logical_not(np.isnan(rhol)) # indices of non-nan values
    frhol = rhol[notnanis] # rhol filtered out for nans
    frholmean = frhol.mean()
    t, p = ttest_1samp(frhol, 0) # 2-sided ttest relative to 0
    print('mean=%g, t=%g, p=%g' % (frholmean, t, p))
    if p < ALPHA0:
        pstring = '$p<%g$' % ceilsigfig(p)
    else:
        pstring = '$p>%g$' % floorsigfig(p)
    figure(figsize=FIGSIZE)
    rhobins = np.arange(RHODIFFMIN, RHODIFFMAX+0.0333, 0.0333) # left edges + rightmost edge
    n = hist(frhol, bins=rhobins, color='k')[0]
    axvline(x=frholmean, c='r', ls='--') # draw vertical red line at mean frhol
    axvline(x=0, c='e', ls='--') # draw vertical grey line at x=0
    xlim(xmin=RHODIFFMIN, xmax=RHODIFFMAX)
    ylim(ymax=n.max()) # effectively normalizes the histogram
    rhoticks = np.arange(-0.6, 0.6+0.2, 0.2)
    xticks(rhoticks)
    yticks([n.max()]) # turn off y ticks to save space
    #yticks([0, n.max()])
    text(0.98, 0.98, '$\mu$=%.2g\n%s' % (frholmean, pstring), color='k',
         transform=gca().transAxes, horizontalalignment='right', verticalalignment='top')
    gcfm().window.setWindowTitle(basetitle + '_rhod_hist')
    tight_layout(pad=0.3)
    
    # plot rho difference vs separation:
    fseps = seps[notnanis] # seps filtered out for nans
    figure(figsize=FIGSIZE)
    # scatter plot:
    pl.plot(fseps, frhol, 'k.')
    # bin seps and plot mean rho in each bin:
    sortis = np.argsort(fseps)
    seps = fseps[sortis]
    rhos = frhol[sortis]
    sepbins = np.arange(0, seps.max()+SEPBINW, SEPBINW) # left edges
    sepis = seps.searchsorted(sepbins)
    sepmeans, rhomeans, rhostds = [], [], []
    for sepi0, sepi1 in zip(sepis[:-1], sepis[1:]): # iterate over sepbins
        sepmeans.append(seps[sepi0:sepi1].mean()) # mean sep of all points in this sepbin
        rhoslice = rhos[sepi0:sepi1] # rhos in this sepbin
        rhomeans.append(rhoslice.mean()) # mean rho of all points in this sepbin
        rhostds.append(rhoslice.std()) # std of rho in this sepbin
    #pl.plot(sepmeans, rhomeans, 'r.-', ms=10, lw=2)
    errorbar(sepmeans, rhomeans, yerr=rhostds, fmt='r.-', ms=10, lw=2, zorder=9999)
    xlim(xmin=0, xmax=SEPMAX)
    ylim(ymin=RHODIFFMIN, ymax=RHODIFFMAX)
    septicks = np.arange(0, seps.max()+100, 500)
    xticks(septicks)
    yticks(rhoticks)
    gcfm().window.setWindowTitle(basetitle + '_rhod_sep')
    tight_layout(pad=0.3)
Exemplo n.º 5
0
plot(modelx, dmodel, 'b--', lw=1, alpha=0.5)
xscale('log')
xlim(xmin=10**logmin, xmax=10**logmax)
ylim(ymax=ymax)
xticks(ticks)
yticks(range(0, 40+10, 10))
xlabel('mean firing rate (Hz)')
ylabel('unit count')
# display geometric means and p value:
text(0.02, 0.98, '$\mu$ = %.2f Hz' % smean, # synched
                 horizontalalignment='left', verticalalignment='top',
                 transform=gca().transAxes, color='r')
text(0.02, 0.90, '$\mu$ = %.2f Hz' % dmean, # desynched
                 horizontalalignment='left', verticalalignment='top',
                 transform=gca().transAxes, color='b')
text(0.02, 0.82, 'p < %.1g' % ceilsigfig(p, 1),
                 horizontalalignment='left', verticalalignment='top',
                 transform=gca().transAxes, color='k')
text(0.98, 0.98, '$\sigma$ = %.2f' % slogstd, # synched
                 horizontalalignment='right', verticalalignment='top',
                 transform=gca().transAxes, color='r')
text(0.98, 0.90, '$\sigma$ = %.2f' % dlogstd, # desynched
                 horizontalalignment='right', verticalalignment='top',
                 transform=gca().transAxes, color='b')
# arrow doesn't display correctly on log axis, use annotate instead:
annotate('', xy=(smean, (6/7)*40), xycoords='data', # synched
             xytext=(smean, 40), textcoords='data',
             arrowprops=dict(fc='r', ec='none', width=1.3, headwidth=7, frac=0.5))
annotate('', xy=(dmean, (6/7)*40), xycoords='data', # desynched
             xytext=(dmean, 40), textcoords='data',
             arrowprops=dict(fc='b', ec='none', width=1.3, headwidth=7, frac=0.5))
Exemplo n.º 6
0
            gcfm().window.setWindowTitle(titlestr)
            tight_layout(pad=0.3)

# concatenate rho and sep lists into arrays:
rhos, nrhos, seps = {}, {}, {}
for slabel in ([None]+slabels):
    rhos[slabel] = np.hstack(rhoslist[slabel])
    nrhos[slabel] = np.hstack(nrhoslist[slabel])
    seps[slabel] = np.hstack(sepslist[slabel])

# plot (signal) rho histogram:
dmean = rhos['desynch'].mean()
smean = rhos['synch'].mean()
u, p = mannwhitneyu(rhos['desynch'], rhos['synch']) # 1-sided
if p < ALPHA:
    pstring = 'p < %g' % ceilsigfig(p)
else:
    pstring = 'p > %g' % floorsigfig(p)
'''
# T-tests of both distribs relative to 0, not so useful:
dt, dp = ttest_1samp(rhos['desynch'], 0) # 2-sided ttest relative to 0
st, sp = ttest_1samp(rhos['synch'], 0) # 2-sided ttest relative to 0
print('dmean=%g, t=%g, p=%g' % (dmean, dt, dp))
print('smean=%g, t=%g, p=%g' % (smean, st, sp))
if dp < ALPHA:
    dpstring = 'p < %g' % ceilsigfig(dp)
else:
    dpstring = 'p > %g' % floorsigfig(dp)
if sp < ALPHA:
    spstring = 'p < %g' % ceilsigfig(sp)
else:
Exemplo n.º 7
0
        '$\mu$ = %.1f ms' % smean,  # synched
        horizontalalignment='left',
        verticalalignment='top',
        transform=gca().transAxes,
        color='r')
    text(
        0.03,
        0.90,
        '$\mu$ = %.1f ms' % dmean,  # desynched
        horizontalalignment='left',
        verticalalignment='top',
        transform=gca().transAxes,
        color='b')
    text(0.03,
         0.82,
         'p < %.1g' % ceilsigfig(p, 1),
         horizontalalignment='left',
         verticalalignment='top',
         transform=gca().transAxes,
         color='k')
    statesstr = 'manualstates'
else:
    statesstr = 'autostates'
# now that ymax is calculated, plot arrows:
for state in states:
    meanpeakwidth = meanpeakwidths[state]
    clr = STATECOLOURS[state]
    annotate(
        '',
        xy=(meanpeakwidth, (6 / 7) * ymax),
        xycoords='data',  # desynched
Exemplo n.º 8
0
arrow(dmean, dmax+ah*1.1, 0, -ah, head_width=aw, head_length=ah/2,
      length_includes_head=True, color='b')
arrow(smean, smax+ah*1.1, 0, -ah, head_width=aw, head_length=ah/2,
      length_includes_head=True, color='r')
xlabel('LFP reliability')
ylabel('trial count')
xticks([0, 0.2, 0.4, 0.6, 0.8, 1], ['0', '0.2', '0.4', '0.6', '0.8', '1'])
ylim(0, nmax+ah*1.1)
# display means and p value:
text(0.98, 0.98, '$\mu$ = %.2f' % smean, # synched
                 horizontalalignment='right', verticalalignment='top',
                 transform=gca().transAxes, color='r')
text(0.98, 0.90, '$\mu$ = %.2f' % dmean, # desynched
                 horizontalalignment='right', verticalalignment='top',
                 transform=gca().transAxes, color='b')
text(0.98, 0.82, 'p < %.1g' % ceilsigfig(lfpcorrsp, 1),
                 horizontalalignment='right', verticalalignment='top',
                 transform=gca().transAxes, color='k')
gcfm().window.setWindowTitle('LFP_reliability_hist')
tight_layout(pad=0.3)
pl.show() # ensure figures pop up in order

# plot MUACORRS PDFs:
nd = np.histogram(MUACORRS[0], bins=corrbins, density=False)[0]
ns = np.histogram(MUACORRS[1], bins=corrbins, density=False)[0]
dmax, smax = nd.max(), ns.max()
nmax = max(np.hstack([nd, ns]))
ah = nmax / 7 # arrow height
nd = np.hstack([nd, nd[-1]]) # repeat last point for right edge
ns = np.hstack([ns, ns[-1]])
figure(figsize=(3, 3))
Exemplo n.º 9
0
            # calculate coupling of this PSTH with tMUA:
            coup = core.corrcoef(psth, tmua)
            coups[statei].append(coup)
        print()

for statei in stateis:
    rels[statei] = np.asarray(rels[statei])
    spars[statei] = np.asarray(spars[statei])
    coups[statei] = np.asarray(coups[statei])

# plot MUA coupling histogram:
dmean = coups[0].mean()
smean = coups[1].mean()
u, p = mannwhitneyu(coups[0], coups[1])  # 1-sided
if p < ALPHA:
    pstring = 'p < %g' % ceilsigfig(p)
else:
    pstring = 'p > %g' % floorsigfig(p)
figure(figsize=FIGSIZE)
nd = hist(coups[0], bins=coupbins, histtype='step', color='b')[0]
ns = hist(coups[1], bins=coupbins, histtype='step', color='r')[0]
nmax = max(np.hstack([nd, ns]))
xlim(xmin=COUPMIN, xmax=COUPMAX)
ymin, ymax = ylim(0, 34)
axvline(x=0, c='e', ls='-', alpha=0.5,
        zorder=-1)  # draw vertical grey line at x=0
# draw arrows at means:
ah = ymax / 8  # arrow height
arrow(dmean,
      ymax,
      0,
    rec = eval(recname)
    mviname = os.path.basename(rec.e0.s.fname)
    framei0, framei1 = rec.e0.d.framei[0], rec.e0.d.framei[-1]
    print('%s: %s, frameis %d:%d' % (recname, mviname, framei0, framei1))
    mvi2mot[(mviname, framei0)] = mot[recname]
allmotion = np.hstack(list(mvi2mot.values()))
allmotion = np.hstack([allmotion, -allmotion])  # make it symmetric around 0
motionbins = np.arange(-300, 300 + MOTIONBINW,
                       MOTIONBINW)  # deg/s, symmetric around 0
midbins = motionbins[:-1] + MOTIONBINW / 2
motioncount = np.histogram(allmotion, bins=motionbins)[0]
k = kurtosis(allmotion)
# kurtosistest() seems to use the method of Anscombe & Glynn (1983),
# http://biomet.oxfordjournals.org/content/70/1/227
z, p = kurtosistest(allmotion)
pstring = 'p < %g' % ceilsigfig(p)
# normally distributed signal with same std as data, to check that its kurtosis is 0:
#nsamples = 10000000
#normal = scipy.random.normal(0, allmotion.std(), nsamples)
#normalcount = np.histogram(normal, bins=motionbins)[0]
normalcount = core.g(0, allmotion.std(),
                     midbins)  # generate normal distrib directly
# normalize to get same probability mass:
normalcount = normalcount / normalcount.sum() * motioncount.sum()
plot(midbins, normalcount, marker=None, ls='-', c='0.7', lw=2)
plot(midbins, motioncount, marker=None, ls='-', c='k', lw=2)
text(
    0.98,
    0.98,
    'k = %.1f' % k,  # kurtosis
    horizontalalignment='right',
Exemplo n.º 11
0
    '$\mu$ = %.2f' % smean,  # synched
    horizontalalignment='right',
    verticalalignment='top',
    transform=gca().transAxes,
    color='r')
text(
    0.98,
    0.90,
    '$\mu$ = %.2f' % dmean,  # desynched
    horizontalalignment='right',
    verticalalignment='top',
    transform=gca().transAxes,
    color='b')
text(0.98,
     0.82,
     'p < %.1g' % ceilsigfig(lfpcorrsp, 1),
     horizontalalignment='right',
     verticalalignment='top',
     transform=gca().transAxes,
     color='k')
gcfm().window.setWindowTitle('LFP_reliability_hist')
tight_layout(pad=0.3)
pl.show()  # ensure figures pop up in order

# plot MUACORRS PDFs:
nd = np.histogram(MUACORRS[0], bins=corrbins, density=False)[0]
ns = np.histogram(MUACORRS[1], bins=corrbins, density=False)[0]
dmax, smax = nd.max(), ns.max()
nmax = max(np.hstack([nd, ns]))
ah = nmax / 7  # arrow height
nd = np.hstack([nd, nd[-1]])  # repeat last point for right edge
Exemplo n.º 12
0
def psthcorr(rec,
             nids=None,
             ssnids=None,
             ssseps=None,
             natexps=False,
             strange=None,
             plot=True):
    if nids == None:
        nids = sorted(rec.n)  # use active neurons
    if ssnids == None:
        ssnids = nids  # use nids as the superset
    nn = len(nids)
    nnss = len(ssnids)
    # note that using norm=True or norm='ntrials' doesn't seem to make a difference to the
    # results, probably doesn't matter for calculating corrs:
    midbins, psths, spikets = rec.psth(nids=nids,
                                       natexps=natexps,
                                       strange=strange,
                                       plot=False,
                                       binw=0.02,
                                       tres=0.005,
                                       norm=True)
    rho = np.corrcoef(psths)  # defaults to bias=1
    rho[np.diag_indices(
        nn)] = np.nan  # nan the diagonal, which imshow plots as white
    ssrho = np.zeros((nnss, nnss))  # superset rho matrix
    ssrho.fill(np.nan)  # init with nans
    # load up values into appropriate spots in superset rho matrix:
    for i in range(nn):
        for j in range(nn):
            ssi, ssj = ssnids.searchsorted([nids[i], nids[j]])
            ssrho[ssi, ssj] = rho[i, j]

    if plot == False:
        return ssrho

    # plot superset rho matrix:
    figure(figsize=FIGSIZE)
    imshow(ssrho, vmin=-1, vmax=1, cmap='jet')  # cmap='gray' is too bland
    ssnidticks = np.arange(0, nnss, 10)
    xticks(ssnidticks)
    yticks(ssnidticks)
    if SHOWCOLORBAR:
        colorbar()
    basetitle = rec.absname
    if strange != None:
        strange_sec = tuple(np.array(strange) /
                            1e6)  # convert to sec for display
        basetitle += '_strange=(%.f, %.f)' % strange_sec
    gcfm().window.setWindowTitle(basetitle + '_rho_mat')
    tight_layout(pad=0.3)

    # plot rho histogram:
    lti = np.tril_indices(
        nnss, -1)  # lower triangle (below diagonal) indices of ssrho
    ssrhol = ssrho[lti]
    notnanis = np.logical_not(np.isnan(ssrhol))  # indices of non-nan values
    fssrhol = ssrhol[notnanis]  # ssrhol filtered out for nans
    fssrholmean = fssrhol.mean()
    t, p = ttest_1samp(fssrhol, 0)  # 2-sided ttest relative to 0
    print('mean=%g, t=%g, p=%g' % (fssrholmean, t, p))
    if p < ALPHA0:
        pstring = '$p<%g$' % ceilsigfig(p)
    else:
        pstring = '$p>%g$' % floorsigfig(p)
    figure(figsize=FIGSIZE)
    rhobins = np.arange(RHOMIN, RHOMAX + 0.0333,
                        0.0333)  # left edges + rightmost edge
    n = hist(fssrhol, bins=rhobins, color='k')[0]
    axvline(x=fssrholmean, c='r',
            ls='--')  # draw vertical red line at mean fssrhol
    axvline(x=0, c='e', ls='--')  # draw vertical grey line at x=0
    xlim(xmin=RHOMIN, xmax=RHOMAX)
    ylim(ymax=n.max())  # effectively normalizes the histogram
    rhoticks = np.arange(-0.2, 1 + 0.2, 0.2)  # excluding the final 1
    xticks(rhoticks)
    yticks([n.max()])  # turn off y ticks to save space
    #yticks([0, n.max()])
    text(0.98,
         0.98,
         '$\mu$=%.2g\n%s' % (fssrholmean, pstring),
         color='k',
         transform=gca().transAxes,
         horizontalalignment='right',
         verticalalignment='top')
    gcfm().window.setWindowTitle(basetitle + '_rho_hist')
    tight_layout(pad=0.3)

    # plot rho vs separation:
    fssseps = ssseps[notnanis]  # ssseps filtered out for nans
    figure(figsize=FIGSIZE)
    # scatter plot:
    pl.plot(fssseps, fssrhol, 'k.')
    # bin seps and plot mean rho in each bin:
    sepbins = np.arange(0, fssseps.max() + SEPBINW, SEPBINW)  # left edges
    sepmeans, rhomeans, rhostds = scatterbin(fssseps, fssrhol, sepbins)
    #pl.plot(sepmeans, rhomeans, 'r.-', ms=10, lw=2)
    errorbar(sepmeans,
             rhomeans,
             yerr=rhostds,
             fmt='r.-',
             ms=10,
             lw=2,
             zorder=9999)
    xlim(xmin=0, xmax=SEPMAX)
    ylim(ymin=RHOMIN, ymax=RHOMAX)
    septicks = np.arange(0, fssseps.max() + 100, 500)
    xticks(septicks)
    yticks(rhoticks)
    gcfm().window.setWindowTitle(basetitle + '_rho_sep')
    tight_layout(pad=0.3)
    return ssrho
Exemplo n.º 13
0
def psthcorrdiff(rhos, seps, basetitle):
    """Plot difference of a pair of rho matrices (rhos[0] - rhos[1]). seps is the
    corresponding distance matrix"""
    assert len(rhos) == 2

    # calc rho difference matrix:
    rhod = rhos[0] - rhos[1]
    assert rhod.shape[0] == rhod.shape[1]  # square
    nn = rhod.shape[0]

    # plot rho diff matrix:
    figure(figsize=FIGSIZE)
    imshow(rhod, vmin=-1, vmax=1, cmap='jet')  # cmap='gray' is too bland
    ssnidticks = np.arange(0, nn, 10)
    xticks(ssnidticks)
    yticks(ssnidticks)
    if SHOWCOLORBAR:
        colorbar()
    gcfm().window.setWindowTitle(basetitle + '_rhod_mat')
    tight_layout(pad=0.3)

    # plot rho difference histogram:
    lti = np.tril_indices(nn, -1)  # lower triangle (below diagonal) indices
    rhol = rhod[lti]
    notnanis = np.logical_not(np.isnan(rhol))  # indices of non-nan values
    frhol = rhol[notnanis]  # rhol filtered out for nans
    frholmean = frhol.mean()
    t, p = ttest_1samp(frhol, 0)  # 2-sided ttest relative to 0
    print('mean=%g, t=%g, p=%g' % (frholmean, t, p))
    if p < ALPHA0:
        pstring = '$p<%g$' % ceilsigfig(p)
    else:
        pstring = '$p>%g$' % floorsigfig(p)
    figure(figsize=FIGSIZE)
    rhobins = np.arange(RHODIFFMIN, RHODIFFMAX + 0.0333,
                        0.0333)  # left edges + rightmost edge
    n = hist(frhol, bins=rhobins, color='k')[0]
    axvline(x=frholmean, c='r',
            ls='--')  # draw vertical red line at mean frhol
    axvline(x=0, c='e', ls='--')  # draw vertical grey line at x=0
    xlim(xmin=RHODIFFMIN, xmax=RHODIFFMAX)
    ylim(ymax=n.max())  # effectively normalizes the histogram
    rhoticks = np.arange(-0.6, 0.6 + 0.2, 0.2)
    xticks(rhoticks)
    yticks([n.max()])  # turn off y ticks to save space
    #yticks([0, n.max()])
    text(0.98,
         0.98,
         '$\mu$=%.2g\n%s' % (frholmean, pstring),
         color='k',
         transform=gca().transAxes,
         horizontalalignment='right',
         verticalalignment='top')
    gcfm().window.setWindowTitle(basetitle + '_rhod_hist')
    tight_layout(pad=0.3)

    # plot rho difference vs separation:
    fseps = seps[notnanis]  # seps filtered out for nans
    figure(figsize=FIGSIZE)
    # scatter plot:
    pl.plot(fseps, frhol, 'k.')
    # bin seps and plot mean rho in each bin:
    sortis = np.argsort(fseps)
    seps = fseps[sortis]
    rhos = frhol[sortis]
    sepbins = np.arange(0, seps.max() + SEPBINW, SEPBINW)  # left edges
    sepis = seps.searchsorted(sepbins)
    sepmeans, rhomeans, rhostds = [], [], []
    for sepi0, sepi1 in zip(sepis[:-1], sepis[1:]):  # iterate over sepbins
        sepmeans.append(
            seps[sepi0:sepi1].mean())  # mean sep of all points in this sepbin
        rhoslice = rhos[sepi0:sepi1]  # rhos in this sepbin
        rhomeans.append(
            rhoslice.mean())  # mean rho of all points in this sepbin
        rhostds.append(rhoslice.std())  # std of rho in this sepbin
    #pl.plot(sepmeans, rhomeans, 'r.-', ms=10, lw=2)
    errorbar(sepmeans,
             rhomeans,
             yerr=rhostds,
             fmt='r.-',
             ms=10,
             lw=2,
             zorder=9999)
    xlim(xmin=0, xmax=SEPMAX)
    ylim(ymin=RHODIFFMIN, ymax=RHODIFFMAX)
    septicks = np.arange(0, seps.max() + 100, 500)
    xticks(septicks)
    yticks(rhoticks)
    gcfm().window.setWindowTitle(basetitle + '_rhod_sep')
    tight_layout(pad=0.3)