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 __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 test_ascii_reader_power_law(): filename = "tardis_configv1_density_power_law_test.yml" config = Configuration.from_yaml(data_path(filename)) model = Radial1DModel.from_config(config) expected_densites = [ 3.29072513e-14, 2.70357804e-14, 2.23776573e-14, 1.86501954e-14, 1.56435277e-14, 1.32001689e-14, 1.12007560e-14, 9.55397475e-15, 8.18935779e-15, 7.05208050e-15, 6.09916083e-15, 5.29665772e-15, 4.61758699e-15, 4.04035750e-15, 3.54758837e-15, 3.12520752e-15, 2.76175961e-15, 2.44787115e-15, 2.17583442e-15, 1.93928168e-15, ] assert model.no_of_shells == 20 for i, mdens in enumerate(expected_densites): assert_almost_equal(model.density[i].to(u.Unit("g / (cm3)")).value, mdens)
def test_ascii_reader_exponential_law(): filename = "tardis_configv1_density_exponential_test.yml" config = Configuration.from_yaml(data_path(filename)) model = Radial1DModel.from_config(config) expected_densites = [ 5.18114795e-14, 4.45945537e-14, 3.83828881e-14, 3.30364579e-14, 2.84347428e-14, 2.44740100e-14, 2.10649756e-14, 1.81307925e-14, 1.56053177e-14, 1.34316215e-14, 1.15607037e-14, 9.95038990e-15, 8.56437996e-15, 7.37143014e-15, 6.34464872e-15, 5.46088976e-15, 4.70023138e-15, 4.04552664e-15, 3.48201705e-15, 2.99699985e-15, ] expected_unit = "g / (cm3)" assert model.no_of_shells == 20 for i, mdens in enumerate(expected_densites): assert_almost_equal(model.density[i].value, mdens) assert model.density[i].unit == u.Unit(expected_unit)
def test_model_decay(simple_isotope_abundance): filename = "tardis_configv1_verysimple.yml" config = Configuration.from_yaml(data_path(filename)) model = Radial1DModel.from_config(config) model.raw_isotope_abundance = simple_isotope_abundance decayed = simple_isotope_abundance.decay(model.time_explosion).as_atoms() norm_factor = 1.4 assert_almost_equal( model.abundance.loc[8][0], model.raw_abundance.loc[8][0] / norm_factor, decimal=4, ) assert_almost_equal( model.abundance.loc[14][0], (model.raw_abundance.loc[14][0] + decayed.loc[14][0]) / norm_factor, decimal=4, ) assert_almost_equal( model._abundance.loc[12][5], (model.raw_abundance.loc[12][5] + decayed.loc[12][5]) / norm_factor, decimal=4, ) assert_almost_equal( model.abundance.loc[6][12], (decayed.loc[6][12]) / norm_factor, decimal=4, )
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 setup(self): filename = "tardis_configv1_artis_density_v_slice.yml" self.config = Configuration.from_yaml(data_path(filename)) self.config.model.abundances.type = "file" self.config.model.abundances.filename = "artis_abundances.dat" self.config.model.abundances.filetype = "artis" self.model = Radial1DModel.from_config(self.config)
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_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 setup(self): filename = 'tardis_configv1_artis_density_v_slice.yml' self.config = Configuration.from_yaml(data_path(filename)) self.config.model.abundances.type = 'file' self.config.model.abundances.filename = 'artis_abundances.dat' self.config.model.abundances.filetype = 'artis' self.model = Radial1DModel.from_config(self.config)
def simulation( self, request, atomic_data_fname, generate_reference, tardis_ref_data): name = request.param[0] config = Configuration.from_yaml(request.param[1]) config['atom_data'] = atomic_data_fname simulation = Simulation.from_config(config) simulation.run() self._test_name = name if not generate_reference: return simulation else: simulation.plasma.hdf_properties = [ 'level_number_density', ] simulation.model.hdf_properties = [ 't_radiative' ] simulation.plasma.to_hdf( tardis_ref_data, self.name, self._test_name) simulation.model.to_hdf( tardis_ref_data, self.name, self._test_name) pytest.skip( 'Reference data was generated during this run.') return simulation
def setup(self): filename = 'tardis_configv1_artis_density.yml' self.config = Configuration.from_yaml(data_path(filename)) self.config.model.abundances.type = 'file' self.config.model.abundances.filename = 'artis_abundances.dat' self.config.model.abundances.filetype = 'artis' self.model = Radial1DModel.from_config(self.config)
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 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 test_compare_models(model_config_fnames): """Compare identical models produced by .from_config and .from_csvy to check that velocities, densities and abundances (pre and post decay) are the same""" csvy_config_file, old_config_file = model_config_fnames tardis_config = Configuration.from_yaml(csvy_config_file) tardis_config_old = Configuration.from_yaml(old_config_file) csvy_model = Radial1DModel.from_csvy(tardis_config) config_model = Radial1DModel.from_config(tardis_config_old) csvy_model_props = csvy_model.get_properties().keys() config_model_props = config_model.get_properties().keys() npt.assert_array_equal(csvy_model_props, config_model_props) for prop in config_model_props: csvy_model_val = csvy_model.get_properties()[prop] config_model_val = config_model.get_properties()[prop] if prop == "homologous_density": npt.assert_array_almost_equal( csvy_model_val.density_0.value, config_model_val.density_0.value ) npt.assert_array_almost_equal( csvy_model_val.time_0.value, config_model_val.time_0.value ) else: if hasattr(config_model_val, "value"): config_model_val = config_model_val.value csvy_model_val = csvy_model_val.value npt.assert_array_almost_equal(csvy_model_val, config_model_val) assert csvy_model.raw_abundance.shape == config_model.raw_abundance.shape assert ( csvy_model.raw_isotope_abundance.shape == config_model.raw_isotope_abundance.shape ) assert csvy_model.abundance.shape == config_model.abundance.shape npt.assert_array_almost_equal( csvy_model.raw_abundance.to_numpy(), config_model.raw_abundance.to_numpy(), ) npt.assert_array_almost_equal( csvy_model.raw_isotope_abundance.to_numpy(), config_model.raw_isotope_abundance.to_numpy(), ) npt.assert_array_almost_equal( csvy_model.abundance.to_numpy(), config_model.abundance.to_numpy() )
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 test_plasma_vboundary(config_init_trad_fname, v_inner_boundary, v_outer_boundary, atomic_data_fname): tardis_config = Configuration.from_yaml(config_init_trad_fname) tardis_config.atom_data = atomic_data_fname tardis_config.model.structure.v_inner_boundary = (v_inner_boundary * u.km / u.s) tardis_config.model.structure.v_outer_boundary = (v_outer_boundary * u.km / u.s) simulation = Simulation.from_config(tardis_config)
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 config(request): config = Configuration.from_yaml( 'tardis/io/tests/data/tardis_configv1_verysimple.yml') config["plasma"]["line_interaction_type"] = request.param config["montecarlo"]["no_of_packets"] = 4.0e+4 config["montecarlo"]["last_no_of_packets"] = 1.0e+5 config["montecarlo"]["no_of_virtual_packets"] = 0 config["spectrum"]["method"] = "integrated" return config
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_csvy_abundance(): csvypath = os.path.join(DATA_PATH, 'config_v_filter.yml') config = Configuration.from_yaml(csvypath) csvy_model = Radial1DModel.from_csvy(config) csvy_abund = csvy_model.abundance ref_abund = pd.DataFrame( np.array([[0.35, 0.3, 0.6, 0.4], [0.65, 0.7, 0.4, 0.6]])) ref_abund.index.name = 'atomic_number' ref_abund.index = np.array([1, 2]) assert csvy_abund.equals(ref_abund)
def base_config(request): config = Configuration.from_yaml( 'tardis/io/tests/data/tardis_configv1_verysimple.yml') config["plasma"]["line_interaction_type"] = request.param config["montecarlo"]["no_of_packets"] = 4.0e+4 config["montecarlo"]["last_no_of_packets"] = 1.0e+5 config["montecarlo"]["no_of_virtual_packets"] = 0 config["spectrum"]["method"] = "integrated" config["spectrum"]["integrated"]["points"] = 200 return config
def setup(self, request, reference, data_path, atomic_data_fname): """ This method does initial setup of creating configuration and performing a single run of integration test. """ # The last component in dirpath can be extracted as name of setup. self.name = data_path['setup_name'] self.config_file = os.path.join(data_path['config_dirpath'], "config.yml") # Load atom data file separately, pass it for forming tardis config. self.atom_data = AtomData.from_hdf5(atomic_data_fname) # Check whether the atom data file in current run and the atom data # file used in obtaining the reference data 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 # Create a Configuration through yaml file and atom data. tardis_config = Configuration.from_yaml( self.config_file, atom_data=self.atom_data) # Check whether current run is with less packets. if request.config.getoption("--less-packets"): less_packets = request.config.integration_tests_config['less_packets'] tardis_config['montecarlo']['no_of_packets'] = ( less_packets['no_of_packets'] ) tardis_config['montecarlo']['last_no_of_packets'] = ( less_packets['last_no_of_packets'] ) # We now do a run with prepared config and get radial1d model. self.result = Radial1DModel(tardis_config) # If current test run is just for collecting reference data, store the # output model to HDF file, save it at specified path. Skip all tests. # Else simply perform the run and move further for performing # assertions. if request.config.getoption("--generate-reference"): run_radial1d(self.result, hdf_path_or_buf=os.path.join( data_path['gen_ref_dirpath'], "{0}.h5".format(self.name) )) pytest.skip("Reference data saved at {0}".format( data_path['gen_ref_dirpath'] )) else: run_radial1d(self.result) # Get the reference data through the fixture. self.reference = reference
def base_config(request): config = Configuration.from_yaml( "tardis/io/tests/data/tardis_configv1_verysimple.yml") config["plasma"]["line_interaction_type"] = request.param config["montecarlo"]["no_of_packets"] = 4.0e4 config["montecarlo"]["last_no_of_packets"] = 1.0e5 config["montecarlo"]["no_of_virtual_packets"] = 0 config["spectrum"]["method"] = "integrated" config["spectrum"]["integrated"]["points"] = 200 print("config", config) return config
def test_compare_models(filename): fn, fnold = filename tardis_config = Configuration.from_yaml(fn) tardis_config_old = Configuration.from_yaml(fnold) csvy_model = Radial1DModel.from_csvy(tardis_config) config_model = Radial1DModel.from_config(tardis_config_old) csvy_model_props = csvy_model.get_properties().keys() config_model_props = config_model.get_properties().keys() npt.assert_array_equal(csvy_model_props, config_model_props) for prop in config_model_props: csvy_model_val = csvy_model.get_properties()[prop] config_model_val = config_model.get_properties()[prop] if prop == 'homologous_density': npt.assert_array_almost_equal(csvy_model_val.density_0.value, config_model_val.density_0.value) npt.assert_array_almost_equal(csvy_model_val.time_0.value, config_model_val.time_0.value) else: if hasattr(config_model_val, 'value'): config_model_val = config_model_val.value csvy_model_val = csvy_model_val.value npt.assert_array_almost_equal(csvy_model_val, config_model_val)
def test_logging_config(self, atomic_data_fname, caplog, log_state, specific): config = Configuration.from_yaml( "tardis/io/tests/data/tardis_configv1_verysimple_logger.yml") config["atom_data"] = atomic_data_fname caplog.clear() run_tardis(config=config, log_state=log_state, specific=specific) for record in caplog.records: if specific == True: assert record.levelno == LOGGING_LEVELS[log_state.upper()] else: assert record.levelno >= LOGGING_LEVELS[log_state.upper()]
def test_run_tardis_from_config_obj(atomic_data_fname): """ Tests whether the run_tardis function can take in the Configuration object as arguments """ config = Configuration.from_yaml( "tardis/io/tests/data/tardis_configv1_verysimple.yml") config["atom_data"] = atomic_data_fname try: sim = run_tardis(config) except Exception as e: pytest.fail(str(e.args[0]))
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 run_final_models_plus_pickle(params, fname='blondin_model_compare_ddc25.yml'): model_config = Configuration.from_yaml(fname) model_config.model.v_inner_boundary = params[2] model_config.model.v_outer_boundary = 35000*u.km/u.s model_config.supernova.luminosity_requested = params[1] model_config.supernova.time_explosion = params[0] sim = Simulation.from_config(model_config) print(sim.model.v_boundary_inner) sim.run() import pickle dump = 'Output/ddc25/ddc25_t{}_v{}.pickle'.format(params[0].value, params[2].value) with open(dump, 'wb') as dumpfile: pickle.dump(sim, dumpfile) return 1
def test_logging_simulation(atomic_data_fname, caplog): """ Testing the logs for simulations runs """ config = Configuration.from_yaml( "tardis/io/tests/data/tardis_configv1_verysimple.yml") config["atom_data"] = atomic_data_fname simulation = Simulation.from_config(config) simulation.run() for record in caplog.records: assert record.levelno >= logging.INFO
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 runner(self, atomic_data_fname, tardis_ref_data, generate_reference): config = Configuration.from_yaml( 'tardis/io/tests/data/tardis_configv1_verysimple.yml') config['atom_data'] = atomic_data_fname simulation = Simulation.from_config(config) simulation.run() if not generate_reference: return simulation.runner else: simulation.runner.hdf_properties = [ 'j_blue_estimator', 'spectrum', 'spectrum_virtual' ] simulation.runner.to_hdf(tardis_ref_data, '', self.name) pytest.skip('Reference data was generated during this run.')
def test_ascii_reader_power_law(): filename = 'tardis_configv1_density_power_law_test.yml' config = Configuration.from_yaml(data_path(filename)) model = Radial1DModel.from_config(config) expected_densites = [3.29072513e-14, 2.70357804e-14, 2.23776573e-14, 1.86501954e-14, 1.56435277e-14, 1.32001689e-14, 1.12007560e-14, 9.55397475e-15, 8.18935779e-15, 7.05208050e-15, 6.09916083e-15, 5.29665772e-15, 4.61758699e-15, 4.04035750e-15, 3.54758837e-15, 3.12520752e-15, 2.76175961e-15, 2.44787115e-15, 2.17583442e-15, 1.93928168e-15] assert model.no_of_shells == 20 for i, mdens in enumerate(expected_densites): assert_almost_equal(model.density[i].to(u.Unit('g / (cm3)')).value, mdens)
def config(self, request): config_path = os.path.join( 'tardis', 'plasma', 'tests', 'data', 'plasma_base_test_config.yml') config = Configuration.from_yaml(config_path) hash_string = '' for prop, value in request.param.items(): hash_string = '_'.join((hash_string, prop)) if prop == 'nlte': for nlte_prop, nlte_value in request.param[prop].items(): config.plasma.nlte[nlte_prop] = nlte_value if nlte_prop != 'species': hash_string = '_'.join((hash_string, nlte_prop)) else: config.plasma[prop] = value hash_string = '_'.join((hash_string, str(value))) setattr(config.plasma, 'save_path', hash_string) return config
def config(self, request): config_path = os.path.join('tardis', 'plasma', 'tests', 'data', 'plasma_base_test_config.yml') config = Configuration.from_yaml(config_path) hash_string = '' for prop, value in request.param.items(): hash_string = '_'.join((hash_string, prop)) if prop == 'nlte': for nlte_prop, nlte_value in request.param[prop].items(): config.plasma.nlte[nlte_prop] = nlte_value if nlte_prop != 'species': hash_string = '_'.join((hash_string, nlte_prop)) else: config.plasma[prop] = value hash_string = '_'.join((hash_string, str(value))) setattr(config.plasma, 'save_path', hash_string) return config
def test_ascii_reader_exponential_law(): filename = 'tardis_configv1_density_exponential_test.yml' config = Configuration.from_yaml(data_path(filename)) model = Radial1DModel.from_config(config) expected_densites = [5.18114795e-14, 4.45945537e-14, 3.83828881e-14, 3.30364579e-14, 2.84347428e-14, 2.44740100e-14, 2.10649756e-14, 1.81307925e-14, 1.56053177e-14, 1.34316215e-14, 1.15607037e-14, 9.95038990e-15, 8.56437996e-15, 7.37143014e-15, 6.34464872e-15, 5.46088976e-15, 4.70023138e-15, 4.04552664e-15, 3.48201705e-15, 2.99699985e-15] expected_unit = 'g / (cm3)' assert model.no_of_shells == 20 for i, mdens in enumerate(expected_densites): assert_almost_equal(model.density[i].value, mdens) assert model.density[i].unit == u.Unit(expected_unit)
def test_model_decay(simple_isotope_abundance): filename = 'tardis_configv1_verysimple.yml' config = Configuration.from_yaml(data_path(filename)) model = Radial1DModel.from_config(config) model.raw_isotope_abundance = simple_isotope_abundance decayed = simple_isotope_abundance.decay( model.time_explosion).as_atoms() norm_factor = 1.4 assert_almost_equal( model.abundance.loc[8][0], model.raw_abundance.loc[8][0] / norm_factor, decimal=4) assert_almost_equal(model.abundance.loc[14][0], ( model.raw_abundance.loc[14][0] + decayed.loc[14][0]) / norm_factor, decimal=4) assert_almost_equal(model._abundance.loc[12][5], ( model.raw_abundance.loc[12][5] + decayed.loc[12][5]) / norm_factor, decimal=4) assert_almost_equal( model.abundance.loc[6][12], (decayed.loc[6][12]) / norm_factor, decimal=4)
def runner(self, atomic_data_fname, tardis_ref_data, generate_reference): config = Configuration.from_yaml( "tardis/io/tests/data/tardis_configv1_verysimple.yml") config["atom_data"] = atomic_data_fname simulation = Simulation.from_config(config) simulation.run() if not generate_reference: return simulation.runner else: simulation.runner.hdf_properties = [ "j_blue_estimator", "spectrum", "spectrum_virtual", ] simulation.runner.to_hdf(tardis_ref_data, "", self.name) pytest.skip("Reference data was generated during this run.")
def runner( self, atomic_data_fname, tardis_ref_data, generate_reference): config = Configuration.from_yaml( 'tardis/io/tests/data/tardis_configv1_verysimple.yml') config['atom_data'] = atomic_data_fname simulation = Simulation.from_config(config) simulation.run() if not generate_reference: return simulation.runner else: simulation.runner.hdf_properties = [ 'j_blue_estimator', 'spectrum', 'spectrum_virtual' ] simulation.runner.to_hdf( tardis_ref_data, '', self.name) pytest.skip( 'Reference data was generated during this run.')
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 setup(self): filename = 'tardis_configv1_uniform_density.yml' self.config = Configuration.from_yaml(data_path(filename)) self.config.plasma.initial_t_inner = 2508 * u.K self.model = Radial1DModel.from_config(self.config)
def isotope_uniform_abundance(): config_path = os.path.join( data_path, 'tardis_configv1_isotope_uniabund.yml') config = Configuration.from_yaml(config_path) return config.model.abundances
def setup(self): filename = 'paper1_tardis_configv1.yml' self.config = Configuration.from_yaml(data_path(filename)) self.model = Radial1DModel.from_config(self.config)
def config_verysimple(): filename = 'tardis_configv1_verysimple.yml' path = os.path.abspath(os.path.join('tardis/io/tests/data/', filename)) config = Configuration.from_yaml(path) return config
def setup(self): filename = 'tardis_configv1_ascii_density_abund.yml' self.config = Configuration.from_yaml(data_path(filename)) self.config.model.structure.filename = 'density.dat' self.config.model.abundances.filename = 'abund.dat' self.model = Radial1DModel.from_config(self.config)
def setup(self, request, reference, data_path, pytestconfig): """ This method does initial setup of creating configuration and performing a single run of integration test. """ # Get capture manager capmanager = pytestconfig.pluginmanager.getplugin('capturemanager') # The last component in dirpath can be extracted as name of setup. self.name = data_path['setup_name'] self.config_file = os.path.join(data_path['config_dirpath'], "config.yml") # A quick hack to use atom data per setup. Atom data is ingested from # local HDF or downloaded and cached from a url, depending on data_path # keys. atom_data_name = yaml.load(open(self.config_file))['atom_data'] # Get the path to HDF file: atom_data_filepath = os.path.join( data_path['atom_data_path'], atom_data_name ) # Load atom data file separately, pass it for forming tardis config. self.atom_data = AtomData.from_hdf(atom_data_filepath) # Check whether the atom data file in current run and the atom data # file used in obtaining the reference data 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 # Create a Configuration through yaml file and atom data. tardis_config = Configuration.from_yaml(self.config_file) # Check whether current run is with less packets. if request.config.getoption("--less-packets"): less_packets = request.config.integration_tests_config['less_packets'] tardis_config['montecarlo']['no_of_packets'] = ( less_packets['no_of_packets'] ) tardis_config['montecarlo']['last_no_of_packets'] = ( less_packets['last_no_of_packets'] ) # We now do a run with prepared config and get the simulation object. self.result = Simulation.from_config(tardis_config, atom_data=self.atom_data) capmanager.suspendcapture(True) # If current test run is just for collecting reference data, store the # output model to HDF file, save it at specified path. Skip all tests. # Else simply perform the run and move further for performing # assertions. self.result.run() if request.config.getoption("--generate-reference"): ref_data_path = os.path.join( data_path['reference_path'], "{0}.h5".format(self.name) ) if os.path.exists(ref_data_path): pytest.skip( 'Reference data {0} does exist and tests will not ' 'proceed generating new data'.format(ref_data_path)) self.result.to_hdf(file_path=ref_data_path) pytest.skip("Reference data saved at {0}".format( data_path['reference_path'] )) capmanager.resumecapture() # Get the reference data through the fixture. self.reference = reference
def setup(self): filename = 'tardis_configv1_artis_density.yml' self.config = Configuration.from_yaml(data_path(filename)) self.model = Radial1DModel.from_config(self.config)
def config(): return Configuration.from_yaml( 'tardis/io/tests/data/tardis_configv1_verysimple.yml')
def tardis_model_density_config(): filename = 'tardis_configv1_tardis_model_format.yml' return Configuration.from_yaml(os.path.join(data_path, filename))
def tardis_config(tardis_config_verysimple): return Configuration.from_config_dict(tardis_config_verysimple)