TauREx 3.0¶
Setup¶
Lets setup the notebook. If the plots arent interactive then run this part again. The interactive plots need ipympl, which pulls in ipywidgets:
pip install ipympl
[1]:
%matplotlib widget
import sys
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
from ipywidgets import interact
# Make the shared notebook helpers importable regardless of the working directory
for candidate in (Path.cwd(), *Path.cwd().parents):
if (candidate / "_shared.py").exists():
sys.path.insert(0, str(candidate))
break
nested = candidate / "examples" / "notebooks"
if (nested / "_shared.py").exists():
sys.path.insert(0, str(nested))
break
And lets disable logging
[2]:
import taurex.log
taurex.log.disableLogging()
Prerequisites¶
You should have a few things on hand. Firstly H2O and CO2 absorption cross sections (xsec) in one of the :ref:supported_data_formats is required, distributed by ExoMol. Secondly some collisionally induced absorption (CIA) cross sections are also required for a later part for H2-He and H2-H2, distributed by HITRAN.
You do not have to fetch them by hand: the cell below calls ensure_opacity_data(download=True) from the shared notebook helpers, which downloads the H2O/CO2 cross-sections and the H2-H2/H2-He CIA files into examples/tmp/xsec and examples/tmp/cia and points TauREx’s caches at them. If you already keep your own copies, skip the download and point the caches at your folders instead.
Once the files are in place, TauREx’s caching system discovers them automatically — path configuration is a one-time step.
Loading cross-sections¶
We need to point TauREx3 to our cross-sections. This is handled by the caching classes. Once a cross-section is loaded it does not need to be loaded again. First lets import the classes:
[3]:
from taurex.cache import OpacityCache,CIACache
Now lets download (or reuse) the files and point the cachers at them:
[4]:
from taurex.cache import OpacityCache, CIACache
from _shared import CIA_DIR, XSEC_DIR, ensure_opacity_data
# Downloads the tutorial H2O/CO2 cross-sections and the H2-H2/H2-He CIA files
# into examples/tmp (files already present are kept) and points both caches at them
ensure_opacity_data(download=True)
print(f"Cross-sections: {XSEC_DIR}")
print(f"CIA: {CIA_DIR}")
Cross-sections: /home/simone/Dropbox/eScience_projects/TauRex/taurex3/examples/tmp/xsec
CIA: /home/simone/Dropbox/eScience_projects/TauRex/taurex3/examples/tmp/cia
TauREx3 is now ready to use them! For fun lets, try grabbing the H2O cross-section and plotting it. First tell the OpacityCache function to grab it.
[5]:
h2o_xsec = OpacityCache()['H2O']
Now we can compute the cross-section for any pressure and temperature! Lets try 2000K and 10 Pa.
[6]:
h2o_xsec.opacity(2000, 10)
[6]:
array([8.93277708e-26, 1.41929962e-25, 1.24608425e-25, ...,
1.27362205e-33, 1.90153779e-33, 1.95851230e-33], shape=(76744,))
But why stop there? We can plot the temperature and pressure interactively
[7]:
xsec_fig = plt.figure()
xsec_ax = xsec_fig.add_subplot(1,1,1)
xsec, = xsec_ax.plot(10000/h2o_xsec.wavenumberGrid,h2o_xsec.opacity(800,1e0))
def update_cross(temperature=1500.0,pressure=6.7):
xsec.set_ydata(h2o_xsec.opacity(temperature,10**pressure))
xsec_ax.relim();
xsec_ax.autoscale_view()
xsec_fig.canvas.draw()
interact(update_cross,temperature=(800.0,2000.0,100),pressure=(-1.0,10.0,1));
Profiles¶
Now we need to setup our forward model. Lets create a temperature profile, we will use the Guillot profile but other brands are available:
[8]:
from taurex.temperature import Guillot2010
guillot = Guillot2010(T_irr=1200.0)
Now lets do the same for our planet:
[9]:
from taurex.planet import Planet
planet = Planet(planet_radius=1.0,planet_mass=1.0)
and the planets star:
[10]:
from taurex.stellar import BlackbodyStar
star = BlackbodyStar(temperature=5700.0,radius=1.0)
Now we need to define a chemistry profile, first lets setup the chemical model, we’re going for the free-type model so we’ll use TaurexChemistry which allows us to freely add any molecule:
[11]:
from taurex.chemistry import TaurexChemistry
chemistry = TaurexChemistry(fill_gases=['H2','He'],ratio=0.172)
Adding molecules¶
Now we need to add some molecules. This is accomplished by the addGas function. We can create varius types of gas profiles for each molecule and add them in. Lets try the constant profile for H2O:
[12]:
from taurex.chemistry import ConstantGas
h2o = ConstantGas('H2O',mix_ratio=1.2e-4)
chemistry.addGas(h2o)
[12]:
<taurex.data.profiles.chemistry.taurexchemistry.TaurexChemistry at 0x7d2c8e26f6b0>
We can also create the gas on the spot as well:
[13]:
chemistry.addGas(ConstantGas('N2',mix_ratio=3.00739e-9))
[13]:
<taurex.data.profiles.chemistry.taurexchemistry.TaurexChemistry at 0x7d2c8e26f6b0>
And we’re done for profiles! Like the cross-sections you can use them in isolation for your own evil deeds. Some require initialization with other profiles like pressure and altitude, you can find how to use them in the API documentation. An easy example are stars. Maybe you want to use the PHOENIX star library but don’t want to bother coding the function to load and interpolate. Well you can just use the new Phoenix4AllStar which auto-downloads (or loads from a local cache) high-resolution PHOENIX spectra from multiple online archives (SVO, STScI Synphot, HiResFITS)!
[14]:
from phoenix4all.taurex import Phoenix4AllStar
# Phoenix4AllStar downloads the spectra on demand and caches them locally
# Sources: "svo", "synphot", "hiresfits"
# We use the STScI Synphot mirror here: SVO answers with HTTP 403 on some networks
anotherstar = Phoenix4AllStar(temperature=5200.0, source="synphot", logg=4.5)
# Wavenumber grid over 0.3-5 um, the wavelength range covered by BT-Settl CIFIST
star_wngrid = np.linspace(2000.0, 33000.0, 1000)
anotherstar.initialize(star_wngrid)
star_fig = plt.figure()
star_ax = star_fig.add_subplot(1, 1, 1)
pstar, = star_ax.plot(10000 / star_wngrid[::-1], anotherstar.spectralEmissionDensity[::-1])
star_ax.set_xscale('log')
star_ax.set_yscale('log')
star_ax.set_xlabel('Wavelength (um)')
star_ax.set_ylabel('Spectral emission density (W/m$^2$/um)')
def update_star(temperature=5200.0):
anotherstar.temperature = temperature
anotherstar.initialize(star_wngrid)
pstar.set_ydata(anotherstar.spectralEmissionDensity[::-1])
star_ax.relim();
star_ax.autoscale_view()
star_fig.canvas.draw()
interact(update_star, temperature=(1200.0, 8000.0, 400));
After that quick detour lets carry on with our goal.
Catalogue mixins¶
TauREx includes built-in catalogue mixins that populate planet and star parameters directly from a CSV file or the ExoMAST online archive. This is done through mixins that enhance the base Planet and Star classes.
Using a local CSV catalogue:
from taurex.mixin import PlanetCatalogueFile, StarCatalogueFile, enhance_class
from taurex.planet import Planet
from taurex.stellar import BlackbodyStar
# Create enhanced classes that read from a catalogue
PlanetFromFile = enhance_class(Planet, PlanetCatalogueFile, catalogue_file="targets.csv")
StarFromFile = enhance_class(BlackbodyStar, StarCatalogueFile, catalogue_file="targets.csv")
Or using the ExoMAST API to automatically fetch known exoplanet parameters:
from taurex.mixin import PlanetCatalogueExomast, StarCatalogueExomast
PlanetFromWeb = enhance_class(Planet, PlanetCatalogueExomast, planet_name="WASP-121 b")
StarFromWeb = enhance_class(BlackbodyStar, StarCatalogueExomast, planet_name="WASP-121 b")
The catalogue mixins read columns prefixed with star_ and planet_ from CSV files and automatically map them to the correct parameters (mass, radius, temperature, metallicity, etc.).
[15]:
# Example: use ExoMAST to get WASP-121 b planet parameters
from taurex.mixin import PlanetCatalogueExomast, enhance_class
from taurex.planet import Planet
wasp121 = enhance_class(Planet, PlanetCatalogueExomast, planet_name="WASP-121 b")
print(f"Mass: {wasp121.fullMass:.2e} kg")
print(f"Radius: {wasp121.fullRadius:.2e} m")
Mass: 2.22e+27 kg
Radius: 1.25e+08 m
Building the model¶
Now we can build our transmission model! Lets first create our transmission model and add our profiles to them:
[16]:
from taurex.model import TransmissionModel
tm = TransmissionModel(planet=planet,
temperature_profile=guillot,
chemistry=chemistry,
star=star,
atm_min_pressure=1e-0,
atm_max_pressure=1e6,
nlayers=30)
At this point our atmosphere has profiles but no physics! We can add this by including some contributions. Lets add in Absorption:
[17]:
from taurex.contributions import AbsorptionContribution
tm.add_contribution(AbsorptionContribution())
And some CIA for good measure:
[18]:
from taurex.contributions import CIAContribution
tm.add_contribution(CIAContribution(cia_pairs=['H2-H2','H2-He']))
And some rayleigh
[19]:
from taurex.contributions import RayleighContribution
tm.add_contribution(RayleighContribution())
Finally, putting it all together we build it to setup all the profiles
[20]:
tm.build()
Thats it! Our transmission model is complete! We can now run it:
[21]:
res = tm.model()
res
[21]:
(array([ 199.99326855, 200.00660143, 200.01993521, ...,
33328.88933329, 33331.11125925, 33333.33333333], shape=(76744,)),
array([0.01108351, 0.01109867, 0.0110766 , ..., 0.01095716, 0.01095717,
0.01095719], shape=(76744,)),
array([[0.00000000e+00, 0.00000000e+00, 0.00000000e+00, ...,
1.93264823e-12, 1.93260216e-12, 1.93261489e-12],
[0.00000000e+00, 0.00000000e+00, 0.00000000e+00, ...,
2.10665009e-05, 2.10661419e-05, 2.10662816e-05],
[0.00000000e+00, 0.00000000e+00, 0.00000000e+00, ...,
1.87106574e-77, 1.77939982e-77, 1.69222862e-77],
...,
[9.26538789e-01, 9.36616596e-01, 9.99452341e-01, ...,
9.98284127e-01, 9.98283627e-01, 9.98283128e-01],
[9.57295669e-01, 9.63275419e-01, 9.99781861e-01, ...,
9.99046539e-01, 9.99046261e-01, 9.99045983e-01],
[9.81321794e-01, 9.83965080e-01, 9.99907547e-01, ...,
9.99587902e-01, 9.99587782e-01, 9.99587662e-01]],
shape=(30, 76744)),
None)
Nice! The output has four components:
The wavenumber grid
The native flux
The optical depth
Any extra information
Now lets plot it! Lets see the chemistry of the atmosphere:
[22]:
plt.figure()
for x,gasname in enumerate(tm.chemistry.activeGases):
plt.plot(tm.chemistry.activeGasMixProfile[x],tm.pressureProfile/1e5,label=gasname)
for x,gasname in enumerate(tm.chemistry.inactiveGases):
plt.plot(tm.chemistry.inactiveGasMixProfile[x],tm.pressureProfile/1e5,label=gasname)
plt.gca().invert_yaxis()
plt.yscale("log")
plt.xscale("log")
plt.legend()
plt.show()
Not interesting, but our chemistry model is pretty simple!
And now lets plot the flux
[23]:
native_grid, rprs, tau, _ = res
full_fig = plt.figure()
plt.plot(np.log10(10000/native_grid),rprs)
plt.show()
Coool! But lets try binning. We will use a simple but fast binner SimpleBinner.
[24]:
from taurex.binning import FluxBinner,SimpleBinner
binned_fig = plt.figure()
#Make a logarithmic grid
wngrid = np.sort(10000/np.logspace(-0.4,1.1,1000))
bn = SimpleBinner(wngrid=wngrid)
bin_wn, bin_rprs,_,_ = bn.bin_model(tm.model(wngrid=wngrid))
plt.plot(10000/bin_wn,bin_rprs)
plt.xscale('log')
plt.show()
Cool but the nice thing about TauREx is that you can alter any of the parameters and it will respond to it!
If any of the profiles are altered then model will respond to it. This means that parameters such as temperature and mix ratios and even contributions can be changed on the fly! Try this example out
[25]:
wngrid = np.sort(10000/np.logspace(-0.4,1.1,1000))
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
model, = ax.plot(np.log(10000/wngrid),bn.bin_model(tm.model(wngrid))[1])
def update_model(temperature=1500.0,h2o_mix=-4):
guillot.equilTemperature = temperature
tm['H2O'] = 10**h2o_mix
model.set_ydata(bn.bin_model(tm.model(wngrid))[1])
ax.relim();
ax.autoscale_view()
fig.canvas.draw()
interact(update_model,temperature=(800.0,2000.0,100),h2o_mix=(-7.0,-2.0,1));
You can do some crazy things! If you reuse the same profiles on other models. You essentially couple them! That means you can have multiple model that all alter at the same time! We can see the equivalant Emission and Direct image spectrum like so:
[26]:
from taurex.model import EmissionModel, DirectImageModel
em = EmissionModel(planet=planet,
temperature_profile=guillot,
chemistry=chemistry,
star=star,
atm_min_pressure=1e-0,
atm_max_pressure=1e6,
nlayers=30)
di = DirectImageModel(planet=planet,
temperature_profile=guillot,
chemistry=chemistry,
star=star,
atm_min_pressure=1e-0,
atm_max_pressure=1e6,
nlayers=30)
em.add_contribution(AbsorptionContribution())
em.add_contribution(CIAContribution(cia_pairs=['H2-H2','H2-He']))
em.add_contribution(RayleighContribution())
di.add_contribution(AbsorptionContribution())
di.add_contribution(CIAContribution(cia_pairs=['H2-H2','H2-He']))
di.add_contribution(RayleighContribution())
em.build()
di.build()
[27]:
wngrid = np.sort(10000/np.logspace(-0.4,1.1,1000))
all_fig = plt.figure(figsize=(9,4))
tm_ax = all_fig.add_subplot(1,3,1)
em_ax = all_fig.add_subplot(1,3,2)
di_ax = all_fig.add_subplot(1,3,3)
model_tm, = tm_ax.plot(10000/wngrid,bn.bin_model(tm.model(wngrid))[1])
model_em, = em_ax.plot(10000/wngrid,bn.bin_model(em.model(wngrid))[1])
model_di, = di_ax.plot(10000/wngrid,bn.bin_model(di.model(wngrid))[1])
tm_ax.set_xscale('log')
em_ax.set_xscale('log')
di_ax.set_xscale('log')
tm_ax.set_title('Transmission')
em_ax.set_title('Emission')
di_ax.set_title('Direct Image')
tm_ax.set_xlabel('Wavelength (um)')
em_ax.set_xlabel('Wavelength (um)')
di_ax.set_xlabel('Wavelength (um)')
def update_model(temperature=1500.0,h2o_mix=-4):
guillot.equilTemperature = temperature
tm['H2O'] = 10**h2o_mix
model_tm.set_ydata(bn.bin_model(tm.model(wngrid))[1])
model_em.set_ydata(bn.bin_model(em.model(wngrid))[1])
model_di.set_ydata(bn.bin_model(di.model(wngrid))[1])
tm_ax.relim();
tm_ax.autoscale_view()
em_ax.relim();
em_ax.autoscale_view()
di_ax.relim();
di_ax.autoscale_view()
all_fig.canvas.draw()
interact(update_model,temperature=(800.0,2000.0,100),h2o_mix=(-7.0,-2.0,1));
Retreivals¶
To see what parameters available for retrievals we can list them like so:
[28]:
list(tm.fittingParameters.keys())
[28]:
['planet_mass',
'planet_radius',
'planet_distance',
'planet_sma',
'distance',
'atm_min_pressure',
'atm_max_pressure',
'T_irr',
'kappa_irr',
'kappa_v1',
'kappa_v2',
'alpha',
'T_int_guillot',
'H2O',
'N2',
'He_H2']
The thing is, this is dynamic, TauREx 3 figures out what can be fit based on whats in it. Lets throw an isothermal profile instead:
[29]:
from taurex.temperature import Isothermal
isothermal = Isothermal(T=1500.0)
tm = TransmissionModel(planet=planet,
temperature_profile=isothermal,
chemistry=chemistry,
star=star,
atm_min_pressure=1e-0,
atm_max_pressure=1e6,
nlayers=30)
tm.add_contribution(AbsorptionContribution())
tm.add_contribution(CIAContribution(cia_pairs=['H2-H2','H2-He']))
tm.add_contribution(RayleighContribution())
tm.build()
[30]:
tm.model()
[30]:
(array([ 199.99326855, 200.00660143, 200.01993521, ...,
33328.88933329, 33331.11125925, 33333.33333333], shape=(76744,)),
array([0.01118238, 0.01116944, 0.01113074, ..., 0.01101443, 0.01101445,
0.01101447], shape=(76744,)),
array([[0.00000000e+000, 0.00000000e+000, 0.00000000e+000, ...,
1.63895518e-010, 1.63892493e-010, 1.63892945e-010],
[0.00000000e+000, 0.00000000e+000, 0.00000000e+000, ...,
3.80199111e-116, 3.52789749e-116, 3.27354321e-116],
[0.00000000e+000, 0.00000000e+000, 0.00000000e+000, ...,
8.55071670e-073, 8.15559750e-073, 7.77871828e-073],
...,
[9.99757948e-001, 9.99837988e-001, 9.99833926e-001, ...,
9.98502552e-001, 9.98502116e-001, 9.98501680e-001],
[9.99875210e-001, 9.99917592e-001, 9.99913887e-001, ...,
9.99167598e-001, 9.99167355e-001, 9.99167113e-001],
[9.99948271e-001, 9.99966114e-001, 9.99964183e-001, ...,
9.99640089e-001, 9.99639985e-001, 9.99639880e-001]],
shape=(30, 76744)),
None)
[31]:
list(tm.fittingParameters.keys())
[31]:
['planet_mass',
'planet_radius',
'planet_distance',
'planet_sma',
'distance',
'atm_min_pressure',
'atm_max_pressure',
'T',
'H2O',
'N2',
'He_H2']
Here we lost the Guillot parameters like T_irr but gained the Isothermal parameter T We can also access them directly from the model using the brackets operator:
[32]:
tm['T']
[32]:
1500.0
And set them
[33]:
tm['H2O']=1.2e-4
Now we’ll need an observation. lets use ObservedSpectrum to load a text one from examples/parfiles/quickstart.dat:
[34]:
from taurex.data.spectrum.observed import ObservedSpectrum
from _shared import PROJECT_ROOT
obs = ObservedSpectrum(str(PROJECT_ROOT / 'examples' / 'parfiles' / 'quickstart.dat'))
Convieniently we have a way of binning our native spectrum down to the observation by calling its create_binner method:
[35]:
obin = obs.create_binner()
And we can now plot
[36]:
plt.figure()
plt.errorbar(obs.wavelengthGrid,obs.spectrum,obs.errorBar,label='Obs')
plt.plot(obs.wavelengthGrid,obin.bin_model(tm.model(obs.wavenumberGrid))[1],label='TM')
plt.legend()
plt.show()
Ew not good! Lets try a retrieval! We have many optimizers to choose so lets create one using the inbuilt optimizer based on nestle
[37]:
from taurex.optimizer.nestle import NestleOptimizer
opt = NestleOptimizer(num_live_points=50)
We need to tell it about our forward model and observation:
[38]:
opt.set_model(tm)
opt.set_observed(obs)
Now lets enable which parameters to fit and their prior boundaries:
[39]:
opt.enable_fit('planet_radius')
opt.enable_fit('T')
opt.set_boundary('T',[1000,2000])
opt.set_boundary('planet_radius',[0.8,2.1])
Now lets fit!!!!
[40]:
solution = opt.fit()
taurex.log.disableLogging()
it= 692 logz=1844.881823844031niter: 693
ncall: 1154
nsamples: 743
logz: 1845.297 +/- 0.490
h: 11.987
Lets loop and plot each solution!
[41]:
for solution,optimized_map,optimized_value,values in opt.get_solution():
opt.update_model(optimized_map)
plt.figure()
plt.errorbar(obs.wavelengthGrid,obs.spectrum,obs.errorBar,label='Obs')
plt.plot(obs.wavelengthGrid,obin.bin_model(tm.model(obs.wavenumberGrid))[1],label='TM')
plt.legend()
plt.show()
Nice!