Example #1
0
def plot_trans_vs_U(iZ, iNHI, grid, trans, ax):

    atoms,nums = zip(*[split_trans_name(t) for t in trans])

    count = dict((k, 0) for k in COLORS)
    for atom, num in zip(atoms, nums):
        col = COLORS[atom]
        N = grid.N[atom][iNHI, :, iZ, roman_map[num]]
        pl.plot(grid.nH, N, lw=3, ls=LS[count[atom] % len(LS)],
                color=col,label=atom+num)
        count[atom] += 1
 
    ax.legend(frameon=0, ncol=2)
    ax.set_ylabel('$\log_{10}\ N\ (\mathrm{cm}^{-2})$')
    ax.set_xlabel('$\log_{10}\ n_\mathrm{H}\ (\mathrm{cm}^{-3})$')

    puttext(0.05, 0.05, '$\log_{10}\ N_\mathrm{HI}=%.3g,\ Z=%.3g$' % (
        grid.NHI[iNHI],grid.Z[iZ]),ax)
    ax.set_xlim(grid.nH[0]+0.01, grid.nH[-1]-0.01)

    ax1 = ax.twiny()
    x0,x1 = ax.get_xlim()
    const = (grid.U + grid.nH)[0]
    assert np.allclose(const, grid.U + grid.nH)
    ax1.set_xlim(const - x0, const - x1)
    ax1.set_xlabel('$\log_{10}\ U$')
def plot_rho_QSO_prop(fig,rho,ab,iqso_from_id,qso_props=None):
    """For a given well defined rho dictionary, it plots different QSO
    properties with the aim to test fo systematics.

    """
    global rbin
    if qso_props is None:
        qso_props=['z','snr','nabs','RMAG','IMAG','ZMAG']
    
    for i,qso_prop in enumerate(qso_props):
        mean = []
        err = []
        median = []
        n = []
        for r in rho:
            # QSOs in this bin
            qids = np.array([iqso_from_id[ind] for ind in r['qid']], dtype=int)
            prop = ab['qso'][qso_prop][qids]
            mean += [np.mean(prop)]
            err  += [np.std(prop)]
            median += [np.median(prop)]
            n  += [len(qids)]
        ax = fig.add_subplot(1,len(qso_props),i)
        ax.errorbar(rbin.cen,mean,yerr=err,capsize=0,fmt='-o',color='k')
        ax.plot(rbin.cen,median,'-r',lw=3)
        for j in range(len(n)):
            puttext(rbin.cen[j], 0.1 , str(n[j]), ax, color='k',
                    fontsize=10, xcoord='data', ha='center')
        ax.set_xlabel('rho')
        ax.set_ylabel(qso_prop)
Example #3
0
def plot_autocorr(chain):
    """ Plot the autocorrelation of parameters in the chain. This can
    be slow if there are many parameters.
    """
    nwalkers, nsamples, npar = chain.shape
    nrows, ncols = get_nrows_ncols(npar)
    fig, axes = get_fig_axes(nrows, ncols, npar)
    for i, ax in enumerate(axes):
        acor = [autocorr(chain[j, :, i], maxlag=150) for j in xrange(nwalkers)]
        distplot(np.transpose(acor), ax=ax)
        ax.axhline(0, color='r', lw=0.5)
        puttext(0.1, 0.1, P['names'][i], ax, fontsize=16)

    return fig, axes
Example #4
0
def plot_autocorr(chain):
    """ Plot the autocorrelation of parameters in the chain. This can
    be slow if there are many parameters.
    """
    nwalkers, nsamples, npar = chain.shape
    nrows, ncols = get_nrows_ncols(npar)
    fig,axes = get_fig_axes(nrows, ncols, npar)
    for i,ax in enumerate(axes):
        acor = [autocorr(chain[j,:,i], maxlag=150) for j in xrange(nwalkers)]
        distplot(np.transpose(acor), ax=ax)
        ax.axhline(0, color='r', lw=0.5)
        puttext(0.1, 0.1, P['names'][i], ax, fontsize=16)

    return fig, axes
Example #5
0
def plot_posteriors_burn(chain, P, npar='all'):
    """ Plot the posteriors of a burn-in sample
    """
    nwalkers, nsamples, npartot = chain.shape
    c = chain.reshape(-1, npartot)

    if npar == 'all':
        npar = npartot

    nrows, ncols = get_nrows_ncols(npar)
    fig, axes = get_fig_axes(nrows, ncols, npar)

    for i, ax in enumerate(axes):
        j = i + 1
        if j == npar:
            j = 0

        ax.plot(c[:, i], c[:, j], '.', ms=1, color='0.5')

        # plot initial walker positions
        ax.plot(chain[:, 0, i],
                chain[:, 0, j],
                '.r',
                ms=4,
                label='p$_{initial}$')

        # and final positions
        ax.plot(chain[:, -1, i],
                chain[:, -1, j],
                '.y',
                ms=4,
                label='p$_{final}$')

        ax.plot(P['ml'][i], P['ml'][j], 'xk', ms=12, mew=4)
        ax.plot(P['ml'][i], P['ml'][j], 'xr', ms=10, mew=2)

        puttext(0.95, 0.05, P['names'][i], ax, fontsize=16, ha='right')
        puttext(0.05, 0.95, P['names'][j], ax, fontsize=16, va='top')
        x0, x1 = chain[:, 0, i].min(), chain[:, 0, i].max()
        dx = x1 - x0
        ax.set_xlim(x0 - 0.1 * dx, x1 + 0.1 * dx)
        y0, y1 = chain[:, 0, j].min(), chain[:, 0, j].max()
        dy = y1 - y0
        ax.set_ylim(y0 - 0.1 * dy, y1 + 0.1 * dy)

    axes[0].legend()
    return fig, axes
Example #6
0
def plot_trans_vs_NHI(iZ, inH, grid, trans, ax):

    atoms,nums = zip(*[split_trans_name(t) for t in trans])

    count = dict((k, 0) for k in COLORS)
    for atom, num in zip(atoms, nums):
        col = COLORS[atom]
        N = grid.N[atom][:, inH, iZ, roman_map[num]]
        pl.plot(grid.NHI, N, lw=2, ls=LS[count[atom] % len(LS)],
                color=col,label=atom+num)
        count[atom] += 1
 
    pl.legend(frameon=0, ncol=3)
    pl.ylabel('$\log_{10}\ N (\mathrm{cm}^{-2}$')
    pl.xlabel('$\log_{10}\ N_\mathrm{HI} (\mathrm{cm}^{-2})$')
    puttext(0.05, 0.95, '$n_{H}=%.3g\  Z=%.3g$' % (
        grid.nH[inH], grid.Z[iZ]), ax)
Example #7
0
def plot_trace(chain, nwplot=10):
    """ Plot the sample trace for a subset of walkers for each parameter.
    """
    nwalkers, nsample, npar = chain.shape
    nrows, ncols = get_nrows_ncols(npar)
    fig, axes = get_fig_axes(nrows, ncols, npar)
    # number of walkers to plot
    nwplot = min(nsample, nwplot)
    for i in range(npar):
        ax = axes[i]
        for j in range(0, nwalkers, max(1, nwalkers // nwplot)):
            ax.plot(chain[j, :, i], lw=0.5)
        puttext(0.9, 0.1, P['names'][i], ax, ha='right', fontsize=14)

        ax.set_xlim(0, nsample)

    return fig, nwplot
Example #8
0
def plot_trace(chain, nwplot=10):
    """ Plot the sample trace for a subset of walkers for each parameter.
    """
    nwalkers, nsample, npar = chain.shape
    nrows, ncols = get_nrows_ncols(npar)
    fig, axes = get_fig_axes(nrows, ncols, npar)
    # number of walkers to plot
    nwplot = min(nsample, nwplot)
    for i in range(npar):
        ax = axes[i]
        for j in range(0, nwalkers, max(1, nwalkers // nwplot)):
            ax.plot(chain[j,:,i], lw=0.5)
        puttext(0.9, 0.1, P['names'][i], ax, ha='right', fontsize=14)

        ax.set_xlim(0, nsample)

    return fig, nwplot
Example #9
0
def plot_posteriors_burn(chain, P, npar="all"):
    """ Plot the posteriors of a burn-in sample
    """
    nwalkers, nsamples, npartot = chain.shape
    c = chain.reshape(-1, npartot)

    if npar == "all":
        npar = npartot

    nrows, ncols = get_nrows_ncols(npar)
    fig, axes = get_fig_axes(nrows, ncols, npar)

    for i, ax in enumerate(axes):
        j = i + 1
        if j == npar:
            j = 0

        ax.plot(c[:, i], c[:, j], ".", ms=1, color="0.5")

        # plot initial walker positions
        ax.plot(chain[:, 0, i], chain[:, 0, j], ".r", ms=4, label="p$_{initial}$")

        # and final positions
        ax.plot(chain[:, -1, i], chain[:, -1, j], ".y", ms=4, label="p$_{final}$")

        ax.plot(P["ml"][i], P["ml"][j], "xk", ms=12, mew=4)
        ax.plot(P["ml"][i], P["ml"][j], "xr", ms=10, mew=2)

        puttext(0.95, 0.05, P["names"][i], ax, fontsize=16, ha="right")
        puttext(0.05, 0.95, P["names"][j], ax, fontsize=16, va="top")
        x0, x1 = chain[:, 0, i].min(), chain[:, 0, i].max()
        dx = x1 - x0
        ax.set_xlim(x0 - 0.1 * dx, x1 + 0.1 * dx)
        y0, y1 = chain[:, 0, j].min(), chain[:, 0, j].max()
        dy = y1 - y0
        ax.set_ylim(y0 - 0.1 * dy, y1 + 0.1 * dy)

    axes[0].legend()
    return fig, axes
Example #10
0
def plot_posteriors_burn(chain, P, npar='all'):
    """ Plot the posteriors of a burn-in sample
    """
    nwalkers, nsamples, npartot = chain.shape
    c = chain.reshape(-1, npartot)

    if npar == 'all':
        npar = npartot

    nrows, ncols = get_nrows_ncols(npar)
    fig, axes = get_fig_axes(nrows, ncols, npar)

    for i,ax in enumerate(axes):
        j = i+1
        if j == npar:
            j = 0

        ax.plot(c[:, i], c[:, j], '.', ms=1, color='0.5')

        # plot initial walker positions
        ax.plot(chain[:,0,i], chain[:,0,j], '.r', ms=4, label='p$_{initial}$')

        # and final positions
        ax.plot(chain[:,-1,i], chain[:,-1,j], '.y', ms=4, label='p$_{final}$')

        ax.plot(P['ml'][i], P['ml'][j], 'xk', ms=12, mew=4)
        ax.plot(P['ml'][i], P['ml'][j], 'xr', ms=10, mew=2)        

        puttext(0.95, 0.05, P['names'][i], ax, fontsize=16, ha='right')
        puttext(0.05, 0.95, P['names'][j], ax, fontsize=16, va='top')
        x0, x1 = chain[:, 0, i].min(), chain[:, 0, i].max()
        dx = x1 - x0
        ax.set_xlim(x0 - 0.1*dx, x1 + 0.1*dx)
        y0, y1 = chain[:, 0, j].min(), chain[:, 0, j].max()
        dy = y1 - y0
        ax.set_ylim(y0 - 0.1*dy, y1 + 0.1*dy)

    axes[0].legend()
    return fig, axes
Example #11
0
def plot_rho_QSO_prop(fig, rho, ab, iqso_from_id, qso_props=None):
    """For a given well defined rho dictionary, it plots different QSO
    properties with the aim to test fo systematics.

    """
    global rbin
    if qso_props is None:
        qso_props = ['z', 'snr', 'nabs', 'RMAG', 'IMAG', 'ZMAG']

    for i, qso_prop in enumerate(qso_props):
        mean = []
        err = []
        median = []
        n = []
        for r in rho:
            # QSOs in this bin
            qids = np.array([iqso_from_id[ind] for ind in r['qid']], dtype=int)
            prop = ab['qso'][qso_prop][qids]
            mean += [np.mean(prop)]
            err += [np.std(prop)]
            median += [np.median(prop)]
            n += [len(qids)]
        ax = fig.add_subplot(1, len(qso_props), i)
        ax.errorbar(rbin.cen, mean, yerr=err, capsize=0, fmt='-o', color='k')
        ax.plot(rbin.cen, median, '-r', lw=3)
        for j in range(len(n)):
            puttext(rbin.cen[j],
                    0.1,
                    str(n[j]),
                    ax,
                    color='k',
                    fontsize=10,
                    xcoord='data',
                    ha='center')
        ax.set_xlabel('rho')
        ax.set_ylabel(qso_prop)
    labels = ['0.6 < Wr$_{2796}$ < 5']
    colors = 'g'
    symbols = 'o'
    offsets = [0]

    for i in range(len(labels)):
        dNdz, dNdz_er, n = find_dndz_vs_rho(
            rho, ab['MgII'], iMgII_from_id,
            ewbins.edges[i], ewbins.edges[i+1])
        y = np.log10(dNdz)
        ylo = np.log10(dNdz - dNdz_er)
        yhi = np.log10(dNdz + dNdz_er)
        errplot(rbin.cen + offsets[i], y, (ylo, yhi), ax=ax,
                fmt=colors[i]+symbols[i], label=labels[i])
        for j in range(len(n)):
            puttext(rbin.cen[j], 0.03 + i*0.03, str(n[j]), ax, color=colors[i],
                    fontsize=10, xcoord='data', ha='center')
    
    ax.legend(frameon=0)
    ax.set_xlabel('Cluster-absorber impact par. (proper Mpc)')
    ax.set_ylabel(r'$dN/dz\ (MgII)$')
    # skip last bin, where not all pairs are measured.
    ax.set_xlim(rbin.edges[0] - rbin.halfwidth[0],
                rbin.edges[-2] + rbin.halfwidth[-1])
    make_log_xlabels(ax)
    make_log_ylabels(ax)
    #fig3.savefig(run_id + '/dNdz_vs_rho.png')
    plt.show()


if 0:
    # check whether QSO properties are consistent across bins
Example #13
0
ax1 = fig1.add_subplot(111)
ax2 = fig2.add_subplot(111)


for ax in (ax1,ax2):
    N0 = -21
    for i,n in enumerate(names):
        T = Table(n)
        ind = T.energy.searchsorted(0.99)
        if i == len(names) - 1:
            ref = T
            ref.log10jnu = T.log10jnu - T.log10jnu[ind] + N0
        color = '0.5' if i != 2 else 'k'
        ax.semilogx(T.energy, T.log10jnu - T.log10jnu[ind] + N0, '-', color=color)

puttext(0.04, 0.07, '$\mathrm{Haardt\ & \ Madau}$\n$2012,\ z=2.5$',
        ax=ax1, ha='left')

# plot a QSO spectrum

X = 10**np.linspace(-1, 4, 1000)   # hv
# alpha = -1.7
# fnu = np.log10(X**alpha)
# ind = X.searchsorted(0.99)
# plt.semilogx(X, fnu - fnu[ind] + N0, '-' + 'c')
#alpha = -1.5
# Scott
alpha = -0.56
fnu = np.log10(X**alpha)
ind = X.searchsorted(0.99)
ax2.semilogx(X, fnu - fnu[ind] + N0, '--c', lw=2,
             label=r'$J_\nu\propto\ \nu^{%.3g}$' % alpha)
Example #14
0
        dy2 = -dy2
        valign = 'top'

    color='b'
    if tr_wrest[i] > 1215.67:
        color = 'r'
    elif tr_wrest[i] > 912.:
        color = 'g'
    
    ax.text(xvals[i] + dx, y[i]+ dy2, t, fontsize=9,
            rotation=90, ha=halign, va=valign, color=color)
    ax.plot([xvals[i]]*2, [y[i] + dy0, y[i] + dy1], lw=0.5, color='0.5')

c = 'k'

ax.set_xlabel('$\mathrm{Energy\ (Rydbergs)}$')
ax.set_ylabel(r'$\log_{10}\ [J_{\nu}\ \mathrm{(erg/s/cm^2/Hz/ster)}]$')
ax.set_xlim(-0.6, 1.6)
make_log_xlabels(ax)
ax.set_ylim(-24.3, -16.8)

puttext(0.95, 0.85, '$\mathrm{Haardt\ & \ Madau}$\n$2012,\ z=2.5$',
        ax=ax, ha='right')
puttext(0.95, 0.75, '$\mathrm{Strongest\ }\lambda_0>\ 1216\ \AA$', ax=ax, ha='right',color='r',fontsize=10)
puttext(0.95, 0.7,  '$\mathrm{Strongest\ }\lambda_0>\ 912\ \AA$', ax=ax, ha='right',color='g' ,fontsize=10)
puttext(0.95, 0.65, '$\mathrm{Strongest\ }\lambda_0>\ 600\ \AA$', ax=ax, ha='right',color='b' ,fontsize=10)

puttext(0.95, 0.55, '$\mathrm{Verner\ }P\ >\ %g$' % prob, ax=ax, ha='right',fontsize=10)

fig1.savefig('incident_field_trans.pdf')
Example #15
0
File: velplot.py Project: nhmc/H2
def make_plot(sp, transitions, model, models, ticks, opt, width=None,
              height=None, aspect=0.5, textloc='lower left',
              unrelated=[], cols=None, flw=0.5, mlw=0.5, nrows=None, ncols=None,
              unrelated_alpha=0.5, trans_fontsize='medium', zerovel_lw=0.5,
              tlw=1):
    """
    Parameters
    ----------
    cols : dict
      An optional dictionary of colours. The keys 'data', 'resid',
      'ticks' and 'model' can be defined.

    """
    if cols is None:
        cols = {}
    if 'data' not in cols:
        cols['data'] = None
    if 'resid' not in cols:
        cols['resid'] = 'g'
    if 'model' not in cols:
        cols['model'] = 'r'
    if 'ticks' not in cols:
        cols['ticks'] = 'b'

    wa = sp.wa
    wextra = np.diff(wa)[0] * 2
    nfl = sp.fl / sp.co
    ner = sp.er / sp.co
    if opt.f26name is not None:
        resid = (nfl - model) / ner

    # actual plotting
    ntrans = len(transitions)
    if None in (nrows, ncols):
        nrows, ncols = get_nrows_ncols(ntrans)
    assert ntrans <= nrows*ncols
    fig, vplot = get_fig_axes(nrows, ncols, ntrans, width=width, height=height,
                              aspect=aspect)

    colour = get_colours(transitions)

    zp1 = opt.redshift + 1
    vmax = opt.vmax
    if opt.vmin is None:
        vmin = -abs(vmax)
    else:
        vmin = opt.vmin

    betamin = vmin / c_kms
    betamax = vmax / c_kms

    fig.subplots_adjust(left=0.05, right=0.99, bottom=0.07, top=0.99,
                        wspace=0.0001, hspace=0.00001)

    # plot top down, so we need reversed()
    for i,trans in enumerate(transitions):
        ax = vplot.axes[i]
        ion = trans[0].split()[0]
        watrans = trans[1][0]
        obswa = watrans * zp1
        wmin = obswa * (1 - 3*abs(betamin))
        wmax = obswa * (1 + 3*abs(betamax))
        cond = between(wa, wmin, wmax)
        wa1 = wa[cond]

        fl = nfl[cond]
        vel = (wa1 / obswa - 1) * c_kms
        ax.axhline(0, color='gray', lw=0.5)
        c = cols['data']
        if c is None:
            c = colour[ion]
        ax.plot(vel, fl, color=c, lw=flw, ls='steps-mid')
        for w0,w1 in unrelated:
            c0 = between(wa1, w0, w1)
            c1 = between(wa1, w0-wextra, w1+wextra)
            if c0.any():
                ax.plot(vel[c0], fl[c0], 'w', lw=flw+2, ls='-',
                        drawstyle='steps-mid')
                #ax.plot(vel[c0], fl[c0], '--', lw=flw, color=c,
                #        drawstyle='steps-mid')
                ax.plot(vel[c1], fl[c1], '-', lw=flw, color=c,
                        alpha=unrelated_alpha, drawstyle='steps-mid')

        ax.axhline(1, color='gray', lw=0.5, ls='dashed', zorder=3)

        for m in models:
            ax.plot(vel, m[cond], cols['model'], lw=0.2)
        if opt.f26name is not None:
            if opt.modelfill:
                ax.fill_between(vel, model[cond], 1, lw=0,
                                color=cols['model'], alpha=0.4, zorder=0)
            else:
                ax.plot(vel, model[cond], cols['model'], lw=mlw)

            for w0,w1 in unrelated:
                c0 = between(wa1, w0, w1)
                if c0.any():
                    ax.plot(vel[c0], model[cond][c0], 'w', lw=flw+2, ls=':')

        if opt.residuals and opt.f26name is not None:
            mult = 0.05
            offset = -0.2
            ax.scatter(vel, offset + mult*resid[cond], marker='.', s=5,
                       faceted=False, c=cols['resid'])
            ax.axhline(offset - mult, color='0.5', lw=0.3)
            ax.axhline(offset + mult, color='0.5', lw=0.3)

        if len(ticks) > 0:
            tickwmin = obswa * (1 + betamin)
            tickwmax = obswa * (1 + betamax)
            wticks = ticks.wa
            cond = between(wticks, tickwmin, tickwmax)
            if cond.any():
                # should really check ion name here too...
                c0 = np.abs(trans[1][0] - ticks.wa0[cond]) < 1e-2
                vel = (wticks[cond][c0] / obswa - 1) * c_kms
                #import pdb; pdb.set_trace()
                for j,t in enumerate(ticks[cond][c0]):
                    T = plot_tick_vel(ax, vel[j], 0, t, lw=tlw, col=cols['ticks'])
                vel = (wticks[cond][~c0] / obswa - 1) * c_kms
                for j,t in enumerate(ticks[cond][~c0]):
                    T = plot_tick_vel(ax, vel[j], 0, t, lw=tlw, col=cols['ticks'],
                                      ls=':')

        #bbox = dict(facecolor='w', edgecolor='None')
        transf = mtransforms.blended_transform_factory(
            ax.transAxes, ax.transData)
        name = trans[0]
        if opt.osc:
            name = name + ' %.3g' % trans[1]['osc']

        if textloc == 'lower left':
            ax.text(0.03, 0.02, name, fontsize=trans_fontsize, transform=transf) # bbox=bbox,
        elif textloc =='upper right':
            puttext(0.97, 0.97, name, ax, fontsize=trans_fontsize, va='top',
                    ha='right') # bbox=bbox,
        #ax.text(0.98, 0.02, name, ha='right', fontsize=13, transform=transf) # bbox=bbox,
    
    for i,ax in enumerate(vplot.axes):
        ax.axvline(0, color='0.7', lw=zerovel_lw, zorder=0)
        ax.set_xlim(vmin, vmax)
        ax.set_ylim(-0.49, 1.49)

    return fig, vplot
Example #16
0
        dy0 = -dy0
        dy1 = -dy1
        dy2 = -dy2
        valign = "top"

    color = "b"
    if tr_wrest[i] > 1215.67:
        color = "r"
    elif tr_wrest[i] > 912.0:
        color = "g"

    ax.text(xvals[i] + dx, y[i] + dy2, t, fontsize=9, rotation=90, ha=halign, va=valign, color=color)
    ax.plot([xvals[i]] * 2, [y[i] + dy0, y[i] + dy1], lw=0.5, color="0.5")

c = "k"

ax.set_xlabel("$\mathrm{Energy\ (Rydbergs)}$")
ax.set_ylabel(r"$\log_{10}\ [J_{\nu}\ \mathrm{(erg/s/cm^2/Hz/ster)}]$")
ax.set_xlim(-0.6, 1.6)
make_log_xlabels(ax)
ax.set_ylim(-24.3, -16.8)

puttext(0.95, 0.85, "$\mathrm{Haardt\ & \ Madau}$\n$2012,\ z=2.5$", ax=ax, ha="right")
puttext(0.95, 0.75, "$\mathrm{Strongest\ }\lambda_0>\ 1216\ \AA$", ax=ax, ha="right", color="r", fontsize=10)
puttext(0.95, 0.7, "$\mathrm{Strongest\ }\lambda_0>\ 912\ \AA$", ax=ax, ha="right", color="g", fontsize=10)
puttext(0.95, 0.65, "$\mathrm{Strongest\ }\lambda_0>\ 600\ \AA$", ax=ax, ha="right", color="b", fontsize=10)

puttext(0.95, 0.55, "$\mathrm{Verner\ }P\ >\ %g$" % prob, ax=ax, ha="right", fontsize=10)

fig1.savefig("incident_field_trans.pdf")
Example #17
0
def plot_posteriors(chain, P, nplot='all'):
    """ Plot the posterior distributions for a series of parameter
    samples. chain has shape (nsample, nparameters).
    """

    if 'posterior_plots' in opt:
        temp = opt['posterior_plots'].split(',')
        pairs = []
        for pair in temp:
            pairs.append(pair.split())
        nplot = len(pairs)
    elif nplot == 'all':
        nplot = chain.shape[-1]


    nrows, ncols = get_nrows_ncols(nplot)
    fig,axes = get_fig_axes(nrows, ncols, nplot)

    for i,ax in enumerate(axes):
        if 'posterior_plots' in opt:
            i0 = P['names'].index(pairs[i][0])
            i1 = P['names'].index(pairs[i][1])
        else:
            i0 = i
            i1 = i + 1
        if i1 == npar:
            i1 = 0

        #ax.plot(chain[:,0,i], chain[:,0,j], '.r', ms=4, label='p$_{initial}$')
        dhist(chain[:, i0], chain[:, i1],
              xbins=P['bins'][i0], ybins=P['bins'][i1],
              fmt='.', ms=1.5, c='0.5', chist='b', ax=ax, loc='left, bottom')

        #if contours:
        #    i1sig = get_levels(np.array([chain[:,i], chain[:,j]]).T,)
        #    #cont = ax.contour(*par, colors='k',linewidths=0.5)
        # for ind in P.ijoint_sig:
        #     x,y = chain[:,i][ind], chain[:,j][ind]
        #     delaunay = Delaunay(np.array([x, y]).T)
        #     for i0,i1 in delaunay.convex_hull:
        #         ax.plot([x[i0], x[i1]], [y[i0], y[i1]], 'k', lw=0.5)
        x,y = chain[:,i0][P['ijoint_sig'][1]], chain[:,i1][P['ijoint_sig'][1]]
        ax.plot(x,y,'g.', ms=3, mew=0)
        x,y = chain[:,i0][P['ijoint_sig'][0]], chain[:,i1][P['ijoint_sig'][0]]
        ax.plot(x,y,'r.', ms=3, mew=0)

        ax.plot(P['ml'][i0], P['ml'][i1], 'xk', ms=12, mew=4)
        ax.plot(P['ml'][i0], P['ml'][i1], 'xr', ms=10, mew=2)

        c = 'crimson'
        ax.axvline(P['p1sig'][i0][0], ymax=0.2, color=c, lw=0.5)
        ax.axvline(P['p1sig'][i0][1], ymax=0.2, color=c, lw=0.5)
        ax.axhline(P['p1sig'][i1][0], xmax=0.2, color=c, lw=0.5)
        ax.axhline(P['p1sig'][i1][1], xmax=0.2, color=c, lw=0.5)
        ax.axvline(P['median'][i0], ymax=0.2, color=c, lw=1.5)
        ax.axhline(P['median'][i1], xmax=0.2, color=c, lw=1.5)

        puttext(0.95, 0.05, P['names'][i0], ax, fontsize=16, ha='right')
        puttext(0.05, 0.95, P['names'][i1], ax, fontsize=16, va='top')
        x0, x1 = np.percentile(chain[:,i0], [5, 95])
        dx = x1 - x0
        ax.set_xlim(x0 - dx, x1 + dx)
        y0, y1 = np.percentile(chain[:,i1], [5, 95])
        dy = y1 - y0
        ax.set_ylim(y0 - dy, y1 + dy)

    return fig, axes
Example #18
0
def triplot(names, vals, sigvals, fig, indirect={}, labels=None, fontsize=14):

    from barak.plot import hist_yedge, hist_xedge, puttext
    npar = len(names)
    bins = {}
    for n in names:
        x0, x1 = vals[n].min(), vals[n].max()
        dx = x1 - x0
        lo = x0 - 0.1*dx
        hi = x1 + 0.1*dx
        bins[n] = np.linspace(lo, hi, 20)

    axes = {}
    for i0,n0 in enumerate(names):
        for i1,n1 in enumerate(names):
            if i0 == i1:# or i1 < i0: # uncomment to keep just one triangle.
                continue
            ax = fig.add_subplot(npar,npar, i0 * npar + i1 + 1)
            ax.locator_params(tight=True, nbins=8)
            ax.xaxis.set_minor_locator(AutoMinorLocator())
            ax.yaxis.set_minor_locator(AutoMinorLocator())
            axes[(n0 + ' ' + n1)] = ax

            y,x = vals[n0], vals[n1]
            if USE_HEXBIN:
                ax.hexbin(x,y,cmap=CM, gridsize=40,linewidths=0.1)
            else:
                ax.plot(x,y,'r.', ms=0.5, mew=0)#, alpha=0.5)

            color = 'k' if n0 not in indirect else 'g'
            text = labels[n0] if labels is not None else n0
            puttext(0.05, 0.95, text, ax, color=color ,fontsize=fontsize, va='top')
            color = 'k' if n1 not in indirect else 'g'
            text = labels[n1] if labels is not None else n1
            puttext(0.95, 0.08, text, ax, color=color ,fontsize=fontsize, ha='right')
            # set limits
            y0, y1 = np.percentile(vals[n0], [5, 95])
            dy = y1 - y0
            ax.set_ylim(y0 - dy, y1 + dy)
            x0, x1 = np.percentile(vals[n1], [5, 95])
            dx = x1 - x0
            ax.set_xlim(x0 - dx, x1 + dx)

            c = 'k'
            if i0 == 0:
                ax.xaxis.set_tick_params(labeltop='on')
                ax.xaxis.set_tick_params(labelbottom='off')
                for t in ax.get_xticklabels():
                    t.set_rotation(60)
            elif i0 == npar-1 or (i0 == npar-2 and i1 == npar-1):
                hist_xedge(vals[n1], ax, color='forestgreen',
                           fill=dict(color='forestgreen',alpha=0.3),
                           bins=bins[n1], loc='bottom')
                ax.axvline(sigvals[n1][0], ymax=0.2, color=c, lw=0.5)
                ax.axvline(sigvals[n1][1], ymax=0.2, color=c, lw=0.5)
                cen = sum(sigvals[n1]) / 2.
                ax.axvline(cen, ymax=0.2, color=c, lw=1.5)
                for t in ax.get_xticklabels():
                    t.set_rotation(60)
            else:
                ax.set_xticklabels('')

            if not (i1 == 0 or (i0 == 0 and i1 == 1) or i1 == npar-1):
                ax.set_yticklabels('')

            if (i0 == 0 and i1 == 1) or i1 == 0:
                hist_yedge(vals[n0], ax, color='forestgreen',
                           fill=dict(color='forestgreen',alpha=0.3),
                           bins=bins[n0], loc='left')
                ax.axhline(sigvals[n0][0], xmax=0.2, color=c, lw=0.5)
                ax.axhline(sigvals[n0][1], xmax=0.2, color=c, lw=0.5)
                cen = sum(sigvals[n0]) / 2.
                ax.axhline(cen, xmax=0.2, color=c, lw=1.5)

            if i1 == npar - 1:
                ax.yaxis.set_tick_params(labelright='on')
                ax.yaxis.set_tick_params(labelleft='off')

            #ax.minorticks_on()

    return axes
Example #19
0
        dNdz, dNdz_er, n = find_dndz_vs_rho(rho, ab['MgII'], iMgII_from_id,
                                            ewbins.edges[i],
                                            ewbins.edges[i + 1])
        y = np.log10(dNdz)
        ylo = np.log10(dNdz - dNdz_er)
        yhi = np.log10(dNdz + dNdz_er)
        errplot(rbin.cen + offsets[i],
                y, (ylo, yhi),
                ax=ax,
                fmt=colors[i] + symbols[i],
                label=labels[i])
        for j in range(len(n)):
            puttext(rbin.cen[j],
                    0.03 + i * 0.03,
                    str(n[j]),
                    ax,
                    color=colors[i],
                    fontsize=10,
                    xcoord='data',
                    ha='center')

    ax.legend(frameon=0)
    ax.set_xlabel('Cluster-absorber impact par. (proper Mpc)')
    ax.set_ylabel(r'$dN/dz\ (MgII)$')
    # skip last bin, where not all pairs are measured.
    ax.set_xlim(rbin.edges[0] - rbin.halfwidth[0],
                rbin.edges[-2] + rbin.halfwidth[-1])
    make_log_xlabels(ax)
    make_log_ylabels(ax)
    #fig3.savefig(run_id + '/dNdz_vs_rho.png')
    plt.show()
Example #20
0
def plot_posteriors(chain, P, nplot='all'):
    """ Plot the posterior distributions for a series of parameter
    samples. chain has shape (nsample, nparameters).
    """

    if nplot == 'all':
        nplot = chain.shape[-1]

    #nrows, ncols = get_nrows_ncols(nplot)
    #fig,axes = get_fig_axes(nrows, ncols, nplot)

    fig = pl.figure(figsize=(8.4, 8.4))
    fig.subplots_adjust(left=0.05, bottom=0.05, hspace=0.001, wspace=0.001)
    axes = []
    pl.rc('xtick', labelsize=8)
    pl.rc('ytick', labelsize=8)

    for i0 in xrange(nplot):
        for i1 in xrange(nplot):
            if i0 == i1:# or i1 < i0:
                continue
            ax = fig.add_subplot(nplot,nplot, i0 * nplot + i1 + 1)

            y,x = chain[:,i0], chain[:,i1]
            ax.plot(x,y,'r.', ms=1, mew=0)#, alpha=0.5)
            #y,x = chain[:,i0][P['ijoint_sig'][1]], chain[:,i1][P['ijoint_sig'][1]]
            #ax.plot(x,y,'g.', ms=1.5, mew=0)
            #y,x = chain[:,i0][P['ijoint_sig'][0]], chain[:,i1][P['ijoint_sig'][0]]
            #ax.plot(x,y,'r.', ms=1.5, mew=0)

            ax.plot(P['ml'][i1], P['ml'][i0], 'xk', ms=8, mew=2)
            ax.plot(P['ml'][i1], P['ml'][i0], 'xr', ms=6, mew=1)


            puttext(0.05, 0.95, P['names'][i0], ax, fontsize=12, va='top')
            puttext(0.95, 0.05, P['names'][i1], ax, fontsize=12, ha='right')
            y0, y1 = np.percentile(chain[:,i0], [5, 95])
            dy = y1 - y0
            ax.set_ylim(y0 - dy, y1 + dy)
            x0, x1 = np.percentile(chain[:,i1], [5, 95])
            dx = x1 - x0
            ax.set_xlim(x0 - dx, x1 + dx)

            c = 'crimson'
            if i0 == 0:
                ax.xaxis.set_tick_params(labeltop='on')
                ax.xaxis.set_tick_params(labelbottom='off')
                for t in ax.get_xticklabels():
                    t.set_rotation(60)
            elif i0 == nplot-1 or (i0 == nplot-2 and i1 == nplot-1):
                hist_xedge(chain[:, i1], ax, fmt='b', bins=P['bins'][i1], loc='bottom')
                ax.axvline(P['p1sig'][i1][0], ymax=0.2, color=c, lw=0.5)
                ax.axvline(P['p1sig'][i1][1], ymax=0.2, color=c, lw=0.5)
                ax.axvline(P['median'][i1], ymax=0.2, color=c, lw=1.5)
                for t in ax.get_xticklabels():
                    t.set_rotation(60)
            else:
                ax.set_xticklabels('')

            if not (i1 == 0 or (i0 == 0 and i1 == 1) or i1 == nplot-1):
                ax.set_yticklabels('')

            if (i0 == 0 and i1 == 1) or i1 == 0:
                hist_yedge(chain[:, i0], ax, fmt='b', bins=P['bins'][i0], loc='left')
                ax.axhline(P['p1sig'][i0][0], xmax=0.2, color=c, lw=0.5)
                ax.axhline(P['p1sig'][i0][1], xmax=0.2, color=c, lw=0.5)
                ax.axhline(P['median'][i0], xmax=0.2, color=c, lw=1.5)


            if i1 == nplot - 1:
                ax.yaxis.set_tick_params(labelright='on')
                ax.yaxis.set_tick_params(labelleft='off')
                
            axes.append(ax)

    return fig, axes
Example #21
0
def plot_posteriors(chain, P, nplot='all'):
    """ Plot the posterior distributions for a series of parameter
    samples. chain has shape (nsample, nparameters).
    """

    if 'posterior_plots' in opt:
        temp = opt['posterior_plots'].split(',')
        pairs = []
        for pair in temp:
            pairs.append(pair.split())
        nplot = len(pairs)
    elif nplot == 'all':
        nplot = chain.shape[-1]

    nrows, ncols = get_nrows_ncols(nplot)
    fig, axes = get_fig_axes(nrows, ncols, nplot)

    for i, ax in enumerate(axes):
        if 'posterior_plots' in opt:
            i0 = P['names'].index(pairs[i][0])
            i1 = P['names'].index(pairs[i][1])
        else:
            i0 = i
            i1 = i + 1
        if i1 == npar:
            i1 = 0

        #ax.plot(chain[:,0,i], chain[:,0,j], '.r', ms=4, label='p$_{initial}$')
        dhist(chain[:, i0],
              chain[:, i1],
              xbins=P['bins'][i0],
              ybins=P['bins'][i1],
              fmt='.',
              ms=1.5,
              c='0.5',
              chist='b',
              ax=ax,
              loc='left, bottom')

        #if contours:
        #    i1sig = get_levels(np.array([chain[:,i], chain[:,j]]).T,)
        #    #cont = ax.contour(*par, colors='k',linewidths=0.5)
        # for ind in P.ijoint_sig:
        #     x,y = chain[:,i][ind], chain[:,j][ind]
        #     delaunay = Delaunay(np.array([x, y]).T)
        #     for i0,i1 in delaunay.convex_hull:
        #         ax.plot([x[i0], x[i1]], [y[i0], y[i1]], 'k', lw=0.5)
        x, y = chain[:, i0][P['ijoint_sig'][1]], chain[:,
                                                       i1][P['ijoint_sig'][1]]
        ax.plot(x, y, 'g.', ms=3, mew=0)
        x, y = chain[:, i0][P['ijoint_sig'][0]], chain[:,
                                                       i1][P['ijoint_sig'][0]]
        ax.plot(x, y, 'r.', ms=3, mew=0)

        ax.plot(P['ml'][i0], P['ml'][i1], 'xk', ms=12, mew=4)
        ax.plot(P['ml'][i0], P['ml'][i1], 'xr', ms=10, mew=2)

        c = 'crimson'
        ax.axvline(P['p1sig'][i0][0], ymax=0.2, color=c, lw=0.5)
        ax.axvline(P['p1sig'][i0][1], ymax=0.2, color=c, lw=0.5)
        ax.axhline(P['p1sig'][i1][0], xmax=0.2, color=c, lw=0.5)
        ax.axhline(P['p1sig'][i1][1], xmax=0.2, color=c, lw=0.5)
        ax.axvline(P['median'][i0], ymax=0.2, color=c, lw=1.5)
        ax.axhline(P['median'][i1], xmax=0.2, color=c, lw=1.5)

        puttext(0.95, 0.05, P['names'][i0], ax, fontsize=16, ha='right')
        puttext(0.05, 0.95, P['names'][i1], ax, fontsize=16, va='top')
        x0, x1 = np.percentile(chain[:, i0], [5, 95])
        dx = x1 - x0
        ax.set_xlim(x0 - dx, x1 + dx)
        y0, y1 = np.percentile(chain[:, i1], [5, 95])
        dy = y1 - y0
        ax.set_ylim(y0 - dy, y1 + dy)

    return fig, axes
Example #22
0
def plot_posteriors(chain, P, nplot="all"):
    """ Plot the posterior distributions for a series of parameter
    samples. chain has shape (nsample, nparameters).
    """

    if nplot == "all":
        nplot = chain.shape[-1]

    # nrows, ncols = get_nrows_ncols(nplot)
    # fig,axes = get_fig_axes(nrows, ncols, nplot)

    fig = pl.figure(figsize=(8.4, 8.4))
    fig.subplots_adjust(left=0.05, bottom=0.06, hspace=0.001, wspace=0.001)
    axes = []
    pl.rc("xtick", labelsize=8)
    pl.rc("ytick", labelsize=8)

    for i0 in xrange(nplot):
        for i1 in xrange(nplot):
            if i0 == i1:  # or i1 < i0: # uncomment to keep just one triangle.
                continue
            ax = fig.add_subplot(nplot, nplot, i0 * nplot + i1 + 1)

            y, x = chain[:, i0], chain[:, i1]
            ax.plot(x, y, "r.", ms=1, mew=0)  # , alpha=0.5)
            # y,x = chain[:,i0][P['ijoint_sig'][1]], chain[:,i1][P['ijoint_sig'][1]]
            # ax.plot(x,y,'g.', ms=1.5, mew=0)
            # y,x = chain[:,i0][P['ijoint_sig'][0]], chain[:,i1][P['ijoint_sig'][0]]
            # ax.plot(x,y,'r.', ms=1.5, mew=0)

            ax.plot(P["ml"][i1], P["ml"][i0], "xk", ms=8, mew=2)
            ax.plot(P["ml"][i1], P["ml"][i0], "xr", ms=6, mew=1)

            puttext(0.05, 0.95, P["names"][i0], ax, fontsize=12, va="top")
            puttext(0.95, 0.05, P["names"][i1], ax, fontsize=12, ha="right")
            y0, y1 = np.percentile(chain[:, i0], [5, 95])
            dy = y1 - y0
            ax.set_ylim(y0 - dy, y1 + dy)
            x0, x1 = np.percentile(chain[:, i1], [5, 95])
            dx = x1 - x0
            ax.set_xlim(x0 - dx, x1 + dx)

            c = "crimson"
            if i0 == 0:
                ax.xaxis.set_tick_params(labeltop="on")
                ax.xaxis.set_tick_params(labelbottom="off")
                for t in ax.get_xticklabels():
                    t.set_rotation(60)
            elif i0 == nplot - 1 or (i0 == nplot - 2 and i1 == nplot - 1):
                hist_xedge(chain[:, i1], ax, fmt="b", bins=P["bins"][i1], loc="bottom")
                ax.axvline(P["p1sig"][i1][0], ymax=0.2, color=c, lw=0.5)
                ax.axvline(P["p1sig"][i1][1], ymax=0.2, color=c, lw=0.5)
                ax.axvline(P["median"][i1], ymax=0.2, color=c, lw=1.5)
                for t in ax.get_xticklabels():
                    t.set_rotation(60)
            else:
                ax.set_xticklabels("")

            if not (i1 == 0 or (i0 == 0 and i1 == 1) or i1 == nplot - 1):
                ax.set_yticklabels("")

            if (i0 == 0 and i1 == 1) or i1 == 0:
                hist_yedge(chain[:, i0], ax, fmt="b", bins=P["bins"][i0], loc="left")
                ax.axhline(P["p1sig"][i0][0], xmax=0.2, color=c, lw=0.5)
                ax.axhline(P["p1sig"][i0][1], xmax=0.2, color=c, lw=0.5)
                ax.axhline(P["median"][i0], xmax=0.2, color=c, lw=1.5)

            if i1 == nplot - 1:
                ax.yaxis.set_tick_params(labelright="on")
                ax.yaxis.set_tick_params(labelleft="off")

            axes.append(ax)

    return fig, axes
Example #23
0
    N0 = -21
    for i, n in enumerate(names):
        T = Table(n)
        ind = T.energy.searchsorted(0.99)
        if i == len(names) - 1:
            ref = T
            ref.log10jnu = T.log10jnu - T.log10jnu[ind] + N0
        color = '0.5' if i != 2 else 'k'
        ax.semilogx(T.energy,
                    T.log10jnu - T.log10jnu[ind] + N0,
                    '-',
                    color=color)

puttext(0.04,
        0.07,
        '$\mathrm{Haardt\ & \ Madau}$\n$2012,\ z=2.5$',
        ax=ax1,
        ha='left')

# plot a QSO spectrum

X = 10**np.linspace(-1, 4, 1000)  # hv
# alpha = -1.7
# fnu = np.log10(X**alpha)
# ind = X.searchsorted(0.99)
# plt.semilogx(X, fnu - fnu[ind] + N0, '-' + 'c')
#alpha = -1.5
# Scott
alpha = -0.56
fnu = np.log10(X**alpha)
ind = X.searchsorted(0.99)
Example #24
0
        if not tr[0].startswith('OVI') and not tr[0].startswith('NV'):
            for j,v in enumerate(tvel):
                #if j in (0,11,13,14,15):
                #    T = plot_tick_vel(ax, v, 0, '', lw=1, col='b')
                if cfg.vmin < v < cfg.vmax:
                    T = plot_tick_vel(ax, v - vzero, 0.04,'',
                                      height=0.14, lw=1, col='b')
        else:
            for j,v in enumerate(tvel_o6):
                #if j in (0,11,13,14,15):
                #    T = plot_tick_vel(ax, v, 0, '', lw=1, col='b')
                if cfg.vmin < v < cfg.vmax:
                    T = plot_tick_vel(ax, v - vzero, 0.04,'',
                                      height=0.14, lw=1, col='r')

        puttext(0.03, 0.12, label[i], ax, ha='left', va='bottom')
        
        #ax.set_xticks([-50, -25, 0, 25, 50])
        ax.set_yticks([0, 0.5, 1])
        ax.minorticks_on()
        ax.set_xlim(cfg.vmin - vzero, cfg.vmax - vzero)
        ax.set_ylim(-0.1, 1.39)
        if i > 9:
            ax.set_yticklabels('')
        if i not in (0,9,10, 19):
            ax.set_xticklabels('')
        if i == 4:
            ax.set_ylabel('Transmission')
        
    fig.text(0.52, 0.01, 'Velocity offset (km s$^{-1}$)', ha='center')
    #fig.text(0.04, 0.4, 'Transmission', va='center', ha='center', rotation=90)
Example #25
0
    # rp must be in units of physical kpc
    xi2h_rp = []
    for rp in rp_vals:
        def integrand(s):
            """rp and s must have the same units """
            R = hypot(s, rp)
            return np.interp(R, rvals, xi_real)

        xi2h_rp.append(quad(integrand, -np.inf, np.inf)[0])


    # make a plot of the 1 halo and two halo results. The
    # normalisations for each term are arbitrary for now

    # convert to proper (physical) coordinates.
    rp_vals1 = rp_vals / (1 + REDSHIFT)
    xi1h_rp = Sigma_1h(rp_vals1, M)
    plt.figure()
    ax = plt.gca()
    ax.plot(np.log10(rp_vals1), np.log10(xi1h_rp.value) - 21.4)
    ax.plot(np.log10(rp_vals1), np.log10(xi2h_rp))
    from barak.plot import make_log_xlabels, puttext
    puttext(0.9, 0.9, 'log10(mass/m_sun) {:.3g}'.format(np.log10(MASS.value)),
            ax, ha='right')
    make_log_xlabels(plt.gca())
    ax.set_xlabel('log10 r_p (Mpc)')
    ax.set_ylabel('log10 xi')
    plt.show()

Example #26
0
File: model.py Project: nhmc/LAE
def plot_model(pars):    
    """ Plot the observed values and errors, along with the predicted
    model values.
    """
    import matplotlib.pyplot as pl
    from barak.plot import draw_arrows, puttext

    fig = pl.figure(figsize=(6.4, 3.4))
    ax = fig.add_subplot(111)
    ms = 6
    ipot = [get_ionization_energy(t) for t in tr_plot]
    for i,tr in enumerate(tr_plot):
        if use_ipot:
            ind = ipot[i]
        else:
            ind = i
        if tr in obs:
            colour = 'k' if tr in trans else 'w'
            fmt = 'o' + colour
            val, siglo, sighi = obs[tr]
            if siglo == 0:
                draw_arrows(ind, val, direction='up', ax=ax,lw=1)
                ax.plot(ind, val, fmt,ms=ms)
            elif sighi == 0:
                draw_arrows(ind, val, direction='down', ax=ax,lw=1)
                ax.plot(ind, val, fmt,ms=ms)
            else:
                ax.plot([ind, ind], [val-siglo, val+sighi], 'k',lw=1)
                ax.plot(ind, val, fmt,ms=ms)
            ax.text(ind, val + 0.8, tr,
                    fontsize=10, ha='center')
        else:
            puttext(ind, 0.02, tr, ax=ax, xcoord='data',
                    fontsize=10, ha='center')

    puttext(0.9,0.1, 'Model', ax, color='r', ha='right')

    xvals = list(range(len(tr_plot)))
    #print np.asarray(pars).shape
    for par in pars:
        Nmodel = model(par, for_plot=True)
        if use_ipot:
            if len(pars) == 1:
                ax.plot(ipot, Nmodel, 'r.-', lw=1, zorder=0)
            else:
                ax.plot(ipot, Nmodel, 'r-', lw=0.2, zorder=0)
        else:
            if len(pars) == 1:
                ax.plot(xvals, Nmodel, 'r.-', lw=1, zorder=0)
            else:
                ax.plot(xvals, Nmodel, 'r-', lw=0.2, zorder=0)

    if use_ipot:
        ax.set_xlabel('Ionization potential (eV)')
        ax.set_xlim(ipot[0]-1, ipot[-1] + 1)
    else:
        ax.set_xlim(-0.5, xvals[-1] + 0.5)
        ax.set_xticks([])

    ax.set_ylabel(r'$\log_{10}\ N$')
    fig.tight_layout()
    #return fig, ax
    return fig
Example #27
0
File: model.py Project: nhmc/H2
def plot_model(pars):
    """
    `regions`, `x` must be defined in the model.py module namespace
    """
    from run_emcee.plot_mcmc import get_fig_axes, get_nrows_ncols

    linepars = pars
    dz = 0
    if options['wa_vary']:
        linepars, regpars = pars[:-len(regions)], pars[-len(regions):]
    lines = copy_par_to_lines(linepars, lines_vary)
    
    nrows, ncols = get_nrows_ncols(len(regions))
    fig, axes = get_fig_axes(nrows, ncols, len(regions), width=8.2)
    fig.subplots_adjust(wspace=1e-6, hspace=1e-6, right=1, top=1,
                        left=0.07, bottom=0.06)
    z0 = lines.z[1]
    zp1 = lines.z.mean()
    colours = dict(J0='purple',J1='g',J2='r',J3='b')

    for ind, (wa, tau0, sp, (i, j), tname) in enumerate(regions):

        tau = tau0.copy()
        for l in lines:
            if options['wa_vary']:
                #import pdb; pdb.set_trace()
                dz = regpars[ind] / wa[len(wa)//2] * (l.z + 1)
                #print l.z, dz, l.logN
            
            trans = atom[l.name.strip()]
            tau += calc_iontau(wa, trans, l.z+1 + dz, l.logN, l.b)

        dwpix = wa[1] - wa[0]
        flmodel0 = convolve_with_COS_FOS(np.exp(-tau), wa, dwpix)
        ymod = np.interp(sp.wa[i:j], wa, flmodel0)


        ax = axes[ind]
        i1 = max(i-50, 0)
        j1 = min(j+50, len(sp.wa)-1)
        nfl = sp.fl[i1:j1] / sp.co[i1:j1]
        ner = sp.er[i1:j1] / sp.co[i1:j1]

        tstr, t = findtrans(tname, atom)
        obswa = t.wa * (1 + z0)
        dv = c_kms * (sp.wa[i:j] / obswa - 1)
        dv1 = c_kms * (sp.wa[i1:j1] / obswa - 1)

        tstr = tstr[2:]
        
        ax.axhline(0, color='0.5',lw=0.5)
        ax.axhline(1, color='k', lw=0.5, ls='--')
        ax.fill_between([-150, 150], -0.35, -0.15, color='0.9')
        ax.axhline(-0.25, color='k', lw=0.25)
        ax.plot(dv1, nfl, color='0.7', lw=0.5, drawstyle='steps-mid')
        ax.plot(dv, sp.fl[i:j]/sp.co[i:j], 'k', lw=0.5, drawstyle='steps-mid')
        ax.plot(dv, ymod, color='0.3')
        #ax.axvline(0, color='0.5', lw=0.5)

        ax.plot([-23]*2, [1.1, 1.4], '0.5')
        ax.plot([0]*2, [1.1, 1.4], '0.5')
        
        puttext(0.95, 0.95, tstr, ax, fontsize=9, va='top', ha='right',
                color=colours[tstr[:2]])

        resid = (sp.fl[i:j]/sp.co[i:j] - ymod) / sp.er[i:j] * sp.co[i:j]

        ax.plot(dv, -0.25 + resid*0.1, '.', color='0.3', ms=2)
        ax.set_ylim(-0.5, 1.9)
        ax.set_xlim(-120, 120)
        ax.set_yticks([0, 0.5, 1, 1.5])
        ax.set_yticklabels(['0.0', '0.5', '1.0', '1.5'])
        ax.set_xticks([-100, -50, 0, 50, 100])
        ax.set_xticklabels(['', '-50', '0', '50', ''])
        if ind+1 < (ncols*(nrows-1)):
            ax.set_xticklabels([])
        if ind % ncols:
            ax.set_yticklabels([])

    fig.text(0.5, 0.00, 'Velocity offset (km/s)', fontsize=12, ha='center',va='bottom')
    fig.text(0.015, 0.5, 'Transmission', fontsize=12, rotation=90,va='center')
    ndf = len(ydata) - len(pars)
    print (((ydata - ymodel(x, pars))/ ysigma) **2).sum() / ndf
    pl.savefig('fig/model.pdf')
    pl.savefig('fig/model.png',dpi=300)

    return fig
Example #28
0
                                      lw=1,
                                      col='b')
        else:
            for j, v in enumerate(tvel_o6):
                #if j in (0,11,13,14,15):
                #    T = plot_tick_vel(ax, v, 0, '', lw=1, col='b')
                if cfg.vmin < v < cfg.vmax:
                    T = plot_tick_vel(ax,
                                      v - vzero,
                                      0.04,
                                      '',
                                      height=0.14,
                                      lw=1,
                                      col='r')

        puttext(0.03, 0.12, label[i], ax, ha='left', va='bottom')

        #ax.set_xticks([-50, -25, 0, 25, 50])
        ax.set_yticks([0, 0.5, 1])
        ax.minorticks_on()
        ax.set_xlim(cfg.vmin - vzero, cfg.vmax - vzero)
        ax.set_ylim(-0.1, 1.39)
        if i > 9:
            ax.set_yticklabels('')
        if i not in (0, 9, 10, 19):
            ax.set_xticklabels('')
        if i == 4:
            ax.set_ylabel('Transmission')

    fig.text(0.52, 0.01, 'Velocity offset (km s$^{-1}$)', ha='center')
    #fig.text(0.04, 0.4, 'Transmission', va='center', ha='center', rotation=90)
Example #29
0
def plot_model(pars):
    """ Plot the observed values and errors, along with the predicted
    model values.
    """
    import matplotlib.pyplot as pl
    from barak.plot import draw_arrows, puttext

    fig = pl.figure(figsize=(6.4, 3.4))
    ax = fig.add_subplot(111)
    ms = 6
    ipot = [get_ionization_energy(t) for t in tr_plot]
    for i, tr in enumerate(tr_plot):
        if use_ipot:
            ind = ipot[i]
        else:
            ind = i
        if tr in obs:
            colour = 'k' if tr in trans else 'w'
            fmt = 'o' + colour
            val, siglo, sighi = obs[tr]
            if siglo == 0:
                draw_arrows(ind, val, direction='up', ax=ax, lw=1)
                ax.plot(ind, val, fmt, ms=ms)
            elif sighi == 0:
                draw_arrows(ind, val, direction='down', ax=ax, lw=1)
                ax.plot(ind, val, fmt, ms=ms)
            else:
                ax.plot([ind, ind], [val - siglo, val + sighi], 'k', lw=1)
                ax.plot(ind, val, fmt, ms=ms)
            ax.text(ind, val + 0.8, tr, fontsize=10, ha='center')
        else:
            puttext(ind,
                    0.02,
                    tr,
                    ax=ax,
                    xcoord='data',
                    fontsize=10,
                    ha='center')

    puttext(0.9, 0.1, 'Model', ax, color='r', ha='right')

    xvals = list(range(len(tr_plot)))
    #print np.asarray(pars).shape
    for par in pars:
        Nmodel = model(par, for_plot=True)
        if use_ipot:
            if len(pars) == 1:
                ax.plot(ipot, Nmodel, 'r.-', lw=1, zorder=0)
            else:
                ax.plot(ipot, Nmodel, 'r-', lw=0.2, zorder=0)
        else:
            if len(pars) == 1:
                ax.plot(xvals, Nmodel, 'r.-', lw=1, zorder=0)
            else:
                ax.plot(xvals, Nmodel, 'r-', lw=0.2, zorder=0)

    if use_ipot:
        ax.set_xlabel('Ionization potential (eV)')
        ax.set_xlim(ipot[0] - 1, ipot[-1] + 1)
    else:
        ax.set_xlim(-0.5, xvals[-1] + 0.5)
        ax.set_xticks([])

    ax.set_ylabel(r'$\log_{10}\ N$')
    fig.tight_layout()
    #return fig, ax
    return fig
Example #30
0
        Y = np.concatenate([[0], np.repeat(y,2), [0]])
        Y = 0.2 * Y / Y.max()
        import matplotlib.transforms as mtransforms
        trans = mtransforms.blended_transform_factory(ax.transAxes, ax.transData)
        ax.plot(Y, b, color='0.5', transform=trans)

    if xaxis == 'NHI':
        ax.set_xlabel('$N(\mathrm{HI})')
    elif xaxis == 'Ntot':      
        ax.set_xlabel('$\log_{10}\ [N_\mathrm{HI}\ +\ 2N_{\mathrm{H}_2}]\ (\mathrm{cm}^{-2})$')

    if xaxis == 'Ntot':
        Nvals, fvals = detlim(np.linspace(17,23), NH2=15.)
        im = shade_to_line(Nvals, fvals, blend=2., y0=-10, color='0.7')
 
        puttext(0.05, -6.8, '$\mathrm{Detection\ limit}$', pl.gca(), rotation=-19, fontsize=14,
                ycoord='data') #'$N$(H$_2)\ < \ 14.5$'

        #pl.plot(Nvals, fvals, '-', label='Nh2=12.5')
        x0,y0 = NHIlo, 0.7
        
        # typical error bars for other points
        # NHI
        pl.plot([x0-0.21, x0+0.21], [y0+0.21, y0-0.21], 'k', lw=0.5)
        pl.plot([x0, x0], [y0-0.3, y0+0.3], 'k', lw=0.5)

    #pl.ylabel('$N$(H$_2$)/($N$(HI) $+\ 2N$(H$_2$)')
    pl.ylabel('$\log_{10}\ f_{\mathrm{H}_2}$')
    if xaxis == 'Ntot':      
        pl.xlim(18.7, 22.15)
    ax.set_ylim(-8.2, 1.5)
    #leg = ax.legend(loc='upper left', ncol=2, frameon=0, scatterpoints=1)
Example #31
0
def plot_posteriors(chain, P, nplot='all'):
    """ Plot the posterior distributions for a series of parameter
    samples. chain has shape (nsample, nparameters).
    """

    if nplot == 'all':
        nplot = chain.shape[-1]

    #nrows, ncols = get_nrows_ncols(nplot)
    #fig,axes = get_fig_axes(nrows, ncols, nplot)

    fig = pl.figure(figsize=(8.4, 8.4))
    fig.subplots_adjust(left=0.05, bottom=0.06, hspace=0.001, wspace=0.001)
    axes = []
    pl.rc('xtick', labelsize=8)
    pl.rc('ytick', labelsize=8)

    for i0 in xrange(nplot):
        for i1 in xrange(nplot):
            if i0 == i1:  # or i1 < i0: # uncomment to keep just one triangle.
                continue
            ax = fig.add_subplot(nplot, nplot, i0 * nplot + i1 + 1)

            y, x = chain[:, i0], chain[:, i1]
            ax.plot(x, y, 'r.', ms=1, mew=0)  #, alpha=0.5)
            #y,x = chain[:,i0][P['ijoint_sig'][1]], chain[:,i1][P['ijoint_sig'][1]]
            #ax.plot(x,y,'g.', ms=1.5, mew=0)
            #y,x = chain[:,i0][P['ijoint_sig'][0]], chain[:,i1][P['ijoint_sig'][0]]
            #ax.plot(x,y,'r.', ms=1.5, mew=0)

            ax.plot(P['ml'][i1], P['ml'][i0], 'xk', ms=8, mew=2)
            ax.plot(P['ml'][i1], P['ml'][i0], 'xr', ms=6, mew=1)

            puttext(0.05, 0.95, P['names'][i0], ax, fontsize=12, va='top')
            puttext(0.95, 0.05, P['names'][i1], ax, fontsize=12, ha='right')
            y0, y1 = np.percentile(chain[:, i0], [5, 95])
            dy = y1 - y0
            ax.set_ylim(y0 - dy, y1 + dy)
            x0, x1 = np.percentile(chain[:, i1], [5, 95])
            dx = x1 - x0
            ax.set_xlim(x0 - dx, x1 + dx)

            c = 'crimson'
            if i0 == 0:
                ax.xaxis.set_tick_params(labeltop='on')
                ax.xaxis.set_tick_params(labelbottom='off')
                for t in ax.get_xticklabels():
                    t.set_rotation(60)
            elif i0 == nplot - 1 or (i0 == nplot - 2 and i1 == nplot - 1):
                hist_xedge(chain[:, i1],
                           ax,
                           fmt='b',
                           bins=P['bins'][i1],
                           loc='bottom')
                ax.axvline(P['p1sig'][i1][0], ymax=0.2, color=c, lw=0.5)
                ax.axvline(P['p1sig'][i1][1], ymax=0.2, color=c, lw=0.5)
                ax.axvline(P['median'][i1], ymax=0.2, color=c, lw=1.5)
                for t in ax.get_xticklabels():
                    t.set_rotation(60)
            else:
                ax.set_xticklabels('')

            if not (i1 == 0 or (i0 == 0 and i1 == 1) or i1 == nplot - 1):
                ax.set_yticklabels('')

            if (i0 == 0 and i1 == 1) or i1 == 0:
                hist_yedge(chain[:, i0],
                           ax,
                           fmt='b',
                           bins=P['bins'][i0],
                           loc='left')
                ax.axhline(P['p1sig'][i0][0], xmax=0.2, color=c, lw=0.5)
                ax.axhline(P['p1sig'][i0][1], xmax=0.2, color=c, lw=0.5)
                ax.axhline(P['median'][i0], xmax=0.2, color=c, lw=1.5)

            if i1 == nplot - 1:
                ax.yaxis.set_tick_params(labelright='on')
                ax.yaxis.set_tick_params(labelleft='off')

            axes.append(ax)

    return fig, axes