Esempio n. 1
0
def spectrum_fm():
    from scipy.ndimage.filters import gaussian_filter1d as gaussf
    pyrat = pb.run(ROOT +
                   'tests/configs/spectrum_transmission_filters_test.cfg')
    params = [-1.5, -0.8, 0.0, 1.0, 1.0, 71500.0, -3.4, 2.0]
    model = pyrat.eval(params, retmodel=True)
    bandflux = pyrat.obs.bandflux

    plt.figure(1)
    plt.clf()
    plt.plot(1e4 / pyrat.spec.wn, pyrat.spec.spectrum, 'blue')
    plt.plot(1e4 / pyrat.spec.wn, gaussf(pyrat.spec.spectrum, 5), 'navy')
    plt.plot(1e4 / pyrat.obs.bandwn, bandflux, "o", c='orange')

    # Now, add noise:
    SNR = 350.0
    std = 35.0
    np.random.seed(209458)
    snr = np.random.normal(SNR, std, len(bandflux))
    uncert = bandflux / snr

    data = bandflux + np.random.normal(0.0, uncert)
    plt.errorbar(1e4 / pyrat.obs.bandwn, data, uncert, fmt='or', zorder=10)
Esempio n. 2
0
sigma = 8.0
fs = 10
lw = 1.0
logxticks = [0.5, 1.0, 2.0, 3.0, 5.0, 8.0]
rect1 = [0.075, 0.54, 0.985, 0.99]
rect2 = [0.075, 0.04, 0.985, 0.49]

fig = plt.figure(8, (8.2, 10))
plt.clf()
axes = []
for i in range(nplanets):
    ax = mp.subplotter(rect1, margin, i + 1, nx=3, ny=4, ymargin=0.025)
    axes.append(ax)
    if tr_bestfit[i] is not None:
        plt.plot(wl,
                 gaussf(tr_bestfit[i], sigma) / pc.percent,
                 lw=lw,
                 c='orange')
    plt.errorbar(bandwl,
                 tr_data[i] / pc.percent,
                 tr_uncert[i] / pc.percent,
                 fmt='o',
                 alpha=0.7,
                 ms=1.5,
                 color='b',
                 ecolor='0.3',
                 elinewidth=lw,
                 capthick=lw,
                 zorder=3)
    yran = ax.get_ylim()
    ax.tick_params(labelsize=fs - 1, direction='in', which='both')
Esempio n. 3
0
def plot_bestFit_Spectrum(filters, kurucz, tepfile, solution, output, data,
                                                          uncert, date_dir):
    '''
    Plot BART best-model spectrum
    '''
    # get star data
    R_star, T_star, sma, gstar = get_starData(tepfile)

    # get surface gravity
    grav, Rp = mat.get_g(tepfile)

    # convert Rp to m
    Rp = Rp * 1000

    # ratio planet to star
    rprs = Rp/R_star
  
    # read kurucz file
    starfl, starwn, tmodel, gmodel = w.readkurucz(kurucz, T_star, gstar)

    # read best-fit spectrum output file, take wn and spectra values
    if solution == 'eclipse':
        specwn, bestspectrum = rt.readspectrum(date_dir + output, wn=True)
        # print on screen
        print("  Plotting BART best-fit eclipse spectrum figure.")
    elif solution == 'transit':
        specwn, bestspectrum = rt.readspectrum(date_dir + output, wn=True)
        # print on screen
        print("  Plotting BART best-fit modulation spectrum figure.")

    # convert wn to wl
    specwl = 1e4/specwn

    # number of filters
    nfilters = len(filters)

    # read and resample the filters:
    nifilter  = [] # Normalized interpolated filter
    istarfl   = [] # interpolated stellar flux
    wnindices = [] # wavenumber indices used in interpolation
    meanwn    = [] # Filter mean wavenumber
    for i in np.arange(nfilters):
        # read filter:
        filtwaven, filttransm = w.readfilter(filters[i])
        meanwn.append(np.sum(filtwaven*filttransm)/sum(filttransm))
        # resample filter and stellar spectrum:
        nifilt, strfl, wnind = w.resample(specwn, filtwaven, filttransm,
                                            starwn,    starfl)
        nifilter.append(nifilt)
        istarfl.append(strfl)
        wnindices.append(wnind)

    # convert mean wn to mean wl
    meanwl = 1e4/np.asarray(meanwn)

    # band-integrate the flux-ratio or modulation:
    bandflux = np.zeros(nfilters, dtype='d')
    bandmod  = np.zeros(nfilters, dtype='d')
    for i in np.arange(nfilters):
        fluxrat = (bestspectrum[wnindices[i]]/istarfl[i]) * rprs*rprs
        bandflux[i] = w.bandintegrate(fluxrat, specwn, nifilter[i],
                                                                 wnindices[i])
        bandmod[i]  = w.bandintegrate(bestspectrum[wnindices[i]],
                                            specwn, nifilter[i], wnindices[i])

    # stellar spectrum on specwn:
    sinterp = si.interp1d(starwn, starfl)
    sflux = sinterp(specwn)
    frat = bestspectrum/sflux * rprs * rprs

    # plot figure
    plt.rcParams["mathtext.default"] = 'rm'
    matplotlib.rcParams.update({'mathtext.default':'rm'})
    matplotlib.rcParams.update({'font.size':10})
    plt.figure(3, (8.5, 5))
    plt.clf()

    # depending on solution plot eclipse or modulation spectrum
    if solution == 'eclipse':
        gfrat = gaussf(frat, 2)
        plt.semilogx(specwl, gfrat*1e3, "b", lw=1.5, label="Best-fit")
        plt.errorbar(meanwl, data*1e3, uncert*1e3, fmt="or", label="data")
        plt.plot(meanwl, bandflux*1e3, "ok", label="model", alpha=1.0)
        plt.ylabel(r"$F_p/F_s$ (10$^{3}$)", fontsize=12)

    elif solution == 'transit':
        gmodel = gaussf(bestspectrum, 2)
        plt.semilogx(specwl, gmodel, "b", lw=1.5, label="Best-fit")
        # Check units!
        plt.errorbar(meanwl, data, uncert, fmt="or", label="data")
        plt.plot(meanwl, bandmod, "ok", label="model", alpha=0.5)
        plt.ylabel(r"$(R_p/R_s)^2$", fontsize=12)

    leg = plt.legend(loc="lower right")
    leg.get_frame().set_alpha(0.5)
    ax = plt.subplot(111)
    ax.set_xscale('log')
    plt.xlabel(r"${\rm Wavelength\ \ (um)}$", fontsize=12)  
    ax.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())
    ax.set_xticks(np.arange(round(min(specwl)),max(specwl),1))
    plt.xlim(min(specwl),max(specwl))
    plt.savefig(date_dir + "BART-bestFit-Spectrum.png")
Esempio n. 4
0
rect1 = [0.073, 0.8, 0.615, 0.19]
rect2 = [0.76, 0.8, 0.23, 0.19]
rect3 = [0.67, 0.51, 1.02, 0.76]
rect4 = [0.115, 0.328, 0.84, 0.823]
rect5 = [0.02, 0.03, 0.99, 0.28]

palette = copy(plt.cm.viridis_r)
palette.set_under(color='w')
palette.set_bad(color='w')
p2019_col = pb.plots.alphatize('r', 0.6, 'darkred')

fig = plt.figure(18, (8.5, 11.0))
plt.clf()
ax = plt.axes(rect1)
ax.plot(wl,
        gaussf(best_spec_mm2017, sigma) / pc.percent,
        lw=lw,
        c='royalblue',
        label='pyratbay fit to MM2017')
ax.plot(wl,
        gaussf(best_spec_p2019, sigma) / pc.percent,
        lw=lw,
        c='orange',
        label='pyratbay fit to P2019')
ax.errorbar(bandwl,
            pyrat.obs.data / pc.percent,
            pyrat.obs.uncert / pc.percent,
            fmt='o',
            alpha=0.7,
            ms=2.5,
            color=p2019_col,
# band-integrate the flux-ratio or modulation:
bandflux = np.zeros(nfilters, dtype='d')
bandmod  = np.zeros(nfilters, dtype='d')
for i in np.arange(nfilters):
    fluxrat = (bestspectrum[wnindices[i]]/istarfl[i]) * rprs*rprs
    bandflux[i] = w.bandintegrate(fluxrat, specwn, nifilter[i], wnindices[i])
    bandmod[i]  = w.bandintegrate(bestspectrum[wnindices[i]],
                                            specwn, nifilter[i], wnindices[i])

# stellar spectrum on specwn:
sinterp = si.interp1d(starwn, starfl)
sflux = sinterp(specwn)
frat = bestspectrum/sflux * rprs * rprs

# plot eclipse spectrum
gfrat = gaussf(frat, 1)
plt.semilogx(specwl, gfrat*1e3, "slateblue", lw=1.5, label="Best-fit", alpha=0.6)
plt.errorbar(meanwl, data*1e3, uncert*1e3, fmt="ro", label="Data", alpha=0.8)
plt.plot(meanwl, bandflux*1e3, "ko", label="Model", alpha=1.0)
leg = plt.legend(loc="upper left")
leg.get_frame().set_alpha(0.5)

nfilters = len(filters)
# plot filter bandpasses
for i in np.arange(nfilters-15):
    (head, tail) = os.path.split(filters[i])
    lbl = tail[:-4]
    # read filter:
    wn, respons = w.readfilter(filters[i])
    respons = respons/3 -0.4
    wl = 10000.0/wn
rp1  = np.sqrt(pyrat.spec.spectrum)*pyrat.phy.rstar  # Transit radius
rad1 = pyrat.atm.radius                  # Atmospheric radius profile

pyrat = pb.pyrat.run(pyrat, [temp, abun2])
rp2  = np.sqrt(pyrat.spec.spectrum)*pyrat.phy.rstar
rad2 = pyrat.atm.radius

pyrat = pb.pyrat.run(pyrat, [temp, abun3])
rp3  = np.sqrt(pyrat.spec.spectrum)*pyrat.phy.rstar
rad3 = pyrat.atm.radius


# Pressure at transit radius as function of wavelength:
sigma = 3.0  # Gauss-convolve for better-looking plots
p   = sip.interp1d(rad1[::-1], press[::-1])
pt1 = p(gaussf(rp1, sigma))
p   = sip.interp1d(rad2[::-1], press[::-1])
pt2 = p(gaussf(rp2, sigma))
p   = sip.interp1d(rad3[::-1], press[::-1])
pt3 = p(gaussf(rp3, sigma))

# Photospheric pressure modulation spectrum:
lw = 1.5
plt.figure(-25)
plt.clf()
ax = plt.subplot(111)
plt.semilogy(1e4/pyrat.spec.wn, pt3, lw=lw, color="orange",
             label=r"$100\times\,{\rm solar}$")
plt.semilogy(1e4/pyrat.spec.wn, pt2, lw=lw, color="sienna",
             label=r"$1.0\times\,{\rm solar}$")
plt.semilogy(1e4/pyrat.spec.wn, pt1, lw=lw, color="k",
def plot_bestFit_Spectrum(filters,
                          kurucz,
                          tepfile,
                          solution,
                          output,
                          data,
                          uncert,
                          date_dir,
                          fs=15):
    '''
    Plot BART best-model spectrum

    Parameters
    ----------
    filters : list, strings. Paths to filter files corresponding to data.
    kurucz  : string. Path to Kurucz stellar model file.
    tepfile : string. Path to Transiting ExoPlanet (TEP) file.
    solution: string. Observing geometry. 'eclipse' or 'transit'.
    output  : string. Best-fit spectrum output file name.
    data    : 1D array. Eclipse or transit depths.
    uncert  : 1D array. Uncertainties for data values.
    date_dir: string. Path to directory where the plot will be saved.
    fs      : int.    Font size for plots.
    '''
    # get star data
    R_star, T_star, sma, gstar = get_starData(tepfile)

    # get surface gravity
    grav, Rp = mat.get_g(tepfile)

    # convert Rp to m
    Rp = Rp * 1000

    # ratio planet to star
    rprs = Rp / R_star

    # read kurucz file
    starfl, starwn, tmodel, gmodel = w.readkurucz(kurucz, T_star, gstar)

    # read best-fit spectrum output file, take wn and spectra values
    if solution == 'eclipse':
        specwn, bestspectrum = rt.readspectrum(date_dir + output, wn=True)
        # print on screen
        print("  Plotting BART best-fit eclipse spectrum figure.")
    elif solution == 'transit':
        specwn, bestspectrum = rt.readspectrum(date_dir + output, wn=True)
        # print on screen
        print("  Plotting BART best-fit modulation spectrum figure.")

    # convert wn to wl
    specwl = 1e4 / specwn

    # number of filters
    nfilters = len(filters)

    # read and resample the filters:
    nifilter = []  # Normalized interpolated filter
    istarfl = []  # interpolated stellar flux
    wnindices = []  # wavenumber indices used in interpolation
    meanwn = []  # Filter mean wavenumber
    for i in np.arange(nfilters):
        # read filter:
        filtwaven, filttransm = w.readfilter(filters[i])
        meanwn.append(np.sum(filtwaven * filttransm) / sum(filttransm))
        # resample filter and stellar spectrum:
        nifilt, strfl, wnind = w.resample(specwn, filtwaven, filttransm,
                                          starwn, starfl)
        nifilter.append(nifilt)
        istarfl.append(strfl)
        wnindices.append(wnind)

    # convert mean wn to mean wl
    meanwl = 1e4 / np.asarray(meanwn)

    # band-integrate the flux-ratio or modulation:
    bandflux = np.zeros(nfilters, dtype='d')
    bandmod = np.zeros(nfilters, dtype='d')
    for i in np.arange(nfilters):
        fluxrat = (bestspectrum[wnindices[i]] / istarfl[i]) * rprs * rprs
        bandflux[i] = w.bandintegrate(fluxrat, specwn, nifilter[i],
                                      wnindices[i])
        bandmod[i] = w.bandintegrate(bestspectrum[wnindices[i]], specwn,
                                     nifilter[i], wnindices[i])

    # stellar spectrum on specwn:
    sinterp = si.interp1d(starwn, starfl)
    sflux = sinterp(specwn)
    frat = bestspectrum / sflux * rprs * rprs

    # plot figure
    plt.rcParams["mathtext.default"] = 'rm'
    matplotlib.rcParams.update({'mathtext.default': 'rm'})
    matplotlib.rcParams.update({'font.size': fs - 2})
    plt.figure(3, (8.5, 6))
    plt.clf()

    # depending on solution plot eclipse or modulation spectrum
    if solution == 'eclipse':
        gfrat = gaussf(frat, 2)
        plt.semilogx(specwl, gfrat * 1e3, "b", lw=1.5, label="Best-fit")
        plt.errorbar(meanwl, data * 1e3, uncert * 1e3, fmt="or", label="data")
        plt.plot(meanwl, bandflux * 1e3, "ok", label="model", alpha=1.0)
        plt.ylabel(r"$F_p/F_s$ (10$^{-3}$)", fontsize=fs)

    elif solution == 'transit':
        gmodel = gaussf(bestspectrum, 2)
        plt.semilogx(specwl, gmodel, "b", lw=1.5, label="Best-fit")
        plt.errorbar(meanwl, data, uncert, fmt="or", label="data")
        plt.plot(meanwl, bandmod, "ok", label="model", alpha=0.5)
        plt.ylabel(r"$(R_p/R_s)^2$", fontsize=fs)

    leg = plt.legend(loc="best")
    leg.get_frame().set_alpha(0.5)
    ax = plt.subplot(111)
    ax.set_xscale('log')
    plt.xlabel("${\\rm Wavelength\ \ (\u03bcm)}$", fontsize=fs)
    #plt.xticks(size=fs)
    #plt.yticks(size=fs)
    formatter = matplotlib.ticker.FuncFormatter(
        lambda y, _: '{:.8g}'.format(y))
    ax.get_xaxis().set_major_formatter(formatter)
    ax.get_xaxis().set_minor_formatter(formatter)
    plt.xlim(min(specwl), max(specwl))
    plt.savefig(date_dir + "BART-bestFit-Spectrum.png")
    plt.close()
Esempio n. 8
0
                 c='orange',
                 label='repack ExoMol',
                 alpha=0.8)
    ax1.text(0.02,
             0.9,
             rf'$T = {temps[i]}$ K',
             fontsize=fs,
             transform=ax1.transAxes)
    ax1.set_xticks(xticks)
    ax1.set_xlim(xlim)
    ax1.tick_params(labelsize=fs - 1, direction='in', which='both', right=True)
    # Fractional difference between log-values:
    diff = 100 * (1 - np.log(exomol_ec[i]) / np.log(repack_ec[i]))
    ax2 = plt.subplot(ntemp, 2, 2 + 2 * i)
    plt.plot(wl, diff, c='red', lw=lw)
    plt.plot(wl[1:-1], gaussf(diff[1:-1], 100), c='black')
    ax2.set_xticks(xticks)
    ax2.set_xlim(xlim)
    ax2.set_ylim(-0.2, 1.0)
    ax2.tick_params(labelsize=fs - 1, direction='in', which='both', right=True)
    if i == 0:
        ax1.legend(loc='lower right', fontsize=fs - 1)
    if i == 1:
        ax1.set_ylabel(r'H$_2$O extinction coefficient (cm$^{-1}$)',
                       fontsize=fs)
        ax2.set_ylabel(r'Dex residuals (%)', fontsize=fs)
ax1.set_xlabel('Wavelength (um)', fontsize=fs)
ax2.set_xlabel('Wavelength (um)', fontsize=fs)
plt.savefig('../plots/H2O_low-resolution_extinction_coefficient.pdf')

# Transmission spectrum at a temperature of 2500K:
Esempio n. 9
0
post[:, 4] = post[:, 5]  # HCN
post[:, 5] = post[:, 6]  # NH3
# Replace with mean molecular weight:
post[:, 6] = mu[uinv]

pname = [
    r"$T$ (K)", "Radius ($R_{\\rm Jup}$)", "$\log_{10}({\\rm H2O})$",
    "$\log_{10}({\\rm CH4})$", "$\log_{10}({\\rm HCN})$",
    "$\log_{10}({\\rm NH3})$", r"$\bar m$", "$\log_{10}(f_{\\rm gray})$"
]

# Spectrum percentiles:
pwl, prprs, plow2, plow, phigh, phigh2 = \
       np.loadtxt(logfile.replace('.log','_percentiles.dat'), unpack=True)
sigma = 9.0
prprs = gaussf(prprs, sigma)
plow = gaussf(plow, sigma)
phigh = gaussf(phigh, sigma)

# ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
# Plot:
plt.figure(0, (8.5, 11))
plt.clf()
rect = [0.15, 0.1, 0.95, 0.71]
margin = 0.01
fs = 10
lw = 1.25

# Get location:
ax0 = mp.subplotter(rect, margin, 15, npars)
plt.clf()
Esempio n. 10
0
spectrum2 = pyrat.spec.spectrum
M2 = (1 - spectrum2) / (1 - spectrum2[0])

pyrat.haze.model[0].pars[0] = 3.63
pyrat.phy.rplanet = 1.156 * pc.rjup
pyrat = pb.pyrat.run(pyrat, [temp, q3])
spectrum3 = pyrat.spec.spectrum
M3 = (1 - spectrum3) / (1 - spectrum3[0])

# The plot:
plt.figure(5, (8.5, 5))
plt.clf()
ax = plt.axes([0.11, 0.2, 0.6, 0.55])
# The models:
plt.plot(1e4 * dwl,
         gaussf(M3, sigma),
         "-",
         lw=1.25,
         zorder=0,
         label=r"$100\times\,{\rm solar}$",
         color='orange')
plt.plot(1e4 * dwl,
         gaussf(M2, sigma),
         "-",
         lw=1.25,
         zorder=0,
         label=r"$1.0\times\,{\rm solar}$",
         color='sienna')
plt.plot(1e4 * dwl,
         gaussf(M1, sigma),
         "-",
Esempio n. 11
0
sys.path.append("../pyratbay")
import pyratbay as pb
import pyratbay.constants as pc

# ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
# Initialize Pyrat object:
pyrat = pb.pyrat.init("spectrum_001Xsolar.cfg")
wl = 1.0 / (pyrat.spec.wn * pc.A)
q = pyrat.atm.q
temp = pyrat.atm.temp

# Compute spectrum:
#pyrat.phy.rplanet = 1.182*pc.rjup
pyrat = pb.pyrat.run(pyrat, [temp, q])
sigma = 5.0
spectrum = gaussf(np.sqrt(pyrat.spec.spectrum), sigma)

# The data:
bandwl = np.array([7280.0, 8386.0, 6641.0])
rprs = 0.136 + np.array([0.001325, 0.001640, 0.001257])
rprse = [0.000371, 0.001161, 0.000505]
width = [550, 950, 495]

# ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
# The plot:
lw = 1.5
plt.figure(5, (8.5, 5))
plt.clf()
ax = plt.axes([0.12, 0.12, 0.82, 0.82])
# models:
plt.plot(wl,
Esempio n. 12
0
for i in range(ntargets):
    page = sum(i >= new_page) - 1
    pos = i - new_page[page]
    if i in new_page:
        fig = plt.figure(20 + page, (8.2, 10.8))
        plt.clf()
    # The spectra:
    ax1 = mc3.plots.subplotter(rect,
                               margin1,
                               1 + 3 * pos,
                               nx=3,
                               ny=ny,
                               ymargin=ymargin)
    if low2[i] is not None:
        ax1.fill_between(wl[i],
                         gaussf(low2[i], sigma) / pc.percent,
                         gaussf(high2[i], sigma) / pc.percent,
                         facecolor="gold",
                         edgecolor="none",
                         alpha=1.0)
        ax1.fill_between(wl[i],
                         gaussf(low1[i], sigma) / pc.percent,
                         gaussf(high1[i], sigma) / pc.percent,
                         facecolor="orange",
                         edgecolor="none",
                         alpha=1.0)
    ax1.plot(wl[i],
             gaussf(best_spec[i], sigma) / pc.percent,
             lw=lw,
             c='red',
             label='Bestfit model')
Esempio n. 13
0
plt.plot(dat021[:, 0], dat021[:, 1], label='0.025 cm$^{-1}$ grid, 11 um max')
plt.plot(dat010[:, 0], dat010[:, 1], label='0.1 cm$^{-1}$ grid, 10 um max')
plt.plot(dat011[:, 0], dat011[:, 1], label='0.1 cm$^{-1}$ grid, 11 um max')
plt.xlim(10000. / 5500., 10000. / 2000.)
plt.legend(loc='center left', prop={'size': 8}, bbox_to_anchor=(1, 0.5))
if title:
    plt.title('Unsmoothed, unbinned')
plt.xlabel('Wavelength (um)')
plt.ylabel('Flux (erg/s/cm)')
plt.savefig(outdir + 'spec_comp_nobin_nosmooth_4small' + fext,
            bbox_inches='tight')
plt.close()

# Unbinned, smoothed data - Gaussian smoothing
# gaussf(spec, stdev)
g020_2 = gaussf(dat020[:, 1], 2 * 40)
g020_5 = gaussf(dat020[:, 1], 5 * 40)
g020_25 = gaussf(dat020[:, 1], 25 * 40)

g021_2 = gaussf(dat021[:, 1], 2 * 40)
g021_5 = gaussf(dat021[:, 1], 5 * 40)
g021_25 = gaussf(dat021[:, 1], 25 * 40)

g010_2 = gaussf(dat010[:, 1], 2 * 10)
g010_5 = gaussf(dat010[:, 1], 5 * 10)
g010_25 = gaussf(dat010[:, 1], 25 * 10)

g011_2 = gaussf(dat011[:, 1], 2 * 10)
g011_5 = gaussf(dat011[:, 1], 5 * 10)
g011_25 = gaussf(dat011[:, 1], 25 * 10)
Esempio n. 14
0
    ticker(ax)


plt.figure(325, (12.5, 8))
plt.clf()
plt.subplots_adjust(0.085, 0.07, 0.98, 0.99, hspace=0.18, wspace=0.22)
ax = plt.subplot(221)
plt.text(0.02,
         0.92,
         'H2O, CO, H2 Ray, H2-H2 CIA',
         fontsize=fs,
         transform=ax.transAxes)
plt.plot(pyrat_wl_no_lbl, pyrat_no_lbl, c='navy')
plt.plot(petit_wl, petit_no_lbl, c='darkorange', alpha=0.75)
plt.plot(1e4 / pyrat.spec.wn,
         gaussf(pyrat_trans, 12),
         c='blue',
         label='pyratbay')
plt.plot(petit_wl, petit_trans, c='orange', label='petitRADTRANS', alpha=0.8)
plt.ylabel(r'Transit radius ($\rm R_{Jup}$)', fontsize=fs)
plt.ylim(yrant)
plt.legend(loc='lower right', fontsize=fs)
boliler_plate(plt, ax)
ax = plt.subplot(223)
plt.plot(pyrat_wl, planck_hot, c='0.5')
plt.plot(pyrat_wl, planck_cold, c='0.5')
plt.plot(pyrat_wl, gaussf(pyrat_emission, 10.0), c='blue')
plt.plot(petit_wl, petit_emission, c='orange', alpha=0.75)
plt.ylabel(r'Planet flux (erg s$^{-1}$ cm$^{-2}$ cm)', fontsize=fs)
plt.ylim(yrane)
boliler_plate(plt, ax)
Esempio n. 15
0
def spectrum(spectrum,
             wavelength,
             rt_path,
             data=None,
             uncert=None,
             bandwl=None,
             bandflux=None,
             bandtrans=None,
             bandidx=None,
             starflux=None,
             rprs=None,
             label='model',
             bounds=None,
             logxticks=None,
             gaussbin=2.0,
             yran=None,
             filename=None,
             fignum=501,
             axis=None):
    """
    Plot a transmission or emission model spectrum with (optional) data
    points with error bars and band-integrated model.

    Parameters
    ----------
    spectrum: 1D float ndarray
        Planetary spectrum evaluated at wavelength.
    wavelength: 1D float ndarray
        The wavelength of the model in microns.
    rt_path: String
        Radiative-transfer observing geometry (transit, eclipse, or emission).
    data: 1D float ndarray
        Observing data points at each bandwl.
    uncert: 1D float ndarray
        Uncertainties of the data points.
    bandwl: 1D float ndarray
        The mean wavelength for each band/data point.
    bandflux: 1D float ndarray
        Band-integrated model spectrum at each bandwl.
    bandtrans: List of 1D float ndarrays
        Transmission curve for each band.
    bandidx: List of 1D float ndarrays.
        The indices in wavelength for each bandtrans.
    starflux: 1D float ndarray
        Stellar spectrum evaluated at wavelength.
    rprs: Float
        Planet-to-star radius ratio.
    label: String
        Label for spectrum curve.
    bounds: Tuple
        Tuple with -2, -1, +1, and, +2 sigma boundaries of spectrum.
        If not None, plot shaded area between +/-1sigma and +/-2sigma
        boundaries.
    logxticks: 1D float ndarray
        If not None, switch the X-axis scale from linear to log, and set
        the X-axis ticks at the locations given by logxticks.
    gaussbin: Integer
        Standard deviation for Gaussian-kernel smoothing (in number of samples).
    yran: 1D float ndarray
        Figure's Y-axis boundaries.
    filename: String
        If not None, save figure to filename.
    fignum: Integer
        Figure number.
    axis: AxesSubplot instance
        The matplotlib Axes of the figure.

    Returns
    -------
    ax: AxesSubplot instance
        The matplotlib Axes of the figure.
    """
    # Plotting setup:
    fs = 14.0
    ms = 6.0
    lw = 1.25

    if axis is None:
        plt.figure(fignum, (8, 5))
        plt.clf()
        ax = plt.subplot(111)
    else:
        ax = axis

    #fscale = {'':1.0, '%':100.0, 'ppt':1e3, 'ppm':1e6}

    spec_kw = {'label': label}
    if bounds is None:
        spec_kw['color'] = 'orange'
    else:
        spec_kw['color'] = 'orangered'

    # Setup according to geometry:
    if rt_path == 'emission':
        fscale = 1.0
        plt.ylabel(r'$F_{\rm p}$ (erg s$^{-1}$ cm$^{-2}$ cm)', fontsize=fs)
    if rt_path == 'eclipse':
        #if starflux is not None and rprs is not None:
        spectrum = spectrum / starflux * rprs**2.0
        if bounds is not None:
            bounds = [bound / starflux * rprs**2.0 for bound in bounds]
        fscale = 1.0 / pc.ppt
        plt.ylabel(r'$F_{\rm p}/F_{\rm s}\ (ppt)$', fontsize=fs)
    elif rt_path == 'transit':
        fscale = 1.0 / pc.percent
        plt.ylabel(r'$(R_{\rm p}/R_{\rm s})^2$ (%)', fontsize=fs)

    gmodel = gaussf(spectrum, gaussbin)
    if bounds is not None:
        gbounds = [gaussf(bound, gaussbin) for bound in bounds]
        ax.fill_between(wavelength,
                        fscale * gbounds[0],
                        fscale * gbounds[3],
                        facecolor='gold',
                        edgecolor='none')
        ax.fill_between(wavelength,
                        fscale * gbounds[1],
                        fscale * gbounds[2],
                        facecolor='orange',
                        edgecolor='none')

    # Plot model:
    plt.plot(wavelength, gmodel * fscale, lw=lw, **spec_kw)
    # Plot band-integrated model:
    if bandflux is not None and bandwl is not None:
        plt.plot(bandwl,
                 bandflux * fscale,
                 'o',
                 ms=ms,
                 color='tomato',
                 mec='maroon',
                 mew=lw)
    # Plot data:
    if data is not None and uncert is not None and bandwl is not None:
        plt.errorbar(bandwl,
                     data * fscale,
                     uncert * fscale,
                     fmt='o',
                     label='data',
                     color='blue',
                     ms=ms,
                     elinewidth=lw,
                     capthick=lw,
                     zorder=3)

    if yran is not None:
        ax.set_ylim(np.array(yran))
    yran = ax.get_ylim()

    # Transmission filters:
    if bandtrans is not None and bandidx is not None:
        bandh = 0.06 * (yran[1] - yran[0])
        for btrans, bidx in zip(bandtrans, bandidx):
            btrans = bandh * btrans / np.amax(btrans)
            plt.plot(wavelength[bidx], yran[0] + btrans, '0.4', zorder=-10)
        ax.set_ylim(yran)

    if logxticks is not None:
        ax.set_xscale('log')
        plt.gca().xaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())
        ax.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())
        ax.set_xticks(logxticks)

    ax.tick_params(which='both',
                   right=True,
                   top=True,
                   direction='in',
                   labelsize=fs - 2)
    plt.xlabel('Wavelength (um)', fontsize=fs)
    plt.legend(loc='best', numpoints=1, fontsize=fs - 1)
    plt.xlim(np.amin(wavelength), np.amax(wavelength))
    plt.tight_layout()

    if filename is not None:
        plt.savefig(filename)
    return ax
ranges = [(-5.5, -1.0), (-12.0, -1.0), (-12.0, -1.0), (-12.0, -1.0)]
nbins = 100
nxpdf = 300
x = np.zeros((nmodes, nphase, nmol, nbins))
post = np.zeros((nmodes, nphase, nmol, nbins))
xpdf = [np.linspace(ran[0], ran[1], nxpdf) for ran in ranges]
fpdf = np.zeros((nmodes, nphase, nmol, nxpdf))

for j, i, m in product(range(nmodes), range(nphase), range(nmol)):
    if k != 2 and i > 8:
        continue
    vals, bins = np.histogram(posteriors[k, j, i][:, m],
                              bins=nbins,
                              range=ranges[m],
                              density=True)
    vals = gaussf(vals, 1.5)
    vals = vals / np.amax(vals) * 0.8
    bins = 0.5 * (bins[1:] + bins[:-1])
    PDF, Xpdf, hpd_min = mc3.stats.cred_region(posteriors[k, j, i][:, m],
                                               quantile=0.683)
    f = si.interp1d(bins,
                    vals,
                    kind='nearest',
                    bounds_error=False,
                    fill_value=0.0)
    x[j, i, m] = bins
    post[j, i, m] = vals
    fpdf[j, i, m] = f(xpdf[m])

plot_phase = np.concatenate([obs_phase - 1, obs_phase, obs_phase + 1])
true_q = atm_models[k]['abund'][::4]
Esempio n. 17
0
def plot_bestFit_Spectrum(low, high, xtic, xlab, spec, clr, specs, atmfile,
                          filters, kurucz, tepfile, outflux, data, uncert,
                          direct):
    '''
    Plot Transit spectrum
    '''
    # get star data
    R_star, T_star, sma, gstar = bf.get_starData(tepfile)

    # get surface gravity
    grav, Rp = mat.get_g(tepfile)

    # convert Rp to m
    Rp = Rp * 1000

    # ratio planet to star
    rprs = Rp / R_star

    # read kurucz file
    starfl, starwn, tmodel, gmodel = w.readkurucz(kurucz, T_star, gstar)

    # read best-fit spectrum output file, take wn and spectra values
    (head, tail) = os.path.split(outflux)
    specwn, bestspectrum = rt.readspectrum(direct + '/' + tail, wn=True)

    # convert wn to wl
    specwl = 1e4 / specwn

    # number of filters
    nfilters = len(filters)

    # read and resample the filters:
    nifilter = []  # Normalized interpolated filter
    istarfl = []  # interpolated stellar flux
    wnindices = []  # wavenumber indices used in interpolation
    meanwn = []  # Filter mean wavenumber
    for i in np.arange(nfilters):
        # read filter:
        filtwaven, filttransm = w.readfilter(filters[i])
        meanwn.append(np.sum(filtwaven * filttransm) / sum(filttransm))
        # resample filter and stellar spectrum:
        nifilt, strfl, wnind = w.resample(specwn, filtwaven, filttransm,
                                          starwn, starfl)
        nifilter.append(nifilt)
        istarfl.append(strfl)
        wnindices.append(wnind)

    # convert mean wn to mean wl
    meanwl = 1e4 / np.asarray(meanwn)

    # band-integrate the flux-ratio or modulation:
    bandflux = np.zeros(nfilters, dtype='d')
    bandmod = np.zeros(nfilters, dtype='d')
    for i in np.arange(nfilters):
        fluxrat = (bestspectrum[wnindices[i]] / istarfl[i]) * rprs * rprs
        bandflux[i] = w.bandintegrate(fluxrat, specwn, nifilter[i],
                                      wnindices[i])
        bandmod[i] = w.bandintegrate(bestspectrum[wnindices[i]], specwn,
                                     nifilter[i], wnindices[i])

    # stellar spectrum on specwn:
    sinterp = si.interp1d(starwn, starfl)
    sflux = sinterp(specwn)
    frat = bestspectrum / sflux * rprs * rprs

    ###################### plot figure #############################

    plt.rcParams["mathtext.default"] = 'rm'
    matplotlib.rcParams.update({'mathtext.default': 'rm'})
    matplotlib.rcParams.update({
        'axes.labelsize': 16,
        'xtick.labelsize': 20,
        'ytick.labelsize': 20,
    })

    plt.figure(2, (8.5, 5))
    plt.clf()

    # smooth the spectrum a fit
    gfrat = gaussf(frat, 2)

    # plot eclipse spectrum
    plt.semilogx(specwl,
                 gfrat * 1e3,
                 clr,
                 lw=1.5,
                 label="Spectrum",
                 linewidth=4)
    plt.errorbar(meanwl,
                 data * 1e3,
                 uncert * 1e3,
                 fmt="ko",
                 label="Data",
                 alpha=0.7)
    plt.ylabel(r"$F_p/F_s$ (10$^{-3}$)", fontsize=24)

    leg = plt.legend(loc="upper left")
    leg.get_frame().set_alpha(0.5)
    ax = plt.subplot(111)
    ax.set_xscale('log')
    plt.xlabel(r"${\rm Wavelength\ \ (um)}$", fontsize=24)
    ax.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())
    plt.gca().xaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())
    ax.set_xticks([0.7, 0.8, 0.9, 1.0, 2.0, 3.0, 4.0, 5.0])
    ax.set_xticklabels(["0.7", "", "", "1.0", "2.0", "3.0", "4.0", "5.0"])
    plt.xlim(min(specwl), max(specwl))

    nfilters = len(filters)
    # plot filter bandpasses
    for i in np.arange(nfilters - 15):
        (head, tail) = os.path.split(filters[i])
        lbl = tail[:-4]
        # read filter:
        wn, respons = w.readfilter(filters[i])
        respons = respons / 3 - 0.4
        wl = 10000.0 / wn
        #plt.plot(wl, respons, color='crimson', linewidth =1)
        if lbl == 'spitzer_irac1_sa' or lbl == 'spitzer_irac2_sa':
            respons = respons * 2 + 0.4
            plt.plot(wl, respons, color='grey', linewidth=1, alpha=0.5)
            #plt.plot(wl, respons*2, color='orangered', linewidth =1)
        elif lbl == 'Wang-Hband' or lbl == 'Wang-Kband':
            plt.plot(wl, respons, 'grey', linewidth=1, alpha=0.5)
        elif lbl == 'VLT_1190' or lbl == 'VLT_2090':
            plt.plot(wl, respons, color='grey', linewidth=2, alpha=0.5)
            #plt.plot(wl, respons, color='firebrick', linewidth =2)
        elif lbl == 'GROND_K_JB' or lbl == 'GROND_i_JB':
            plt.plot(wl, respons, 'grey', linewidth=1, alpha=0.5)
        elif lbl == 'Zhou_Ks':
            plt.plot(wl, respons, 'grey', linewidth=1, alpha=0.5)

    plt.ylim(-0.4, 7)
    plt.text(1.9, 3, specs, color=clr, fontsize=26)

    plt.subplots_adjust(bottom=0.20)

    plt.savefig(spec + "_BestFit-transSpec.png")
    plt.savefig(spec + "_BestFit-transSpec.ps")
Esempio n. 18
0
def plot_bestFit_Spectrum(filters, kurucz, tepfile, solution, output, data,
                                                          uncert, date_dir):
    '''
    Plot BART best-model spectrum
    '''
    # get star data
    R_star, T_star, sma, gstar = get_starData(tepfile)

    # get surface gravity
    grav, Rp = mat.get_g(tepfile)

    # convert Rp to m
    Rp = Rp * 1000

    # ratio planet to star
    rprs = Rp/R_star
  
    # read kurucz file
    starfl, starwn, tmodel, gmodel = w.readkurucz(kurucz, T_star, gstar)

    # read best-fit spectrum output file, take wn and spectra values
    if solution == 'eclipse':
        specwn, bestspectrum = rt.readspectrum(date_dir + output, wn=True)
        # print on screen
        print("  Plotting BART best-fit eclipse spectrum figure.")
    elif solution == 'transit':
        specwn, bestspectrum = rt.readspectrum(date_dir + output, wn=True)
        # print on screen
        print("  Plotting BART best-fit modulation spectrum figure.")

    # convert wn to wl
    specwl = 1e4/specwn

    # number of filters
    nfilters = len(filters)

    # read and resample the filters:
    nifilter  = [] # Normalized interpolated filter
    istarfl   = [] # interpolated stellar flux
    wnindices = [] # wavenumber indices used in interpolation
    meanwn    = [] # Filter mean wavenumber
    for i in np.arange(nfilters):
        # read filter:
        filtwaven, filttransm = w.readfilter(filters[i])
        meanwn.append(np.sum(filtwaven*filttransm)/sum(filttransm))
        # resample filter and stellar spectrum:
        nifilt, strfl, wnind = w.resample(specwn, filtwaven, filttransm,
                                            starwn,    starfl)
        nifilter.append(nifilt)
        istarfl.append(strfl)
        wnindices.append(wnind)

    # convert mean wn to mean wl
    meanwl = 1e4/np.asarray(meanwn)

    # band-integrate the flux-ratio or modulation:
    bandflux = np.zeros(nfilters, dtype='d')
    bandmod  = np.zeros(nfilters, dtype='d')
    for i in np.arange(nfilters):
        fluxrat = (bestspectrum[wnindices[i]]/istarfl[i]) * rprs*rprs
        bandflux[i] = w.bandintegrate(fluxrat, specwn, nifilter[i],
                                                                 wnindices[i])
        bandmod[i]  = w.bandintegrate(bestspectrum[wnindices[i]],
                                            specwn, nifilter[i], wnindices[i])

    # stellar spectrum on specwn:
    sinterp = si.interp1d(starwn, starfl)
    sflux = sinterp(specwn)
    frat = bestspectrum/sflux * rprs * rprs

    # plot figure
    plt.rcParams["mathtext.default"] = 'rm'
    matplotlib.rcParams.update({'mathtext.default':'rm'})
    matplotlib.rcParams.update({'font.size':10})
    plt.figure(3, (8.5, 5))
    plt.clf()

    # depending on solution plot eclipse or modulation spectrum
    if solution == 'eclipse':
        gfrat = gaussf(frat, 2)
        plt.semilogx(specwl, gfrat*1e3, "b", lw=1.5, label="Best-fit")
        plt.errorbar(meanwl, data*1e3, uncert*1e3, fmt="or", label="data")
        plt.plot(meanwl, bandflux*1e3, "ok", label="model", alpha=1.0)
        plt.ylabel(r"$F_p/F_s$ (10$^{3}$)", fontsize=12)

    elif solution == 'transit':
        gmodel = gaussf(bestspectrum, 2)
        plt.semilogx(specwl, gmodel, "b", lw=1.5, label="Best-fit")
        # Check units!
        plt.errorbar(meanwl, data, uncert, fmt="or", label="data")
        plt.plot(meanwl, bandmod, "ok", label="model", alpha=0.5)
        plt.ylabel(r"$(R_p/R_s)^2$", fontsize=12)

    leg = plt.legend(loc="lower right")
    leg.get_frame().set_alpha(0.5)
    ax = plt.subplot(111)
    ax.set_xscale('log')
    plt.xlabel(r"${\rm Wavelength\ \ (um)}$", fontsize=12)  
    ax.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())
    ax.set_xticks(np.arange(min(specwl),max(specwl),1))
    plt.xlim(min(specwl),max(specwl))
    plt.savefig(date_dir + "BART-bestFit-Spectrum.png")
for i in range(nphase):
    plt.semilogy(temps[i, 1], press, lw=1.5, c=bicolor(obs_phase[i]))
ax.set_yticks(np.logspace(2, -6, 5))
ax.set_ylim(np.amax(press), 1e-7)
ax.set_xlim(250, 2200)
ax.set_ylabel('Pressure (bar)', fontsize=fs - 1)
plt.xlabel('Temperature (K)', fontsize=fs - 1)
ax.tick_params(labelsize=fs - 2, direction='in', which='both')

# Spectra:
ax = fig.add_axes([0.29, bot, 0.63, dy])
plt.xscale('log')
ax.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())
ax.set_xticks(logxticks)
for i in range(nphase):
    ax.plot(wl, gaussf(flux[2, i], sigma) * pc.ppt, c=bicolor(obs_phase[i]))
ax.set_xlim(0.8, 5.5)
ax.set_ylim(0, 110)
ax.set_xlabel('Wavelength (um)', fontsize=fs)
ax.set_ylabel(r'Disk-integrated flux ($10^{3}$ erg s$^{-1}$ cm$^{-2}$ cm)',
              fontsize=fs)
ax.tick_params(labelsize=fs - 1, direction='in')

ax1 = fig.add_axes([0.925, bot, 0.015, dy])
norm = matplotlib.colors.Normalize(vmin=0, vmax=1.0)
cb1 = matplotlib.colorbar.ColorbarBase(ax1,
                                       cmap=bicolor,
                                       norm=norm,
                                       ticks=np.linspace(0, 1, 11),
                                       orientation='vertical')
cb1.set_label('Orbital phase', fontsize=fs)
    [c_error[0], ''],
    [c_error[1], ''],
)

fig = plt.figure(21, (8.5, 8.0))
plt.clf()
legs = []
for i in range(nphase):
    rect = [xmin1, ymin, xmax1, ymax]
    ax = mc3.plots.subplotter(rect, margin, i + 1, nx=1, ny=3)
    rect = [xmin1 + 0.04, ymin + 0.13, 0.48, ymax - 0.005]
    margin2 = margin - (rect[3] - rect[1]) + (ymax - ymin)
    ax2 = mc3.plots.subplotter(rect, margin2, i + 1, nx=1, ny=3)
    for k in range(2):
        cr = ax.fill_between(wl,
                             gaussf(lo_fr[k, i], sigma) / pc.ppt,
                             gaussf(hi_fr[k, i], sigma) / pc.ppt,
                             facecolor=c_error[k],
                             edgecolor='none',
                             alpha=alpha[k])
        line, = ax.plot(wl,
                        gaussf(median_fr[k, i], sigma) / pc.ppt,
                        c=c_model[k],
                        lw=lw)
        eb = ax.errorbar(band_wl * offset[k],
                         data[k, i] / pc.ppt,
                         uncerts[k, i] / pc.ppt,
                         zorder=90,
                         mew=0.25,
                         mec="k",
                         lw=lw,
Esempio n. 21
0
    config = cp.SafeConfigParser()
    config.read(["run02/" + files[j, 0] + ".cfg"])
    # Stellar model as a blackbody:
    starflux = ps.bbflux(wn, config.getfloat("pyrat", "tstar"))
    rprs = (float(config.get("pyrat", "rplanet").split()[0]) * pc.rjup /
            (float(config.get("pyrat", "rstar").split()[0]) * pc.rsun))
    plt.figure(1)
    plt.clf()
    plt.subplots_adjust(0.15, 0.1, 0.95, 0.95)
    ax = plt.subplot(111)
    for i in np.arange(nmodels):
        metal = "{:g}".format(float(files[j, i].split("_")[2][0:4]))
        albedo = files[j, i].split("_")[1]
        wl, spectrum = ps.readpyrat("run02/" + files[j, i] + "_radeq.dat",
                                    False)
        plt.plot(wl,
                 gaussf(spectrum / starflux, sigma) * rprs**2,
                 lw=1.0,
                 label="{:04.1f}x  {}".format(float(metal), albedo),
                 color=col2[i])
    plt.xscale("log")
    plt.gca().xaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())
    ax.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())
    plt.xticks([0.5, 1, 2, 4, 10, 20])
    plt.text(0.98, 0.05, planet[j], transform=ax.transAxes, ha="right")
    plt.xlim(np.amin(wl), np.amax(wl))
    plt.legend(loc="upper left", fontsize=9)
    plt.xlabel("Wavelength (um)")
    plt.ylabel("Flux ratio")
    plt.savefig("./plots/{}_thermo-rad-equil_fluxratio.png".format(planet[j]))