test_create_config_from_dict()   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 4
nop 0
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
import pytest
2
3
from asgardpy.config import AsgardpyConfig
4
5
6
def test_config_basic():
7
    """Test on basic Config features."""
8
9
    config = AsgardpyConfig()
10
    assert "AsgardpyConfig\n\n" in str(config)
11
    assert "AsgardpyConfig(general" in repr(config)
12
13
    config_str_0 = """
14
    general:
15
      n_jobs: 100
16
    """
17
    config_100 = AsgardpyConfig.from_yaml(config_str_0)
18
    assert config_100.general.n_jobs == 100
19
20
    with pytest.raises(ValueError):
21
        config_str_1 = """
22
        fit_params:
23
          fit_range:
24
            min: 10 s
25
            max: 10 TeV
26
        """
27
        AsgardpyConfig.from_yaml(config_str_1)
28
29
    with pytest.raises(ValueError):
30
        config_str_2 = """
31
        general:
32
          outdir: ./bla/
33
        """
34
        AsgardpyConfig.from_yaml(config_str_2)
35
36
    with pytest.raises(ValueError):
37
        config_str_3 = """
38
        target:
39
          sky_position:
40
            lon: 30 TeV
41
        """
42
        AsgardpyConfig.from_yaml(config_str_3)
43
44
45
def test_config_time():
46
    """Test for reading Time inputs."""
47
    from pydantic import ValidationError
48
49
    config = AsgardpyConfig()
50
51
    with pytest.raises(ValidationError):
52
        config.dataset1d.instruments[0].dataset_info.observation.obs_time = [
53
            {"format": "abc", "start": "2000-01-01", "stop": "2001-01-01"}
54
        ]
55
    with pytest.raises(ValueError):
56
        config.dataset1d.instruments[0].dataset_info.observation.obs_time = [
57
            {"format": "iso", "start": "60000", "stop": "2001-01-01"}
58
        ]
59
    with pytest.raises(ValueError):
60
        config.dataset1d.instruments[0].dataset_info.observation.obs_time = [
61
            {"format": "iso", "start": "2001-01-01", "stop": "60000"}
62
        ]
63
64
65
def test_get_model_template():
66
    """Test for reading a model template by a given tag."""
67
68
    from asgardpy.config.operations import get_model_template
69
70
    new_model = get_model_template("eclp")
71
72
    new_config = AsgardpyConfig.read(new_model)
73
74
    assert new_config.target.components[0].spectral.type == "ExpCutoffLogParabolaSpectralModel"
75
76
    with pytest.raises(IOError):
77
        new_config.write(new_model, overwrite=False)
78
79
80
def test_create_config_from_dict():
81
    """Test to create AsgardpyConfig from a simple dict."""
82
83
    gen_dict = {"general": {"log": {"level": "warning"}}}
84
    config = AsgardpyConfig(**gen_dict)
85
86
    assert config.general.log.level == "warning"
87
88
89
def test_config_update_gammapy(gammapy_data_path, base_config_1d):
90
    """Tests to update target model config from Gammapy-based YAML files."""
91
92
    import os
93
94
    from asgardpy.config.generator import gammapy_model_to_asgardpy_model_config
95
96
    main_config = AsgardpyConfig()
97
98
    other_config_path = f"{gammapy_data_path}fermi-3fhl-crab/Fermi-LAT-3FHL_models.yaml"
99
    other_config_path_2 = f"{gammapy_data_path}estimators/pks2155_hess_lc/models.yaml"
100
101
    other_config_1 = gammapy_model_to_asgardpy_model_config(
102
        other_config_path,
103
        recursive_merge=False,
104
    )
105
    other_config_2 = gammapy_model_to_asgardpy_model_config(
106
        other_config_path,
107
        base_config_1d,
108
        recursive_merge=False,
109
    )
110
111
    main_config.write("test_base_config.yaml", overwrite=True)
112
    other_config_3 = gammapy_model_to_asgardpy_model_config(
113
        other_config_path_2,
114
        "test_base_config.yaml",
115
        recursive_merge=False,
116
    )
117
118
    main_config_1 = main_config.update(other_config_1)
119
    main_config_2 = base_config_1d.update(other_config_2)
120
    main_config_3 = main_config.update(other_config_3)
121
122
    new_spectral_model_name = main_config_1.target.components[0].spectral.type
123
    new_spectral_model_name_2 = main_config_2.target.components[0].spectral.type
124
    new_spectral_model_name_3 = main_config_3.target.components[0].spectral.type
125
126
    index_max = main_config_3.target.components[0].spectral.parameters[0].max
127
128
    assert new_spectral_model_name == "LogParabolaSpectralModel"
129
    assert new_spectral_model_name_2 == "LogParabolaSpectralModel"
130
    assert new_spectral_model_name_3 == "PowerLawSpectralModel"
131
    assert index_max == 10.0
132
133
    os.remove("test_base_config.yaml")
134
135
136
def test_config_update():
137
    """Tests to update target model config from other AsgardpyConfig file."""
138
139
    from asgardpy.config.operations import get_model_template
140
141
    main_config = AsgardpyConfig()
142
143
    spec_model_template_file_1 = get_model_template("bpl")
144
    spec_model_template_file_2 = get_model_template("sbpl")
145
146
    other_config_1 = AsgardpyConfig.read(spec_model_template_file_1)
147
    other_config_2 = AsgardpyConfig.read(spec_model_template_file_2)
148
149
    main_config = main_config.update(other_config_1)
150
    new_spectral_model_name_1 = main_config.target.components[0].spectral.type
151
152
    new_config_str = """
153
    general:
154
      n_jobs: 100
155
    """
156
    main_config_2 = main_config.update(new_config_str)
157
158
    main_config = main_config.update(other_config_2, merge_recursive=True)
159
160
    new_spectral_model_name_2 = main_config.target.components[0].spectral.type
161
    spectral_model_params = main_config.target.components[0].spectral.parameters
162
163
    assert new_spectral_model_name_1 == "BrokenPowerLawSpectralModel"
164
    assert main_config_2.general.n_jobs == 100
165
    with pytest.raises(TypeError):
166
        main_config.update(5)
167
    assert new_spectral_model_name_2 == "SmoothBrokenPowerLawSpectralModel"
168
    assert len(spectral_model_params) == 6
169
170
171
def test_write_model_config():
172
    """From a Gammapy Models object, write it as an AsgardpyConfig file."""
173
174
    from gammapy.modeling.models import (
175
        ExpCutoffPowerLaw3FGLSpectralModel,
176
        Models,
177
        SkyModel,
178
    )
179
180
    from asgardpy.analysis import AsgardpyAnalysis
181
    from asgardpy.config.generator import AsgardpyConfig, write_asgardpy_model_to_file
182
    from asgardpy.config.operations import CONFIG_PATH, get_model_template
183
184
    config_ = AsgardpyConfig()
185
    analysis_ = AsgardpyAnalysis(config_)
186
    model_ = SkyModel(name="Template", spectral_model=ExpCutoffPowerLaw3FGLSpectralModel())
187
    model_.spectral_model.index.value = 1.5
188
189
    analysis_.final_model = Models(model_)
190
191
    assert get_model_template("ecpl-3fgl")
192
193
    write_asgardpy_model_to_file(
194
        gammapy_model=model_,
195
        output_file=str(CONFIG_PATH) + "/model_templates/model_template_ecpl-3fgl.yaml",
196
    )
197
198
    with pytest.raises(TypeError):
199
        write_asgardpy_model_to_file()
200
201
    write_asgardpy_model_to_file(
202
        gammapy_model=model_,
203
        output_file=None,
204
    )
205