plt.ion() press = np.logspace(-8, 2, 100) kappa = -3.0 gamma1 = 0.3 gamma2 = 0.1 alpha = 0.6 beta = 0.8 R_star = 0.756 * ac.R_sun.value T_star = 5000 T_int = 100 sma = 0.03099 * ac.au.value grav = 2182.73 T_int_type = 'const' temp = PT.PT_line(press, kappa, gamma1, gamma2, alpha, beta, R_star, T_star, T_int, sma, grav, T_int_type) plt.plot(temp, press) plt.yscale('log') plt.gca().invert_yaxis() plt.xlabel('Temperature (K)') plt.ylabel('Pressure (bar)') plt.savefig('inv.png', bbox_inches='tight') plt.close() out = np.zeros((100, 9)) out[:,0] = press out[:,1] = temp out[:,2] = 0.1499751 out[:,3] = 0.8498589 out[:,4] = 1e-4
# Read the pressure file to an array: press = PT.read_press_file(pfile) # System parameters: Rplanet = 1.0 * 6.995e8 # m Tstar = 5700.0 # K Tint = 100.0 # K gplanet = 2200.0 # cm s-2 smaxis = 0.050 * sc.au # m # Fitting parameters: [log10(kappa), log10(g1), log10(g2), alpha, beta] params = np.asarray([-2.0, -0.55, -0.8, 0.5, 1.0]) # Calculate the temperature profile: temp = PT.PT_line(press, params, Rplanet, Tstar, Tint, smaxis, gplanet) # :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: # ( 2) Make an atmospheric file with uniform abundances: import makeatm as ma # Output filename: atmfile = "uniform.atm" # Elemental abundances file: elemabun = "../inputs/abundances_Asplund2009.txt" # Transiting extrasolar planet filename: tep = "../inputs/tep/HD209458b.tep" # Atmospheric species: species = "He H2 CO CO2 CH4 H2O NH3 C2H2 C2H4" # Abundances (mole mixing ratio):
def retrievedPT(datadir, atmfile, tepfile, nmol, solution, outname, outdir=None, T_int=100.): """ Inputs ------ datadir: string. Path/to/directory containing BART-formatted output. atmfile: string. Path/to/atmospheric model file. tepfile: string. Path/to/Transiting ExoPlanet file. nmol: int. Number of molecules being fit by MCMC. solution: string. Geometry of the system. 'eclipse' or 'transit'. outname: string. File name of resulting plot. outdir: string. Path/to/dir to save `outname`. If None, defaults to the results directory of BARTTest if `datadir` is within BARTTest. T_int: float. Internal planetary temperature. Default is 100 K. """ # Set outdir if not specified if outdir is None: try: if datadir[-1] != '/': datadir = datadir + '/' outdir = 'results'.join(datadir.rsplit('code-output', \ 1)).rsplit('/', 2)[0] + '/' if not os.path.isdir(outdir): os.makedirs(outdir) except: print("Data directory not located within BARTTest.") print("Please specify an output directory `outdir` and try again.") sys.exit(1) # Read g_surf and R_planet from TEP file grav, Rp = ma.get_g(tepfile) # Read star data from TEP file, and semi-major axis R_star, T_star, sma, gstar = bf.get_starData(tepfile) # Read atmfile mols, atminfo = readatm(atmfile) pressure = atminfo[:, 1] # Read MCMC output file MCfile = datadir + 'MCMC.log' bestP, uncer = bf.read_MCMC_out(MCfile) allParams = bestP # Get number of burned iterations foo = open(MCfile, 'r') lines = foo.readlines() foo.close() line = [ foop for foop in lines if " Burned in iterations per chain:" in foop ] burnin = int(line[0].split()[-1]) # Figure out number of parameters nparams = len(allParams) nradfit = int(solution == 'transit') nPTparams = nparams - nmol - nradfit PTparams = allParams[:nPTparams] # Plot the best PT profile kappa, gamma1, gamma2, alpha, beta = PTparams best_T = pt.PT_line(pressure, kappa, gamma1, gamma2, alpha, beta, R_star, T_star, T_int, sma, grav * 1e2, 'const') # Load MCMC data MCMCdata = datadir + 'output.npy' data = np.load(MCMCdata) nchains, npars, niter = np.shape(data) # Make datacube from MCMC data data_stack = data[0, :, burnin:] for c in np.arange(1, nchains): data_stack = np.hstack((data_stack, data[c, :, burnin:])) # Datacube of PT profiles PTprofiles = np.zeros((np.shape(data_stack)[1], len(pressure))) curr_PTparams = PTparams for k in np.arange(0, np.shape(data_stack)[1]): j = 0 for i in np.arange(len(PTparams)): curr_PTparams[i] = data_stack[j, k] j += 1 kappa, gamma1, gamma2, alpha, beta = curr_PTparams PTprofiles[k] = pt.PT_line(pressure, kappa, gamma1, gamma2, alpha, beta, R_star, T_star, T_int, sma, grav * 1e2, 'const') # Get percentiles (for 1, 2-sigma boundaries): low1 = np.percentile(PTprofiles, 16.0, axis=0) hi1 = np.percentile(PTprofiles, 84.0, axis=0) low2 = np.percentile(PTprofiles, 2.5, axis=0) hi2 = np.percentile(PTprofiles, 97.5, axis=0) median = np.median(PTprofiles, axis=0) # Plot and save figure plt.figure(2) plt.clf() ax = plt.subplot(111) ax.fill_betweenx(pressure, low2, hi2, facecolor="#62B1FF", edgecolor="0.5") ax.fill_betweenx(pressure, low1, hi1, facecolor="#1873CC", edgecolor="#1873CC") plt.semilogy(median, pressure, "-", lw=2, label='Median', color="k") plt.semilogy(best_T, pressure, "-", lw=2, label="Best fit", color="r") plt.semilogy(atminfo[:, 2], pressure, "--", lw=2, label='Input', color='r') plt.ylim(pressure[0], pressure[-1]) plt.legend(loc="best") plt.xlabel("Temperature (K)", size=15) plt.ylabel("Pressure (bar)", size=15) plt.savefig(outdir + outname) plt.close()
def callTransit(atmfile, tepfile, MCfile, stepsize, molfit, solution, p0, tconfig, date_dir, params, burnin, abun_file): """ Call Transit to produce best-fit outputs. Plot MCMC posterior PT plot. Parameters: ----------- atmfile: String Atmospheric file. tepfile: String Transiting extra-solar planet file. MCfile: String File with MCMC log and best-fitting results. stepsize: 1D float ndarray FINDME molfit: 1D String ndarray List of molecule names to modify their abundances. solution: String Flag to indicate transit or eclipse geometry p0: Float Atmosphere's 'surface' pressure level. tconfig: String Transit configuration file. date_dir: String Directory where to store results. params: 1D float ndarray burnin: Integer abun_file: String Elemental abundances file. """ # read atmfile molecules, pressure, temp, abundances = mat.readatm(atmfile) # get surface gravity grav, Rp = mat.get_g(tepfile) # get star data R_star, T_star, sma, gstar = get_starData(tepfile) # Get best parameters bestP, uncer = read_MCMC_out(MCfile) # get all params #allParams = get_params(bestP, stepsize, params) allParams = bestP # get PTparams and abundances factors nparams = len(allParams) nmol = len(molfit) nradfit = int(solution == 'transit') nPTparams = nparams - nmol - nradfit PTparams = allParams[:nPTparams] # FINDME: Hardcoded value: T_int = 100 # K # call PT line profile to calculate temperature best_T = pt.PT_line(pressure, PTparams, R_star, T_star, T_int, sma, grav*1e2) # Plot best PT profile plt.figure(1) plt.clf() plt.semilogy(best_T, pressure, '-', color = 'r') plt.xlim(0.9*min(best_T), 1.1*max(best_T)) plt.ylim(max(pressure), min(pressure)) plt.title('Best PT', fontsize=14) plt.xlabel('T [K]' , fontsize=14) plt.ylabel('logP [bar]', fontsize=14) # Save plot to current directory plt.savefig(date_dir + 'Best_PT.png') # Update R0, if needed: if nradfit: Rp = allParams[nPTparams] # Mean molecular mass: mu = mat.mean_molar_mass(abun_file, atmfile) # Re-calculate the layers' radii using the Hydrostatic-equilibrium calc: # (Has to be in reversed order since the interpolation requires the # pressure array in increasing order) rad = mat.radpress(pressure[::-1], best_T[::-1], mu[::-1], p0, Rp, grav) rad = rad[::-1] # write best-fit atmospheric file write_atmfile(atmfile, molfit, rad, best_T, allParams[nPTparams+nradfit:], date_dir) # bestFit atm file bestFit_atm = date_dir + 'bestFit.atm' # write new bestFit Transit config bestFit_tconfig(tconfig, date_dir) # ========== plot MCMC PT profiles ========== # get MCMC data: MCMCdata = date_dir + "/output.npy" data = np.load(MCMCdata) nchains, npars, niter = np.shape(data) # stuck chains: data_stack = data[0,:,burnin:] for c in np.arange(1, nchains): data_stack = np.hstack((data_stack, data[c, :, burnin:])) # create array of PT profiles PTprofiles = np.zeros((np.shape(data_stack)[1], len(pressure))) # current PT parameters for each chain, iteration curr_PTparams = PTparams # fill-in PT profiles array print(" Plotting MCMC PT profile figure.") for k in np.arange(0, np.shape(data_stack)[1]): j = 0 for i in np.arange(len(PTparams)): if stepsize[i] != 0.0: curr_PTparams[i] = data_stack[j,k] j +=1 else: pass PTprofiles[k] = pt.PT_line(pressure, curr_PTparams, R_star, T_star, T_int, sma, grav*1e2) # get percentiles (for 1,2-sigma boundaries): low1 = np.percentile(PTprofiles, 16.0, axis=0) hi1 = np.percentile(PTprofiles, 84.0, axis=0) low2 = np.percentile(PTprofiles, 2.5, axis=0) hi2 = np.percentile(PTprofiles, 97.5, axis=0) median = np.median(PTprofiles, axis=0) # plot figure plt.figure(2) plt.clf() ax=plt.subplot(111) ax.fill_betweenx(pressure, low2, hi2, facecolor="#62B1FF", edgecolor="0.5") ax.fill_betweenx(pressure, low1, hi1, facecolor="#1873CC", edgecolor="#1873CC") plt.semilogy(median, pressure, "-", lw=2, label='Median',color="k") plt.semilogy(best_T, pressure, "-", lw=2, label="Best fit", color="r") plt.ylim(pressure[0], pressure[-1]) plt.legend(loc="best") plt.xlabel("Temperature (K)", size=15) plt.ylabel("Pressure (bar)", size=15) # save figure savefile = date_dir + "MCMC_PTprofiles.png" plt.savefig(savefile)
R_star, T_star, sma, gstar = bf.get_starData(tep_name) # get best parameters bestP, uncer = bf.read_MCMC_out(logfile) # get all params allParams = bf.get_params(bestP, stepsize, params) # get PTparams and abundances factors nparams = len(allParams) nmol = len(molfit) nPTparams = nparams - nmol PTparams = allParams[:nPTparams] kappa, gamma1, gamma2, alpha, beta = PTparams # HARDCODED ! T_int = 100 # K T_int_type = 'const' # call PT line profile to calculate temperature best_T = pt.PT_line(pressure, kappa, gamma1, gamma2, alpha, beta, R_star, T_star, T_int, sma, grav, T_int_type) # get MCMC data: data = np.load(MCMCdata) nchains, npars, niter = np.shape(data) # this is data fro first chain zero data_stack = data[0, :, burnin:] # pick a chain that you do not like bad_chain = 0 bad_chain2 = 0 # now he stack all other chains from 1, you can start from 5 here for c in np.arange(1, nchains): if c != bad_chain and c != bad_chain2: data_stack = np.hstack((data_stack, data[c, :, burnin:])) print c