def initialPT2(date_dir, params, pressfile, mode, PTfunc, tepfile, tint=100.0): """ Compute a Temperature profile. Parameters: ----------- params: 1D Float ndarray Array of fitting parameters. pressfile: String File name of the pressure array. mode: String Chose the PT model: 'madhu' or 'line'. tepfile: String Filename of the planet's TEP file. tint: Float Internal planetary temperature. """ # Read pressures from file: pressure = pt.read_press_file(pressfile) # For extra PT arguments: PTargs = None # Read the TEP file: tep = rd.File(tepfile) # Stellar radius (in meters): rstar = float(tep.getvalue('Rs')[0]) * c.Rsun # Stellar temperature in K: tstar = float(tep.getvalue('Ts')[0]) # Semi-major axis (in meters): sma = float(tep.getvalue( 'a')[0]) * sc.au # Planetary radius (in meters): rplanet = float(tep.getvalue('Rp')[0]) * c.Rjup # Planetary mass (in kg): mplanet = float(tep.getvalue('Mp')[0]) * c.Mjup if mode == "line": # Planetary surface gravity (in cm s-2): gplanet = 100.0 * sc.G * mplanet / rplanet**2 # Additional PT arguments for Line case: PTargs = [rstar, tstar, tint, sma, gplanet] # Calculate temperature Temp = pt.PT_generator(pressure, params, PTfunc, PTargs) # Plot PT profile plt.figure(1) plt.semilogy(Temp, pressure, '-', color = 'r') plt.xlim(0.9*min(Temp), 1.1*max(Temp)) plt.ylim(max(pressure), min(pressure)) plt.title('Initial PT Line', fontsize=14) plt.xlabel('T (K)' , fontsize=14) plt.ylabel('logP (bar)', fontsize=14) # Save plot to current directory plt.savefig(date_dir + 'InitialPT.png') return Temp
def uniform(atmfile, press_file, abun_file, tepfile, species, abundances, temp, p0): """ Generate an atmospheric file with uniform abundances. Parameters: ----------- atmfile: String Name of output atmospheric file. press_file: String Input pressure-array filename. abun_file: String Input elemental-abundances filename. tepfile: String Transiting extrasolar planet filename. species: String String with list of atmospheric species (blank space separated). abundances: String String with list of species mole-mixing-ratio (blank space separated). temp: 1D float ndarray Temperature profile. p0: Float Reference pressure level (corresponding to Rp from the tepfile). Modification History: --------------------- 2015-03-04 patricio Initial implementation. """ # Read pressure array: press = pt.read_press_file(press_file) # Put species names into an array: spec = np.asarray(species.split()) # Put abundance values into an array: abun = np.asarray(abundances, np.double) # Write to file: f = open(atmfile, 'w') # Write species names: f.write('#SPECIES\n' + species + '\n\n') # Write header of TEA data: f.write('#TEADATA\n') # Column's header: f.write("#Pressure Temp " + "".join(["{:<18s}".format(mol) for mol in spec]) + "\n") # For each layer write TEA data for i in np.arange(len(press)): # Pressure, and Temperature f.write("{:10.4e} {:8.2f} ".format(press[i], temp[i])) # Elemental abundance list f.write(" ".join(["{:16.10e}".format(ab) for ab in abun]) + "\n") f.close() # Calculate the radius of each layer and put it into the atmfile: makeRadius(species, atmfile, abun_file, tepfile, p0) # Reformat to use in transit: reformat(atmfile)
def generation_verbs(filename, file_out): try: with open(filename, encoding='utf8') as file, open(file_out, 'w', encoding='utf8') as generation_file: try: # FOR EACH LINE IT SAVES LEMMA, ROOT, CODE, INFLECTION AND TAG for each_line in file: if not utilities.delete_line(each_line): (lema, root, code)=each_line.strip().split('\t',2) # parseamos el código dict_code=utilities.parse_code_verbs(code) # 1.- INTERNAL DERIVATION deriv_root = ID.Internal_derivation(root, \ dict_code['Internal derivation']) # 2.- PROSODIC TEMPLATE dict_RootInPT = PT.prosodic_template(deriv_root, \ dict_code['Template'] ) # 3.- EXTERNAL DERIVATION deriv_RootInPT = ED.External_derivation(dict_RootInPT, \ dict_code['External derivation']) # 4.- VOCALIZATION dict_act_pas_forms = vocalization.generate_Active_and_Pasive(deriv_RootInPT, \ dict_code['Vocalization']) # 5.- STEM ADJUSTMENTS dict_syl_forms = stem_adjustment.rules_stem_adjustment(dict_act_pas_forms, dict_code, root, lema) # 6.- INFLECTED SYSTEM dict_inflec_forms = Inflec.Inflectional_system(dict_syl_forms) # 7.- PHONOTACTIC CONSTRAINTS AND ORTHOGRAPHIC NORMALIZATION final_forms = phonotactics.phonotactic_rules(dict_inflec_forms, lema, root, dict_code) utilities.printFile_forms_from_dictForms(lema, root, code, final_forms, generation_file) except ValueError as verror1: print('Value error Principal: ' + str(verror1)) except IOError as ioerr: print('File error: ' + str(ioerr)) return(None)
def initialPT2(params, pressfile, mode, tepfile, tint=100.0): """ Compute a Temperature profile. Parameters: ----------- params: 1D Float ndarray Array of fitting parameters. pressfile: String File name of the pressure array. mode: String Chose the PT model: 'madhu' or 'line'. tepfile: String Filename of the planet's TEP file. tint: Float Internal planetary temperature. """ # Read pressures from file: pressure = pt.read_press_file(pressfile) # PT arguments: PTargs = [mode] # Read the TEP file: tep = rd.File(tepfile) # Stellar radius (in meters): rstar = float(tep.getvalue('Rs')[0]) * Rsun # Stellar temperature in K: tstar = float(tep.getvalue('Ts')[0]) # Semi-major axis (in meters): sma = float(tep.getvalue( 'a')[0]) * sc.au # Planetary radius (in meters): rplanet = float(tep.getvalue('Rp')[0]) * Rjup # Planetary mass (in kg): mplanet = float(tep.getvalue('Mp')[0]) * Mjup if mode == "line": # Planetary surface gravity (in cm s-2): gplanet = 100.0 * sc.G * mplanet / rplanet**2 # Additional PT arguments: PTargs += [rstar, tstar, tint, sma, gplanet] Temp = pt.PT_generator(pressure, params, PTargs) return Temp
def make_preatm(tepfile, press_file, abun_file, in_elem, out_spec, pre_atm, Temp): """ This code produces a pre-atm file in the format that TEA can read it. It reads the pressure file and elemental dex abundance data, trims to the selected elements. It converts dex abundances to number density and divide them by hydrogen number density to get fractional abundances. It writes the pressure, temperature, and elemental-abundances data into a pre-atm file. Parameters ---------- tepfile: String Name of the tepfile. press_file: String Name of the pressure file. abun_file: String Name of the abundances file. in_elem: String String containing input elemental species. out_spec: String String containing output molecular species. pre_atm: String Pre-atmospheric filename. Temp: 1D float array Array containing temperatures for each layer in the atmosphere (in K). Revisions --------- 2014-07-12 Jasmina Written by. 2014-08-15 Patricio Removed PT re-calculation, use input T array. 2014-09-15 Jasmina Added call to readAbun() function. 2014-11-06 Jasmina Adjusted to work properly with TEA. 2015-03-05 Patricio Adapted to use read_eabun function, reworked some bits. """ # Read pressure data pres = pt.read_press_file(press_file) # Number of layers in the atmosphere n_layers = len(pres) # Get the elemental abundace data: index, symbol, dex, name, mass = read_eabun(abun_file) # Take only the elements we need: in_arg = np.in1d(symbol, in_elem.split()) in_symbol = symbol[in_arg] in_dex = dex[in_arg] # Hydrogen number density: H_num = 10**12 # Get fractional number density relative to hydrogen: out_abn = (10.0**in_dex / H_num).tolist() # Write pre-atm file f = open(pre_atm, 'w') # Pre-atm header with basic instructions header = ( "# This is a TEA pre-atmosphere input file.\n" "# TEA accepts a file in this format to produce species abundances as\n" "# a function of pressure and temperature.\n" "# Output species must be added in the line immediately following the \n" "# SPECIES marker and must be named to match JANAF converted names.\n" "# Units: pressure (bar), temperature (K), abundance (unitless).\n\n") # Write header f.write(header) # Write species names f.write('#SPECIES\n' + out_spec + '\n\n') # Write header of TEA data f.write('#TEADATA\n') # Column's header: f.write("#Pressure Temp " + "".join(["{:<18s}".format(elem) for elem in in_symbol]) + "\n") # Write data for each layer: for i in np.arange(n_layers): # Pressure, and Temperature: f.write("{:10.4e} {:8.2f} ".format(pres[i], Temp[i])) # Elemental abundance list: f.write(" ".join(["{:16.10e}".format(abun) for abun in out_abn]) + "\n") f.close()
def ROM_Lower(self): self.result_ROM_LE = PT.ROM_LE()
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
def callTransit(atmfile, tepfile, MCfile, stepsize, molfit, solution, p0, tconfig, date_dir, burnin, abun_file, PTtype, PTfunc, T_int, T_int_type, filters, ctf=None, fs=15): """ 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 Specified step sizes for each parameter. 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. burnin: Integer abun_file: String Elemental abundances file. PTtype: String Pressure-temperature profile type ('line' for Line et al. 2013, 'madhu_noinv' or 'madhu_inv' for Madhusudhan & Seager 2009, 'iso' for isothermal) PTfunc: pointer to function Determines the method of evaluating the PT profile's temperature T_int: float. Internal temperature of the planet. T_int_type: string. Method to evaluate `T_int`. 'const' for constant value of `T_int`, 'thorngren' for Thorngren et al. (2019) filters: list, strings. Filter files associated with the eclipse/transit depths ctf: 2D array. Contribution or transmittance functions corresponding to `filters` fs: int Font size for plots. """ # make sure burnin is an integer burnin = int(burnin) # read atmfile molecules, pressure, temp, abundances = mat.readatm(atmfile) # get surface gravity grav, Rp = mat.get_g(tepfile) # get star data if needed if PTtype == 'line': R_star, T_star, sma, gstar = get_starData(tepfile) PTargs = [R_star, T_star, T_int, sma, grav * 1e2, T_int_type] else: PTargs = None # For non-Line profiles # Get best parameters bestP, uncer = read_MCMC_out(MCfile) allParams = bestP # get PTparams and abundances factors nparams = len(allParams) nmol = len(molfit) nradfit = int(solution == 'transit') nPTparams = nparams - nmol - nradfit PTparams = allParams[:nPTparams] # call PT profile generator to calculate temperature best_T = pt.PT_generator(pressure, PTparams, PTfunc, PTargs) # 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=fs) plt.xlabel('T (K)', fontsize=fs) plt.ylabel('logP (bar)', fontsize=fs) # Save plot to current directory plt.savefig(date_dir + 'Best_PT.png') # Update R0, if needed: if nradfit: Rp = allParams[nPTparams] # write best-fit atmospheric file write_atmfile(atmfile, abun_file, molfit, best_T, allParams[nPTparams + nradfit:], date_dir, p0, Rp, grav) # write new bestFit Transit config if solution == 'transit': bestFit_tconfig(tconfig, date_dir, allParams[nPTparams]) else: bestFit_tconfig(tconfig, date_dir) # Call Transit with the best-fit tconfig Transitdir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "modules", "transit", "") bf_tconfig = os.path.join(date_dir, 'bestFit_tconfig.cfg') Tcall = os.path.join(Transitdir, "transit", "transit") subprocess.call(["{:s} -c {:s}".format(Tcall, bf_tconfig)], shell=True, cwd=date_dir) # ========== plot MCMC PT profiles ========== # get MCMC data: MCMCdata = os.path.join(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 if ctf is None: 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_generator(pressure, curr_PTparams, PTfunc, PTargs) # get percentiles (for 1,2-sigma boundaries): low1 = np.percentile(PTprofiles, 15.87, axis=0) hi1 = np.percentile(PTprofiles, 84.13, axis=0) low2 = np.percentile(PTprofiles, 2.28, axis=0) hi2 = np.percentile(PTprofiles, 97.72, axis=0) median = np.median(PTprofiles, axis=0) # plot figure plt.figure(2, dpi=300) plt.clf() if ctf is not None: plt.subplots_adjust(wspace=0.15) ax1 = plt.subplot(121) else: ax1 = plt.subplot(111) ax1.fill_betweenx(pressure, low2, hi2, facecolor="#62B1FF", edgecolor="0.5") ax1.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=fs) plt.ylabel("Pressure (bar)", size=fs) if ctf is not None: nfilters = len(filters) # Add contribution or transmittance functions ax2 = plt.subplot(122, sharey=ax1) colormap = plt.cm.rainbow(np.linspace(0, 1, len(filters))) ax2.set_prop_cycle(plt.cycler('color', colormap)) # Plot with filter labels for i in np.arange(len(filters)): (head, tail) = os.path.split(filters[i]) lbl = tail[:-4] ax2.semilogy(ctf[i], pressure, '--', linewidth=1, label=lbl) # Hide y axis tick labels plt.setp(ax2.get_yticklabels(), visible=False) # Place legend off figure in case there are many filters lgd = ax2.legend(loc='center left', bbox_to_anchor=(1.05, 0.5), ncol=nfilters // 25 + int(nfilters % 25 != 0), prop={'size': 8}) if solution == 'eclipse': ax2.set_xlabel('Normalized Contribution\nFunctions', fontsize=fs) else: ax2.set_xlabel('Transmittance', fontsize=fs) # save figure if ctf is not None: savefile = date_dir + "MCMC_PTprofiles_cf.png" plt.savefig(savefile, bbox_extra_artists=(lgd, ), bbox_inches='tight') else: savefile = date_dir + "MCMC_PTprofiles.png" plt.savefig(savefile) plt.close()
def f(var1, var2): #Accretion Frame fO2A = var2 p = 1 q = 1 P0 = var1 T0 = 1873 cbe = bulkcomps.cbe k = 1 n = 1000 Ms = 0 Me = 1 Mt = np.linspace(Ms, Me, n + 1) M = np.zeros((1, 3)) h = np.zeros((6, 3)) ebudgets = np.zeros((6, 3)) Dcal = np.zeros(6) wtCore = np.zeros([8, n]) wtBSE = np.zeros([6, n]) F = 0.323 #metal-silicate proportion Earth m = 1 / n #accretion step mb = m * (1 - F) #mass fraction silciate earth mc = m * F #mass fraction core Mv = np.array([Ms, Ms * (1 - F), Ms * F]) #Mass accretion vector Bulk Earth mv = np.array([m, mb, mc]) #reservoir fractions gcalc = 0 #set initial activity coeff to 0 - recalc at end of each iteration. u = len(Mt) #set length of simulation #begin accretion: for i in range(0, u - 1): #print(i) M = Mv + mv #Mass accretion Earth Mv = M #compute fO2 evolution: fO2BE, fO2, Fec, DIW, Feq = fO2m.f(fO2A, p, q, M, Me) #, p, q, M, Me) FeOcore = (fO2BE - (1 - F) * fO2) / F #FeO partitioning into Core Ocore = FeOcore / 4.49 #Compute Pressure and Temperature Evolution P, T, T0T = PT.f(P0, M, T0) #compute evolution of activity coefficients [gT] = gamma.f(T0T, T) if (i == 0): gTx = gT else: gTx = gcalc #compute partition coeffs DSi, DNi, DCo, DV, DCr, DW = partition.f(gTx, P, T, DIW) Dcal = np.array([DSi, DNi, DCo, DV, DCr, DW]) #compute metal-silicate partitioning fluxes Si_BE, Si_Sil, Si_Met, Ni_BE, Ni_Sil, Ni_Met, Co_BE, Co_Sil, Co_Met, V_BE, V_Sil, V_Met, Cr_BE, Cr_Sil, Cr_Met, W_BE, W_Sil, W_Met = metsilequi.f( Dcal, cbe, F, mb, mc, m, k) eflux = np.array([[Si_BE, Si_Sil, Si_Met], [Ni_BE, Ni_Sil, Ni_Met], [Co_BE, Co_Sil, Co_Met], [V_BE, V_Sil, V_Met], [Cr_BE, Cr_Sil, Cr_Met], [W_BE, W_Sil, W_Met]]) #elfux = np.array(eflux) ebudgets = h + eflux h = ebudgets fmolar, wtcomp = wttomolar.f(ebudgets, Ocore, Fec, M) wtCore[:, i] = wtcomp wtBSE[:, i] = ebudgets[:, 1] / M[1] #DObs[:,i] = wtCore[[1,2,3,4,5,7]] / wtBSE #compute epsilon interaction parameters eTeM, eTeSi = epsilon.f(T0T) #compute interaction of solutes in solvent gcalc = interaction.f(gT, eTeM, eTeSi, fmolar) #gcalc = gT DObs = wtCore[[1, 2, 3, 4, 5, 7]] / wtBSE import zscoremod zs, zmod = zscoremod.f(DObs) final_zmod = zmod[-1] return final_zmod, DObs #print(time.time()-ComTime)
def make_preatm(tepfile, press_file, abun_file, in_elem, out_spec, pre_atm, Temp): """ This code produces a pre-atm file in the format that TEA can read it. It reads the pressure file and elemental dex abundance data, trims to the selected elements. It converts dex abundances to number density and divide them by hydrogen number density to get fractional abundances. It writes the pressure, temperature, and elemental-abundances data into a pre-atm file. Parameters ---------- tepfile: String Name of the tepfile. press_file: String Name of the pressure file. abun_file: String Name of the abundances file. in_elem: String String containing input elemental species. out_spec: String String containing output molecular species. pre_atm: String Pre-atmospheric filename. Temp: 1D float array Array containing temperatures for each layer in the atmosphere (in K). Revisions --------- 2014-07-12 Jasmina Written by. 2014-08-15 Patricio Removed PT re-calculation, use input T array. 2014-09-15 Jasmina Added call to readAbun() function. 2014-11-06 Jasmina Adjusted to work properly with TEA. 2015-03-05 Patricio Adapted to use read_eabun function, reworked some bits. """ # Read pressure data pres = pt.read_press_file(press_file) # Number of layers in the atmosphere n_layers = len(pres) # Get the elemental abundace data: index, symbol, dex, name, mass = read_eabun(abun_file) # Take only the elements we need: in_arg = np.in1d(symbol, in_elem.split()) in_symbol = symbol[in_arg] in_dex = dex [in_arg] # Hydrogen number density: H_num = 10**12 # Get fractional number density relative to hydrogen: out_abn = (10.0**in_dex / H_num).tolist() # Write pre-atm file f = open(pre_atm, 'w') # Pre-atm header with basic instructions header = ("# This is a TEA pre-atmosphere input file.\n" "# TEA accepts a file in this format to produce species abundances as\n" "# a function of pressure and temperature.\n" "# Output species must be added in the line immediately following the \n" "# SPECIES marker and must be named to match JANAF converted names.\n" "# Units: pressure (bar), temperature (K), abundance (unitless).\n\n") # Write header f.write(header) # Write species names f.write('#SPECIES\n' + out_spec + '\n\n') # Write header of TEA data f.write('#TEADATA\n') # Column's header: f.write("#Pressure Temp " + "".join(["{:<18s}".format(elem) for elem in in_symbol]) + "\n") # Write data for each layer: for i in np.arange(n_layers): # Pressure, and Temperature: f.write("{:10.4e} {:8.2f} ".format(pres[i], Temp[i])) # Elemental abundance list: f.write(" ".join(["{:16.10e}".format(abun) for abun in out_abn]) + "\n") f.close()
# Pressure variables: nlayers = 100 ptop = 1e-5 # bar pbottom = 1e2 # bar # Write the pressure to file: mp.makeP(nlayers, ptop, pbottom, pfile, log=True) # :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: # ( 1) Make a Temperature profile using model from Line et al. (2013): import PT as PT # [Run script ( 0) to make a pressure profile file] # 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) # ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
def Movements(self): PT.Posture_Move()
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
def MMT_Test(self): self.result = PT.MMT_TEST()
nlayers = 100 ptop = 1e-5 # bar pbottom = 1e2 # bar # Write the pressure to file: mp.makeP(nlayers, ptop, pbottom, pfile, log=True) # :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: # ( 1) Make a Temperature profile using model from Line et al. (2013): import PT as PT # [Run script ( 0) to make a pressure profile file] # 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)
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 ROM_Upper(self): self.result_ROM_UE = PT.ROM_UE()
def main(comm): """ This is a hacked version of MC3's func.py. This function directly call's the modeling function for the BART project. """ # Parse arguments: cparser = argparse.ArgumentParser( description=__doc__, add_help=False, formatter_class=argparse.RawDescriptionHelpFormatter) # Add config file option: cparser.add_argument("-c", "--config_file", help="Configuration file", metavar="FILE") # Remaining_argv contains all other command-line-arguments: args, remaining_argv = cparser.parse_known_args() # Get parameters from configuration file: cfile = args.config_file if cfile: config = ConfigParser.SafeConfigParser() config.optionxform = str config.read([cfile]) defaults = dict(config.items("MCMC")) else: defaults = {} parser = argparse.ArgumentParser(parents=[cparser]) parser.add_argument("--func", dest="func", type=mu.parray, action="store", default=None) parser.add_argument("--indparams", dest="indparams", type=mu.parray, action="store", default=[]) parser.add_argument("--params", dest="params", type=mu.parray, action="store", default=None, help="Model-fitting parameters [default: %(default)s]") parser.add_argument("--molfit", dest="molfit", type=mu.parray, action="store", default=None, help="Molecules fit [default: %(default)s]") parser.add_argument( "--Tmin", dest="Tmin", type=float, action="store", default=400.0, help="Lower Temperature boundary [default: %(default)s]") parser.add_argument( "--Tmax", dest="Tmax", type=float, action="store", default=3000.0, help="Higher Temperature boundary [default: %(default)s]") parser.add_argument("--quiet", action="store_true", help="Set verbosity level to minimum", dest="quiet") # Input-Converter Options: group = parser.add_argument_group("Input Converter Options") group.add_argument("--atmospheric_file", action="store", help="Atmospheric file [default: %(default)s]", dest="atmfile", type=str, default=None) group.add_argument("--PTtype", action="store", help="PT profile type.", dest="PTtype", type=str, default="none") group.add_argument("--tint", action="store", help="Internal temperature of the planet [default: " "%(default)s].", dest="tint", type=float, default=100.0) # transit Options: group = parser.add_argument_group("transit Options") group.add_argument( "--config", action="store", help="transit configuration file [default: %(default)s]", dest="config", type=str, default=None) # Output-Converter Options: group = parser.add_argument_group("Output Converter Options") group.add_argument("--filters", action="store", help="Waveband filter name [default: %(default)s]", dest="filters", type=mu.parray, default=None) group.add_argument("--tep_name", action="store", help="A TEP file [default: %(default)s]", dest="tep_name", type=str, default=None) group.add_argument("--kurucz_file", action="store", help="Stellar Kurucz file [default: %(default)s]", dest="kurucz", type=str, default=None) group.add_argument("--solution", action="store", help="Solution geometry [default: %(default)s]", dest="solution", type=str, default="None", choices=('transit', 'eclipse')) parser.set_defaults(**defaults) args2, unknown = parser.parse_known_args(remaining_argv) # Quiet all threads except rank 0: rank = comm.Get_rank() verb = rank == 0 # Get (Broadcast) the number of parameters and iterations from MPI: array1 = np.zeros(2, np.int) mu.comm_bcast(comm, array1) npars, niter = array1 # ::::::: Initialize the Input converter :::::::::::::::::::::::::: atmfile = args2.atmfile molfit = args2.molfit PTtype = args2.PTtype params = args2.params tepfile = args2.tep_name tint = args2.tint Tmin = args2.Tmin Tmax = args2.Tmax solution = args2.solution # Solution type # Dictionary of functions to calculate temperature for PTtype PTfunc = { 'iso': pt.PT_iso, 'line': pt.PT_line, 'madhu_noinv': pt.PT_NoInversion, 'madhu_inv': pt.PT_Inversion } # Extract necessary values from the TEP file: tep = rd.File(tepfile) # Stellar temperature in K: tstar = float(tep.getvalue('Ts')[0]) # Stellar radius (in meters): rstar = float(tep.getvalue('Rs')[0]) * c.Rsun # Semi-major axis (in meters): sma = float(tep.getvalue('a')[0]) * sc.au # Planetary radius (in meters): rplanet = float(tep.getvalue('Rp')[0]) * c.Rjup # Planetary mass (in kg): mplanet = float(tep.getvalue('Mp')[0]) * c.Mjup # Number of fitting parameters: nfree = len(params) # Total number of free parameters nmolfit = len(molfit) # Number of molecular free parameters nradfit = int(solution == 'transit') # 1 for transit, 0 for eclipse nPT = nfree - nmolfit - nradfit # Number of PT free parameters # Read atmospheric file to get data arrays: species, pressure, temp, abundances = mat.readatm(atmfile) # Reverse pressure order (for PT to work): pressure = pressure[::-1] nlayers = len(pressure) # Number of atmospheric layers nspecies = len(species) # Number of species in the atmosphere mu.msg(verb, "There are {:d} layers and {:d} species.".format(nlayers, nspecies)) # Find index for Hydrogen and Helium: species = np.asarray(species) iH2 = np.where(species == "H2")[0] iHe = np.where(species == "He")[0] # Get H2/He abundance ratio: ratio = (abundances[:, iH2] / abundances[:, iHe]).squeeze() # Find indices for the metals: imetals = np.where((species != "He") & (species != "H2") & \ (species != "H-") & (species != 'e-'))[0] # Index of molecular abundances being modified: imol = np.zeros(nmolfit, dtype='i') for i in np.arange(nmolfit): imol[i] = np.where(np.asarray(species) == molfit[i])[0] # Pressure-Temperature profile: if PTtype == "line": # Planetary surface gravity (in cm s-2): gplanet = 100.0 * sc.G * mplanet / rplanet**2 # Additional PT arguments: PTargs = [rstar, tstar, tint, sma, gplanet] else: PTargs = None # Allocate arrays for receiving and sending data to master: freepars = np.zeros(nfree, dtype='d') profiles = np.zeros((nspecies + 1, nlayers), dtype='d') # This are sub-sections of profiles, containing just the temperature and # the abundance profiles, respectively: tprofile = profiles[0, :] aprofiles = profiles[1:, :] # Store abundance profiles: for i in np.arange(nspecies): aprofiles[i] = abundances[:, i] # ::::::: Spawn transit code ::::::::::::::::::::::::::::::::::::: # # transit configuration file: transitcfile = args2.tconfig # Initialize the transit python module: transit_args = ["transit", "-c", transitcfile] trm.transit_init(len(transit_args), transit_args) # Get wavenumber array from transit: nwave = trm.get_no_samples() specwn = trm.get_waveno_arr(nwave) # ::::::: Output Converter ::::::::::::::::::::::::::::::::::::::: ffile = args2.filters # Filter files kurucz = args2.kurucz # Kurucz file # Log10(stellar gravity) gstar = float(tep.getvalue('loggstar')[0]) # Planet-to-star radius ratio: rprs = rplanet / rstar nfilters = len(ffile) # Number of filters: # FINDME: Separate filter/stellar interpolation? # Get stellar model: starfl, starwn, tmodel, gmodel = w.readkurucz(kurucz, tstar, gstar) # Read and resample the filters: nifilter = [] # Normalized interpolated filter istarfl = [] # interpolated stellar flux wnindices = [] # wavenumber indices used in interpolation for i in np.arange(nfilters): # Read filter: filtwaven, filttransm = w.readfilter(ffile[i]) # Check that filter boundaries lie within the spectrum wn range: if filtwaven[0] < specwn[0] or filtwaven[-1] > specwn[-1]: mu.exit(message="Wavenumber array ({:.2f} - {:.2f} cm-1) does not " "cover the filter[{:d}] wavenumber range ({:.2f} - {:.2f} " "cm-1).".format(specwn[0], specwn[-1], i, filtwaven[0], filtwaven[-1])) # Resample filter and stellar spectrum: nifilt, strfl, wnind = w.resample(specwn, filtwaven, filttransm, starwn, starfl) nifilter.append(nifilt) istarfl.append(strfl) wnindices.append(wnind) # Allocate arrays for receiving and sending data to master: spectrum = np.zeros(nwave, dtype='d') bandflux = np.zeros(nfilters, dtype='d') # Allocate array to receive parameters from MPI: params = np.zeros(npars, np.double) # :::::: Main MCMC Loop :::::::::::::::::::::::::::::::::::::::::: # :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: while niter >= 0: niter -= 1 # Receive parameters from MCMC: mu.comm_scatter(comm, params) # Check for the MCMC-end flag: if params[0] == np.inf: break # Input converter calculate the profiles: try: tprofile[:] = pt.PT_generator(pressure, params[0:nPT], PTfunc[PTtype], PTargs)[::-1] except ValueError: mu.msg(verb, 'Input parameters give non-physical profile.') # FINDME: what to do here? # If the temperature goes out of bounds: if np.any(tprofile < Tmin) or np.any(tprofile > Tmax): mu.comm_gather(comm, -np.ones(nfilters), MPI.DOUBLE) continue # Scale abundance profiles: for i in np.arange(nmolfit): m = imol[i] # Use variable as the log10: aprofiles[m] = abundances[:, m] * 10.0**params[nPT + nradfit + i] # Update H2, He abundances so sum(abundances) = 1.0 in each layer: q = 1.0 - np.sum(aprofiles[imetals], axis=0) if np.any(q < 0.0): mu.comm_gather(comm, -np.ones(nfilters), MPI.DOUBLE) continue aprofiles[iH2] = ratio * q / (1.0 + ratio) aprofiles[iHe] = q / (1.0 + ratio) # Set the 'surface' level: if solution == "transit": trm.set_radius(params[nPT]) # Let transit calculate the model spectrum: spectrum = trm.run_transit(profiles.flatten(), nwave) # Calculate the band-integrated intensity per filter: for i in np.arange(nfilters): if solution == "eclipse": fluxrat = (spectrum[wnindices[i]] / istarfl[i]) * rprs * rprs bandflux[i] = w.bandintegrate(fluxrat, specwn, nifilter[i], wnindices[i]) elif solution == "transit": bandflux[i] = w.bandintegrate(spectrum[wnindices[i]], specwn, nifilter[i], wnindices[i]) # Send resutls back to MCMC: mu.comm_gather(comm, bandflux, MPI.DOUBLE) # :::::: End main Loop ::::::::::::::::::::::::::::::::::::::::::: # :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: # Close communications and disconnect: mu.comm_disconnect(comm) trm.free_memory()
def initialPT(date_dir, tepfile, press_file, a1, a2, p1, p3, T3_fac): """ This function generates a non-inverted temperature profile using the parametrized model described in Madhusudhan & Seager (2009). It plots the profile to screen and save the figures in the output directory. The generated PT profile is a semi-adiabatic profile with a bottom-layer temperature corresponding (within certain range) to the planetary effective temperature. Parameters ---------- date_dir: String Directory where to save the output plots. tepfile: String Name of ASCII tep file with planetary system data. press_file: String Name of ASCII file with pressure array data. a1: Float Model exponential factor in Layer 1. a2: Float Model exponential factor in Layer 2. p1: Float Pressure boundary between Layers 1 and 2 (in bars). p3: Float Pressure boundary between Layers 2 and 3 (in bars). T3_fac: Float Multiplicative factor to set T3 (T3 = Teff * T3_fac). Empirically determined to be between (1, 1.5) to account for the possible spectral features. Notes ----- See model details in Madhusudhan & Seager (2009): http://adsabs.harvard.edu/abs/2009ApJ...707...24M Returns ------- T_smooth: 1D float ndarray Array of temperatures. Developers ---------- Jasmina Blecic [email protected] Patricio Cubillos [email protected] Revisions --------- 2014-04-08 Jasmina Written by 2014-07-23 Jasmina Added date_dir and PT profile arguments. 2014-08-15 Patricio Replaced call to PT_Initial by PT_NoInversion. 2014-09-24 Jasmina Updated documentation. """ # Calculate the planetary effective temperature from the TEP file Teff = pt.planet_Teff(tepfile) # Calculate T3 temperature based on Teff T3 = float(T3_fac) * Teff # Read pressures from file p = pt.read_press_file(press_file) # Generate initial PT profile PT, T_smooth = pt.PT_NoInversion(p, a1, a2, p1, p3, T3) # Take temperatures from PT generator T, T0, T1, T3 = PT[5], PT[7], PT[8], PT[9] # Plot raw PT profile plt.figure(1) plt.clf() plt.semilogy(PT[0], PT[1], '.', color = 'r' ) plt.semilogy(PT[2], PT[3], '.', color = 'b' ) plt.semilogy(PT[4], PT[5], '.', color = 'orange') plt.title('Initial PT', fontsize=14) plt.xlabel('T (K)', fontsize=14) plt.ylabel('logP (bar)', fontsize=14) plt.xlim(0.9*T0, 1.1*T3) plt.ylim(max(p), min(p)) # Save plot to current directory plt.savefig(date_dir + '/InitialPT.png') # Plot Smoothed PT profile plt.figure(2) plt.clf() plt.semilogy(T_smooth, p, '-', color = 'b', linewidth=1) plt.title('Initial PT Smoothed', fontsize=14) plt.xlabel('T (K)' , fontsize=14) plt.ylabel('logP (bar)', fontsize=14) plt.ylim(max(p), min(p)) plt.xlim(0.9*T0, 1.1*T3) # Save plot to output directory plt.savefig(date_dir + '/InitialPTSmoothed.png') return T_smooth
def TER_test(self): return PT.TER()