From 849317481152e17ffb871e1f7ffe8fbc890f03ed Mon Sep 17 00:00:00 2001 From: Applin Date: Thu, 14 Sep 2023 11:30:51 +0100 Subject: [PATCH 01/18] Add ability to specify color to recoil overplot --- src/mslice/cli/__init__.py | 4 ++-- src/mslice/plotting/plot_window/overplot_interface.py | 4 ++-- src/mslice/presenters/cut_plotter_presenter.py | 4 ++-- src/mslice/presenters/slice_plotter_presenter.py | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/mslice/cli/__init__.py b/src/mslice/cli/__init__.py index cb8360afd..eeb633403 100644 --- a/src/mslice/cli/__init__.py +++ b/src/mslice/cli/__init__.py @@ -36,7 +36,7 @@ def pcolormesh(self, *args, **kwargs): else: return Axes.pcolormesh(self, *args, **kwargs) - def recoil(self, workspace, element=None, rmm=None): + def recoil(self, workspace, element=None, rmm=None, **kwargs): from mslice.app.presenters import get_slice_plotter_presenter _check_workspace_name(workspace) workspace = get_workspace_handle(workspace) @@ -48,7 +48,7 @@ def recoil(self, workspace, element=None, rmm=None): plot_handler = GlobalFigureManager.get_active_figure().plot_handler plot_handler._arb_nuclei_rmm = rmm - get_slice_plotter_presenter().add_overplot_line(workspace.name, key, recoil=True, cif=None) + get_slice_plotter_presenter().add_overplot_line(workspace.name, key, recoil=True, cif=None, **kwargs) _update_overplot_checklist(key) _update_legend() diff --git a/src/mslice/plotting/plot_window/overplot_interface.py b/src/mslice/plotting/plot_window/overplot_interface.py index 9dfc86ff0..1153f0dd9 100644 --- a/src/mslice/plotting/plot_window/overplot_interface.py +++ b/src/mslice/plotting/plot_window/overplot_interface.py @@ -71,8 +71,8 @@ def remove_line(line): plt.gca().lines.remove(line) -def plot_overplot_line(x, y, key, recoil, cache): - color = OVERPLOT_COLORS[key] if key in OVERPLOT_COLORS else 'c' +def plot_overplot_line(x, y, key, recoil, cache, **kwargs): + color = kwargs.get('color', OVERPLOT_COLORS.get(key, 'c')) if recoil: return overplot_line(x, y, color, get_recoil_label(key), cache.rotated) else: diff --git a/src/mslice/presenters/cut_plotter_presenter.py b/src/mslice/presenters/cut_plotter_presenter.py index 2737de75c..bd560db66 100644 --- a/src/mslice/presenters/cut_plotter_presenter.py +++ b/src/mslice/presenters/cut_plotter_presenter.py @@ -186,7 +186,7 @@ def _get_log_bragg_y_coords(size, portion_of_axes, datum): return np.resize(np.array([10 ** adj_factor, 10 ** (-adj_factor), np.nan]), size) * datum def add_overplot_line(self, workspace_name, key, recoil, cif=None, e_is_logarithmic=None, datum=0, - intensity_correction=IntensityType.SCATTERING_FUNCTION): + intensity_correction=IntensityType.SCATTERING_FUNCTION, **kwargs): cache = self._cut_cache_dict[plt.gca()][0] if cache.rotated: warnings.warn("No Bragg peak found as cut has no |Q| dimension.") @@ -209,7 +209,7 @@ def add_overplot_line(self, workspace_name, key, recoil, cif=None, e_is_logarith else: y = self._get_log_bragg_y_coords(len(y), BRAGG_SIZE_ON_AXES, datum) - self._overplot_cache[key] = plot_overplot_line(x, y, key, recoil, cache) + self._overplot_cache[key] = plot_overplot_line(x, y, key, recoil, cache, **kwargs) except (ValueError, IndexError): warnings.warn("No Bragg peak found.") diff --git a/src/mslice/presenters/slice_plotter_presenter.py b/src/mslice/presenters/slice_plotter_presenter.py index 118338244..1ee17f66e 100644 --- a/src/mslice/presenters/slice_plotter_presenter.py +++ b/src/mslice/presenters/slice_plotter_presenter.py @@ -93,14 +93,14 @@ def hide_overplot_line(self, workspace, key): remove_line(line) def add_overplot_line(self, workspace_name, key, recoil, cif=None, y_has_logarithmic=None, datum=None, - intensity_correction=None): + intensity_correction=None, **kwargs): cache = self._slice_cache[workspace_name] if recoil: x, y = compute_recoil_line(workspace_name, cache.momentum_axis, key) else: x, y = compute_powder_line(workspace_name, cache.momentum_axis, key, cif_file=cif) y = convert_energy_to_meV(y, cache.energy_axis.e_unit) - cache.overplot_lines[key] = plot_overplot_line(x, y, key, recoil, cache) + cache.overplot_lines[key] = plot_overplot_line(x, y, key, recoil, cache, **kwargs) def validate_intensity(self, intensity_start, intensity_end): intensity_start = self._to_float(intensity_start) From 2ad8bb0b1fc32d6914abcb34fdc393d390c856e2 Mon Sep 17 00:00:00 2001 From: Applin Date: Thu, 14 Sep 2023 11:32:26 +0100 Subject: [PATCH 02/18] Add ability to specify color to bragg overplot --- src/mslice/cli/__init__.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/mslice/cli/__init__.py b/src/mslice/cli/__init__.py index eeb633403..21a9217be 100644 --- a/src/mslice/cli/__init__.py +++ b/src/mslice/cli/__init__.py @@ -53,7 +53,7 @@ def recoil(self, workspace, element=None, rmm=None, **kwargs): _update_overplot_checklist(key) _update_legend() - def bragg(self, workspace, element=None, cif=None): + def bragg(self, workspace, element=None, cif=None, **kwargs): from mslice.app.presenters import get_cut_plotter_presenter, get_slice_plotter_presenter _check_workspace_name(workspace) workspace = get_workspace_handle(workspace) @@ -62,9 +62,9 @@ def bragg(self, workspace, element=None, cif=None): ws_type = _get_workspace_type(workspace) if ws_type == 'HistogramWorkspace': - get_cut_plotter_presenter().add_overplot_line(workspace.name, key, recoil=True, cif=None) + get_cut_plotter_presenter().add_overplot_line(workspace.name, key, recoil=True, cif=None, **kwargs) elif ws_type == 'MatrixWorkspace': - get_slice_plotter_presenter().add_overplot_line(workspace.name, key, recoil=False, cif=cif) + get_slice_plotter_presenter().add_overplot_line(workspace.name, key, recoil=False, cif=cif, **kwargs) _update_overplot_checklist(key) _update_legend() From b6d17171c05185f077c5461a68a721eab04aebe0 Mon Sep 17 00:00:00 2001 From: Applin Date: Thu, 14 Sep 2023 11:44:31 +0100 Subject: [PATCH 03/18] Propagate line color to generated script --- src/mslice/scripting/helperfunctions.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/mslice/scripting/helperfunctions.py b/src/mslice/scripting/helperfunctions.py index b20643d9a..a2ac5d252 100644 --- a/src/mslice/scripting/helperfunctions.py +++ b/src/mslice/scripting/helperfunctions.py @@ -97,6 +97,7 @@ def add_overplot_statements(script_lines, plot_handler): line_artists = ax.lines for line in line_artists: + color = line._color label = line._label if "nolegend" in label: continue @@ -108,15 +109,15 @@ def add_overplot_statements(script_lines, plot_handler): if recoil: if element is None: - script_lines.append("ax.recoil(workspace='{}', rmm={})\n".format(plot_handler.ws_name, rmm)) + script_lines.append(f"ax.recoil(workspace='{plot_handler.ws_name}', rmm={rmm}, color='{color}')\n") else: - script_lines.append("ax.recoil(workspace='{}', element='{}')\n".format(plot_handler.ws_name, element)) + script_lines.append(f"ax.recoil(workspace='{plot_handler.ws_name}', element='{element}', color='{color}')\n") else: if cif is None: - script_lines.append("ax.bragg(workspace='{}', element='{}')\n".format(plot_handler.ws_name, element)) + script_lines.append(f"ax.bragg(workspace='{plot_handler.ws_name}', element='{element}', color='{color}')\n") else: - script_lines.append("ax.bragg(workspace='{}', cif='{}')\n".format(plot_handler.ws_name, cif)) + script_lines.append(f"ax.bragg(workspace='{plot_handler.ws_name}', cif='{cif}', color='{color}')\n") def add_cut_plot_statements(script_lines, plot_handler, ax): From bba2578fe1a63b47542dc6c627463727a0e7af4a Mon Sep 17 00:00:00 2001 From: Applin Date: Thu, 14 Sep 2023 11:57:09 +0100 Subject: [PATCH 04/18] Update tests to ensure color is passed to script lines --- tests/scripting_helperfunctions_test.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/tests/scripting_helperfunctions_test.py b/tests/scripting_helperfunctions_test.py index 48d81f3e5..117e096b7 100644 --- a/tests/scripting_helperfunctions_test.py +++ b/tests/scripting_helperfunctions_test.py @@ -179,32 +179,32 @@ def test_that_add_overplot_statements_works_as_expected_with_recoil_element(self add_overplot_statements(script_lines, plot_handler) - self.assertIn("ax.recoil(workspace='{}', element='{}')\n".format(workspace_name, "Hydrogen"), script_lines) + self.assertIn(f"ax.recoil(workspace='{workspace_name}', element='Hydrogen', color='C0')\n", script_lines) @mock.patch('mslice.cli._mslice_commands.GlobalFigureManager') def test_that_add_overplot_statements_works_as_expected_with_arbitrary_nuclei(self, gfm): plot_handler = gfm.get_active_figure().plot_handler plot_handler.add_mock_spec(SlicePlot) self.assign_slice_parameters(plot_handler) - plot_handler._canvas.figure.gca().lines = [Line2D([1, 2], [1, 2], label="Relative Mass 55")] + plot_handler._canvas.figure.gca().lines = [Line2D([1, 2], [1, 2], label="Relative Mass 55", color="red")] workspace_name = plot_handler.ws_name script_lines = [] add_overplot_statements(script_lines, plot_handler) - self.assertIn("ax.recoil(workspace='{}', rmm={})\n".format(workspace_name, 55), script_lines) + self.assertIn(f"ax.recoil(workspace='{workspace_name}', rmm=55, color='red')\n", script_lines) @mock.patch('mslice.cli._mslice_commands.GlobalFigureManager') def test_that_add_overplot_statements_works_as_expected_with_bragg_peaks_elements(self, gfm): plot_handler = gfm.get_active_figure().plot_handler plot_handler.add_mock_spec(SlicePlot) - plot_handler._canvas.figure.gca().lines = [Line2D([1, 2], [1, 2], label="Tantalum")] + plot_handler._canvas.figure.gca().lines = [Line2D([1, 2], [1, 2], label="Tantalum", color="green")] workspace_name = plot_handler.ws_name script_lines = [] add_overplot_statements(script_lines, plot_handler) - self.assertIn("ax.bragg(workspace='{}', element='{}')\n".format(workspace_name, "Tantalum"), script_lines) + self.assertIn(f"ax.bragg(workspace='{workspace_name}', element='Tantalum', color='green')\n", script_lines) @mock.patch('mslice.scripting.helperfunctions.add_plot_options') @mock.patch('mslice.scripting.helperfunctions.add_cut_lines') From a1cd08290067882b0751898700a446b3b9456d36 Mon Sep 17 00:00:00 2001 From: MialLewis <95620982+MialLewis@users.noreply.github.com> Date: Thu, 14 Sep 2023 12:33:57 +0100 Subject: [PATCH 05/18] ensure filename is raw string --- src/mslice/scripting/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/mslice/scripting/__init__.py b/src/mslice/scripting/__init__.py index e02594295..c1611c2ee 100644 --- a/src/mslice/scripting/__init__.py +++ b/src/mslice/scripting/__init__.py @@ -98,7 +98,7 @@ def get_algorithm_kwargs(algorithm, existing_ws_refs): continue if algorithm.name() == "Load": if prop.name() == "Filename": - arguments += [f"{prop.name()}='{pval}'"] + arguments += [f"{prop.name()}=r'{pval}'"] continue elif prop.name() == "LoaderName" or prop.name() == "LoaderVersion": continue From 5c318833a693dda844c62e9d3d506c214fcc6c3f Mon Sep 17 00:00:00 2001 From: MialLewis <95620982+MialLewis@users.noreply.github.com> Date: Fri, 15 Sep 2023 11:40:17 +0100 Subject: [PATCH 06/18] change intensity range to default to tuple --- src/mslice/cli/_mslice_commands.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/mslice/cli/_mslice_commands.py b/src/mslice/cli/_mslice_commands.py index 030ee5cd8..0dc70ec84 100644 --- a/src/mslice/cli/_mslice_commands.py +++ b/src/mslice/cli/_mslice_commands.py @@ -275,7 +275,7 @@ def PlotCut(InputWorkspace, IntensityStart=0, IntensityEnd=0, PlotOver=False): raise RuntimeError("Incorrect workspace type.") if IntensityStart == 0 and IntensityEnd == 0: - intensity_range = None + intensity_range = (None, None) else: intensity_range = (IntensityStart, IntensityEnd) from mslice.app.presenters import cli_cut_plotter_presenter From 2125be340db8a3d328a329baccaa0250975866d2 Mon Sep 17 00:00:00 2001 From: MialLewis <95620982+MialLewis@users.noreply.github.com> Date: Fri, 15 Sep 2023 11:47:52 +0100 Subject: [PATCH 07/18] fix unit tests --- tests/command_line_test.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/command_line_test.py b/tests/command_line_test.py index e57752bcb..4e842438b 100644 --- a/tests/command_line_test.py +++ b/tests/command_line_test.py @@ -224,7 +224,7 @@ def test_plot_cut(self, cpp, is_gui): workspace = self.create_pixel_workspace('test_plot_cut_cli') cut = Cut(workspace) PlotCut(cut) - cpp.plot_cut_from_workspace.assert_called_once_with(cut, intensity_range=None, plot_over=False) + cpp.plot_cut_from_workspace.assert_called_once_with(cut, intensity_range=(None, None), plot_over=False) @mock.patch('mslice.cli._mslice_commands.is_gui') @mock.patch('mslice.app.presenters.cli_cut_plotter_presenter') @@ -233,7 +233,7 @@ def test_plot_cut_non_psd(self, cpp, is_gui): workspace = self.create_workspace('test_plot_cut_non_psd_cli') cut = Cut(workspace) PlotCut(cut) - cpp.plot_cut_from_workspace.assert_called_once_with(cut, intensity_range=None, plot_over=False) + cpp.plot_cut_from_workspace.assert_called_once_with(cut, intensity_range=(None, None), plot_over=False) @mock.patch('mantid.plots.axesfunctions.errorbar') @mock.patch('mslice.cli._mslice_commands.is_gui') From 7139e445b80f389e6fb7eb0bccec9f3fd8957aab Mon Sep 17 00:00:00 2001 From: MialLewis <95620982+MialLewis@users.noreply.github.com> Date: Fri, 15 Sep 2023 12:04:57 +0100 Subject: [PATCH 08/18] add unit test --- tests/scripting_tests.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/tests/scripting_tests.py b/tests/scripting_tests.py index b9640daf2..a1146dfbd 100644 --- a/tests/scripting_tests.py +++ b/tests/scripting_tests.py @@ -253,3 +253,18 @@ def test_generate_script_produces_the_same_script_for_file_and_clipboard(self, m mock_clipboard.assert_called_once() self.assertEqual(fake_clipboard.text, fake_file.text) + + def test_that_get_algorithm_kwargs_produces_raw_string_for_loaded_filename(self): + some_alg = mock.MagicMock() + some_alg.name.return_value = 'Load' + + some_alg_prop = mock.MagicMock() + some_alg_prop.name.return_value = "Filename" + some_alg_prop.isDefault.return_value = False + some_alg_prop.value.return_value = "test_filename" + + some_alg.getProperties.return_value = [some_alg_prop] + + args, _ = get_algorithm_kwargs(some_alg, 'workspace_name') + + self.assertEqual("Filename=r'test_filename'", args) From 4b5b5fe8a8ae729f3adb2e0980ed8c4b19707215 Mon Sep 17 00:00:00 2001 From: MialLewis <95620982+MialLewis@users.noreply.github.com> Date: Fri, 15 Sep 2023 16:12:56 +0100 Subject: [PATCH 09/18] roll back is_slice change to if conditional --- .../models/workspacemanager/workspace_algorithms.py | 10 +++++----- src/mslice/plotting/plot_window/plot_figure_manager.py | 3 +-- tests/file_io_test.py | 2 +- 3 files changed, 7 insertions(+), 8 deletions(-) diff --git a/src/mslice/models/workspacemanager/workspace_algorithms.py b/src/mslice/models/workspacemanager/workspace_algorithms.py index 942bb1a36..adab616d7 100644 --- a/src/mslice/models/workspacemanager/workspace_algorithms.py +++ b/src/mslice/models/workspacemanager/workspace_algorithms.py @@ -236,13 +236,12 @@ def scale_workspaces(workspaces, scale_factor=None, from_temp=None, to_temp=None propagate_properties(ws, result) -def save_workspaces(workspaces, path, save_name, extension, slice_nonpsd=False): +def save_workspaces(workspaces, path, save_name, extension): """ :param workspaces: list of workspaces to save :param path: directory to save to :param save_name: name to save the file as (plus file extension). Pass none to use workspace name :param extension: file extension (such as .txt) - :param slice_nonpsd: whether the selection is in non_psd mode """ if extension == '.nxs': save_method = save_nexus @@ -265,7 +264,7 @@ def save_workspaces(workspaces, path, save_name, extension, slice_nonpsd=False): if len(save_names) != len(workspaces): save_names = [None] * len(workspaces) for workspace, save_name_single in zip(workspaces, save_names): - _save_single_ws(workspace, save_name_single, save_method, path, extension, slice_nonpsd) + _save_single_ws(workspace, save_name_single, save_method, path, extension) def export_workspace_to_ads(workspace): @@ -279,11 +278,12 @@ def export_workspace_to_ads(workspace): add_to_ads(workspace) -def _save_single_ws(workspace, save_name, save_method, path, extension, slice_nonpsd): +def _save_single_ws(workspace, save_name, save_method, path, extension): save_as = save_name if save_name is not None else str(workspace) + extension full_path = os.path.join(str(path), save_as) workspace = get_workspace_handle(workspace) - if workspace.is_slice: + non_psd_slice = isinstance(workspace, Workspace) and not workspace.is_PSD + if is_pixel_workspace(workspace) or non_psd_slice: workspace = _get_slice_mdhisto(workspace, get_workspace_name(workspace)) save_method(workspace, full_path) diff --git a/src/mslice/plotting/plot_window/plot_figure_manager.py b/src/mslice/plotting/plot_window/plot_figure_manager.py index 2a54ff32d..51bc823bd 100644 --- a/src/mslice/plotting/plot_window/plot_figure_manager.py +++ b/src/mslice/plotting/plot_window/plot_figure_manager.py @@ -222,8 +222,7 @@ def save_plot(self): save_workspaces(workspaces, file_path, save_name, - ext, - slice_nonpsd=True) + ext) except RuntimeError as e: if str(e) == "unrecognised file extension": supported_image_types = list( diff --git a/tests/file_io_test.py b/tests/file_io_test.py index d0e2ff797..b665ee1dd 100644 --- a/tests/file_io_test.py +++ b/tests/file_io_test.py @@ -112,4 +112,4 @@ def test_to_absolute_path_returns_a_path_in_the_default_save_dir_if_the_path_pro ConfigService.setString("defaultsave.directory", default_save_directory) rel_path = "datadir/filename.txt" - self.assertEqual(f"{default_save_directory}/{rel_path}", _to_absolute_path(rel_path)) + self.assertEqual(join(default_save_directory, rel_path), _to_absolute_path(rel_path)) From 1657ac81bf38b8605035f3e181e0d09d5b95150b Mon Sep 17 00:00:00 2001 From: MialLewis <95620982+MialLewis@users.noreply.github.com> Date: Tue, 19 Sep 2023 16:38:44 +0100 Subject: [PATCH 10/18] fix scriptig plot_over issue --- src/mslice/scripting/helperfunctions.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/mslice/scripting/helperfunctions.py b/src/mslice/scripting/helperfunctions.py index a2ac5d252..9c85d94ff 100644 --- a/src/mslice/scripting/helperfunctions.py +++ b/src/mslice/scripting/helperfunctions.py @@ -201,15 +201,16 @@ def add_cut_lines_with_width(errorbars, script_lines, cuts, intensity_correction '\n'.format(index, replace_ws_special_chars(cut.parent_ws_name), cut_axis, integration_axis, norm_to_one, algo_str, intensity_correction_arg, cut.raw_sample_temp)) + plot_over = False if index == 0 else True if intensity_range != (None, None): script_lines.append( 'ax.errorbar(cut_ws_{}, label="{}", color="{}", marker="{}", ls="{}", ' - 'lw={}, intensity_range={})\n\n'.format(index, label, colour, marker, style, width, - intensity_range)) + 'lw={}, intensity_range={}, plot_over={})\n\n'.format(index, label, colour, marker, style, width, + intensity_range, plot_over)) else: script_lines.append( 'ax.errorbar(cut_ws_{}, label="{}", color="{}", marker="{}", ls="{}", ' - 'lw={})\n\n'.format(index, label, colour, marker, style, width)) + 'lw={}, plot_over={})\n\n'.format(index, label, colour, marker, style, width, plot_over)) cut_start, cut_end = cut_end, min(cut_end + cut.width, integration_end) index += 1 From 89686b6cf5da94b70b3517aadd76eb45dd1bf08f Mon Sep 17 00:00:00 2001 From: MialLewis <95620982+MialLewis@users.noreply.github.com> Date: Tue, 19 Sep 2023 16:55:41 +0100 Subject: [PATCH 11/18] update helper fns to f string --- src/mslice/scripting/helperfunctions.py | 50 ++++++++++++------------- 1 file changed, 23 insertions(+), 27 deletions(-) diff --git a/src/mslice/scripting/helperfunctions.py b/src/mslice/scripting/helperfunctions.py index 9c85d94ff..a96e8eb9a 100644 --- a/src/mslice/scripting/helperfunctions.py +++ b/src/mslice/scripting/helperfunctions.py @@ -13,7 +13,7 @@ def header(plot_handler): """Creates a list of import statements to be used in the generated script header""" from mslice.plotting.plot_window.cut_plot import CutPlot from mslice.plotting.plot_window.slice_plot import SlicePlot - statements = ["# Python Script Generated by Mslice on {}\n".format(datetime.now().replace(microsecond=0))] + statements = [f"# Python Script Generated by Mslice on {datetime.now().replace(microsecond=0)}\n"] statements.append("\n".join(COMMON_PACKAGES)) if isinstance(plot_handler, SlicePlot) and plot_handler.colorbar_log is True: @@ -63,25 +63,25 @@ def add_slice_plot_statements(script_lines, plot_handler): energy_axis = str(slice.energy_axis) norm = slice.norm_to_one - script_lines.append('slice_ws = mc.Slice(ws_{}, Axis1="{}", Axis2="{}", NormToOne={})\n\n'.format( - plot_handler.ws_name.replace(".", "_"), momentum_axis, energy_axis, norm)) + script_lines.append(f'slice_ws = mc.Slice(ws_{plot_handler.ws_name.replace(".", "_")}, Axis1="{momentum_axis}", Axis2="{energy_axis}",' + f'NormToOne={norm})\n\n') if plot_handler.intensity is True: intensity = IntensityCache.get_desc_from_type(plot_handler.intensity_type) if plot_handler.temp_dependent: - script_lines.append('mesh = ax.pcolormesh(slice_ws, cmap="{}", intensity="{}", temperature={})\n'.format( - cache[plot_handler.ws_name].colourmap, intensity, plot_handler.temp)) + script_lines.append(f'mesh = ax.pcolormesh(slice_ws, cmap="{cache[plot_handler.ws_name].colourmap}", intensity="{intensity}",' + f'temperature={plot_handler.temp})\n') else: - script_lines.append('mesh = ax.pcolormesh(slice_ws, cmap="{}", intensity="{}")\n'.format( - cache[plot_handler.ws_name].colourmap, intensity)) + script_lines.append(f'mesh = ax.pcolormesh(slice_ws, cmap="{cache[plot_handler.ws_name].colourmap}",' + f'intensity="{intensity}")\n') else: - script_lines.append('mesh = ax.pcolormesh(slice_ws, cmap="{}")\n'.format(cache[plot_handler.ws_name].colourmap)) + script_lines.append(f'mesh = ax.pcolormesh(slice_ws, cmap="{cache[plot_handler.ws_name].colourmap}")\n') - script_lines.append("mesh.set_clim({}, {})\n".format(*plot_handler.colorbar_range)) + script_lines.append(f"mesh.set_clim({plot_handler.colorbar_range[0]}, {plot_handler.colorbar_range[1]})\n") if plot_handler.colorbar_log: min, maximum = plot_handler.colorbar_range[0], plot_handler.colorbar_range[1] min = max(min, LOG_SCALE_MIN) - script_lines.append("mesh.set_norm(colors.LogNorm({}, {}))\n".format(min, maximum)) + script_lines.append(f"mesh.set_norm(colors.LogNorm({min}, {maximum}))\n") script_lines.append("cb = plt.colorbar(mesh, ax=ax)\n") script_lines.append(f"cb.set_label('{plot_handler.colorbar_label}', labelpad=20, rotation=270, picker=5, " @@ -179,7 +179,7 @@ def add_cut_lines_with_width(errorbars, script_lines, cuts, intensity_correction cut_start, cut_end = integration_start, min(integration_start + cut.width, integration_end) intensity_range = (cut.intensity_start, cut.intensity_end) norm_to_one = cut.norm_to_one - algo_str = '' if 'Rebin' in cut.algorithm else ', Algorithm="{}"'.format(cut.algorithm) + algo_str = '' if 'Rebin' in cut.algorithm else f', Algorithm="{cut.algorithm}"' while cut_start != cut_end and index < len(errorbars): cut.integration_axis.start = cut_start @@ -196,21 +196,19 @@ def add_cut_lines_with_width(errorbars, script_lines, cuts, intensity_correction intensity_correction_arg = f"'{IntensityCache.get_desc_from_type(intensity_correction)}'" \ if not intensity_correction == IntensityType.SCATTERING_FUNCTION else False - script_lines.append('cut_ws_{} = mc.Cut(ws_{}, CutAxis="{}", IntegrationAxis="{}", ' - 'NormToOne={}{}, IntensityCorrection={}, SampleTemperature={})' - '\n'.format(index, replace_ws_special_chars(cut.parent_ws_name), cut_axis, integration_axis, - norm_to_one, algo_str, intensity_correction_arg, cut.raw_sample_temp)) + script_lines.append(f'cut_ws_{index} = mc.Cut(ws_{replace_ws_special_chars(cut.parent_ws_name)}, CutAxis="{cut_axis}", ' + f'IntegrationAxis="{integration_axis}", NormToOne={norm_to_one}{algo_str},' + f'IntensityCorrection={intensity_correction_arg}, SampleTemperature={cut.raw_sample_temp})\n') plot_over = False if index == 0 else True if intensity_range != (None, None): script_lines.append( - 'ax.errorbar(cut_ws_{}, label="{}", color="{}", marker="{}", ls="{}", ' - 'lw={}, intensity_range={}, plot_over={})\n\n'.format(index, label, colour, marker, style, width, - intensity_range, plot_over)) + f'ax.errorbar(cut_ws_{index}, label="{label}", color="{colour}", marker="{marker}", ls="{style}", ' + f'lw={width}, intensity_range={intensity_range}, plot_over={plot_over})\n\n') else: script_lines.append( - 'ax.errorbar(cut_ws_{}, label="{}", color="{}", marker="{}", ls="{}", ' - 'lw={}, plot_over={})\n\n'.format(index, label, colour, marker, style, width, plot_over)) + f'ax.errorbar(cut_ws_{index}, label="{label}", color="{colour}", marker="{marker}", ls="{style}", ' + f'lw={width}, plot_over={plot_over})\n\n') cut_start, cut_end = cut_end, min(cut_end + cut.width, integration_end) index += 1 @@ -228,16 +226,16 @@ def add_plot_options(script_lines, plot_handler): script_lines.append(f"ax.set_xlabel(r'{plot_handler.x_label}', fontsize={plot_handler.x_label_size})\n") if plot_handler.is_changed("y_grid"): - script_lines.append("ax.grid({}, axis='y')\n".format(plot_handler.y_grid)) + script_lines.append(f"ax.grid({plot_handler.y_grid}, axis='y')\n") if plot_handler.is_changed("x_grid"): - script_lines.append("ax.grid({}, axis='x')\n".format(plot_handler.x_grid)) + script_lines.append(f"ax.grid({plot_handler.x_grid}, axis='x')\n") if plot_handler.is_changed("y_range"): - script_lines.append("ax.set_ylim(bottom={}, top={})\n".format(*plot_handler.y_range)) + script_lines.append(f"ax.set_ylim(bottom={plot_handler.y_range[0]}, top={plot_handler.y_range[1]})\n") if plot_handler.is_changed("x_range"): - script_lines.append("ax.set_xlim(left={}, right={})\n".format(*plot_handler.x_range)) + script_lines.append(f"ax.set_xlim(left={plot_handler.x_range[0]}, right={plot_handler.x_range[1]})\n") if plot_handler.is_changed("y_range_font_size"): script_lines.append(f"ax.yaxis.set_tick_params(labelsize={plot_handler.y_range_font_size})\n") @@ -247,9 +245,7 @@ def add_plot_options(script_lines, plot_handler): from mslice.plotting.plot_window.cut_plot import CutPlot if isinstance(plot_handler, CutPlot) and plot_handler.is_changed("waterfall"): - script_lines.append("ax.set_waterfall({}, {}, {})\n".format(plot_handler.waterfall, - plot_handler.waterfall_x, - plot_handler.waterfall_y)) + script_lines.append(f"ax.set_waterfall({plot_handler.waterfall}, {plot_handler.waterfall_x},{plot_handler.waterfall_y})\n") def replace_ws_special_chars(workspace_name): From 79fff9476e848d516848917712fcd19ced6d67f5 Mon Sep 17 00:00:00 2001 From: MialLewis <95620982+MialLewis@users.noreply.github.com> Date: Tue, 19 Sep 2023 17:28:09 +0100 Subject: [PATCH 12/18] fix and extend unit tests --- src/mslice/scripting/helperfunctions.py | 8 ++++---- tests/scripting_helperfunctions_test.py | 22 +++++++++++++++++----- 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/src/mslice/scripting/helperfunctions.py b/src/mslice/scripting/helperfunctions.py index a96e8eb9a..ed7083e3a 100644 --- a/src/mslice/scripting/helperfunctions.py +++ b/src/mslice/scripting/helperfunctions.py @@ -63,16 +63,16 @@ def add_slice_plot_statements(script_lines, plot_handler): energy_axis = str(slice.energy_axis) norm = slice.norm_to_one - script_lines.append(f'slice_ws = mc.Slice(ws_{plot_handler.ws_name.replace(".", "_")}, Axis1="{momentum_axis}", Axis2="{energy_axis}",' + script_lines.append(f'slice_ws = mc.Slice(ws_{plot_handler.ws_name.replace(".", "_")}, Axis1="{momentum_axis}", Axis2="{energy_axis}", ' f'NormToOne={norm})\n\n') if plot_handler.intensity is True: intensity = IntensityCache.get_desc_from_type(plot_handler.intensity_type) if plot_handler.temp_dependent: - script_lines.append(f'mesh = ax.pcolormesh(slice_ws, cmap="{cache[plot_handler.ws_name].colourmap}", intensity="{intensity}",' + script_lines.append(f'mesh = ax.pcolormesh(slice_ws, cmap="{cache[plot_handler.ws_name].colourmap}", intensity="{intensity}", ' f'temperature={plot_handler.temp})\n') else: - script_lines.append(f'mesh = ax.pcolormesh(slice_ws, cmap="{cache[plot_handler.ws_name].colourmap}",' + script_lines.append(f'mesh = ax.pcolormesh(slice_ws, cmap="{cache[plot_handler.ws_name].colourmap}", ' f'intensity="{intensity}")\n') else: script_lines.append(f'mesh = ax.pcolormesh(slice_ws, cmap="{cache[plot_handler.ws_name].colourmap}")\n') @@ -197,7 +197,7 @@ def add_cut_lines_with_width(errorbars, script_lines, cuts, intensity_correction intensity_correction_arg = f"'{IntensityCache.get_desc_from_type(intensity_correction)}'" \ if not intensity_correction == IntensityType.SCATTERING_FUNCTION else False script_lines.append(f'cut_ws_{index} = mc.Cut(ws_{replace_ws_special_chars(cut.parent_ws_name)}, CutAxis="{cut_axis}", ' - f'IntegrationAxis="{integration_axis}", NormToOne={norm_to_one}{algo_str},' + f'IntegrationAxis="{integration_axis}", NormToOne={norm_to_one}{algo_str}, ' f'IntensityCorrection={intensity_correction_arg}, SampleTemperature={cut.raw_sample_temp})\n') plot_over = False if index == 0 else True diff --git a/tests/scripting_helperfunctions_test.py b/tests/scripting_helperfunctions_test.py index 117e096b7..09c0f6fc0 100644 --- a/tests/scripting_helperfunctions_test.py +++ b/tests/scripting_helperfunctions_test.py @@ -299,8 +299,8 @@ def test_that_add_cut_lines_with_width_works_as_expected_without_intensity_range False, None), script_lines) self.assertIn( - 'ax.errorbar(cut_ws_{}, label="{}", color="{}", marker="{}", ls="{}", lw={})\n\n'.format( - 0, 'errorbar_label', 'blue', None, '-', 1.5), script_lines) + 'ax.errorbar(cut_ws_{}, label="{}", color="{}", marker="{}", ls="{}", lw={}, plot_over={})\n\n'.format( + 0, 'errorbar_label', 'blue', None, '-', 1.5, False), script_lines) def test_that_add_cut_lines_with_width_works_as_expected_with_intensity_range(self): x_data, y_data = np.arange(0, 10), np.arange(0, 10) @@ -316,7 +316,7 @@ def test_that_add_cut_lines_with_width_works_as_expected_with_intensity_range(se self.assertIn( 'ax.errorbar(cut_ws_{}, label="{}", color="{}", marker="{}", ls="{}", lw={}, ' - 'intensity_range={})\n\n'.format(0, 'errorbar_label', 'blue', None, '-', 1.5, (1.0, 2.0)), + 'intensity_range={}, plot_over={})\n\n'.format(0, 'errorbar_label', 'blue', None, '-', 1.5, (1.0, 2.0), False), script_lines) def test_that_add_cut_lines_with_width_works_as_expected_with_multiple_cuts(self): @@ -350,8 +350,20 @@ def test_that_add_cut_lines_with_width_works_as_expected_with_multiple_cuts(self 'SampleTemperature={})\n'.format(2, 'ws_1', cuts[1].cut_axis, cuts[1].integration_axis, cuts[1].norm_to_one, False, None), script_lines) - # Each mc.Cut statement has a corresponding errorbar statement - self.assertEqual(len(script_lines), 6) + self.assertIn( + 'ax.errorbar(cut_ws_{}, label="{}", color="{}", marker="{}", ls="{}", lw={}, ' + 'intensity_range={}, plot_over={})\n\n'.format(0, 'error_label_0', 'blue', None, '-', 1.5, (1.0, 2.0), False), + script_lines) + + self.assertIn( + 'ax.errorbar(cut_ws_{}, label="{}", color="{}", marker="{}", ls="{}", lw={}, ' + 'intensity_range={}, plot_over={})\n\n'.format(1, 'error_label_1', 'blue', None, '-', 1.5, (1.0, 2.0), True), + script_lines) + + self.assertIn( + 'ax.errorbar(cut_ws_{}, label="{}", color="{}", marker="{}", ls="{}", lw={}, ' + 'intensity_range={}, plot_over={})\n\n'.format(2, 'error_label_2', 'blue', None, '-', 1.5, (1.0, 2.0), True), + script_lines) def test_show_or_hide_containers_in_script(self): fig, ax = plt.subplots() From ba26a101d1e6f3b9ef038236393b7b6d9609a30b Mon Sep 17 00:00:00 2001 From: MialLewis <95620982+MialLewis@users.noreply.github.com> Date: Tue, 19 Sep 2023 17:53:20 +0100 Subject: [PATCH 13/18] clear figure between each test --- tests/scripting_helperfunctions_test.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/scripting_helperfunctions_test.py b/tests/scripting_helperfunctions_test.py index 09c0f6fc0..005f3a208 100644 --- a/tests/scripting_helperfunctions_test.py +++ b/tests/scripting_helperfunctions_test.py @@ -15,6 +15,9 @@ class ScriptingHelperFunctionsTest(unittest.TestCase): + def tearDown(self) -> None: + plt.gcf().clf() + def assign_slice_parameters(self, plot_handler, intensity=True, temp_dependent=True): plot_handler.colorbar_label = 'colorbar_label' plot_handler.colorbar_label_size = 10 From 842ebf229b983ef25907946746308697a1ca78c9 Mon Sep 17 00:00:00 2001 From: MialLewis <95620982+MialLewis@users.noreply.github.com> Date: Wed, 20 Sep 2023 09:14:45 +0100 Subject: [PATCH 14/18] fix scripting issue ws name --- src/mslice/plotting/plot_window/cut_plot.py | 1 + src/mslice/scripting/helperfunctions.py | 1 - 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/src/mslice/plotting/plot_window/cut_plot.py b/src/mslice/plotting/plot_window/cut_plot.py index bc0dd5d05..ca8964b15 100644 --- a/src/mslice/plotting/plot_window/cut_plot.py +++ b/src/mslice/plotting/plot_window/cut_plot.py @@ -515,6 +515,7 @@ def on_newplot(self, plot_over, ws_name): self.plot_window.toggle_waterfall_edit() if not plot_over: self._reset_plot_window_options() + self.ws_name = ws_name all_lines = [line for container in line_containers for line in container.get_children()] for cached_lines in list(self._waterfall_cache.keys()): diff --git a/src/mslice/scripting/helperfunctions.py b/src/mslice/scripting/helperfunctions.py index ed7083e3a..cad3eb274 100644 --- a/src/mslice/scripting/helperfunctions.py +++ b/src/mslice/scripting/helperfunctions.py @@ -115,7 +115,6 @@ def add_overplot_statements(script_lines, plot_handler): else: if cif is None: script_lines.append(f"ax.bragg(workspace='{plot_handler.ws_name}', element='{element}', color='{color}')\n") - else: script_lines.append(f"ax.bragg(workspace='{plot_handler.ws_name}', cif='{cif}', color='{color}')\n") From 215b0e1cb361b479a6b1c8fba70b0dfba58bf521 Mon Sep 17 00:00:00 2001 From: MialLewis <95620982+MialLewis@users.noreply.github.com> Date: Wed, 20 Sep 2023 10:27:52 +0100 Subject: [PATCH 15/18] use var name rather than ws name --- src/mslice/scripting/helperfunctions.py | 28 +++++++++++++++---------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/src/mslice/scripting/helperfunctions.py b/src/mslice/scripting/helperfunctions.py index cad3eb274..aa279588f 100644 --- a/src/mslice/scripting/helperfunctions.py +++ b/src/mslice/scripting/helperfunctions.py @@ -47,8 +47,8 @@ def add_plot_statements(script_lines, plot_handler, ax): add_slice_plot_statements(script_lines, plot_handler) add_overplot_statements(script_lines, plot_handler) elif isinstance(plot_handler, CutPlot): - add_cut_plot_statements(script_lines, plot_handler, ax) - add_overplot_statements(script_lines, plot_handler) + return_ws_vars = add_cut_plot_statements(script_lines, plot_handler, ax) + add_overplot_statements(script_lines, plot_handler, return_ws_vars) script_lines.append("mc.Show()\n") @@ -91,7 +91,7 @@ def add_slice_plot_statements(script_lines, plot_handler): add_plot_options(script_lines, plot_handler) -def add_overplot_statements(script_lines, plot_handler): +def add_overplot_statements(script_lines, plot_handler, cut_ws_vars): """Adds overplot line statements to the script if they were plotted""" ax = plot_handler._canvas.figure.gca() line_artists = ax.lines @@ -107,22 +107,23 @@ def add_overplot_statements(script_lines, plot_handler): recoil = True if rmm is not None or key in [1, 2, 4] else False cif = None # Does not yet account for CIF files + ws_var = cut_ws_vars.pop(0) if recoil: if element is None: - script_lines.append(f"ax.recoil(workspace='{plot_handler.ws_name}', rmm={rmm}, color='{color}')\n") + script_lines.append(f"ax.recoil(workspace={ws_var}, rmm={rmm}, color='{color}')\n") else: - script_lines.append(f"ax.recoil(workspace='{plot_handler.ws_name}', element='{element}', color='{color}')\n") + script_lines.append(f"ax.recoil(workspace={ws_var}, element='{element}', color='{color}')\n") else: if cif is None: - script_lines.append(f"ax.bragg(workspace='{plot_handler.ws_name}', element='{element}', color='{color}')\n") + script_lines.append(f"ax.bragg(workspace={ws_var}, element='{element}', color='{color}')\n") else: - script_lines.append(f"ax.bragg(workspace='{plot_handler.ws_name}', cif='{cif}', color='{color}')\n") + script_lines.append(f"ax.bragg(workspace={ws_var}, cif='{cif}', color='{color}')\n") def add_cut_plot_statements(script_lines, plot_handler, ax): """Adds cut specific statements to the script""" - add_cut_lines(script_lines, plot_handler, ax) + return_ws_vars = add_cut_lines(script_lines, plot_handler, ax) add_plot_options(script_lines, plot_handler) if plot_handler.is_changed("x_log"): @@ -132,14 +133,16 @@ def add_cut_plot_statements(script_lines, plot_handler, ax): if plot_handler.is_changed("y_log"): script_lines.append(f"ax.set_yscale('symlog', " f"linthresh=pow(10, np.floor(np.log10({plot_handler.y_axis_min}))))\n") + return return_ws_vars def add_cut_lines(script_lines, plot_handler, ax): cuts = plot_handler._cut_plotter_presenter._cut_cache_dict[ax] errorbars = plot_handler._canvas.figure.gca().containers intensity_correction = plot_handler.intensity_type - add_cut_lines_with_width(errorbars, script_lines, cuts, intensity_correction) + return_cut_vars = add_cut_lines_with_width(errorbars, script_lines, cuts, intensity_correction) hide_lines(script_lines, plot_handler, ax) + return return_cut_vars def hide_lines(script_lines, plot_handler, ax): @@ -172,6 +175,7 @@ def hide_lines(script_lines, plot_handler, ax): def add_cut_lines_with_width(errorbars, script_lines, cuts, intensity_correction): """Adds the cut statements for each interval of the cuts that were plotted""" index = 0 # Required as we run through the loop multiple times for each cut + return_ws_vars = [] for cut in cuts: integration_start = cut.integration_axis.start integration_end = cut.integration_axis.end @@ -195,10 +199,11 @@ def add_cut_lines_with_width(errorbars, script_lines, cuts, intensity_correction intensity_correction_arg = f"'{IntensityCache.get_desc_from_type(intensity_correction)}'" \ if not intensity_correction == IntensityType.SCATTERING_FUNCTION else False - script_lines.append(f'cut_ws_{index} = mc.Cut(ws_{replace_ws_special_chars(cut.parent_ws_name)}, CutAxis="{cut_axis}", ' + cut_ws = f'cut_ws_{index}' + script_lines.append(f'{cut_ws} = mc.Cut(ws_{replace_ws_special_chars(cut.parent_ws_name)}, CutAxis="{cut_axis}", ' f'IntegrationAxis="{integration_axis}", NormToOne={norm_to_one}{algo_str}, ' f'IntensityCorrection={intensity_correction_arg}, SampleTemperature={cut.raw_sample_temp})\n') - + return_ws_vars.append(cut_ws) plot_over = False if index == 0 else True if intensity_range != (None, None): script_lines.append( @@ -212,6 +217,7 @@ def add_cut_lines_with_width(errorbars, script_lines, cuts, intensity_correction cut_start, cut_end = cut_end, min(cut_end + cut.width, integration_end) index += 1 cut.reset_integration_axis(cut.start, cut.end) + return return_ws_vars def add_plot_options(script_lines, plot_handler): From 93205ba1accc75068f17c346007366c4ed1ac5e4 Mon Sep 17 00:00:00 2001 From: MialLewis <95620982+MialLewis@users.noreply.github.com> Date: Wed, 20 Sep 2023 11:18:44 +0100 Subject: [PATCH 16/18] fix unit tests --- src/mslice/scripting/helperfunctions.py | 4 ++-- tests/scripting_helperfunctions_test.py | 15 ++++++++------- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/src/mslice/scripting/helperfunctions.py b/src/mslice/scripting/helperfunctions.py index aa279588f..563c73f6b 100644 --- a/src/mslice/scripting/helperfunctions.py +++ b/src/mslice/scripting/helperfunctions.py @@ -91,7 +91,7 @@ def add_slice_plot_statements(script_lines, plot_handler): add_plot_options(script_lines, plot_handler) -def add_overplot_statements(script_lines, plot_handler, cut_ws_vars): +def add_overplot_statements(script_lines, plot_handler, ws_vars=None): """Adds overplot line statements to the script if they were plotted""" ax = plot_handler._canvas.figure.gca() line_artists = ax.lines @@ -107,7 +107,7 @@ def add_overplot_statements(script_lines, plot_handler, cut_ws_vars): recoil = True if rmm is not None or key in [1, 2, 4] else False cif = None # Does not yet account for CIF files - ws_var = cut_ws_vars.pop(0) + ws_var = ws_vars.pop(0) if ws_vars else f"'{plot_handler.ws_name}'" if recoil: if element is None: script_lines.append(f"ax.recoil(workspace={ws_var}, rmm={rmm}, color='{color}')\n") diff --git a/tests/scripting_helperfunctions_test.py b/tests/scripting_helperfunctions_test.py index 005f3a208..222612e9c 100644 --- a/tests/scripting_helperfunctions_test.py +++ b/tests/scripting_helperfunctions_test.py @@ -82,11 +82,12 @@ def test_that_add_plot_statements_works_as_expected_for_cuts(self, add_overplot, fig = mock.MagicMock() ax = fig.add_subplot(111, projection='mslice') + add_cut.return_value = mock.MagicMock() add_plot_statements(script_lines, plot_handler, ax) add_header.assert_called_once_with(script_lines, plot_handler) add_cut.assert_called_once_with(script_lines, plot_handler, ax) - add_overplot.assert_called_once_with(script_lines, plot_handler) + add_overplot.assert_called_once_with(script_lines, plot_handler, add_cut.return_value) self.assertIn("mc.Show()\n", script_lines) self.assertIn('fig = plt.gcf()\n', script_lines) @@ -175,39 +176,39 @@ def test_that_add_slice_plot_statements_works_with_intensity_and_no_temp_depende def test_that_add_overplot_statements_works_as_expected_with_recoil_element(self, gfm): plot_handler = gfm.get_active_figure().plot_handler plot_handler.add_mock_spec(SlicePlot) + plot_handler.ws_name = 'test_ws_name' self.assign_slice_parameters(plot_handler) plot_handler._canvas.figure.gca().lines = [Line2D([1, 2], [1, 2], label="Hydrogen")] - workspace_name = plot_handler.ws_name script_lines = [] add_overplot_statements(script_lines, plot_handler) - self.assertIn(f"ax.recoil(workspace='{workspace_name}', element='Hydrogen', color='C0')\n", script_lines) + self.assertIn(f"ax.recoil(workspace='{plot_handler.ws_name}', element='Hydrogen', color='C0')\n", script_lines) @mock.patch('mslice.cli._mslice_commands.GlobalFigureManager') def test_that_add_overplot_statements_works_as_expected_with_arbitrary_nuclei(self, gfm): plot_handler = gfm.get_active_figure().plot_handler plot_handler.add_mock_spec(SlicePlot) + plot_handler.ws_name = 'test_ws_name' self.assign_slice_parameters(plot_handler) plot_handler._canvas.figure.gca().lines = [Line2D([1, 2], [1, 2], label="Relative Mass 55", color="red")] - workspace_name = plot_handler.ws_name script_lines = [] add_overplot_statements(script_lines, plot_handler) - self.assertIn(f"ax.recoil(workspace='{workspace_name}', rmm=55, color='red')\n", script_lines) + self.assertIn(f"ax.recoil(workspace='{plot_handler.ws_name}', rmm=55, color='red')\n", script_lines) @mock.patch('mslice.cli._mslice_commands.GlobalFigureManager') def test_that_add_overplot_statements_works_as_expected_with_bragg_peaks_elements(self, gfm): plot_handler = gfm.get_active_figure().plot_handler plot_handler.add_mock_spec(SlicePlot) plot_handler._canvas.figure.gca().lines = [Line2D([1, 2], [1, 2], label="Tantalum", color="green")] - workspace_name = plot_handler.ws_name + plot_handler.ws_name = 'test_ws_name' script_lines = [] add_overplot_statements(script_lines, plot_handler) - self.assertIn(f"ax.bragg(workspace='{workspace_name}', element='Tantalum', color='green')\n", script_lines) + self.assertIn(f"ax.bragg(workspace='{plot_handler.ws_name}', element='Tantalum', color='green')\n", script_lines) @mock.patch('mslice.scripting.helperfunctions.add_plot_options') @mock.patch('mslice.scripting.helperfunctions.add_cut_lines') From cd094bdeb5bbd952860311b79459b2fe9e73d11e Mon Sep 17 00:00:00 2001 From: MialLewis <95620982+MialLewis@users.noreply.github.com> Date: Wed, 20 Sep 2023 11:23:57 +0100 Subject: [PATCH 17/18] test for return of ws var --- tests/scripting_helperfunctions_test.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/tests/scripting_helperfunctions_test.py b/tests/scripting_helperfunctions_test.py index 222612e9c..56cf216a1 100644 --- a/tests/scripting_helperfunctions_test.py +++ b/tests/scripting_helperfunctions_test.py @@ -185,6 +185,18 @@ def test_that_add_overplot_statements_works_as_expected_with_recoil_element(self self.assertIn(f"ax.recoil(workspace='{plot_handler.ws_name}', element='Hydrogen', color='C0')\n", script_lines) + @mock.patch('mslice.cli._mslice_commands.GlobalFigureManager') + def test_that_add_overplot_statements_works_as_expected_with_recoil_element_with_cut_ws_var(self, gfm): + plot_handler = gfm.get_active_figure().plot_handler + plot_handler.add_mock_spec(CutPlot) + self.assign_cut_parameters(plot_handler) + plot_handler._canvas.figure.gca().lines = [Line2D([1, 2], [1, 2], label="Hydrogen")] + script_lines = [] + + add_overplot_statements(script_lines, plot_handler, ['test_ws_name']) + + self.assertIn("ax.recoil(workspace=test_ws_name, element='Hydrogen', color='C0')\n", script_lines) + @mock.patch('mslice.cli._mslice_commands.GlobalFigureManager') def test_that_add_overplot_statements_works_as_expected_with_arbitrary_nuclei(self, gfm): plot_handler = gfm.get_active_figure().plot_handler From 2737647dc8bec5b1cef61b752ba74233048f48bd Mon Sep 17 00:00:00 2001 From: MialLewis <95620982+MialLewis@users.noreply.github.com> Date: Wed, 20 Sep 2023 11:42:07 +0100 Subject: [PATCH 18/18] extend tests to check return of vars --- src/mslice/scripting/helperfunctions.py | 4 ++-- tests/scripting_helperfunctions_test.py | 22 +++++++++++++++++----- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/src/mslice/scripting/helperfunctions.py b/src/mslice/scripting/helperfunctions.py index 563c73f6b..22035e668 100644 --- a/src/mslice/scripting/helperfunctions.py +++ b/src/mslice/scripting/helperfunctions.py @@ -140,9 +140,9 @@ def add_cut_lines(script_lines, plot_handler, ax): cuts = plot_handler._cut_plotter_presenter._cut_cache_dict[ax] errorbars = plot_handler._canvas.figure.gca().containers intensity_correction = plot_handler.intensity_type - return_cut_vars = add_cut_lines_with_width(errorbars, script_lines, cuts, intensity_correction) + return_ws_vars = add_cut_lines_with_width(errorbars, script_lines, cuts, intensity_correction) hide_lines(script_lines, plot_handler, ax) - return return_cut_vars + return return_ws_vars def hide_lines(script_lines, plot_handler, ax): diff --git a/tests/scripting_helperfunctions_test.py b/tests/scripting_helperfunctions_test.py index 56cf216a1..b4c140f1b 100644 --- a/tests/scripting_helperfunctions_test.py +++ b/tests/scripting_helperfunctions_test.py @@ -233,7 +233,9 @@ def test_that_add_cut_plot_statements_works_as_expected(self, gfm, add_cut_lines fig = mock.MagicMock() ax = fig.add_subplot(111, projection='mslice') - add_cut_plot_statements(script_lines, plot_handler, ax) + add_cut_lines.return_value = ['test_ws_var'] + + ret_val = add_cut_plot_statements(script_lines, plot_handler, ax) add_cut_lines.assert_called_once_with(script_lines, plot_handler, ax) add_plot_options.assert_called_once_with(script_lines, plot_handler) @@ -242,6 +244,7 @@ def test_that_add_cut_plot_statements_works_as_expected(self, gfm, add_cut_lines plot_handler.x_axis_min), script_lines) self.assertIn("ax.set_yscale('symlog', linthresh=pow(10, np.floor(np.log10({}))))\n".format( plot_handler.y_axis_min), script_lines) + self.assertEqual(['test_ws_var'], ret_val) @mock.patch('mslice.scripting.helperfunctions.add_cut_lines_with_width') @mock.patch('mslice.cli._mslice_commands.GlobalFigureManager') @@ -253,14 +256,17 @@ def test_that_add_cut_lines_works_as_expected(self, gfm, add_cut_lines_with_widt plot_handler.add_mock_spec(CutPlot) plot_handler.intensity_type = IntensityType.SCATTERING_FUNCTION + add_cut_lines_with_width.return_value = ['test_ws_var'] + script_lines = [] - add_cut_lines(script_lines, plot_handler, ax) + ret_val = add_cut_lines(script_lines, plot_handler, ax) cuts = plot_handler._cut_plotter_presenter._cut_cache_dict[ax] errorbars = plot_handler._canvas.figure.gca().containers add_cut_lines_with_width.assert_called_once_with(errorbars, script_lines, cuts, plot_handler.intensity_type) + self.assertEqual(['test_ws_var'], ret_val) @mock.patch('mslice.cli._mslice_commands.GlobalFigureManager') def test_that_add_plot_options_works_as_expected(self, gfm): @@ -307,7 +313,8 @@ def test_that_add_cut_lines_with_width_works_as_expected_without_intensity_range cuts = [cut] script_lines = [] - add_cut_lines_with_width(errorbars, script_lines, cuts, IntensityType.SCATTERING_FUNCTION) + ret_val = add_cut_lines_with_width(errorbars, script_lines, cuts, IntensityType.SCATTERING_FUNCTION) + pass self.assertIn( 'cut_ws_{} = mc.Cut(ws_{}, CutAxis="{}", IntegrationAxis="{}", NormToOne={}, IntensityCorrection={}, ' @@ -318,6 +325,8 @@ def test_that_add_cut_lines_with_width_works_as_expected_without_intensity_range 'ax.errorbar(cut_ws_{}, label="{}", color="{}", marker="{}", ls="{}", lw={}, plot_over={})\n\n'.format( 0, 'errorbar_label', 'blue', None, '-', 1.5, False), script_lines) + self.assertEqual(['cut_ws_0'], ret_val) + def test_that_add_cut_lines_with_width_works_as_expected_with_intensity_range(self): x_data, y_data = np.arange(0, 10), np.arange(0, 10) plt.errorbar(x_data, y_data, linestyle='-', linewidth=1.5, color='blue', label='errorbar_label') @@ -328,12 +337,13 @@ def test_that_add_cut_lines_with_width_works_as_expected_with_intensity_range(se cuts = [cut] script_lines = [] - add_cut_lines_with_width(errorbars, script_lines, cuts, IntensityType.SCATTERING_FUNCTION) + ret_val = add_cut_lines_with_width(errorbars, script_lines, cuts, IntensityType.SCATTERING_FUNCTION) self.assertIn( 'ax.errorbar(cut_ws_{}, label="{}", color="{}", marker="{}", ls="{}", lw={}, ' 'intensity_range={}, plot_over={})\n\n'.format(0, 'errorbar_label', 'blue', None, '-', 1.5, (1.0, 2.0), False), script_lines) + self.assertEqual(['cut_ws_0'], ret_val) def test_that_add_cut_lines_with_width_works_as_expected_with_multiple_cuts(self): x_data, y_data = np.arange(0, 10), np.arange(0, 10) @@ -349,7 +359,7 @@ def test_that_add_cut_lines_with_width_works_as_expected_with_multiple_cuts(self cuts = [cut_0, cut_2] script_lines = [] - add_cut_lines_with_width(errorbars, script_lines, cuts, IntensityType.SCATTERING_FUNCTION) + ret_val = add_cut_lines_with_width(errorbars, script_lines, cuts, IntensityType.SCATTERING_FUNCTION) self.assertIn( 'cut_ws_{} = mc.Cut(ws_{}, CutAxis="{}", IntegrationAxis="{}", NormToOne={}, IntensityCorrection={}, ' @@ -381,6 +391,8 @@ def test_that_add_cut_lines_with_width_works_as_expected_with_multiple_cuts(self 'intensity_range={}, plot_over={})\n\n'.format(2, 'error_label_2', 'blue', None, '-', 1.5, (1.0, 2.0), True), script_lines) + self.assertEqual(['cut_ws_0', 'cut_ws_1', 'cut_ws_2'], ret_val) + def test_show_or_hide_containers_in_script(self): fig, ax = plt.subplots() ax.errorbar([1], [2], [0.3], label="label1")