def opacities():
    from taurex.opacity.fakeopacity import FakeOpacity
    NUM_T = 27
    NUM_P = 20
    WN_RES = 10000
    WN_SIZE = 300, 30000

    from taurex.contributions import AbsorptionContribution
    OpacityCache().add_opacity(FakeOpacity('H2O'))
    OpacityCache().add_opacity(FakeOpacity('CH4'))
    yield AbsorptionContribution()
    OpacityCache().clear_cache()
    def __init__(self, gases=None, filename=None):
        super().__init__(self.__class__.__name__)

        self._gases = gases

        self._mix_ratios = np.loadtxt(filename).T
        self.molecules_i_have = OpacityCache().find_list_of_molecules()

        active = []
        active_profile = []
        inactive = []
        inactive_profile = []

        for i, g in enumerate(self._gases):
            if g in self.molecules_i_have:
                active.append(g)
                active_profile.append(self._mix_ratios[i, :])
            else:
                inactive.append(g)
                inactive_profile.append(self._mix_ratios[i, :])

        self.active_gases = active
        self.inactive_gases = inactive

        self.active_mixratio_profile = np.array(active_profile)
        self.inactive_mixratio_profile = np.array(inactive_profile)
    def __init__(self, fill_gases=['H2', 'He'], ratio=0.17567):
        super().__init__('ChemistryModel')

        self._gases = []
        self._active = []
        self._inactive = []

        if isinstance(fill_gases, str):
            fill_gases = [fill_gases]

        if isinstance(ratio, float):
            ratio = [ratio]

        if len(fill_gases) > 1 and len(ratio) != len(fill_gases) - 1:
            self.error('Fill gases and ratio count are not correctly matched')
            self.error('There should be %s ratios, you have defined %s',
                       len(fill_gases) - 1, len(ratio))
            raise InvalidChemistryException

        self._fill_gases = fill_gases
        self._fill_ratio = ratio
        self.active_mixratio_profile = None
        self.inactive_mixratio_profile = None
        self.molecules_i_have = OpacityCache().find_list_of_molecules()
        self.debug('MOLECULES I HAVE %s', self.molecules_i_have)
        self.setup_fill_params()
Example #4
0
    def setup_globals(self):
        from taurex.cache import CIACache, OpacityCache
        config = self._raw_config.dict()
        if 'Global' in config:
            try:
                OpacityCache().set_opacity_path(config['Global']['xsec_path'])
            except KeyError:
                self.warning(
                    'No xsec path set, opacities cannot be used in model')
            try:

                OpacityCache().set_interpolation(
                    config['Global']['xsec_interpolation'])
                self.info('Interpolation mode set to {}'.format(
                    config['Global']['xsec_interpolation']))
            except KeyError:
                self.info('Interpolation mode set to linear')

            try:
                CIACache().set_cia_path(config['Global']['cia_path'])
            except KeyError:
                self.warning('No cia path set, cia cannot be used in model')

            try:
                OpacityCache().set_memory_mode(
                    config['Global']['xsec_in_memory'])
            except KeyError:
                self.warning('Xsecs will be loaded in memory')

            try:
                OpacityCache().enable_radis(config['Global']['use_radis'])
            except KeyError:
                self.warning('Radis is disabled')

            try:
                wn_start, wn_end, wn_points = config['Global']['radis_grid']

                OpacityCache().set_radis_wavenumber(wn_start, wn_end,
                                                    wn_points)
            except KeyError:
                self.warning('Radis default grid will be used')
Example #5
0
    def prepare_each(self, model, wngrid):
        """
        Prepares each molecular opacity by weighting them
        by their mixing ratio in the atmosphere

        Parameters
        ----------
        model: :class:`~taurex.model.model.ForwardModel`
            Forward model

        wngrid: :obj:`array`
            Wavenumber grid

        Yields
        ------
        component: :obj:`tuple` of type (str, :obj:`array`)
            Name of molecule and weighted opacity

        """

        self.debug('Preparing model with %s', wngrid.shape)
        self._ngrid = wngrid.shape[0]
        sigma_xsec = np.zeros(shape=(model.nLayers, wngrid.shape[0]))

        # Get the opacity cache
        self._opacity_cache = OpacityCache()
        # Loop through all active gases
        for gas in model.chemistry.activeGases:

            # Clear sigma array
            sigma_xsec[...] = 0.0

            # Get the mix ratio of the gas
            gas_mix = model.chemistry.get_gas_mix_profile(gas)
            self.info('Recomputing active gas %s opacity', gas)

            # Get the cross section object relating to the gas
            xsec = self._opacity_cache[gas]
            # Loop through the layers
            for idx_layer, tp in enumerate(
                    zip(model.temperatureProfile, model.pressureProfile)):
                self.debug('Got index,tp %s %s', idx_layer, tp)

                temperature, pressure = tp

                # Place into the array
                sigma_xsec[idx_layer] += \
                    xsec.opacity(temperature, pressure,
                                 wngrid)*gas_mix[idx_layer]

            # Temporarily assign to master cross-section
            self.sigma_xsec = sigma_xsec
            yield gas, sigma_xsec
    def prepare_each(self, model, wngrid):
        self.debug('Preparing model with %s', wngrid.shape)
        self._ngrid = wngrid.shape[0]
        self._use_ktables = GlobalCache()['opacity_method'] == 'ktables'
        self.info('Using cross-sections? %s', not self._use_ktables)
        weights = None

        if self._use_ktables:
            self._opacity_cache = KTableCache()
        else:
            self._opacity_cache = OpacityCache()
        sigma_xsec = None
        self.weights = None

        for gas in model.chemistry.activeGases:

            #self._total_contrib[...] =0.0
            gas_mix = model.chemistry.get_gas_mix_profile(gas)
            self.info('Recomputing active gas %s opacity', gas)

            xsec = self._opacity_cache[gas]

            if self._use_ktables and self.weights is None:
                self.weights = xsec.weights

            if sigma_xsec is None:

                if self._use_ktables:
                    sigma_xsec = np.zeros(shape=(self._nlayers, self._ngrid,
                                                 len(self.weights)))
                else:
                    sigma_xsec = np.zeros(shape=(self._nlayers, self._ngrid))
            else:
                sigma_xsec[...] = 0.0

            for idx_layer, tp in enumerate(
                    zip(model.temperatureProfile, model.pressureProfile)):
                self.debug('Got index,tp %s %s', idx_layer, tp)

                temperature, pressure = tp
                #print(gas,self._opacity_cache[gas].opacity(temperature,pressure,wngrid),gas_mix[idx_layer])
                sigma_xsec[idx_layer] += xsec.opacity(
                    temperature, pressure, wngrid) * gas_mix[idx_layer]

            self.sigma_xsec = sigma_xsec

            self.debug('SIGMAXSEC %s', self.sigma_xsec)

            yield gas, sigma_xsec
Example #7
0
    def __init__(self, name):
        Logger.__init__(self, name)
        Fittable.__init__(self)

        self.mu_profile = None


        if GlobalCache()['opacity_method'] == 'ktables':
            self._avail_active = KTableCache().find_list_of_molecules()
        else:

            self._avail_active = OpacityCache().find_list_of_molecules()
        #self._avail_active = OpacityCache().find_list_of_molecules()
        deactive_list = GlobalCache()['deactive_molecules']
        if deactive_list is not None:
            self._avail_active = [k for k in self._avail_active if k not in deactive_list]
    def _get_gas_mask(self):
        import operator
        from taurex.constants import AMU
        self._active_mask = np.ndarray(shape=(105, ), dtype=np.bool)
        self._inactive_mask = np.ndarray(shape=(105, ), dtype=np.bool)
        self._active_mask[:] = False
        self._inactive_mask[:] = False
        new_active_gases = []
        new_inactive_gases = []

        self._molecule_weight = {}

        with open(self._specfile, 'r') as textfile:

            molecules_i_have = OpacityCache().find_list_of_molecules()
            self.debug('MOLECULES %s', molecules_i_have)
            for line in textfile:
                sl = line.split()
                idx = int(sl[0]) - 1
                molecule = sl[1]
                self._molecule_weight[molecule] = float(sl[2]) * AMU

                if molecule in molecules_i_have:
                    self._active_mask[idx] = True
                    new_active_gases.append((molecule, idx))
                else:
                    self._inactive_mask[idx] = True
                    new_inactive_gases.append((molecule, idx))
        # Create a new list where the gases are in the correct order
        new_active_gases.sort(key=operator.itemgetter(1))
        new_inactive_gases.sort(key=operator.itemgetter(1))

        self.active_gases = [molecule for molecule, _ in new_active_gases]
        self.inactive_gases = [molecule for molecule, _ in new_inactive_gases]
        self.info('Active gases: %s', self.active_gases)
        self.info('Inactive gases: %s', self.inactive_gases)
Example #9
0
def setup_cache():
    inputs_dir = '../inputs/taurex/'
    OpacityCache().clear_cache()
    OpacityCache().set_opacity_path(inputs_dir)
    CIACache().set_cia_path(inputs_dir)
Example #10
0
@author: dario

Forward-modelling for hot jupiter HD209458b
Synthethic data is produced using ArielRad noise estimates
The output is the .txt datafile and plots
"""
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
from astropy.io import ascii
import numpy as np
import taurex.log
taurex.log.disableLogging()

#loading cross sections
from taurex.cache import OpacityCache, CIACache
OpacityCache().clear_cache()
#cross sections at R=7000 in the 0.3 to 15 micrometer range
OpacityCache().set_opacity_path("C:\\Users\dario\Desktop\TFG\Opacities")
CIACache().set_cia_path("C:\\Users\dario\Desktop\TFG\CIA")

from taurex.planet import Planet
from taurex.temperature import Isothermal
from taurex.pressure import SimplePressureProfile
from taurex.stellar import Star
from taurex.chemistry import TaurexChemistry, ConstantGas
from taurex.model import TransmissionModel
from taurex.contributions import AbsorptionContribution, CIAContribution
from taurex.contributions import RayleighContribution, SimpleCloudsContribution
from spectres import spectres

# LOAD OPACITIES
Example #11
0
 def __init__(self):
     super().__init__('Absorption')
     self._opacity_cache = OpacityCache()
Example #12
0
    def __init__(self, name):
        Logger.__init__(self, name)
        Fittable.__init__(self)

        self.mu_profile = None
        self._avail_active = OpacityCache().find_list_of_molecules()
    def setup_globals(self):
        from taurex.cache import GlobalCache
        from taurex.cache import CIACache, OpacityCache
        config = self._raw_config.dict()

        if 'Global' in config:
            global_config = config['Global']
            try:
                OpacityCache().set_opacity_path(config['Global']['xsec_path'])
            except KeyError:
                self.warning('No xsec path set, opacities '
                             'cannot be used in model')
            try:

                OpacityCache().set_interpolation(config['Global']
                                                       ['xsec_interpolation'])
                self.info('Interpolation mode set '
                          'to {}'.format(config['Global']
                                               ['xsec_interpolation']))
            except KeyError:
                self.info('Interpolation mode set to linear')

            try:
                CIACache().set_cia_path(config['Global']['cia_path'])
            except KeyError:
                self.warning('No cia path set, cia cannot be used in model')

            try:
                OpacityCache().set_memory_mode(config['Global']
                                                     ['xsec_in_memory'])
            except KeyError:
                self.warning('Xsecs will be loaded in memory')

            try:
                OpacityCache().enable_radis(config['Global']['use_radis'])
            except KeyError:
                self.warning('Radis is disabled')

            try:
                wn_start, wn_end, wn_points = config['Global']['radis_grid']

                OpacityCache().set_radis_wavenumber(wn_start, wn_end,
                                                    wn_points)
            except KeyError:
                self.warning('Radis default grid will be used')

            try:

                extension_paths = config['Global']['extension_paths']
                if isinstance(extension_paths, str):
                    extension_paths = [extension_paths, ]

                from .classfactory import ClassFactory
                ClassFactory().set_extension_paths(paths=extension_paths)
            except KeyError:
                pass


            gc = GlobalCache()

            for key, value in global_config.items():
                gc[key] = value