def setUp(self): self.plots_loader = PlotsLoader() plt.plot = mock.MagicMock() mantid.plots.plotfunctions.plot = mock.MagicMock() self.dictionary = {u'legend': {u'exists': False}, u'lines': [], u'properties': {u'axisOn': True, u'bounds': (0.0, 0.0, 0.0, 0.0), u'dynamic': True, u'frameOn': True, u'visible': True, u'xAxisProperties': {u'fontSize': 10.0, u'gridStyle': {u'gridOn': False}, u'majorTickFormat': None, u'majorTickFormatter': 'ScalarFormatter', u'majorTickLocator': 'AutoLocator', u'majorTickLocatorValues': None, u'minorTickFormat': None, u'minorTickFormatter': 'NullFormatter', u'minorTickLocator': 'NullLocator', u'minorTickLocatorValues': None, u'position': u'Bottom', u'visible': True}, u'xAxisScale': u'linear', u'xLim': (0.0, 1.0), u'yAxisProperties': {u'fontSize': 10.0, u'gridStyle': {u'gridOn': False}, u'majorTickFormat': None, u'majorTickFormatter': 'ScalarFormatter', u'majorTickLocator': 'AutoLocator', u'majorTickLocatorValues': None, u'minorTickFormat': None, u'minorTickFormatter': 'NullFormatter', u'minorTickLocator': 'NullLocator', u'minorTickLocatorValues': None, u'position': u'Left', u'visible': True}, u'yAxisScale': u'linear', u'yLim': (0.0, 1.0)}, u'textFromArtists': {}, u'texts': [], u'title': u'', u'xAxisTitle': u'', u'yAxisTitle': u''}
class ProjectLoader(object): def __init__(self, project_file_ext): self.project_reader = ProjectReader(project_file_ext) self.workspace_loader = WorkspaceLoader() self.plot_loader = PlotsLoader() self.decoder_factory = DecoderFactory() self.project_file_ext = project_file_ext def load_project(self, file_name, load_workspaces=True): """ Will load the project in the given file_name :param file_name: String or string castable object; the file_name of the project :param load_workspaces: Bool; True if you want ProjectLoader to handle loading workspaces else False. :return: Bool; True if all workspace loaded successfully, False if not loaded successfully. """ # It can be expected that if at this point it is NoneType that it's an error if file_name is None: return # Read project self.project_reader.read_project(file_name) directory = os.path.dirname(file_name) # Load in the workspaces if load_workspaces: self.workspace_loader.load_workspaces( directory=directory, workspaces_to_load=self.project_reader.workspace_names) workspace_success = _confirm_all_workspaces_loaded( workspaces_to_confirm=self.project_reader.workspace_names) if workspace_success: # Load plots if self.project_reader.plot_list is not None: self.plot_loader.load_plots(self.project_reader.plot_list) # Load interfaces if self.project_reader.interface_list is not None: self.load_interfaces(directory=directory) return workspace_success def load_interfaces(self, directory): for interface in self.project_reader.interface_list: # Find decoder decoder = self.decoder_factory.find_decoder(interface["tag"]) # Decode and Show the interface try: decoded_interface = decoder.decode(interface, directory) decoded_interface.show() except Exception as e: # Catch any exception and log it for the encoder if isinstance(e, KeyboardInterrupt): raise logger.warning( "Project Loader: An interface could not be loaded error: " + str(e))
def test_update_axis_ticks_format(self): fig, ax = plt.subplots() x_axis = ax.xaxis x_axis.set_major_formatter(LogFormatterSciNotation()) x_axis.set_minor_formatter(LogFormatterSciNotation()) PlotsLoader.update_axis_ticks( x_axis, self.dictionary['properties']['xAxisProperties']) self.assertIsInstance(x_axis.get_major_formatter(), ScalarFormatter) self.assertIsInstance(x_axis.get_minor_formatter(), NullFormatter)
class ProjectLoader(object): def __init__(self, project_file_ext): self.project_reader = ProjectReader(project_file_ext) self.workspace_loader = WorkspaceLoader() self.plot_loader = PlotsLoader() self.decoder_factory = DecoderFactory() self.project_file_ext = project_file_ext def load_project(self, file_name, load_workspaces=True): """ Will load the project in the given file_name :param file_name: String or string castable object; the file_name of the project :param load_workspaces: Bool; True if you want ProjectLoader to handle loading workspaces else False. :return: Bool; True if all workspace loaded successfully, False if not loaded successfully. """ # It can be expected that if at this point it is NoneType that it's an error if file_name is None: return # Read project self.project_reader.read_project(file_name) directory = os.path.dirname(file_name) # Load in the workspaces if load_workspaces: self.workspace_loader.load_workspaces(directory=directory, workspaces_to_load=self.project_reader.workspace_names) workspace_success = _confirm_all_workspaces_loaded(workspaces_to_confirm=self.project_reader.workspace_names) if workspace_success: # Load plots if self.project_reader.plot_list is not None: self.plot_loader.load_plots(self.project_reader.plot_list) # Load interfaces if self.project_reader.interface_list is not None: self.load_interfaces(directory=directory) return workspace_success def load_interfaces(self, directory): for interface in self.project_reader.interface_list: # Find decoder decoder = self.decoder_factory.find_decoder(interface["tag"]) # Decode and Show the interface try: decoded_interface = decoder.decode(interface, directory) decoded_interface.show() except Exception as e: # Catch any exception and log it for the encoder if isinstance(e, KeyboardInterrupt): raise logger.warning("Project Loader: An interface could not be loaded error: " + str(e))
class PlotsLoaderTest(unittest.TestCase): def setUp(self): self.plots_loader = PlotsLoader() plt.plot = mock.MagicMock() mantid.plots.plotfunctions.plot = mock.MagicMock() self.dictionary = {u'legend': {u'exists': False}, u'lines': [], u'properties': {u'axisOn': True, u'bounds': (0.0, 0.0, 0.0, 0.0), u'dynamic': True, u'frameOn': True, u'visible': True, u'xAxisProperties': {u'fontSize': 10.0, u'gridStyle': {u'gridOn': False}, u'majorTickFormat': None, u'majorTickFormatter': 'ScalarFormatter', u'majorTickLocator': 'AutoLocator', u'majorTickLocatorValues': None, u'minorTickFormat': None, u'minorTickFormatter': 'NullFormatter', u'minorTickLocator': 'NullLocator', u'minorTickLocatorValues': None, u'position': u'Bottom', u'visible': True}, u'xAxisScale': u'linear', u'xLim': (0.0, 1.0), u'yAxisProperties': {u'fontSize': 10.0, u'gridStyle': {u'gridOn': False}, u'majorTickFormat': None, u'majorTickFormatter': 'ScalarFormatter', u'majorTickLocator': 'AutoLocator', u'majorTickLocatorValues': None, u'minorTickFormat': None, u'minorTickFormatter': 'NullFormatter', u'minorTickLocator': 'NullLocator', u'minorTickLocatorValues': None, u'position': u'Left', u'visible': True}, u'yAxisScale': u'linear', u'yLim': (0.0, 1.0)}, u'textFromArtists': {}, u'texts': [], u'title': u'', u'xAxisTitle': u'', u'yAxisTitle': u''} def test_load_plots_does_the_right_calls(self): self.plots_loader.make_fig = mock.MagicMock() self.plots_loader.load_plots(["plot1", "plot2"]) self.assertEqual(self.plots_loader.make_fig.call_count, 2) @mock.patch("matplotlib.figure.Figure.show") def test_make_fig_makes_the_right_calls(self, pass_func): ws = Workspace2D() ADS.add("ws", ws) plot_dict = {"label": "plot", "creationArguments": [[{"workspaces": "ws", "wkspIndex": 0}, {}, {}]]} self.plots_loader.plot_extra_lines = mock.MagicMock() self.plots_loader.plot_func = mock.MagicMock() self.plots_loader.restore_figure_data = mock.MagicMock() self.plots_loader.make_fig(plot_dict) self.assertEqual(self.plots_loader.plot_func.call_count, 1) self.assertEqual(self.plots_loader.plot_extra_lines.call_count, 1) self.assertEqual(self.plots_loader.restore_figure_data.call_count, 1) def test_restore_fig_properties(self): matplotlib.figure.Figure.set_figheight = mock.MagicMock() matplotlib.figure.Figure.set_figwidth = mock.MagicMock() matplotlib.figure.Figure.set_dpi = mock.MagicMock() self.plots_loader.restore_fig_properties(matplotlib.figure.Figure(), {"figHeight": 1, "figWidth": 1, "dpi": 1}) self.assertEqual(matplotlib.figure.Figure.set_figheight.call_count, 1) self.assertEqual(matplotlib.figure.Figure.set_figwidth.call_count, 1) self.assertEqual(matplotlib.figure.Figure.set_dpi.call_count, 1) def test_restore_fig_axes(self): self.plots_loader.update_properties = mock.MagicMock() self.plots_loader.update_lines = mock.MagicMock() self.plots_loader.create_text_from_dict = mock.MagicMock() self.plots_loader.update_legend = mock.MagicMock() fig = matplotlib.figure.Figure() self.plots_loader.restore_fig_axes(matplotlib.axes.Axes(fig=fig, rect=[0, 0, 0, 0]), self.dictionary) self.assertEqual(self.plots_loader.update_properties.call_count, 1) self.assertEqual(self.plots_loader.update_lines.call_count, 0) self.assertEqual(self.plots_loader.create_text_from_dict.call_count, 0) self.assertEqual(self.plots_loader.update_legend.call_count, 1) def test_create_text_from_dict(self): fig = matplotlib.figure.Figure() ax = matplotlib.axes.Axes(fig=fig, rect=[0, 0, 0, 0]) ax.text = mock.MagicMock() self.plots_loader.create_text_from_dict(ax=ax, dic={"text": "text", "position": (1, 1), "useTeX": 1, "style": {"alpha": 1, "textSize": 1, "color": 1, "hAlign": 1, "vAlign": 1, "rotation": 1, "zOrder": 1}}) self.assertEqual(ax.text.call_count, 1) ax.text.assert_called_once_with(fontdict={u'zorder': 1, u'fontsize': 1, u'color': 1, u'alpha': 1, u'rotation': 1, u'verticalalignment': 1, u'usetex': 1, u'horizontalalignment': 1}, s=u'text', x=1, y=1) @mock.patch("matplotlib.figure.Figure.show") def test_load_plot_from_dict(self, pass_func): # The fact this runs is the test self.plots_loader.load_plots([self.dictionary])
def setUp(self): CreateSampleWorkspace(OutputWorkspace="ws1") self.plots_loader = PlotsLoader() # Make a figure with a given input with all these values already set self.loader_plot_dict = { u'axes': [{ u'colorbar': { u'exists': False }, u'legend': { u'exists': True, u'visible': True, u'title': "Legend", u'background_color': u'#ffffff', u'edge_color': u'#000000', u'transparency': 0.5, u'entries_font': u'DejaVu Sans', u'entries_size': 10.0, u'entries_color': u'#000000', u'title_font': u'DejaVu Sans', u'title_size': 12.0, u'title_color': u'#000000', u'marker_size': 2.0, u'box_visible': True, u'shadow': False, u'round_edges': True, u'columns': 1, u'column_spacing': 0.5, u'label_spacing': 0.5, u'marker_position': u'Left of Entries', u'markers': 1, u'border_padding': 0.5, u'marker_label_padding': 1.0 }, u'lines': [{ u'alpha': 1, u'color': u'#1f77b4', u'label': u'ws1: spec 2', u'lineIndex': 0, u'lineStyle': u'-', u'lineWidth': 1.5, u'markerStyle': { u'edgeColor': u'#1f77b4', u'edgeWidth': 1.0, u'faceColor': u'#1f77b4', u'markerSize': 6.0, u'markerType': u'None', u'zOrder': 2 }, u'errorbars': { u'exists': False } }], u'properties': { u'axisOn': True, u'bounds': (0.0, 0.0, 0.0, 0.0), u'dynamic': True, u'frameOn': True, u'visible': True, u'xAxisProperties': { u'fontSize': 10.0, u'gridStyle': { u'gridOn': False }, u'majorTickFormat': None, u'majorTickFormatter': u'ScalarFormatter', u'majorTickLocator': u'AutoLocator', u'majorTickLocatorValues': None, u'minorTickFormat': None, u'minorTickFormatter': u'NullFormatter', u'minorTickLocator': u'NullLocator', u'minorTickLocatorValues': None, u'visible': True }, u'xAxisScale': u'linear', u'xLim': (0.0, 1.0), u"xAutoScale": False, u'yAxisProperties': { u'fontSize': 10.0, u'gridStyle': { u'gridOn': False }, u'majorTickFormat': None, u'majorTickFormatter': u'ScalarFormatter', u'majorTickLocator': u'AutoLocator', u'majorTickLocatorValues': None, u'minorTickFormat': None, u'minorTickFormatter': u'NullFormatter', u'minorTickLocator': u'NullLocator', u'minorTickLocatorValues': None, u'visible': True }, u'yAxisScale': u'linear', u'yLim': (0.0, 1.0), u"yAutoScale": False, u"facecolor": (0.0, 0.0, 0.0, 0.0), u'showMinorGrid': False, u'tickParams': { 'xaxis': { 'major': { 'bottom': True, 'top': True, 'labelbottom': True, 'labeltop': True, 'direction': 'inout', 'width': 1, 'size': 6 }, 'minor': { 'bottom': True, 'top': True, 'labelbottom': True, 'labeltop': True, 'direction': 'inout', 'width': 1, 'size': 3 } }, 'yaxis': { 'major': { 'left': True, 'right': True, 'labelleft': True, 'labelright': True, 'direction': 'inout', 'width': 1, 'size': 6 }, 'minor': { 'left': True, 'right': True, 'labelleft': True, 'labelright': True, 'direction': 'inout', 'width': 1, 'size': 3 } } }, u'spineWidths': { 'left': 0.4, 'right': 0.4, 'bottom': 0.4, 'top': 0.4 } }, u'textFromArtists': {}, u'texts': [{ u'position': (0, 0), u'style': { u'alpha': 1, u'color': u'#000000', u'hAlign': u'left', u'rotation': 0.0, u'textSize': 10.0, u'vAlign': u'baseline', u'zOrder': 3 }, u'text': u'text', u'useTeX': False }], u'title': u'', u'xAxisTitle': u'', u'yAxisTitle': u'' }], u'creationArguments': [[{ u"workspaces": u"ws1", u"specNum": 2, u"function": u"plot" }]], u'label': u'', u'properties': { u'dpi': 100.0, u'figHeight': 4.8, u'figWidth': 6.4 } } self.fig = self.plots_loader.make_fig(self.loader_plot_dict, create_plot=False) self.plot_saver = PlotsSaver()
class PlotsSaverTest(unittest.TestCase): def setUp(self): CreateSampleWorkspace(OutputWorkspace="ws1") self.plots_loader = PlotsLoader() # Make a figure with a given input with all these values already set self.loader_plot_dict = { u'axes': [{ u'colorbar': { u'exists': False }, u'legend': { u'exists': True, u'visible': True, u'title': "Legend", u'background_color': u'#ffffff', u'edge_color': u'#000000', u'transparency': 0.5, u'entries_font': u'DejaVu Sans', u'entries_size': 10.0, u'entries_color': u'#000000', u'title_font': u'DejaVu Sans', u'title_size': 12.0, u'title_color': u'#000000', u'marker_size': 2.0, u'box_visible': True, u'shadow': False, u'round_edges': True, u'columns': 1, u'column_spacing': 0.5, u'label_spacing': 0.5, u'marker_position': u'Left of Entries', u'markers': 1, u'border_padding': 0.5, u'marker_label_padding': 1.0 }, u'lines': [{ u'alpha': 1, u'color': u'#1f77b4', u'label': u'ws1: spec 2', u'lineIndex': 0, u'lineStyle': u'-', u'lineWidth': 1.5, u'markerStyle': { u'edgeColor': u'#1f77b4', u'edgeWidth': 1.0, u'faceColor': u'#1f77b4', u'markerSize': 6.0, u'markerType': u'None', u'zOrder': 2 }, u'errorbars': { u'exists': False } }], u'properties': { u'axisOn': True, u'bounds': (0.0, 0.0, 0.0, 0.0), u'dynamic': True, u'frameOn': True, u'visible': True, u'xAxisProperties': { u'fontSize': 10.0, u'gridStyle': { u'gridOn': False }, u'majorTickFormat': None, u'majorTickFormatter': u'ScalarFormatter', u'majorTickLocator': u'AutoLocator', u'majorTickLocatorValues': None, u'minorTickFormat': None, u'minorTickFormatter': u'NullFormatter', u'minorTickLocator': u'NullLocator', u'minorTickLocatorValues': None, u'visible': True }, u'xAxisScale': u'linear', u'xLim': (0.0, 1.0), u"xAutoScale": False, u'yAxisProperties': { u'fontSize': 10.0, u'gridStyle': { u'gridOn': False }, u'majorTickFormat': None, u'majorTickFormatter': u'ScalarFormatter', u'majorTickLocator': u'AutoLocator', u'majorTickLocatorValues': None, u'minorTickFormat': None, u'minorTickFormatter': u'NullFormatter', u'minorTickLocator': u'NullLocator', u'minorTickLocatorValues': None, u'visible': True }, u'yAxisScale': u'linear', u'yLim': (0.0, 1.0), u"yAutoScale": False, u"facecolor": (0.0, 0.0, 0.0, 0.0), u'showMinorGrid': False, u'tickParams': { 'xaxis': { 'major': { 'bottom': True, 'top': True, 'labelbottom': True, 'labeltop': True, 'direction': 'inout', 'width': 1, 'size': 6 }, 'minor': { 'bottom': True, 'top': True, 'labelbottom': True, 'labeltop': True, 'direction': 'inout', 'width': 1, 'size': 3 } }, 'yaxis': { 'major': { 'left': True, 'right': True, 'labelleft': True, 'labelright': True, 'direction': 'inout', 'width': 1, 'size': 6 }, 'minor': { 'left': True, 'right': True, 'labelleft': True, 'labelright': True, 'direction': 'inout', 'width': 1, 'size': 3 } } }, u'spineWidths': { 'left': 0.4, 'right': 0.4, 'bottom': 0.4, 'top': 0.4 } }, u'textFromArtists': {}, u'texts': [{ u'position': (0, 0), u'style': { u'alpha': 1, u'color': u'#000000', u'hAlign': u'left', u'rotation': 0.0, u'textSize': 10.0, u'vAlign': u'baseline', u'zOrder': 3 }, u'text': u'text', u'useTeX': False }], u'title': u'', u'xAxisTitle': u'', u'yAxisTitle': u'' }], u'creationArguments': [[{ u"workspaces": u"ws1", u"specNum": 2, u"function": u"plot" }]], u'label': u'', u'properties': { u'dpi': 100.0, u'figHeight': 4.8, u'figWidth': 6.4 } } self.fig = self.plots_loader.make_fig(self.loader_plot_dict, create_plot=False) self.plot_saver = PlotsSaver() def tearDown(self): ADS.clear() def test_save_plots(self): plot_dict = {} return_value = self.plot_saver.save_plots(plot_dict) self.assertEqual(return_value, []) def test_get_dict_from_fig(self): self.fig.axes[0].creation_args = [{u"specNum": 2, "function": "plot"}] return_value = self.plot_saver.get_dict_from_fig(self.fig) self.loader_plot_dict[u'creationArguments'] = [[{ u"specNum": 2, "function": "plot", u"normalize_by_bin_width": True }]] self.maxDiff = None self.assertDictEqual(return_value, self.loader_plot_dict) def test_get_dict_from_axes(self): self.plot_saver.figure_creation_args = [{"function": "plot"}] return_value = self.plot_saver.get_dict_for_axes(self.fig.axes[0]) self.loader_plot_dict["axes"][0]['_is_norm'] = True expected_value = self.loader_plot_dict["axes"][0] self.maxDiff = None self.assertDictEqual(return_value, expected_value) def test_get_dict_from_axes_properties(self): return_value = self.plot_saver.get_dict_from_axes_properties( self.fig.axes[0]) expected_value = self.loader_plot_dict["axes"][0]["properties"] self.maxDiff = None self.assertDictEqual(return_value, expected_value) def test_get_dict_from_tick_properties(self): return_value = self.plot_saver.get_dict_from_tick_properties( self.fig.axes[0]) expected_value = self.loader_plot_dict["axes"][0]["properties"][ "tickParams"] self.assertDictEqual(return_value, expected_value) def test_get_dict_from_spine_widths(self): return_value = self.plot_saver.get_dict_from_spine_widths( self.fig.axes[0]) expected_value = self.loader_plot_dict["axes"][0]["properties"][ "spineWidths"] self.assertDictEqual(return_value, expected_value) def test_get_dict_from_axis_properties(self): return_value = self.plot_saver.get_dict_from_axis_properties( self.fig.axes[0].xaxis) expected_value = self.loader_plot_dict["axes"][0]["properties"][ "xAxisProperties"] self.assertDictEqual(return_value, expected_value) def test_get_dict_for_grid_style(self): return_value = self.plot_saver.get_dict_for_grid_style( self.fig.axes[0].xaxis) expected_value = self.loader_plot_dict["axes"][0]["properties"][ "xAxisProperties"]["gridStyle"] self.assertDictEqual(return_value, expected_value) def test_get_dict_from_line(self): self.plot_saver.figure_creation_args = [{"function": "plot"}] line = self.fig.axes[0].lines[0] return_value = self.plot_saver.get_dict_from_line(line, 0) expected_value = self.loader_plot_dict["axes"][0]["lines"][0] self.assertDictEqual(return_value, expected_value) def test_get_dict_from_marker_style(self): line = self.fig.axes[0].lines[0] return_value = self.plot_saver.get_dict_from_marker_style(line) expected_value = self.loader_plot_dict["axes"][0]["lines"][0][ "markerStyle"] self.assertDictEqual(return_value, expected_value) def test_get_dict_from_text_style(self): text = self.fig.axes[0].texts[0] return_value = self.plot_saver.get_dict_from_text(text) expected_value = self.loader_plot_dict["axes"][0]["texts"][0] self.maxDiff = None self.assertDictEqual(return_value, expected_value) def test_get_dict_from_fig_properties(self): return_value = self.plot_saver.get_dict_from_fig_properties(self.fig) expected_value = {u'dpi': 100.0, u'figHeight': 4.8, u'figWidth': 6.4} self.assertDictEqual(return_value, expected_value) def test_get_dict_from_fig_with_Normalize(self): self.fig.axes[0].creation_args = [{ u"specNum": None, "function": "pcolormesh", "norm": Normalize() }] return_value = self.plot_saver.get_dict_from_fig(self.fig) expected_creation_args = [[{ 'specNum': None, 'function': 'pcolormesh', 'norm': { 'type': 'Normalize', 'clip': False, 'vmin': None, 'vmax': None }, 'normalize_by_bin_width': True }]] self.loader_plot_dict[u'creationArguments'] = expected_creation_args self.maxDiff = None self.assertDictEqual(return_value, self.loader_plot_dict) def test_get_dict_from_fig_with_LogNorm(self): self.fig.axes[0].creation_args = [{ u"specNum": None, "function": "pcolormesh", "norm": LogNorm() }] return_value = self.plot_saver.get_dict_from_fig(self.fig) expected_creation_args = [[{ 'specNum': None, 'function': 'pcolormesh', 'norm': { 'type': 'LogNorm', 'clip': False, 'vmin': None, 'vmax': None }, 'normalize_by_bin_width': True }]] self.loader_plot_dict[u'creationArguments'] = expected_creation_args self.maxDiff = None self.assertDictEqual(return_value, self.loader_plot_dict)
def setUp(self): CreateSampleWorkspace(OutputWorkspace="ws1") self.plots_loader = PlotsLoader() # Make a figure with a given input with all these values already set self.loader_plot_dict = { u'axes': [{ u'colorbar': { u'exists': False }, u'legend': { u'exists': False }, u'lines': [{ u'alpha': 1, u'color': u'#1f77b4', u'label': u'ws1: spec 2', u'lineIndex': 0, u'lineStyle': u'-', u'lineWidth': 1.5, u'markerStyle': { u'edgeColor': u'#1f77b4', u'edgeWidth': 1.0, u'faceColor': u'#1f77b4', u'markerSize': 6.0, u'markerType': u'None', u'zOrder': 2 }, u'errorbars': { u'exists': False } }], u'properties': { u'axisOn': True, u'bounds': (0.0, 0.0, 0.0, 0.0), u'dynamic': True, u'frameOn': True, u'visible': True, u'xAxisProperties': { u'fontSize': 10.0, u'gridStyle': { u'gridOn': False }, u'majorTickFormat': None, u'majorTickFormatter': u'ScalarFormatter', u'majorTickLocator': u'AutoLocator', u'majorTickLocatorValues': None, u'minorTickFormat': None, u'minorTickFormatter': u'NullFormatter', u'minorTickLocator': u'NullLocator', u'minorTickLocatorValues': None, u'position': u'Bottom', u'visible': True }, u'xAxisScale': u'linear', u'xLim': (0.0, 1.0), u'yAxisProperties': { u'fontSize': 10.0, u'gridStyle': { u'gridOn': False }, u'majorTickFormat': None, u'majorTickFormatter': u'ScalarFormatter', u'majorTickLocator': u'AutoLocator', u'majorTickLocatorValues': None, u'minorTickFormat': None, u'minorTickFormatter': u'NullFormatter', u'minorTickLocator': u'NullLocator', u'minorTickLocatorValues': None, u'position': u'Left', u'visible': True }, u'yAxisScale': u'linear', u'yLim': (0.0, 1.0) }, u'textFromArtists': {}, u'texts': [{ u'position': (0, 0), u'style': { u'alpha': 1, u'color': u'#000000', u'hAlign': u'left', u'rotation': 0.0, u'textSize': 10.0, u'vAlign': u'baseline', u'zOrder': 3 }, u'text': u'text', u'useTeX': False }], u'title': u'', u'xAxisTitle': u'', u'yAxisTitle': u'' }], u'creationArguments': [[{ u"workspaces": u"ws1", u"specNum": 2, u"function": u"plot" }]], u'label': u'', u'properties': { u'dpi': 100.0, u'figHeight': 4.8, u'figWidth': 6.4 } } self.fig = self.plots_loader.make_fig(self.loader_plot_dict, create_plot=False) self.plot_saver = PlotsSaver()
class PlotsSaverTest(unittest.TestCase): def setUp(self): CreateSampleWorkspace(OutputWorkspace="ws1") self.plots_loader = PlotsLoader() # Make a figure with a given input with all these values already set self.loader_plot_dict = { u'axes': [{ u'colorbar': { u'exists': False }, u'legend': { u'exists': False }, u'lines': [{ u'alpha': 1, u'color': u'#1f77b4', u'label': u'ws1: spec 2', u'lineIndex': 0, u'lineStyle': u'-', u'lineWidth': 1.5, u'markerStyle': { u'edgeColor': u'#1f77b4', u'edgeWidth': 1.0, u'faceColor': u'#1f77b4', u'markerSize': 6.0, u'markerType': u'None', u'zOrder': 2 }, u'errorbars': { u'exists': False } }], u'properties': { u'axisOn': True, u'bounds': (0.0, 0.0, 0.0, 0.0), u'dynamic': True, u'frameOn': True, u'visible': True, u'xAxisProperties': { u'fontSize': 10.0, u'gridStyle': { u'gridOn': False }, u'majorTickFormat': None, u'majorTickFormatter': u'ScalarFormatter', u'majorTickLocator': u'AutoLocator', u'majorTickLocatorValues': None, u'minorTickFormat': None, u'minorTickFormatter': u'NullFormatter', u'minorTickLocator': u'NullLocator', u'minorTickLocatorValues': None, u'position': u'Bottom', u'visible': True }, u'xAxisScale': u'linear', u'xLim': (0.0, 1.0), u'yAxisProperties': { u'fontSize': 10.0, u'gridStyle': { u'gridOn': False }, u'majorTickFormat': None, u'majorTickFormatter': u'ScalarFormatter', u'majorTickLocator': u'AutoLocator', u'majorTickLocatorValues': None, u'minorTickFormat': None, u'minorTickFormatter': u'NullFormatter', u'minorTickLocator': u'NullLocator', u'minorTickLocatorValues': None, u'position': u'Left', u'visible': True }, u'yAxisScale': u'linear', u'yLim': (0.0, 1.0) }, u'textFromArtists': {}, u'texts': [{ u'position': (0, 0), u'style': { u'alpha': 1, u'color': u'#000000', u'hAlign': u'left', u'rotation': 0.0, u'textSize': 10.0, u'vAlign': u'baseline', u'zOrder': 3 }, u'text': u'text', u'useTeX': False }], u'title': u'', u'xAxisTitle': u'', u'yAxisTitle': u'' }], u'creationArguments': [[{ u"workspaces": u"ws1", u"specNum": 2, u"function": u"plot" }]], u'label': u'', u'properties': { u'dpi': 100.0, u'figHeight': 4.8, u'figWidth': 6.4 } } self.fig = self.plots_loader.make_fig(self.loader_plot_dict, create_plot=False) self.plot_saver = PlotsSaver() def tearDown(self): ADS.clear() def test_save_plots(self): plot_dict = {} return_value = self.plot_saver.save_plots(plot_dict) self.assertEqual(return_value, []) def test_get_dict_from_fig(self): self.fig.axes[0].creation_args = [{u"specNum": 2, "function": "plot"}] return_value = self.plot_saver.get_dict_from_fig(self.fig) self.loader_plot_dict[u'creationArguments'] = [[{ u"specNum": 2, "function": "plot" }]] self.maxDiff = None self.assertDictEqual(return_value, self.loader_plot_dict) def test_get_dict_from_axes(self): self.plot_saver.figure_creation_args = [{"function": "plot"}] return_value = self.plot_saver.get_dict_for_axes(self.fig.axes[0]) expected_value = self.loader_plot_dict["axes"][0] self.maxDiff = None self.assertDictEqual(return_value, expected_value) def test_get_dict_from_axes_properties(self): return_value = self.plot_saver.get_dict_from_axes_properties( self.fig.axes[0]) expected_value = self.loader_plot_dict["axes"][0]["properties"] self.maxDiff = None self.assertDictEqual(return_value, expected_value) def test_get_dict_from_axis_properties(self): return_value = self.plot_saver.get_dict_from_axis_properties( self.fig.axes[0].xaxis) expected_value = self.loader_plot_dict["axes"][0]["properties"][ "xAxisProperties"] self.assertDictEqual(return_value, expected_value) def test_get_dict_for_grid_style(self): return_value = self.plot_saver.get_dict_for_grid_style( self.fig.axes[0].xaxis) expected_value = self.loader_plot_dict["axes"][0]["properties"][ "xAxisProperties"]["gridStyle"] self.assertDictEqual(return_value, expected_value) def test_get_dict_from_line(self): self.plot_saver.figure_creation_args = [{"function": "plot"}] line = self.fig.axes[0].lines[0] return_value = self.plot_saver.get_dict_from_line(line, 0) expected_value = self.loader_plot_dict["axes"][0]["lines"][0] self.assertDictEqual(return_value, expected_value) def test_get_dict_from_marker_style(self): line = self.fig.axes[0].lines[0] return_value = self.plot_saver.get_dict_from_marker_style(line) expected_value = self.loader_plot_dict["axes"][0]["lines"][0][ "markerStyle"] self.assertDictEqual(return_value, expected_value) def test_get_dict_from_text_style(self): text = self.fig.axes[0].texts[0] return_value = self.plot_saver.get_dict_from_text(text) expected_value = self.loader_plot_dict["axes"][0]["texts"][0] self.maxDiff = None self.assertDictEqual(return_value, expected_value) def test_get_dict_from_fig_properties(self): return_value = self.plot_saver.get_dict_from_fig_properties(self.fig) expected_value = {u'dpi': 100.0, u'figHeight': 4.8, u'figWidth': 6.4} self.assertDictEqual(return_value, expected_value)
def __init__(self, project_file_ext): self.project_reader = ProjectReader(project_file_ext) self.workspace_loader = WorkspaceLoader() self.plot_loader = PlotsLoader() self.decoder_factory = DecoderFactory() self.project_file_ext = project_file_ext
def setUp(self): self.plots_loader = PlotsLoader() plt.plot = mock.MagicMock() mantid.plots.axesfunctions.plot = mock.MagicMock() self.dictionary = { u'legend': { u'exists': False }, u'lines': [], u'properties': { u'axisOn': True, u'bounds': (0.0, 0.0, 0.0, 0.0), u'dynamic': True, u'frameOn': True, u'visible': True, u'xAxisProperties': { u'fontSize': 10.0, u'gridStyle': { u'gridOn': False }, u'majorTickFormat': None, u'majorTickFormatter': 'ScalarFormatter', u'majorTickLocator': 'AutoLocator', u'majorTickLocatorValues': None, u'minorTickFormat': None, u'minorTickFormatter': 'NullFormatter', u'minorTickLocator': 'NullLocator', u'minorTickLocatorValues': None, u'visible': True }, u'xAxisScale': u'linear', u'xLim': (0.0, 1.0), u'yAxisProperties': { u'fontSize': 10.0, u'gridStyle': { u'gridOn': False }, u'majorTickFormat': None, u'majorTickFormatter': 'ScalarFormatter', u'majorTickLocator': 'AutoLocator', u'majorTickLocatorValues': None, u'minorTickFormat': None, u'minorTickFormatter': 'NullFormatter', u'minorTickLocator': 'NullLocator', u'minorTickLocatorValues': None, u'visible': True }, u'yAxisScale': u'linear', u'yLim': (0.0, 1.0), u'showMinorGrid': False, u"xAutoScale": False, u"yAutoScale": False, u'tickParams': { 'xaxis': { 'major': { 'bottom': True, 'top': True, 'labelbottom': True, 'labeltop': True, 'direction': 'inout', 'width': 1, 'size': 6 }, 'minor': { 'bottom': True, 'top': True, 'labelbottom': True, 'labeltop': True, 'direction': 'inout', 'width': 1, 'size': 3 } }, 'yaxis': { 'major': { 'left': True, 'right': True, 'labelleft': True, 'labelright': True, 'direction': 'inout', 'width': 1, 'size': 6 }, 'minor': { 'left': True, 'right': True, 'labelleft': True, 'labelright': True, 'direction': 'inout', 'width': 1, 'size': 3 } } }, u'spineWidths': { 'left': 0.4, 'right': 0.4, 'bottom': 0.4, 'top': 0.4 } }, u'textFromArtists': {}, u'texts': [], u'title': u'', u'xAxisTitle': u'', u'yAxisTitle': u'' }
class PlotsLoaderTest(unittest.TestCase): def setUp(self): self.plots_loader = PlotsLoader() plt.plot = mock.MagicMock() mantid.plots.axesfunctions.plot = mock.MagicMock() self.dictionary = { u'legend': { u'exists': False }, u'lines': [], u'properties': { u'axisOn': True, u'bounds': (0.0, 0.0, 0.0, 0.0), u'dynamic': True, u'frameOn': True, u'visible': True, u'xAxisProperties': { u'fontSize': 10.0, u'gridStyle': { u'gridOn': False }, u'majorTickFormat': None, u'majorTickFormatter': 'ScalarFormatter', u'majorTickLocator': 'AutoLocator', u'majorTickLocatorValues': None, u'minorTickFormat': None, u'minorTickFormatter': 'NullFormatter', u'minorTickLocator': 'NullLocator', u'minorTickLocatorValues': None, u'visible': True }, u'xAxisScale': u'linear', u'xLim': (0.0, 1.0), u'yAxisProperties': { u'fontSize': 10.0, u'gridStyle': { u'gridOn': False }, u'majorTickFormat': None, u'majorTickFormatter': 'ScalarFormatter', u'majorTickLocator': 'AutoLocator', u'majorTickLocatorValues': None, u'minorTickFormat': None, u'minorTickFormatter': 'NullFormatter', u'minorTickLocator': 'NullLocator', u'minorTickLocatorValues': None, u'visible': True }, u'yAxisScale': u'linear', u'yLim': (0.0, 1.0), u'showMinorGrid': False, u"xAutoScale": False, u"yAutoScale": False, u'tickParams': { 'xaxis': { 'major': { 'bottom': True, 'top': True, 'labelbottom': True, 'labeltop': True, 'direction': 'inout', 'width': 1, 'size': 6 }, 'minor': { 'bottom': True, 'top': True, 'labelbottom': True, 'labeltop': True, 'direction': 'inout', 'width': 1, 'size': 3 } }, 'yaxis': { 'major': { 'left': True, 'right': True, 'labelleft': True, 'labelright': True, 'direction': 'inout', 'width': 1, 'size': 6 }, 'minor': { 'left': True, 'right': True, 'labelleft': True, 'labelright': True, 'direction': 'inout', 'width': 1, 'size': 3 } } }, u'spineWidths': { 'left': 0.4, 'right': 0.4, 'bottom': 0.4, 'top': 0.4 } }, u'textFromArtists': {}, u'texts': [], u'title': u'', u'xAxisTitle': u'', u'yAxisTitle': u'' } def test_load_plots_does_the_right_calls(self): self.plots_loader.make_fig = mock.MagicMock() self.plots_loader.load_plots(["plot1", "plot2"]) self.assertEqual(self.plots_loader.make_fig.call_count, 2) @mock.patch("matplotlib.figure.Figure.show") def test_make_fig_makes_the_right_calls(self, pass_func): ws = Workspace2D() ADS.add("ws", ws) plot_dict = { "label": "plot", "creationArguments": [[{ "workspaces": "ws", "wkspIndex": 0 }, { "function": "axhline", "args": [10, 0, 1], "kwargs": {} }, { "function": "axvline", "args": [], "kwargs": { "x": 0, "ymin": 0, "ymax": 1 } }]] } self.plots_loader.workspace_plot_func = mock.MagicMock() self.plots_loader.plot_func = mock.MagicMock() self.plots_loader.restore_figure_data = mock.MagicMock() self.plots_loader.make_fig(plot_dict) self.assertEqual(self.plots_loader.workspace_plot_func.call_count, 1) self.assertEqual(self.plots_loader.plot_func.call_count, 2) self.assertEqual(self.plots_loader.restore_figure_data.call_count, 1) def test_restore_fig_properties(self): matplotlib.figure.Figure.set_figheight = mock.MagicMock() matplotlib.figure.Figure.set_figwidth = mock.MagicMock() matplotlib.figure.Figure.set_dpi = mock.MagicMock() self.plots_loader.restore_fig_properties(matplotlib.figure.Figure(), { "figHeight": 1, "figWidth": 1, "dpi": 1 }) self.assertEqual(matplotlib.figure.Figure.set_figheight.call_count, 1) self.assertEqual(matplotlib.figure.Figure.set_figwidth.call_count, 1) self.assertEqual(matplotlib.figure.Figure.set_dpi.call_count, 1) def test_restore_fig_axes(self): self.plots_loader.update_properties = mock.MagicMock() self.plots_loader.update_lines = mock.MagicMock() self.plots_loader.create_text_from_dict = mock.MagicMock() self.plots_loader.update_legend = mock.MagicMock() fig = matplotlib.figure.Figure() self.plots_loader.restore_fig_axes( matplotlib.axes.Axes(fig=fig, rect=[0, 0, 0, 0]), self.dictionary) self.assertEqual(self.plots_loader.update_properties.call_count, 1) self.assertEqual(self.plots_loader.update_lines.call_count, 0) self.assertEqual(self.plots_loader.create_text_from_dict.call_count, 0) self.assertEqual(self.plots_loader.update_legend.call_count, 1) def test_update_properties_limits(self): dic = self.dictionary[u"properties"] dic.pop("spineWidths", None) # Not needed for this test and causes error on mock. mock_ax = mock.Mock() plots_loader = self.plots_loader with mock.patch.object(plots_loader, "update_axis", mock.Mock()): plots_loader.update_properties(mock_ax, dic) mock_ax.set_xlim.assert_called_once_with(dic['xLim']) mock_ax.set_xlim.assert_called_once_with(dic['yLim']) def test_update_properties_limits_autoscale(self): dic = self.dictionary[u"properties"] dic.pop("spineWidths", None) # Not needed for this test and causes error on mock. dic.update({"xAutoScale": True, "yAutoScale": True}) mock_ax = mock.Mock() plots_loader = self.plots_loader with mock.patch.object(plots_loader, "update_axis", mock.Mock()): plots_loader.update_properties(mock_ax, dic) mock_ax.autoscale.assert_has_calls( [mock.call(True, axis="x"), mock.call(True, axis="y")]) mock_ax.set_xlim.assert_not_called() mock_ax.set_xlim.assert_not_called() def test_update_properties_sets_tick_params_and_spine_widths(self): dic = self.dictionary[u"properties"] mock_ax = mock.Mock() mock_ax.spines = { "left": mock.Mock(), "right": mock.Mock(), "top": mock.Mock(), "bottom": mock.Mock(), } plots_loader = self.plots_loader with mock.patch.object(plots_loader, "update_axis", mock.Mock()): plots_loader.update_properties(mock_ax, dic) mock_ax.xaxis.set_tick_params.assert_has_calls([ mock.call(which="major", **dic["tickParams"]["xaxis"]["major"]), mock.call(which="minor", **dic["tickParams"]["xaxis"]["minor"]) ]) mock_ax.yaxis.set_tick_params.assert_has_calls([ mock.call(which="major", **dic["tickParams"]["yaxis"]["major"]), mock.call(which="minor", **dic["tickParams"]["yaxis"]["minor"]) ]) for (spine_name, mock_spine) in mock_ax.spines.items(): mock_spine.set_linewidth.assert_called_with( dic["spineWidths"][spine_name]) def test_create_text_from_dict(self): fig = matplotlib.figure.Figure() ax = matplotlib.axes.Axes(fig=fig, rect=[0, 0, 0, 0]) ax.text = mock.MagicMock() self.plots_loader.create_text_from_dict(ax=ax, dic={ "text": "text", "position": (1, 1), "useTeX": 1, "style": { "alpha": 1, "textSize": 1, "color": 1, "hAlign": 1, "vAlign": 1, "rotation": 1, "zOrder": 1 } }) self.assertEqual(ax.text.call_count, 1) ax.text.assert_called_once_with(fontdict={ u'zorder': 1, u'fontsize': 1, u'color': 1, u'alpha': 1, u'rotation': 1, u'verticalalignment': 1, u'usetex': 1, u'horizontalalignment': 1 }, s=u'text', x=1, y=1) @mock.patch("matplotlib.figure.Figure.show") def test_load_plot_from_dict(self, pass_func): # The fact this runs is the test self.plots_loader.load_plots([self.dictionary]) def test_update_axis_ticks_format(self): fig, ax = plt.subplots() x_axis = ax.xaxis x_axis.set_major_formatter(LogFormatterSciNotation()) x_axis.set_minor_formatter(LogFormatterSciNotation()) PlotsLoader.update_axis_ticks( x_axis, self.dictionary['properties']['xAxisProperties']) self.assertIsInstance(x_axis.get_major_formatter(), ScalarFormatter) self.assertIsInstance(x_axis.get_minor_formatter(), NullFormatter) @mock.patch("matplotlib.colors.LogNorm", autospec=True) def test_restore_normalise_obj_from_dict_creates_correct_norm_instance_from_supported_norm( self, mock_LogNorm): norm_dict = {'type': 'LogNorm', 'vmin': 1, 'vmax': 2, 'clip': True} _ = self.plots_loader.restore_normalise_obj_from_dict(norm_dict) mock_LogNorm.assert_called_once_with(norm_dict['vmin'], norm_dict['vmax'], norm_dict['clip']) def test_restore_normalise_obj_from_dict_returns_none_with_unsupported_norm( self): norm_dict = { 'type': 'unsupported_norm', 'vmin': 1, 'vmax': 2, 'clip': True } return_value = self.plots_loader.restore_normalise_obj_from_dict( norm_dict) self.assertIsNone(return_value) @mock.patch("matplotlib.colors.Normalize", autospec=True) def test_restore_normalise_obj_from_dict_returns_Normalize_type_with_unspecified_norm( self, mock_Normalize): """If the type of the norm is unspecified, the method should return a Normalize object, which is the most general norm and is subclassed by LogNorm, etc.""" norm_dict = {'vmin': 1, 'vmax': 2, 'clip': True} _ = self.plots_loader.restore_normalise_obj_from_dict(norm_dict) mock_Normalize.assert_called_once_with(norm_dict['vmin'], norm_dict['vmax'], norm_dict['clip']) def test_update_properties_without_spineWidths(self): # Test that old versions of the .mtdproj file that don't include spine widths # still load. The fact this runs is the test props = self.dictionary['properties'] props.pop("spineWidths") mock_ax = mock.Mock() plots_loader = self.plots_loader with mock.patch.object(plots_loader, "update_axis", mock.Mock()): plots_loader.update_properties(mock_ax, props) def test_update_axis_with_old_tick_position(self): # Test that old versions of the .mtdproj file that represented which side of the # plot had ticks differently. mock_xaxis = mock.MagicMock(spec=matplotlib.axis.XAxis) mock_yaxis = mock.MagicMock(spec=matplotlib.axis.YAxis) mock_ax = mock.MagicMock() mock_ax.xaxis = mock_xaxis mock_ax.yaxis = mock_yaxis dic = self.dictionary["properties"] dic.pop("tickParams") dic["xAxisProperties"]["position"] = "top" dic["yAxisProperties"]["position"] = "right" self.plots_loader.update_properties(mock_ax, dic) mock_ax.set_tick_params.assert_not_called() mock_xaxis.tick_top.assert_called() mock_yaxis.tick_right.assert_called()