Skip to content

Commit e3b3e56

Browse files
authored
MDEConfig update for Sample Parameters and Polarization Options (#132)
* mde config updated for sample parameters, tests added/updated * refine ub sample logs updates and confg save function used in sample and refine_ub * polarized MDE config added, refine_ub_ui tst updated * refine un and sample parameters mde config tests * polarized tests * test reduce qtbot time
1 parent 89e5acc commit e3b3e56

8 files changed

+321
-9
lines changed

src/shiver/models/polarized.py

+20-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
# pylint: disable=no-name-in-module
44
from mantid.simpleapi import mtd, AddSampleLog
55
from mantid.kernel import Logger
6-
6+
from shiver.models.generate import gather_mde_config_dict, save_mde_config_dict
77

88
logger = Logger("SHIVER")
99

@@ -24,6 +24,8 @@ def save_experiment_sample_log(self, log_name, log_value):
2424
if self.workspace_name and mtd.doesExist(self.workspace_name):
2525
workspace = mtd[self.workspace_name]
2626
AddSampleLog(workspace, LogName=log_name, LogText=log_value, LogType="String")
27+
# update the MDEConfig with the polarized options
28+
self.update_polarized_mde_config()
2729

2830
def save_polarization_logs(self, polarization_logs):
2931
"""Save polarization logs in workspace"""
@@ -112,3 +114,20 @@ def get_flipping_ratio(self):
112114
err = f"{flipping_formula} is invalid!"
113115
logger.error(err)
114116
return flipping_ratio
117+
118+
def update_polarized_mde_config(self):
119+
"""Update the MDE Config Polarized Parameters, if the MDE Config exists"""
120+
121+
# update mde config if it exists
122+
saved_mde_config = {}
123+
saved_mde_config.update(gather_mde_config_dict(self.workspace_name))
124+
125+
# if MDEConfig exists
126+
if len(saved_mde_config.keys()) != 0:
127+
# update the MDEConfig with the current values
128+
sample_data = self.get_polarization_logs_for_workspace()
129+
# format
130+
sample_data["PSDA"] = sample_data["psda"]
131+
del sample_data["psda"]
132+
saved_mde_config["PolarizedOptions"] = sample_data
133+
save_mde_config_dict(self.workspace_name, saved_mde_config)

src/shiver/models/refine_ub.py

+2
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
IndexPeaks,
1919
)
2020
from mantid.kernel import Logger
21+
from shiver.models.sample import update_sample_mde_config
2122

2223
logger = Logger("SHIVER")
2324

@@ -194,6 +195,7 @@ def predict_peaks(self):
194195
def update_mde_with_new_ub(self):
195196
"""Update the UB in the MDE from the one in the peaks workspace"""
196197
CopySample(self.peaks, self.mde, CopyName=False, CopyMaterial=False, CopyEnvironment=False, CopyShape=False)
198+
update_sample_mde_config(self.mde.name(), self.mde.getExperimentInfo(0).sample().getOrientedLattice())
197199

198200
def get_perpendicular_slices(self, peak_row):
199201
"""Create 3 perpendicular slices center on the peaks corresponding to the given row"""

src/shiver/models/sample.py

+28
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
from mantid.kernel import Logger
1919
from mantidqtinterfaces.DGSPlanner.LoadNexusUB import LoadNexusUB
2020
from mantidqtinterfaces.DGSPlanner.ValidateOL import ValidateUB
21+
from shiver.models.generate import gather_mde_config_dict, save_mde_config_dict
2122

2223
logger = Logger("SHIVER")
2324

@@ -135,6 +136,10 @@ def set_ub(self, params):
135136
v=vvec,
136137
)
137138
logger.information(f"SetUB completed for {self.name}")
139+
# get the saved oriented lattice
140+
self.oriented_lattice = workspace.getExperimentInfo(0).sample().getOrientedLattice()
141+
# update the mdeconfig
142+
update_sample_mde_config(self.name, self.oriented_lattice)
138143
return True
139144
except ValueError as value_error:
140145
err_msg = f"Invalid lattices: {value_error}\n"
@@ -227,3 +232,26 @@ def save_isaw(self, filename):
227232
logger.error(err_msg)
228233
if self.error_callback:
229234
self.error_callback(err_msg)
235+
236+
237+
def update_sample_mde_config(name, oriented_lattice):
238+
"""Update the MDE Config Sample Parameters, if the MDE Config exists"""
239+
240+
# updated mde config if it exists
241+
saved_mde_config = {}
242+
saved_mde_config.update(gather_mde_config_dict(name))
243+
244+
# if MDEConfig exists
245+
if len(saved_mde_config.keys()) != 0:
246+
# update the MDEConfig with the current value
247+
sample_data = {}
248+
sample_data["a"] = oriented_lattice.a()
249+
sample_data["b"] = oriented_lattice.b()
250+
sample_data["c"] = oriented_lattice.c()
251+
sample_data["alpha"] = oriented_lattice.alpha()
252+
sample_data["beta"] = oriented_lattice.beta()
253+
sample_data["gamma"] = oriented_lattice.gamma()
254+
sample_data["u"] = ",".join(str(item) for item in oriented_lattice.getuVector())
255+
sample_data["v"] = ",".join(str(item) for item in oriented_lattice.getvVector())
256+
saved_mde_config["SampleParameters"] = sample_data
257+
save_mde_config_dict(name, saved_mde_config)

src/shiver/presenters/polarized.py

+6-4
Original file line numberDiff line numberDiff line change
@@ -35,13 +35,15 @@ def get_polarization_logs(self):
3535

3636
def handle_apply_button(self, polarization_logs):
3737
"""Save the values for the sample logs"""
38+
saved_logs = {}
39+
saved_logs.update(polarization_logs)
3840
# do not update psda value if readonly field
3941
if self.view.dialog.disable_psda:
40-
del polarization_logs["PSDA"]
42+
del saved_logs["PSDA"]
4143
else:
42-
polarization_logs["psda"] = polarization_logs["PSDA"]
43-
del polarization_logs["PSDA"]
44-
self.model.save_polarization_logs(polarization_logs)
44+
saved_logs["psda"] = saved_logs["PSDA"]
45+
del saved_logs["PSDA"]
46+
self.model.save_polarization_logs(saved_logs)
4547

4648

4749
def create_dictionary_polarized_options(sample_log_data):

tests/models/test_histogram_saving.py

+81
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
from shiver.models.polarized import PolarizedModel
2323
from shiver.views.polarized_options import PolarizedView
2424
from shiver.presenters.polarized import PolarizedPresenter
25+
from shiver.models.generate import gather_mde_config_dict
2526

2627

2728
def test_saving(tmp_path):
@@ -664,6 +665,86 @@ def test_polarization_parameters(tmp_path, shiver_app, qtbot):
664665
assert saved_pol_logs["PSDA"] == "1.3"
665666

666667

668+
def test_polarization_mdeconfig_parameters(tmp_path, qtbot):
669+
"""Test the polarization parameters are saved in the MDEConfig"""
670+
671+
# clear mantid workspace
672+
mtd.clear()
673+
674+
name = "px_mini_NSF"
675+
filepath = f"{tmp_path}/{name}.nxs"
676+
677+
# load mde workspace
678+
LoadMD(
679+
Filename=os.path.join(os.path.dirname(os.path.abspath(__file__)), "../data/mde/px_mini_NSF.nxs"),
680+
OutputWorkspace="data",
681+
)
682+
683+
MakeSlice(
684+
InputWorkspace="data",
685+
BackgroundWorkspace=None,
686+
NormalizationWorkspace=None,
687+
QDimension0="0,0,1",
688+
QDimension1="1,1,0",
689+
QDimension2="-1,1,0",
690+
Dimension0Name="QDimension1",
691+
Dimension0Binning="0.35,0.025,0.65",
692+
Dimension1Name="QDimension0",
693+
Dimension1Binning="0.45,0.55",
694+
Dimension2Name="QDimension2",
695+
Dimension2Binning="-0.2,0.2",
696+
Dimension3Name="DeltaE",
697+
Dimension3Binning="-0.5,0.5",
698+
SymmetryOperations=None,
699+
Smoothing=1,
700+
OutputWorkspace=name,
701+
)
702+
model = HistogramModel()
703+
workspace = mtd[name]
704+
model.save(name, filepath)
705+
706+
# check the mde config values
707+
mde_config = gather_mde_config_dict(name)
708+
assert len(mde_config) != 0
709+
710+
pol_sample_logs = {
711+
"PolarizationState": "NSF",
712+
"PolarizationDirection": "Px",
713+
"FlippingRatio": "3Ei+1/4",
714+
"FlippingRatioSampleLog": "Ei",
715+
"PSDA": "1.8",
716+
}
717+
718+
qtbot.wait(100)
719+
# save polarization parameters
720+
polarized_view = PolarizedView()
721+
polarized_model = PolarizedModel(name)
722+
polarized_presenter = PolarizedPresenter(polarized_view, polarized_model)
723+
polarized_view.start_dialog(False)
724+
polarized_presenter.handle_apply_button(pol_sample_logs)
725+
726+
# check polarization parameters in sample logs
727+
run = workspace.getExperimentInfo(0).run()
728+
assert run.getLogData("PolarizationState").value == pol_sample_logs["PolarizationState"]
729+
assert run.getLogData("PolarizationDirection").value == pol_sample_logs["PolarizationDirection"]
730+
assert run.getLogData("FlippingRatio").value == pol_sample_logs["FlippingRatio"]
731+
assert run.getLogData("FlippingRatioSampleLog").value == pol_sample_logs["FlippingRatioSampleLog"]
732+
assert run.getPropertyAsSingleValueWithTimeAveragedMean("psda") == 1.8
733+
734+
# check the MDEConfig dictionary
735+
config = {}
736+
config_data = run.getProperty("MDEConfig").value
737+
config.update(ast.literal_eval(config_data))
738+
739+
assert len(config.keys()) != 0
740+
assert config["mde_name"] == name
741+
assert config["PolarizedOptions"]["PolarizationState"] == pol_sample_logs["PolarizationState"]
742+
assert config["PolarizedOptions"]["PolarizationDirection"] == pol_sample_logs["PolarizationDirection"]
743+
assert config["PolarizedOptions"]["FlippingRatio"] == pol_sample_logs["FlippingRatio"]
744+
assert config["PolarizedOptions"]["FlippingRatioSampleLog"] == pol_sample_logs["FlippingRatioSampleLog"]
745+
assert config["PolarizedOptions"]["PSDA"] == pol_sample_logs["PSDA"]
746+
747+
667748
def test_polarization_state_invalid(tmp_path):
668749
"""Test the polarization state for invalid state"""
669750

tests/models/test_refine_ub.py

+97
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
"""Tests for the RefineUBModel"""
22

33
import pytest
4+
import numpy as np
45
from shiver.models.refine_ub import RefineUBModel
6+
from shiver.models.generate import gather_mde_config_dict, save_mde_config_dict
57
from mantid.simpleapi import ( # pylint: disable=no-name-in-module,wrong-import-order
68
CreateMDWorkspace,
79
FakeMDEventData,
@@ -172,3 +174,98 @@ def test_refine_ub_model():
172174
assert peak_table_model.ws.sample().getOrientedLattice().gamma() == pytest.approx(90)
173175
assert peak_table_model.ws.sample().getOrientedLattice().getuVector() == pytest.approx([1, 0, 0])
174176
assert peak_table_model.ws.sample().getOrientedLattice().getvVector() == pytest.approx([0, 1, 0])
177+
178+
179+
def test_mdeconfig_refine_ub():
180+
"""test the mdeconfig in RefineUBModel"""
181+
182+
expt_info = CreateSampleWorkspace()
183+
SetUB(expt_info)
184+
185+
mde = CreateMDWorkspace(
186+
Dimensions=4,
187+
Extents="-10,10,-10,10,-10,10,-10,10",
188+
Names="x,y,z,DeltaE",
189+
Units="r.l.u.,r.l.u.,r.l.u.,DeltaE",
190+
Frames="QSample,QSample,QSample,General Frame",
191+
)
192+
mde.addExperimentInfo(expt_info)
193+
FakeMDEventData(mde, PeakParams="1e+05,6.283,0,0,0,0.02", RandomSeed="3873875")
194+
FakeMDEventData(mde, PeakParams="1e+05,0,6.283,0,0,0.02", RandomSeed="3873875")
195+
FakeMDEventData(mde, PeakParams="1e+05,0,0,6.283,0,0.02", RandomSeed="3873875")
196+
197+
# add new MDEConfig
198+
new_mde_config = {}
199+
new_mde_config["mde_name"] = mde.name()
200+
new_mde_config["output_dir"] = "/test/file/path"
201+
new_mde_config["mde_type"] = "Data"
202+
save_mde_config_dict(mde.name(), new_mde_config)
203+
# check the mde config values
204+
mde_config = gather_mde_config_dict(mde.name())
205+
206+
assert len(mde_config) == 3
207+
208+
mdh = CreateMDWorkspace(
209+
Dimensions=4,
210+
Extents="-5,5,-5,5,-5,5,-10,10",
211+
Names="[H,0,0],[0,K,0],[0,0,L],DeltaE",
212+
Units="r.l.u.,r.l.u.,r.l.u.,DeltaE",
213+
Frames="HKL,HKL,HKL,General Frame",
214+
)
215+
mdh.addExperimentInfo(expt_info)
216+
SetUB(mdh)
217+
FakeMDEventData(mdh, PeakParams="1e+05,1,0,0,0,0.02", RandomSeed="3873875")
218+
FakeMDEventData(mdh, PeakParams="1e+05,0,1,0,0,0.02", RandomSeed="3873875")
219+
FakeMDEventData(mdh, PeakParams="1e+05,0,0,1,0,0.02", RandomSeed="3873875")
220+
mdh.getExperimentInfo(0).run().addProperty("W_MATRIX", [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0], True)
221+
222+
mdh = BinMD(
223+
mdh,
224+
AlignedDim0="[H,0,0],-2,2,50",
225+
AlignedDim1="[0,K,0],-2,2,50",
226+
AlignedDim2="[0,0,L],-2,2,50",
227+
AlignedDim3="DeltaE,-1.25,1.25,1",
228+
)
229+
230+
model = RefineUBModel("mdh", "mde")
231+
model.predict_peaks()
232+
233+
# peak table model
234+
peak_table_model = model.get_peaks_table_model()
235+
peak_table_model.set_peak_number_to_rows()
236+
237+
# recenter peaks
238+
peak_table_model.recenter_rows([0, 4])
239+
240+
# refine, should change the lattice parameters and u/v vectors
241+
peak_table_model.refine([3, 4, 5], "")
242+
model.update_mde_with_new_ub()
243+
# check the oriented lattice
244+
mde_oriented_lattice = mde.getExperimentInfo(0).sample().getOrientedLattice()
245+
peak_oriented_lattice = peak_table_model.ws.sample().getOrientedLattice()
246+
247+
assert peak_oriented_lattice.a() == mde_oriented_lattice.a()
248+
assert peak_oriented_lattice.b() == mde_oriented_lattice.b()
249+
assert peak_oriented_lattice.c() == mde_oriented_lattice.c()
250+
assert peak_oriented_lattice.alpha() == mde_oriented_lattice.alpha()
251+
assert peak_oriented_lattice.beta() == mde_oriented_lattice.beta()
252+
assert peak_oriented_lattice.gamma() == mde_oriented_lattice.gamma()
253+
assert peak_oriented_lattice.getuVector() == pytest.approx(mde_oriented_lattice.getuVector())
254+
assert peak_oriented_lattice.getvVector() == pytest.approx(mde_oriented_lattice.getvVector())
255+
256+
# check the mde config values
257+
mde_config = gather_mde_config_dict(mde.name())
258+
259+
assert len(mde_config) == 4
260+
assert "SampleParameters" in mde_config
261+
assert mde_config["SampleParameters"]["a"] == mde_oriented_lattice.a()
262+
assert mde_config["SampleParameters"]["b"] == mde_oriented_lattice.b()
263+
assert mde_config["SampleParameters"]["c"] == mde_oriented_lattice.c()
264+
assert mde_config["SampleParameters"]["alpha"] == mde_oriented_lattice.alpha()
265+
assert mde_config["SampleParameters"]["beta"] == mde_oriented_lattice.beta()
266+
assert mde_config["SampleParameters"]["gamma"] == mde_oriented_lattice.gamma()
267+
268+
u_array = np.array(mde_config["SampleParameters"]["u"].split(","), dtype=float)
269+
assert u_array == pytest.approx(mde_oriented_lattice.getuVector())
270+
v_array = np.array(mde_config["SampleParameters"]["v"].split(","), dtype=float)
271+
assert v_array == pytest.approx(mde_oriented_lattice.getvVector())

0 commit comments

Comments
 (0)