Skip to content

Commit

Permalink
Merge pull request #85 from neutrons/useful_script
Browse files Browse the repository at this point in the history
Clean up script generation
  • Loading branch information
AndreiSavici authored May 18, 2023
2 parents 2865d60 + 27ca8d1 commit 27fd82e
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 17 deletions.
38 changes: 27 additions & 11 deletions src/shiver/models/histogram.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ def load(self, filename, ws_type):
"""Method to take filename and workspace type and load with correct algorithm"""
ws_name, _ = os.path.splitext(os.path.basename(filename))

additional_parameters = {}
if ws_type == "mde":
logger.information(f"Loading {filename} as MDE")
load = AlgorithmManager.create("LoadMD")
Expand All @@ -41,6 +42,7 @@ def load(self, filename, ws_type):
elif ws_type == "norm":
logger.information(f"Loading {filename} as normalization")
load = AlgorithmManager.create("LoadNexusProcessed")
additional_parameters = {"LoadHistory": False}
else:
logger.error(f"Unsupported workspace type {ws_type} for {filename}")

Expand All @@ -54,6 +56,8 @@ def load(self, filename, ws_type):
try:
load.setProperty("Filename", filename)
load.setProperty("OutputWorkspace", ws_name)
for key, value in additional_parameters.items():
load.setProperty(key, value)
load.executeAsync()
except ValueError as err:
logger.error(str(err))
Expand Down Expand Up @@ -237,19 +241,31 @@ def save_history(self, ws_name, filename):
"""Save the mantid algorithm history"""
history = mtd[ws_name].getHistory()

script = [f"from mantid.simpleapi import {', '.join(alg.name() for alg in history.getAlgorithmHistories())}"]
script = [
"import shiver",
f"from mantid.simpleapi import {', '.join(set(alg.name() for alg in history.getAlgorithmHistories()))}",
"",
"",
]

previous_name = ""
for alg in history.getAlgorithmHistories():
script.append(
"{}({})".format( # pylint: disable=consider-using-f-string
alg.name(),
", ".join(
f"{p.name()}='{alg.getPropertyValue(p.name())}'"
for p in alg.getProperties()
if alg.getPropertyValue(p.name())
),
)
)
alg_name = alg.name()
if alg_name == "LoadMD" and previous_name == "GenerateDGSMDE":
comment = "# "
else:
comment = ""
previous_name = alg_name
separator = ",\n" + comment + "\t"
alg_props = []
for prop in alg.getProperties():
default = prop.isDefault()
value = prop.value()
if value and not default:
value = value.replace('"', "'")
alg_props.append(f'{prop.name()}="{value}"')
alg_props = separator.join(alg_props)
script.append(f"{comment}{alg_name}({alg_props})")

with open(filename, "w", encoding="utf-8") as f_open:
f_open.write("\n".join(script))
Expand Down
6 changes: 4 additions & 2 deletions src/shiver/views/loading_buttons.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,10 @@ def __init__(self, parent=None):
self.load_dataset_callback = None
self.error_msg_callback = None

# disable generate dataset button (not implemented for phase 1)
self.gen_dataset.setEnabled(False)
self.gen_dataset.clicked.connect(self._gen_dataset_click)

def _gen_dataset_click(self):
self.parent().parent().parent().setCurrentIndex(1)

def _on_load_mde_click(self):
filename, _ = QFileDialog.getOpenFileName(
Expand Down
9 changes: 5 additions & 4 deletions tests/models/test_histogram_saving.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,10 @@ def test_saving(tmp_path):
with open(tmp_path / "test_workspace.py", encoding="utf-8") as f_open:
lines = f_open.readlines()

assert len(lines) == 2
assert lines[0] == "from mantid.simpleapi import CreateMDHistoWorkspace\n"
assert len(lines) == 12
assert lines[0] == "import shiver\n"
assert lines[1] == "from mantid.simpleapi import CreateMDHistoWorkspace\n"
assert (
lines[1] == "CreateMDHistoWorkspace(SignalInput='2,3', ErrorInput='1,1', Dimensionality='1', "
"Extents='-2,2', NumberOfBins='2', Names='A', Units='a', OutputWorkspace='test_workspace')"
" ".join([line.strip() for line in lines[4:]]) == 'CreateMDHistoWorkspace(SignalInput="2,3", ErrorInput="1,1", '
'Dimensionality="1", Extents="-2,2", NumberOfBins="2", Names="A", Units="a", OutputWorkspace="test_workspace")'
)

1 comment on commit 27fd82e

@github-actions
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

GitLab pipeline for shiver-dev has been submitted for this commit: "https://code.ornl.gov/sns-hfir-scse/deployments/conda-legacy-deploy/-/pipelines/382840"

Please sign in to comment.