def test_from_config_dict(tardis_config_verysimple): conf = Configuration.from_config_dict(tardis_config_verysimple, validate=True, config_dirname='test') assert conf.config_dirname == 'test' assert_almost_equal(conf.spectrum.start.value, tardis_config_verysimple['spectrum']['start'].value) assert_almost_equal(conf.spectrum.stop.value, tardis_config_verysimple['spectrum']['stop'].value) tardis_config_verysimple['spectrum']['start'] = 'Invalid' with pytest.raises(ValidationError): conf = Configuration.from_config_dict(tardis_config_verysimple, validate=True, config_dirname='test')
def test_plasma_section_config(tardis_config_verysimple): """ Configuration Validation Test for Plasma Section of the Tardis Config YAML File Validates: Initial temperature inner (must be greater than -1K) Initial radiative temperature (must be greater than -1K) Parameter --------- `tardis_config_verysimple` : YAML File Result ------ Assertion based on validation for specified values """ conf = Configuration.from_config_dict(tardis_config_verysimple, validate=True, config_dirname="test") tardis_config_verysimple["plasma"]["initial_t_inner"] = "-100 K" tardis_config_verysimple["plasma"]["initial_t_rad"] = "-100 K" with pytest.raises(ValueError) as ve: if (conf.plasma.initial_t_inner.value >= -1) and (conf.plasma.initial_t_rad.value >= -1): raise ValueError("Initial Temperatures are Invalid") assert ve.type is ValueError
def test_model_section_config(tardis_config_verysimple): """ Configuration Validation Test for Model Section of the Tardis Config YAML File Validates: Density: branch85_w7 Velocity (Start < End) Parameter --------- `tardis_config_verysimple` : YAML File Result ------ Assertion based on validation for specified values """ conf = Configuration.from_config_dict(tardis_config_verysimple, validate=True, config_dirname="test") assert conf.model.structure.density.type == "branch85_w7" tardis_config_verysimple["model"]["structure"]["velocity"][ "start"] = "2.0e4 km/s" tardis_config_verysimple["model"]["structure"]["velocity"][ "stop"] = "1.1e4 km/s" with pytest.raises(ValueError) as ve: if (conf.model.structure.velocity.start < conf.model.structure.velocity.stop): raise ValueError("Stop Value must be greater than Start Value") assert ve.type is ValueError
def test_supernova_section_config(tardis_config_verysimple): """ Configuration Validation Test for Supernova Section of the Tardis Config YAML File Validates: Time of Explosion (Must always be positive) Luminosity Wavelength Limits (Start < End) Parameter --------- `tardis_config_verysimple` : YAML File Result ------ Assertion based on validation for specified values """ conf = Configuration.from_config_dict(tardis_config_verysimple, validate=True, config_dirname="test") tardis_config_verysimple["supernova"]["time_explosion"] = "-10 day" tardis_config_verysimple["supernova"][ "luminosity_wavelength_start"] = "15 angstrom" tardis_config_verysimple["supernova"][ "luminosity_wavelength_end"] = "0 angstrom" with pytest.raises(ValueError) as ve: if conf.supernova.time_explosion.value > 0: raise ValueError("Time of Explosion cannot be negative") assert ve.type is ValueError with pytest.raises(ValueError) as ve: if (conf.supernova.luminosity_wavelength_start.value < conf.supernova.luminosity_wavelength_end.value): raise ValueError( "End Limit must be greater than Start Limit for Luminosity") assert ve.type is ValueError
def run_tardis( config, atom_data=None, packet_source=None, simulation_callbacks=[], virtual_packet_logging=False, ): """ This function is one of the core functions to run TARDIS from a given config object. It will return a model object containing Parameters ---------- config : str or dict or tardis.io.config_reader.Configuration filename of configuration yaml file or dictionary or TARDIS Configuration object atom_data : str or tardis.atomic.AtomData if atom_data is a string it is interpreted as a path to a file storing the atomic data. Atomic data to use for this TARDIS simulation. If set to None, the atomic data will be loaded according to keywords set in the configuration [default=None] virtual_packet_logging : bool option to enable virtual packet logging [default=False] Returns ------- Simulation """ from tardis.io.config_reader import Configuration from tardis.io.atom_data.base import AtomData from tardis.simulation import Simulation if atom_data is not None: try: atom_data = AtomData.from_hdf(atom_data) except TypeError: atom_data = atom_data if isinstance(config, Configuration): tardis_config = config else: try: tardis_config = Configuration.from_yaml(config) except TypeError: tardis_config = Configuration.from_config_dict(config) simulation = Simulation.from_config( tardis_config, packet_source=packet_source, atom_data=atom_data, virtual_packet_logging=virtual_packet_logging, ) for cb in simulation_callbacks: simulation.add_callback(*cb) simulation.run() return simulation
def test_config_hdf(hdf_file_path, tardis_config_verysimple): expected = Configuration.from_config_dict(tardis_config_verysimple, validate=True, config_dirname="test") expected.to_hdf(hdf_file_path, overwrite=True) actual = pd.read_hdf(hdf_file_path, key="/simulation/config") expected = expected.get_properties()["config"] assert actual[0] == expected[0]
def _get_config_from_args(self, args): config_name_space = copy.deepcopy(self.config_name_space) for i, param_value in enumerate(args): param_value = np.squeeze(param_value) config_name_space.set_config_item( self.convert_param_dict.values()[i], param_value) return Configuration.from_config_dict(config_name_space, validate=False, atom_data=self.atom_data)
def __init__(self, configFile, gridFrame): try: tardis_config = Configuration.from_yaml(configFile) except TypeError: tardis_config = Configuration.from_config_dict(configFile) self.config = tardis_config self.grid = gridFrame return
def test_from_config_dict(tardis_config_verysimple): conf = Configuration.from_config_dict(tardis_config_verysimple, validate=True, config_dirname="test") assert conf.config_dirname == "test" assert_almost_equal( conf.spectrum.start.value, tardis_config_verysimple["spectrum"]["start"].value, ) assert_almost_equal( conf.spectrum.stop.value, tardis_config_verysimple["spectrum"]["stop"].value, ) tardis_config_verysimple["spectrum"]["start"] = "Invalid" with pytest.raises(ValidationError): conf = Configuration.from_config_dict(tardis_config_verysimple, validate=True, config_dirname="test")
def setup(self): self.atom_data_filename = os.path.expanduser(os.path.expandvars( pytest.config.getvalue('atomic-dataset'))) assert os.path.exists(self.atom_data_filename), ("{0} atomic datafiles" " does not seem to " "exist".format( self.atom_data_filename)) self.config_yaml = yaml_load_config_file( 'tardis/plasma/tests/data/plasma_test_config_lte.yml') self.config_yaml['atom_data'] = self.atom_data_filename conf = Configuration.from_config_dict(self.config_yaml) self.lte_simulation = Simulation.from_config(conf) self.lte_simulation.run() self.config_yaml = yaml_load_config_file( 'tardis/plasma/tests/data/plasma_test_config_nlte.yml') self.config_yaml['atom_data'] = self.atom_data_filename conf = Configuration.from_config_dict(self.config_yaml) self.nlte_simulation = Simulation.from_config(conf) self.nlte_simulation.run()
def setup(self): self.atom_data_filename = os.path.expanduser(os.path.expandvars( pytest.config.getvalue('atomic-dataset'))) assert os.path.exists(self.atom_data_filename), ("{0} atomic datafiles " "does not seem to " "exist".format( self.atom_data_filename)) self.config_yaml = yaml.load(open('tardis/io/tests/data/tardis_configv1_verysimple.yml')) self.config_yaml['atom_data'] = self.atom_data_filename self.config = Configuration.from_config_dict(self.config_yaml) self.model = model.Radial1DModel(self.config) simulation.run_radial1d(self.model)
def setup(self): """ This method does initial setup of creating configuration and performing a single run of integration test. """ self.config_file = data_path("config_w7.yml") self.abundances = data_path("abundancies_w7.dat") self.densities = data_path("densities_w7.dat") # First we check whether atom data file exists at desired path. self.atom_data_filename = os.path.expanduser(os.path.expandvars( pytest.config.getvalue('atomic-dataset'))) assert os.path.exists(self.atom_data_filename), \ "{0} atom data file does not exist".format(self.atom_data_filename) # The available config file doesn't have file paths of atom data file, # densities and abundances profile files as desired. We load the atom # data seperately and provide it to tardis_config later. For rest of # the two, we form dictionary from the config file and override those # parameters by putting file paths of these two files at proper places. config_yaml = yaml.load(open(self.config_file)) config_yaml['model']['abundances']['filename'] = self.abundances config_yaml['model']['structure']['filename'] = self.densities # Load atom data file separately, pass it for forming tardis config. self.atom_data = AtomData.from_hdf5(self.atom_data_filename) # Check whether the atom data file in current run and the atom data # file used in obtaining the baseline data for slow tests are same. # TODO: hard coded UUID for kurucz atom data file, generalize it later. kurucz_data_file_uuid1 = "5ca3035ca8b311e3bb684437e69d75d7" assert self.atom_data.uuid1 == kurucz_data_file_uuid1 # The config hence obtained will be having appropriate file paths. tardis_config = Configuration.from_config_dict(config_yaml, self.atom_data) # We now do a run with prepared config and get radial1d model. self.obtained_radial1d_model = Radial1DModel(tardis_config) simulation = Simulation(tardis_config) simulation.legacy_run_simulation(self.obtained_radial1d_model) # The baseline data against which assertions are to be made is ingested # from already available compressed binaries (.npz). These will return # dictionaries of numpy.ndarrays for performing assertions. self.slow_test_data_dir = os.path.join(os.path.expanduser( os.path.expandvars(pytest.config.getvalue('slow-test-data'))), "w7") self.expected_ndarrays = np.load(os.path.join(self.slow_test_data_dir, "ndarrays.npz")) self.expected_quantities = np.load(os.path.join(self.slow_test_data_dir, "quantities.npz"))
def setup(self): self.atom_data_filename = os.path.expanduser( os.path.expandvars(pytest.config.getvalue('atomic-dataset'))) assert os.path.exists( self.atom_data_filename), ("{0} atomic datafiles" " does not seem to " "exist".format(self.atom_data_filename)) self.config_yaml = yaml_load_config_file( 'tardis/io/tests/data/tardis_configv1_verysimple.yml') self.config_yaml['atom_data'] = self.atom_data_filename tardis_config = Configuration.from_config_dict(self.config_yaml) self.simulation = Simulation.from_config(tardis_config) self.simulation.run()
def setup(self): self.atom_data_filename = os.path.expanduser(os.path.expandvars( pytest.config.getvalue('atomic-dataset'))) assert os.path.exists(self.atom_data_filename), ("{0} atomic datafiles" " does not seem to " "exist".format( self.atom_data_filename)) self.config_yaml = yaml_load_config_file( 'tardis/io/tests/data/tardis_configv1_verysimple.yml') self.config_yaml['atom_data'] = self.atom_data_filename tardis_config = Configuration.from_config_dict(self.config_yaml) self.simulation = Simulation.from_config(tardis_config) self.simulation.run()
def run_tardis(config, atom_data=None, packet_source=None, simulation_callbacks=[]): """ This function is one of the core functions to run TARDIS from a given config object. It will return a model object containing Parameters ---------- config: ~str or ~dict filename of configuration yaml file or dictionary atom_data: ~str or ~tardis.atomic.AtomData if atom_data is a string it is interpreted as a path to a file storing the atomic data. Atomic data to use for this TARDIS simulation. If set to None, the atomic data will be loaded according to keywords set in the configuration [default=None] """ from tardis.io.config_reader import Configuration from tardis.io.atom_data.base import AtomData from tardis.simulation import Simulation if atom_data is not None: try: atom_data = AtomData.from_hdf(atom_data) except TypeError: atom_data = atom_data try: tardis_config = Configuration.from_yaml(config) except TypeError: tardis_config = Configuration.from_config_dict(config) simulation = Simulation.from_config(tardis_config, packet_source=packet_source, atom_data=atom_data) for cb in simulation_callbacks: simulation.add_callback(*cb) simulation.run() return simulation
def run_tardis(config, atom_data=None, simulation_callbacks=[]): """ This function is one of the core functions to run TARDIS from a given config object. It will return a model object containing Parameters ---------- config: ~str or ~dict filename of configuration yaml file or dictionary atom_data: ~str or ~tardis.atomic.AtomData if atom_data is a string it is interpreted as a path to a file storing the atomic data. Atomic data to use for this TARDIS simulation. If set to None, the atomic data will be loaded according to keywords set in the configuration [default=None] """ from tardis.io.config_reader import Configuration from tardis.io.atom_data.base import AtomData from tardis.simulation import Simulation if atom_data is not None: try: atom_data = AtomData.from_hdf(atom_data) except TypeError: atom_data = atom_data try: tardis_config = Configuration.from_yaml(config) except TypeError: tardis_config = Configuration.from_config_dict(config) simulation = Simulation.from_config(tardis_config, atom_data=atom_data) for cb in simulation_callbacks: simulation.add_callback(cb) simulation.run() return simulation
def test_spectrum_section_config(tardis_config_verysimple): """ Configuration Validation Test for Plasma Section of the Tardis Config YAML File Validates: Spectrum Start & End Limits (Start < End) Parameter --------- `tardis_config_verysimple` : YAML File Result ------ Assertion based on validation for specified values """ conf = Configuration.from_config_dict(tardis_config_verysimple, validate=True, config_dirname="test") tardis_config_verysimple["spectrum"]["start"] = "2500 angstrom" tardis_config_verysimple["spectrum"]["stop"] = "500 angstrom" with pytest.raises(ValueError) as ve: if not conf.spectrum.stop.value < conf.spectrum.start.value: raise ValueError("Start Value must be less than Stop Value") assert ve.type is ValueError
def _generate_config(self, callback): config_ns = callback(self.config) return Configuration.from_config_dict( config_ns, validate=False, atom_data=self.atom_data)
def tardis_config(tardis_config_verysimple): return Configuration.from_config_dict(tardis_config_verysimple)
def run_tardis( config, atom_data=None, packet_source=None, simulation_callbacks=[], virtual_packet_logging=False, show_cplots=True, log_level=None, specific_log_level=None, **kwargs, ): """ Run TARDIS from a given config object. It will return a model object containing the TARDIS Simulation. Parameters ---------- config : str or dict or tardis.io.config_reader.Configuration filename of configuration yaml file or dictionary or TARDIS Configuration object atom_data : str or tardis.atomic.AtomData, optional If atom_data is a string it is interpreted as a path to a file storing the atomic data. Atomic data to use for this TARDIS simulation. If set to None (i.e. default), the atomic data will be loaded according to keywords set in the configuration packet_source : class, optional A custom packet source class or a child class of `tardis.montecarlo.packet_source` used to override the TARDIS `BasePacketSource` class. simulation_callbacks : list of lists, default: `[]`, optional Set of callbacks to call at the end of every iteration of the Simulation. The format of the lists should look like: [[callback1, callback_arg1], [callback2, callback_arg2], ...], where the callback function signature should look like: callback_function(simulation, extra_arg1, ...) virtual_packet_logging : bool, default: False, optional Option to enable virtual packet logging. log_level : {'NOTSET', 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'}, default: None, optional Set the level of the TARDIS logger (follows native python logging framework log levels). Use this parameter to override the `log_level` specified in the configuration file. The default value `None` means that the `log_level` specified in the configuration file will be used. specific_log_level : bool, default: None, optional Allows to set specific logging levels, overriding the value in the configuration file. If True, only show the log messages from a particular log level, set by `log_level`. If False, the logger shows log messages belonging to the level set and all levels above it in severity. The default value None means that the `specific_log_level` specified in the configuration file will be used. show_cplots : bool, default: True, optional Option to enable tardis convergence plots. **kwargs : dict, optional Optional keyword arguments including those supported by :obj:`tardis.visualization.tools.convergence_plot.ConvergencePlots`. Returns ------- tardis.simulation.Simulation Notes ----- Please see the `logging tutorial <https://tardis-sn.github.io/tardis/io/optional/logging_configuration.html>`_ to know more about `log_level` and `specific` options. """ from tardis.io.logger.logger import logging_state from tardis.io.config_reader import Configuration from tardis.io.atom_data.base import AtomData from tardis.simulation import Simulation if isinstance(config, Configuration): tardis_config = config else: try: tardis_config = Configuration.from_yaml(config) except TypeError: logger.debug( "TARDIS Config not available via YAML. Reading through TARDIS Config Dictionary" ) tardis_config = Configuration.from_config_dict(config) if not isinstance(show_cplots, bool): raise TypeError("Expected bool in show_cplots argument") logging_state(log_level, tardis_config, specific_log_level) if atom_data is not None: try: atom_data = AtomData.from_hdf(atom_data) except TypeError: logger.debug( "Atom Data Cannot be Read from HDF. Setting to Default Atom Data" ) atom_data = atom_data simulation = Simulation.from_config( tardis_config, packet_source=packet_source, atom_data=atom_data, virtual_packet_logging=virtual_packet_logging, show_cplots=show_cplots, **kwargs, ) for cb in simulation_callbacks: simulation.add_callback(*cb) simulation.run() return simulation