def plotconditional(
    s, dists, add, mult, parameters, cube, plotinds, n_sec, n_dims, nicenames, modecolors=["g", "m", "y", "c"]
):
    import matplotlib.cm as cm

    mp = multipanel(dims=(n_dims - 1, n_dims - 1), diagonal=True, figID=4, panel_size=(3, 3))

    for i in plotinds[0]:
        for j in range(i):
            ind = (n_dims - 1) * (i - 1) + j
            mp.grid[ind].contourf(
                dists["all"][i, j][:, :, 1] * mult[j] + add[j],
                dists["all"][i, j][:, :, 0] * mult[i] + add[i],
                dists["all"][i, j][:, :, 2],
                5,
                cmap=cm.gray_r,
                alpha=0.8,
                origin="lower",
            )  # NEed to transpose?????

            # mp.grid[ind].scatter(datsep['all'][:,j+2]*mult[j]+add[j],datsep['all'][:,i+2]*mult[i]+add[i], color='k',marker='+',s=1, alpha=0.4)

            if i == n_dims - 1:
                mp.grid[ind].set_xlabel(parameters[j])
            if j == 0:
                mp.grid[ind].set_ylabel(parameters[i])

            for m, mode in enumerate(s["modes"]):
                mp.grid[ind].axvline(x=mode["mean"][j] * mult[j] + add[j], color=modecolors[m], label="Mode")
                mp.grid[ind].axhline(y=mode["mean"][i] * mult[i] + add[i], color=modecolors[m])

            mp.grid[ind].axvline(x=cube[j] * mult[j] + add[j], color="k", linestyle="--", label="4D Max")
            mp.grid[ind].axhline(y=cube[i] * mult[i] + add[i], color="k", linestyle="--")

    ###### Still need to get everything aligned right.  Fix ticks moves the outer boxes
    mp.fix_ticks()
    for i in plotinds[0]:
        for j in range(i):
            ind = (n_dims - 1) * (i - 1) + j
            mp.grid[ind].set_xlim(
                [
                    numpy.min(dists["all"][i, j][:, :, 1] * mult[j] + add[j]),
                    numpy.max(dists["all"][i, j][:, :, 1] * mult[j] + add[j]),
                ]
            )
            mp.grid[ind].set_ylim(
                [
                    numpy.min(dists["all"][i, j][:, :, 0] * mult[i] + add[i]),
                    numpy.max(dists["all"][i, j][:, :, 0] * mult[i] + add[i]),
                ]
            )

    plt.legend(bbox_to_anchor=(0.0, 1.02, 1.0, 0.102), loc=3)
    plt.draw()

    plt.savefig("fig_conditional.png")
    print "Saved fig_conditional.png"
def plotconditional2(
    s, dists, add, mult, parameters, cube, plotinds, n_sec, n_dims, nicenames, modecolors=["g", "m", "y", "c"]
):
    import matplotlib.cm as cm

    if n_dims > 7:
        nplot = n_sec[0] - 1
    else:
        nplot = n_sec - 1
    mp = multipanel(dims=(nplot, nplot), diagonal=True, figID=5, panel_size=(3, 3))

    for i in plotinds[1]:
        for j in range(n_dims, i):
            ind = (nplot) * (i - n_dims - 1) + j - n_dims
            mp.grid[ind].contourf(
                dists["all"][i, j][:, :, 1] + add[j],
                dists["all"][i, j][:, :, 0] + add[i],
                dists["all"][i, j][:, :, 2],
                5,
                cmap=cm.gray_r,
                alpha=0.8,
                origin="lower",
            )  # NEed to transpose?????

            if i == plotinds[1][nplot]:
                mp.grid[ind].set_xlabel(parameters[j])
            if j == plotinds[1][0]:
                mp.grid[ind].set_ylabel(parameters[i])

            for m, mode in enumerate(s["modes"]):
                mp.grid[ind].axvline(x=mode["mean"][j] + add[j], color=modecolors[m], label="Mode")
                mp.grid[ind].axhline(y=mode["mean"][i] + add[i], color=modecolors[m])

            mp.grid[ind].axvline(x=cube[j] + add[j], color="k", linestyle="--", label="4D Max")
            mp.grid[ind].axhline(y=cube[i] + add[i], color="k", linestyle="--")

    ###### Still need to get everything aligned right.
    mp.fix_ticks()
    for i in plotinds[1]:
        for j in range(n_dims, i):
            ind = (nplot) * (i - n_dims - 1) + j - n_dims
            mp.grid[ind].set_xlim(
                [numpy.min(dists["all"][i, j][:, :, 1] + add[j]), numpy.max(dists["all"][i, j][:, :, 1] + add[j])]
            )
            mp.grid[ind].set_ylim(
                [numpy.min(dists["all"][i, j][:, :, 0] + add[i]), numpy.max(dists["all"][i, j][:, :, 0] + add[i])]
            )

    plt.legend(bbox_to_anchor=(0.0, 1.02, 1.0, 0.102), loc=3)
    plt.draw()

    plt.savefig("fig_conditional2.png")
    print "Saved fig_conditional2.png"
pl.savefig(fpath("electron_temperature_77vs111.pdf"))


keys = [r"$S_{5 GHz}$", r"$S_{15 GHz}$", r"H112$\alpha$", r"H77$\alpha$"]

data = {r"H77$\alpha$": h77a, r"$S_{15 GHz}$": h77c, r"H112$\alpha$": h112a, r"$S_{5 GHz}$": h112c}

combs = list(itertools.combinations(keys, 2))

xpos = {r"$S_{5 GHz}$": 0, r"$S_{15 GHz}$": 1, r"H112$\alpha$": 2}

ypos = {r"$S_{15 GHz}$": 0, r"H112$\alpha$": 1, r"H77$\alpha$": 2}

pl.figure(ii + 4)
pl.clf()
mp = multiplot.multipanel(dims=(3, 3), diagonal=False, figID=ii + 4)
for ii, (xd, yd) in zip(mp.grid.keys(), combs):
    if not (yd in ypos and xd in xpos):
        continue
    print mp.axis_number(ypos[yd], xpos[xd]), xpos[xd], ypos[yd]
    ax = mp.grid[mp.axis_number(ypos[yd], xpos[xd])]
    # ax.plot(data[xd][rrlmask],data[yd][rrlmask],'.')
    mpl_plot_templates.adaptive_param_plot(
        data[xd][rrlmask].to(u.Jy).value,
        data[yd][rrlmask].to(u.Jy).value,
        bins=30,
        threshold=5,
        fill=False,
        alpha=0.8,
        axis=ax,
        cmap=pl.mpl.cm.spectral,
def docontours_multi(mc, start=6000, end=None, skip=None, dosave=False,
                     parnames=(), bins=30, fignum=35,
                     savename='multipanel.png'):
    if isinstance(mc, dict):
        traces = mc
    elif isinstance(mc, astropy.io.fits.fitsrec.FITS_rec):
        traces = {n:mc[n] for n in mc.names}
    else:
        mcnames = mc.db._traces.keys()
        traces = {k:np.concatenate([v.squeeze()
                  for v in mc.trace(k)._trace.values()])[start:end:skip]
                  for k in mcnames
                  if k in parnames}

    pl.figure(fignum)
    pl.clf()
    npars = len(traces.keys())
    mp = multiplot.multipanel(dims=(npars,npars), padding=(0,0), diagonal=True, figID=fignum)
    parnumbers = {p:i for i,p in enumerate(traces.keys())}
    for par1,par2 in itertools.combinations(traces.keys(),2):
        # coordinates are -y, x
        axno = mp.axis_number(parnumbers[par2],parnumbers[par1])
        if axno is None:
            continue
        ax = mp.grid[axno]
        try:
            agpy.pymc_plotting.hist2d(traces, par1, par2,
                                      varslice=(None,None,None), axis=ax,
                                      colorbar=False, clear=True,
                                      doerrellipse=False, bins=bins)
        except ValueError as E:
            print E
            continue
        # if x > 0, hide y labels.
        if parnumbers[par1] > 0:
            ax.set_ylabel("")
            ax.set_yticks([])
        else:
            ax.set_ylabel(ax.get_ylabel(), fontsize=12)
            ax.tick_params(axis='both', which='major', labelsize=12)
            ax.yaxis.get_major_locator().set_params(nbins=4)
        if parnumbers[par2] == npars-1:
            ax.set_xlabel(ax.get_xlabel(), fontsize=12)
            ax.xaxis.get_major_locator().set_params(nbins=4)
            ax.tick_params(axis='both', which='major', labelsize=12)
        else:
            ax.set_xlabel('')
            ax.set_xticks([])
    for par in traces.keys():
        ax = mp.grid[mp.axis_number(parnumbers[par],parnumbers[par])]
        try:
            agpy.pymc_plotting.plot_mc_hist(traces, par,
                                            varslice=(None,None,None),
                                            onesided=False, axis=ax,
                                            legend=False)
        except Exception as E:
            print E
            continue
        # if x > 0, hide y labels.
        if parnumbers[par] > 0:
            ax.set_ylabel("")
            ax.set_yticks([])
        else:
            ax.set_ylabel(par, fontsize=12)
            ax.tick_params(axis='both', which='major', labelsize=12)
            ax.yaxis.get_major_locator().set_params(nbins=4)
        if npars-1 == parnumbers[par]: # label bottom panel
            ax.set_xlabel(par, fontsize=12)
            ax.xaxis.get_major_locator().set_params(nbins=4)
            ax.tick_params(axis='both', which='major', labelsize=12)

    if dosave:
        savefig(savename,bbox_inches='tight')
def plotmarginal2(
    s,
    dists,
    add,
    mult,
    parameters,
    cube,
    plotinds,
    n_sec,
    n_dims,
    nicenames,
    title="",
    norm1=True,
    modecolors=["g", "m", "y", "c"],
    colors=["b", "b", "b", "b", "r", "r", "r", "r", "b", "b", "b", "r", "r", "r", "k", "k", "k"],
    meas=0,
):
    mp = multipanel(dims=(1, 3), figID=2, padding=(0, 0), panel_size=(3, 1))
    mp.title(title)

    for j in plotinds[1]:
        # The filling was not adding up right; don't plot each individual mode.
        for m, mode in enumerate(s["modes"]):
            #    yplot=dists[m][j][1,:]
            #    yplot*=numpy.exp(mode['local evidence'])/numpy.exp(s['global evidence'])
            #    if norm1: yplot/=numpy.max(dists['all'][j][1,:])
            #    #mp.grid[numpy.mod(j,4)].plot(dists[m][j][0,:]*mult[j]+add[j],yplot,':',color=modecolors[m],label='Mode',drawstyle='steps')
            #    dx=(dists[m][j][0,1]-dists[m][j][0,0])*mult[j]
            #    xx= numpy.ravel(zip(dists[m][j][0,:]*mult[j]+add[j], dists[m][j][0,:]*mult[j]+add[j] + dx))
            #    yy =numpy.ravel(zip(yplot, yplot))
            #    mp.grid[numpy.mod(j-n_dims,3)].fill_between(xx-dx,0,yy,color=modecolors[m],alpha=0.2)

            mp.grid[numpy.mod(j - n_dims, 3)].axvline(
                x=mode["mean"][j] * mult[j] + add[j], color=modecolors[m], label="Mode"
            )
            mp.grid[numpy.mod(j - n_dims, 3)].axvline(
                x=mode["mean"][j] * mult[j] + add[j] + mode["sigma"][j],
                color=modecolors[m],
                label="Mode",
                linestyle="--",
            )
            mp.grid[numpy.mod(j - n_dims, 3)].axvline(
                x=mode["mean"][j] * mult[j] + add[j] - mode["sigma"][j],
                color=modecolors[m],
                label="Mode",
                linestyle="--",
            )

        yplot = dists["all"][j][1, :]
        if norm1:
            yplot /= numpy.max(yplot)
        mp.grid[numpy.mod(j - n_dims, 3)].plot(
            dists["all"][j][0, :] * mult[j] + add[j], yplot, "-", color=colors[j], drawstyle="steps"
        )
        mp.grid[numpy.mod(j - n_dims, 3)].axvline(x=cube[j] * mult[j] + add[j], color=colors[j])
        if norm1:
            mp.grid[numpy.mod(j - n_dims, 3)].set_ylim(0, 1)

        if j == n_dims:
            ax2a = mp.grid[numpy.mod(j - n_dims, 3)].twiny()
            newx = dists["all"][j][0, :] - numpy.log10(units.solLum.to("erg/s"))
            ax2a.plot(newx, yplot, "-", color=colors[j], drawstyle="steps")

        if j == n_dims + 2:
            ax2b = mp.grid[numpy.mod(j - n_dims, 3)].twiny()
            newx = dists["all"][j][0, :] + add[j] + meas["addmass"]
            ax2b.plot(newx, yplot, "-", color=colors[j], drawstyle="steps")

    # Add a secondary x-axis for BACD --> Mass
    # log(mass) = log(BACD) + log(area) + log(mu)+log(m_H2) - log(X)
    #     meas['areacm'] + meas['head']['mol_weight'] + log10(2.0*units.M_p.to('kg')/units.solMass.to('kg')) - meas['head']['abundance']
    # Makes sure aligned
    ax2a.set_xlim(mp.grid[0].set_xlim() - numpy.log10(units.solLum.to("erg/s")))
    ax2a.set_xlabel(r"log(L [L$_{sol}$])")
    ax2b.set_xlim(mp.grid[2].set_xlim() + meas["addmass"])
    ax2b.set_xlabel(r"log(M(H$_{2}$ [M$_{sol}$])")

    mp.grid[0].set_ylabel("Probability")
    [mp.grid[i - 4].set_xlabel(nicenames[i]) for i in [4, 5, 6]]

    mp.fix_ticks()
    plt.savefig("fig_marginalized2.png")
    print "Saved fig_marginalized2.png"

    if n_dims == 8:
        mp = multipanel(dims=(1, 3), figID=3, padding=(0, 0), panel_size=(3, 1))
        mp.title(title)

        for j in plotinds[2]:
            for m, mode in enumerate(s["modes"]):
                yplot = dists[m][j][1, :]
                yplot *= numpy.exp(mode["local evidence"]) / numpy.exp(s["global evidence"])
                if norm1:
                    yplot /= numpy.max(dists["all"][j][1, :])
                # mp.grid[numpy.mod(j,4)].plot(dists[m][j][0,:]*mult[j]+add[j],yplot,':',color=modecolors[m],label='Mode',drawstyle='steps')
                dx = (dists[m][j][0, 1] - dists[m][j][0, 0]) * mult[j]
                xx = numpy.ravel(zip(dists[m][j][0, :] * mult[j] + add[j], dists[m][j][0, :] * mult[j] + add[j] + dx))
                yy = numpy.ravel(zip(yplot, yplot))
                mp.grid[numpy.mod(j - n_dims, 3)].fill_between(xx - dx, 0, yy, color=modecolors[m], alpha=0.2)
                # mp.grid[numpy.mod(j-n_dims,3)].axvline(x=mode['mean'][j]+add[j],color=modecolors[m],label='Mode')
                # mp.grid[numpy.mod(j-n_dims,3)].axvline(x=mode['mean'][j]+add[j]+mode['sigma'][j],color=modecolors[m],label='Mode',linestyle='--')
                # mp.grid[numpy.mod(j-n_dims,3)].axvline(x=mode['mean'][j]+add[j]-mode['sigma'][j],color=modecolors[m],label='Mode',linestyle='--')

            yplot = dists["all"][j][1, :]
            if norm1:
                yplot /= numpy.max(yplot)
            mp.grid[numpy.mod(j - n_dims, 3)].plot(
                dists["all"][j][0, :] + add[j], yplot, "-", color=colors[j], drawstyle="steps"
            )
            mp.grid[numpy.mod(j - n_dims, 3)].axvline(x=cube[j] + add[j], color=colors[j])

        mp.grid[0].set_ylabel("Probability")
        [mp.grid[i - 7].set_xlabel(nicenames[i]) for i in [7, 8, 9]]

        mp.fix_ticks()
        plt.savefig("fig_marginalized2ratio.png")
        print "Saved fig_marginalized2ratio.png"
def plotmarginal(
    s,
    dists,
    add,
    mult,
    parameters,
    cube,
    plotinds,
    n_sec,
    n_dims,
    nicenames,
    title="",
    norm1=True,
    modecolors=["g", "m", "y", "c"],
    colors=["b", "b", "b", "b", "r", "r", "r", "r", "b", "b", "b", "r", "r", "r", "k", "k", "k"],
    dists2={},
    colors2=["g", "g", "g", "g", "m", "m", "m", "m", "g", "g", "g", "m", "m", "m", "gray", "gray", "gray"],
    cube2=[],
):
    mp = multipanel(dims=(2, 2), figID=1, padding=(0, 0.2))
    mp.title(title)

    for j in plotinds[0]:
        # The filling was not adding up right; don't plot each individual mode.  FUTURE NOTE: normalization is messed up
        # because numpy arrays are pointers, and I've modified the value of dists.
        for m, mode in enumerate(s["modes"]):
            #    yplot=dists[m][j][1,:]
            #    yplot*=numpy.exp(mode['local evidence'])/numpy.exp(s['global evidence'])
            #    if norm1: yplot/=numpy.max(dists['all'][j][1,:])
            #    #mp.grid[numpy.mod(j,4)].plot(dists[m][j][0,:]*mult[j]+add[j],yplot,':',color=modecolors[m],label='Mode',drawstyle='steps')
            #    dx=(dists[m][j][0,1]-dists[m][j][0,0])*mult[j]
            #    xx= numpy.ravel(zip(dists[m][j][0,:]*mult[j]+add[j], dists[m][j][0,:]*mult[j]+add[j] + dx))
            #    yy =numpy.ravel(zip(yplot, yplot))
            #    #mp.grid[numpy.mod(j,4)].fill_between(xx-dx,0,yy,color=modecolors[m],alpha=0.2)
            #
            mp.grid[numpy.mod(j, 4)].axvline(x=mode["mean"][j] * mult[j] + add[j], color=modecolors[m], label="Mode")
            mp.grid[numpy.mod(j, 4)].axvline(
                x=mode["mean"][j] * mult[j] + add[j] + mode["sigma"][j],
                color=modecolors[m],
                label="Mode",
                linestyle="--",
            )
            mp.grid[numpy.mod(j, 4)].axvline(
                x=mode["mean"][j] * mult[j] + add[j] - mode["sigma"][j],
                color=modecolors[m],
                label="Mode",
                linestyle="--",
            )
            ##print mode['maximum'][j]+add[j],mode['sigma'][j]

        yplot = dists["all"][j][1, :]  # WHY DOES DISTS CHANGE SOMEWHERE HERE?
        if norm1:
            yplot /= numpy.max(dists["all"][j][1, :])
        mp.grid[numpy.mod(j, 4)].plot(
            dists["all"][j][0, :] * mult[j] + add[j], yplot, "-", color=colors[j], drawstyle="steps"
        )
        mp.grid[numpy.mod(j, 4)].axvline(x=cube[j] * mult[j] + add[j], color=colors[j], linestyle="-", label="4D Max")

        if dists2:
            yplot2 = dists2["all"][j][1, :]
            if norm1:
                yplot2 /= numpy.max(dists2["all"][j][1, :])
            mp.grid[numpy.mod(j, 4)].plot(
                dists2["all"][j][0, :] * mult[j] + add[j], yplot2, "-", color=colors2[j], drawstyle="steps"
            )
            mp.grid[numpy.mod(j, 4)].axvline(
                x=cube2[j] * mult[j] + add[j], color=colors2[j], linestyle="-", label="4D Max, Comparison"
            )

        if norm1:
            mp.grid[numpy.mod(j, 4)].set_ylim(0, 1)

    mp.grid[0].set_ylabel("Probability")
    mp.grid[2].set_ylabel("Probability")

    if parameters[0] == "h2den1":  # CO likelihood
        mp.grid[0].set_xticks([2, 3, 4, 5, 6])
        mp.grid[0].set_xticks([2.5, 3.5, 4.5, 5.5], minor=True)
        mp.grid[1].set_xticks([1, 1.5, 2, 2.5, 3.0])
        mp.grid[3].set_xticks([-2.0, -1.0])
        mp.grid[3].set_xticks([-2.5, -1.5, -0.5], minor=True)
        # [mp.grid[i].set_xlim(xrange[i]) for i in range(4)]
        [mp.grid[i].set_xlabel(nicenames[i]) for i in range(4)]
    else:
        [mp.grid[i].set_xlabel(nicenames[i]) for i in plotinds[0]]
    mp.grid[0].text(4, 1, "ln(like):")
    for m, mode in enumerate(s["modes"]):
        mp.grid[0].text(4, 0.9 - 0.1 * m, "%.2f" % mode["local evidence"], color=modecolors[m])

    mp.fix_ticks()
    plt.savefig("fig_marginalized.png")
    print "Saved fig_marginalized.png"