Skip to content

Commit cf58890

Browse files
committed
Better error message for missing parameter in the file.
1 parent 9520917 commit cf58890

File tree

2 files changed

+39
-4
lines changed

2 files changed

+39
-4
lines changed

src/ess/nmx/mcstas/load.py

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -67,12 +67,27 @@ def load_raw_event_data(
6767
def load_crystal_rotation(
6868
file_path: FilePath, instrument: McStasInstrument
6969
) -> CrystalRotation:
70-
"""Retrieve crystal rotation from the file."""
70+
"""Retrieve crystal rotation from the file.
71+
72+
Raises
73+
------
74+
KeyError
75+
If the crystal rotation is not found in the file.
76+
77+
"""
7178
with snx.File(file_path, 'r') as file:
72-
return sc.vector(
73-
value=[file[f"entry1/simulation/Param/XtalPhi{key}"][...] for key in "XYZ"],
79+
param_keys = tuple(f"entry1/simulation/Param/XtalPhi{key}" for key in "XYZ")
80+
if not all(key in file for key in param_keys):
81+
raise KeyError(
82+
f"Crystal rotations [{', '.join(param_keys)}] not found in file."
83+
)
84+
85+
return CrystalRotation(
86+
sc.vector(
87+
value=[file[param_key][...] for param_key in param_keys],
7488
unit=instrument.simulation_settings.angle_unit,
7589
)
90+
)
7691

7792

7893
def event_weights_from_probability(

tests/loader_test.py

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
import scippnexus as snx
1111
from ess.nmx import default_parameters
1212
from ess.nmx.data import small_mcstas_2_sample, small_mcstas_3_sample
13-
from ess.nmx.mcstas.load import bank_names_to_detector_names
13+
from ess.nmx.mcstas.load import bank_names_to_detector_names, load_crystal_rotation
1414
from ess.nmx.mcstas.load import providers as loader_providers
1515
from ess.nmx.reduction import NMXData
1616
from ess.nmx.types import (
@@ -192,6 +192,26 @@ def test_file_reader_mcstas_additional_fields(tmp_mcstas_file: pathlib.Path) ->
192192
assert isinstance(dg, sc.DataGroup)
193193

194194

195+
@pytest.fixture()
196+
def rotation_mission_tmp_file(tmp_mcstas_file: pathlib.Path) -> pathlib.Path:
197+
import h5py
198+
199+
param_keys = tuple(f"entry1/simulation/Param/XtalPhi{key}" for key in "XYZ")
200+
201+
# Remove the rotation parameters from the file.
202+
with h5py.File(tmp_mcstas_file, 'a') as file:
203+
for key in param_keys:
204+
del file[key]
205+
206+
return tmp_mcstas_file
207+
208+
209+
def test_missing_rotation(rotation_mission_tmp_file: FilePath) -> None:
210+
with pytest.raises(KeyError, match="XtalPhiX"):
211+
load_crystal_rotation(rotation_mission_tmp_file, None)
212+
# McStasInstrument is not used due to error in the file.
213+
214+
195215
def test_bank_names_to_detector_names_two_detectors():
196216
res = bank_names_to_detector_names(two_detectors_two_filenames)
197217
assert len(res) == 2

0 commit comments

Comments
 (0)