Пример #1
0
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
Пример #2
0
def simulation_one_loop(
        atomic_data_fname, config,
        tardis_ref_data, generate_reference):
    config.atom_data = atomic_data_fname
    config.montecarlo.iterations = 2
    config.montecarlo.no_of_packets = int(4e4)
    config.montecarlo.last_no_of_packets = int(4e4)

    simulation = Simulation.from_config(config)
    simulation.run()

    if not generate_reference:
        return simulation
    else:
        simulation.model.hdf_properties = [
                't_radiative',
                'dilution_factor'
                ]
        simulation.runner.hdf_properties = [
                'j_estimator',
                'nu_bar_estimator',
                'output_nu',
                'output_energy'
                ]
        simulation.model.to_hdf(
                tardis_ref_data,
                '',
                'test_simulation')
        simulation.runner.to_hdf(
                tardis_ref_data,
                '',
                'test_simulation')
        pytest.skip(
                'Reference data was generated during this run.')
Пример #3
0
 def plasma(self, request, chianti_he_db_fpath, config, tardis_ref_data):
     config["atom_data"] = chianti_he_db_fpath
     sim = Simulation.from_config(config)
     if request.config.getoption("--generate-reference"):
         sim.plasma.to_hdf(tardis_ref_data, path=config.plasma.save_path)
         pytest.skip(f"Reference data saved at {tardis_ref_data}")
     return sim.plasma
Пример #4
0
 def plasma(self, chianti_he_db_fpath, config, reference_fpath, reference):
     config['atom_data'] = chianti_he_db_fpath
     sim = Simulation.from_config(config)
     if pytest.config.getvalue("--generate-reference"):
         sim.plasma.to_hdf(reference_fpath, path=config.plasma.save_path)
         pytest.skip("Reference data saved at {0}".format(reference_fpath))
     return sim.plasma
Пример #5
0
def simulation_one_loop(raw_model, raw_plasma, tardis_config):
    sim = Simulation.from_config(tardis_config,
                                 model=raw_model,
                                 plasma=raw_plasma)
    sim.iterate(40000)

    return sim
Пример #6
0
 def plasma(self, chianti_he_db_fpath, config, reference_fpath, reference):
     config['atom_data'] = chianti_he_db_fpath
     sim = Simulation.from_config(config)
     if pytest.config.getvalue("--generate-reference"):
         sim.plasma.to_hdf(reference_fpath, path=config.plasma.save_path)
         pytest.skip("Reference data saved at {0}".format(reference_fpath))
     return sim.plasma
Пример #7
0
    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
Пример #8
0
def simulation_one_loop(atomic_data_fname, config, tardis_ref_data,
                        generate_reference):
    config.atom_data = atomic_data_fname
    config.montecarlo.iterations = 2
    config.montecarlo.no_of_packets = int(4e4)
    config.montecarlo.last_no_of_packets = int(4e4)

    simulation = Simulation.from_config(config)
    simulation.run()

    if not generate_reference:
        return simulation
    else:
        simulation.hdf_properties = [
            "iterations_w",
            "iterations_t_rad",
            "iterations_electron_densities",
            "iterations_t_inner",
        ]
        simulation.model.hdf_properties = ["t_radiative", "dilution_factor"]
        simulation.runner.hdf_properties = [
            "j_estimator",
            "nu_bar_estimator",
            "output_nu",
            "output_energy",
        ]
        simulation.to_hdf(tardis_ref_data, "", "test_simulation")
        simulation.model.to_hdf(tardis_ref_data, "", "test_simulation")
        simulation.runner.to_hdf(tardis_ref_data, "", "test_simulation")
        pytest.skip("Reference data was generated during this run.")
Пример #9
0
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)
Пример #10
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_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()
Пример #11
0
def simulation_one_loop(atomic_data_fname, config, tardis_ref_data,
                        generate_reference):
    config.atom_data = atomic_data_fname
    config.montecarlo.iterations = 2
    config.montecarlo.no_of_packets = int(4e4)
    config.montecarlo.last_no_of_packets = int(4e4)

    simulation = Simulation.from_config(config)
    simulation.run()

    return simulation
Пример #12
0
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
Пример #13
0
def test_montecarlo_main_loop(
    config_montecarlo_1e5_verysimple,
    atomic_dataset,
    tardis_ref_path,
    tmpdir,
    set_seed_fixture,
    random_call_fixture,
    request,
):

    montecarlo_configuration.LEGACY_MODE_ENABLED = True
    # Setup model config from verysimple
    atomic_data = deepcopy(atomic_dataset)
    config_montecarlo_1e5_verysimple.montecarlo.last_no_of_packets = 1e5
    config_montecarlo_1e5_verysimple.montecarlo.no_of_virtual_packets = 0
    config_montecarlo_1e5_verysimple.montecarlo.iterations = 1
    config_montecarlo_1e5_verysimple.plasma.line_interaction_type = "macroatom"
    del config_montecarlo_1e5_verysimple["config_dirname"]

    sim = Simulation.from_config(config_montecarlo_1e5_verysimple,
                                 atom_data=atomic_data)
    sim.run()

    compare_fname = os.path.join(tardis_ref_path,
                                 "montecarlo_1e5_compare_data.h5")
    if request.config.getoption("--generate-reference"):
        sim.to_hdf(compare_fname, overwrite=True)

    # Load compare data from refdata
    expected_nu = pd.read_hdf(compare_fname,
                              key="/simulation/runner/output_nu").values
    expected_energy = pd.read_hdf(
        compare_fname, key="/simulation/runner/output_energy").values
    expected_nu_bar_estimator = pd.read_hdf(
        compare_fname, key="/simulation/runner/nu_bar_estimator").values
    expected_j_estimator = pd.read_hdf(
        compare_fname, key="/simulation/runner/j_estimator").values

    actual_energy = sim.runner.output_energy
    actual_nu = sim.runner.output_nu
    actual_nu_bar_estimator = sim.runner.nu_bar_estimator
    actual_j_estimator = sim.runner.j_estimator

    # Compare
    npt.assert_allclose(actual_nu_bar_estimator,
                        expected_nu_bar_estimator,
                        rtol=1e-13)
    npt.assert_allclose(actual_j_estimator, expected_j_estimator, rtol=1e-13)
    npt.assert_allclose(actual_energy.value, expected_energy, rtol=1e-13)
    npt.assert_allclose(actual_nu.value, expected_nu, rtol=1e-13)
Пример #14
0
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
Пример #15
0
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
Пример #16
0
def run_tardis_model(params):
    model_config = Configuration.from_yaml('blondin_model_compare_ddc25.yml')
    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()
    fname = 'Output/ddc25/ddc25_t{}_v{}.hdf'.format(params[0].value, params[2].value)
    with pd.HDFStore(fname) as hdf:
        hdf.put('wavelength', pd.Series(sim.runner.spectrum.wavelength.value))
        hdf.put('lum', pd.Series(sim.runner.spectrum_integrated.luminosity_density_lambda.value))
        hdf.put('w', pd.Series(sim.plasma.w))
        hdf.put('t_electrons', pd.Series(sim.plasma.t_electrons))
        hdf.put('ion_num_dens', sim.plasma.ion_number_density)
        hdf.put('electron_dens', sim.plasma.electron_densities)
    return 1
Пример #17
0
def simulation_one_loop(atomic_data_fname, config, tardis_ref_data,
                        generate_reference):
    config.atom_data = atomic_data_fname
    config.montecarlo.iterations = 2
    config.montecarlo.no_of_packets = int(4e4)
    config.montecarlo.last_no_of_packets = int(4e4)

    simulation = Simulation.from_config(config)
    simulation.run()

    if not generate_reference:
        return simulation
    else:
        simulation.model.hdf_properties = ['t_radiative', 'dilution_factor']
        simulation.runner.hdf_properties = [
            'j_estimator', 'nu_bar_estimator', 'output_nu', 'output_energy'
        ]
        simulation.model.to_hdf(tardis_ref_data, '', 'test_simulation')
        simulation.runner.to_hdf(tardis_ref_data, '', 'test_simulation')
        pytest.skip('Reference data was generated during this run.')
Пример #18
0
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
Пример #19
0
    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
Пример #20
0
def simulation_verysimple(config_verysimple, atomic_dataset):
    atomic_data = deepcopy(atomic_dataset)
    sim = Simulation.from_config(config_verysimple, atom_data=atomic_data)
    sim.iterate(4000)
    return sim
Пример #21
0
def simulation_verysimple(config_verysimple, atomic_dataset):
    atomic_data = deepcopy(atomic_dataset)
    sim = Simulation.from_config(config_verysimple, atom_data=atomic_data)
    sim.iterate(4000)
    return sim
Пример #22
0
    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
Пример #23
0
def simulation_one_loop(raw_model, raw_plasma, tardis_config):
    sim = Simulation.from_config(tardis_config, model=raw_model,
                                 plasma=raw_plasma)
    sim.iterate(40000)

    return sim
Пример #24
0
    console_handler.setFormatter(console_formatter)
    logger.addHandler(console_handler)

if args.packet_log_file:
    logger = logging.getLogger("tardis_packet_logger")
    logger.setLevel(logging.DEBUG)
    packet_logging_handler = logging.FileHandler(packet_logging_fname,
                                                 mode="w")
    packet_logging_handler.setLevel(logging.DEBUG)
    packet_logging_formatter = logging.Formatter(
        "%(name)s - %(levelname)s - %(message)s")
    console_handler.setFormatter(packet_logging_formatter)
    logger.addHandler(packet_logging_handler)

tardis_config = config_reader.Configuration.from_yaml(args.config_fname)
simulation = Simulation.from_config(tardis_config)


def get_virtual_spectrum():
    # Catch warning when acessing invalid spectrum_virtual
    with warnings.catch_warnings(record=True) as w:
        spectrum = simulation.runner.spectrum_virtual

        if len(w) > 0 and w[-1]._category_name == "UserWarning":
            warnings.warn("Virtual spectrum is not available, using the "
                          "real packet spectrum instead.")
            spectrum = simulation.runner.spectrum
    return spectrum


print("Saving the {} spectrum.".format(tardis_config.spectrum.method))
Пример #25
0
    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), Loader=yaml.CLoader)['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.suspend_global_capture(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.resume_global_capture()

        # Get the reference data through the fixture.
        self.reference = reference
Пример #26
0
def simulation_without_loop(atomic_data_fname, config):

    config.atom_data = atomic_data_fname
    config.montecarlo.iterations = 2
    return Simulation.from_config(config)
Пример #27
0
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
Пример #28
0
def test_montecarlo_main_loop(
    config_verysimple,
    atomic_dataset,
    tardis_ref_path,
    tmpdir,
    set_seed_fixture,
    random_call_fixture,
):

    montecarlo_configuration.LEGACY_MODE_ENABLED = True

    # Load C data from refdata
    C_fname = os.path.join(tardis_ref_path, "montecarlo_1e5_compare_data.h5")
    expected_nu = pd.read_hdf(C_fname,
                              key="/simulation/runner/output_nu").values
    expected_energy = pd.read_hdf(
        C_fname, key="/simulation/runner/output_energy").values
    expected_nu_bar_estimator = pd.read_hdf(
        C_fname, key="/simulation/runner/nu_bar_estimator").values
    expected_j_estimator = pd.read_hdf(
        C_fname, key="/simulation/runner/j_estimator").values

    # Setup model config from verysimple
    atomic_data = deepcopy(atomic_dataset)
    config_verysimple.montecarlo.last_no_of_packets = 1e5
    config_verysimple.montecarlo.no_of_virtual_packets = 0
    config_verysimple.montecarlo.iterations = 1
    config_verysimple.montecarlo.single_packet_seed = 0
    del config_verysimple["config_dirname"]

    sim = Simulation.from_config(config_verysimple, atom_data=atomic_data)

    # Init model
    numba_plasma = numba_plasma_initialize(sim.plasma,
                                           line_interaction_type="macroatom")

    runner = sim.runner
    model = sim.model

    runner._initialize_geometry_arrays(model)
    runner._initialize_estimator_arrays(numba_plasma.tau_sobolev.shape)
    runner._initialize_packets(model.t_inner.value, 100000, 0)

    # Init parameters
    montecarlo_configuration.v_packet_spawn_start_frequency = (
        runner.virtual_spectrum_spawn_range.end.to(
            u.Hz, equivalencies=u.spectral()).value)
    montecarlo_configuration.v_packet_spawn_end_frequency = (
        runner.virtual_spectrum_spawn_range.start.to(
            u.Hz, equivalencies=u.spectral()).value)
    montecarlo_configuration.temporary_v_packet_bins = 20000
    montecarlo_configuration.full_relativity = runner.enable_full_relativity
    montecarlo_configuration.single_packet_seed = 0

    # Init packet collection from runner
    packet_collection = PacketCollection(
        runner.input_nu,
        runner.input_mu,
        runner.input_energy,
        runner._output_nu,
        runner._output_energy,
    )

    # Init model from runner
    numba_model = NumbaModel(
        runner.r_inner_cgs,
        runner.r_outer_cgs,
        model.time_explosion.to("s").value,
    )

    # Init estimators from runner
    estimators = Estimators(
        runner.j_estimator,
        runner.nu_bar_estimator,
        runner.j_blue_estimator,
        runner.Edotlu_estimator,
    )

    # Empty vpacket collection
    vpacket_collection = VPacketCollection(0, np.array([0, 0],
                                                       dtype=np.float64), 0,
                                           np.inf, 0, 0)

    # output arrays
    output_nus = np.empty_like(packet_collection.packets_output_nu)
    output_energies = np.empty_like(packet_collection.packets_output_nu)

    # IMPORTANT: seeds RNG state within JIT
    seed = 23111963
    set_seed_fixture(seed)
    for i in range(len(packet_collection.packets_input_nu)):
        # Generate packet
        packet = r_packet.RPacket(
            numba_model.r_inner[0],
            packet_collection.packets_input_mu[i],
            packet_collection.packets_input_nu[i],
            packet_collection.packets_input_energy[i],
            seed,
            i,
            0,
        )

        # Loop packet
        spl.single_packet_loop(packet, numba_model, numba_plasma, estimators,
                               vpacket_collection)
        output_nus[i] = packet.nu
        if packet.status == r_packet.PacketStatus.REABSORBED:
            output_energies[i] = -packet.energy
        elif packet.status == r_packet.PacketStatus.EMITTED:
            output_energies[i] = packet.energy

        # RNG to match C
        random_call_fixture()

    packet_collection.packets_output_energy[:] = output_energies[:]
    packet_collection.packets_output_nu[:] = output_nus[:]

    actual_energy = packet_collection.packets_output_energy
    actual_nu = packet_collection.packets_output_nu
    actual_nu_bar_estimator = estimators.nu_bar_estimator
    actual_j_estimator = estimators.j_estimator

    # Compare
    npt.assert_allclose(actual_nu_bar_estimator,
                        expected_nu_bar_estimator,
                        rtol=1e-13)
    npt.assert_allclose(actual_j_estimator, expected_j_estimator, rtol=1e-13)
    npt.assert_allclose(actual_energy, expected_energy, rtol=1e-13)
    npt.assert_allclose(actual_nu, expected_nu, rtol=1e-13)