Exemplo n.º 1
0
 def float_log(wksp_name, log_name):
     try:
         run = ads.Instance().retrieve(wksp_name).run()
         prop = run.getProperty(log_name)
         if isinstance(prop, FloatTimeSeriesProperty):
             return True
         try:
             float(prop.value)
             return True
         except ValueError:
             return False
     except (TypeError, ValueError):
         for fit in all_fits:
             for input_workspace in fit.input_workspaces:
                 ws = ads.Instance().retrieve(input_workspace)
                 if ws.run().hasProperty(log_name):
                     return float_log(input_workspace, log_name)
Exemplo n.º 2
0
    def __init__(self, parent):
        super(WorkspaceWidget, self).__init__(parent)

        self._ads = AnalysisDataService.Instance()

        # layout
        self.workspacewidget = WorkspaceTreeWidget()
        layout = QVBoxLayout()
        layout.addWidget(self.workspacewidget)
        self.setLayout(layout)

        # behaviour
        self.workspacewidget.plotSpectrumClicked.connect(
            partial(self._do_plot_spectrum, errors=False, overplot=False))

        self.workspacewidget.plotMDHistoClicked.connect(
            partial(self._do_plot_1d_md, errors=False, overplot=False))
        self.workspacewidget.overplotMDHistoClicked.connect(
            partial(self._do_plot_1d_md, errors=False, overplot=True))
        self.workspacewidget.plotMDHistoWithErrorsClicked.connect(
            partial(self._do_plot_1d_md, errors=True, overplot=False))
        self.workspacewidget.overplotMDHistoWithErrorsClicked.connect(
            partial(self._do_plot_1d_md, errors=True, overplot=True))

        self.workspacewidget.plotBinClicked.connect(
            partial(self._do_plot_bin, errors=False, overplot=False))
        self.workspacewidget.overplotSpectrumClicked.connect(
            partial(self._do_plot_spectrum, errors=False, overplot=True))
        self.workspacewidget.plotSpectrumWithErrorsClicked.connect(
            partial(self._do_plot_spectrum, errors=True, overplot=False))
        self.workspacewidget.overplotSpectrumWithErrorsClicked.connect(
            partial(self._do_plot_spectrum, errors=True, overplot=True))
        self.workspacewidget.plotColorfillClicked.connect(self._do_plot_colorfill)
        self.workspacewidget.sampleLogsClicked.connect(self._do_sample_logs)
        self.workspacewidget.sliceViewerClicked.connect(self._do_slice_viewer)
        self.workspacewidget.showDataClicked.connect(self._do_show_data)
        self.workspacewidget.showInstrumentClicked.connect(self._do_show_instrument)
        self.workspacewidget.showAlgorithmHistoryClicked.connect(self._do_show_algorithm_history)
        self.workspacewidget.showDetectorsClicked.connect(self._do_show_detectors)
        self.workspacewidget.plotAdvancedClicked.connect(
            partial(self._do_plot_spectrum, errors=False, overplot=False, advanced=True))
        self.workspacewidget.plotSurfaceClicked.connect(
            partial(self._do_plot_3D, plot_type='surface'))
        self.workspacewidget.plotWireframeClicked.connect(
            partial(self._do_plot_3D, plot_type='wireframe'))
        self.workspacewidget.plotContourClicked.connect(
            partial(self._do_plot_3D, plot_type='contour'))
        self.workspacewidget.sampleMaterialClicked.connect(self._do_sample_material)
        self.workspacewidget.superplotClicked.connect(self._do_superplot)
        self.workspacewidget.superplotWithErrsClicked.connect(
                self._do_superplot_with_errors)
        self.workspacewidget.superplotBinsClicked.connect(self._do_superplot_bins)
        self.workspacewidget.superplotBinsWithErrsClicked.connect(
                self._do_superplot_bins_with_errors)
        self.workspacewidget.contextMenuAboutToShow.connect(
            self._on_context_menu)

        self.workspacewidget.workspaceDoubleClicked.connect(self._action_double_click_workspace)
    def test_workspaces_removed_from_workspace_list_widget_if_deleted_from_ADS(self):
        name = "ws"
        fig, canvas_mock, _ = self._create_and_plot_matrix_workspace(name)
        property_browser = self._create_widget(canvas=canvas_mock)
        property_browser.setOutputName(name)

        # create fake fit output results
        matrixWorkspace = WorkspaceFactory.Instance().create("Workspace2D", NVectors=3, YLength=5, XLength=5)
        AnalysisDataService.Instance().addOrReplace(name + "_Workspace", matrixWorkspace)
        tableWorkspace = WorkspaceFactory.createTable()
        AnalysisDataService.Instance().addOrReplace(name + "_Parameters", tableWorkspace)

        property_browser.fitting_done_slot(name + "_Workspace")
        AnalysisDataService.Instance().remove(name + "_Parameters")
        property_browser.postDeleteHandle(name + "_Parameters")

        wsList = property_browser.getWorkspaceList()
        self.assertEqual(1, len(wsList))
 def _create_and_plot_matrix_workspace(self, name="workspace"):
     ws = WorkspaceFactory.Instance().create("Workspace2D",
                                             NVectors=2,
                                             YLength=5,
                                             XLength=5)
     AnalysisDataService.Instance().addOrReplace(name, ws)
     fig = plot([ws], spectrum_nums=[1])
     canvas = fig.canvas
     return fig, canvas
Exemplo n.º 5
0
 def test_plot_from_names_calls_plot(self, get_spectra_selection_mock,
                                     plot_mock):
     ws_name = 'test_plot_from_names_calls_plot-1'
     AnalysisDataService.Instance().addOrReplace(ws_name, self._test_ws)
     selection = SpectraSelection([self._test_ws])
     selection.wksp_indices = [0]
     get_spectra_selection_mock.return_value = selection
     plot_from_names([ws_name], errors=False, overplot=False)
     self.assertEqual(1, plot_mock.call_count)
Exemplo n.º 6
0
    def plot(self, workspace_list, title, domain, force_redraw, window_title):
        """
        Plots a list of workspaces in a new plot window, closing any existing plot windows.
        :param workspace_list: A list of workspace name to plot. They must be in the ADS
        :param title: The name to give to the subplot created, currently only one subplot is ever created
        :param domain: if frequency or time domain
        :param force_redraw: if to force a redraw
        :param window_title: title for the plot window
        :return: A reference to the newly created plot window is passed back
        """
        if not workspace_list:
            self.plotted_workspaces = []
            self.plotted_workspaces_inverse_binning = {}
            self.plotted_fit_workspaces = []
            self.plot_figure.clear()
            self.plot_figure.canvas.draw()
            return self.plot_figure
        try:
            workspaces = AnalysisDataService.Instance().retrieveWorkspaces(workspace_list, unrollGroups=True)
        except RuntimeError:
            return
        if (force_redraw or self.plotted_workspaces == []) and self.plot_figure:

            self.plot_figure.clear()
            self.plotted_workspaces = []
            self.plotted_workspaces_inverse_binning = {}
            self.plotted_fit_workspaces = []
            self.plot_figure = plot(workspaces,wksp_indices=[0], fig=self.plot_figure, window_title=title,
                                    plot_kwargs={'distribution': True, 'autoscale_on_update': False}, errors=True)
            self.set_x_lim(domain)

        elif self.plot_figure:
            axis = self.plot_figure.gca()
            xlim = axis.get_xlim()
            ylim = axis.get_ylim()
            self._remove_all_data_workspaces_from_plot()
            self.plot_figure = plot(workspaces, wksp_indices=[0], fig=self.plot_figure, window_title=title,
                                    plot_kwargs={'distribution': True, 'autoscale_on_update': False}, errors=True)
            axis = self.plot_figure.gca()
            axis.set_xlim(xlim)
            axis.set_ylim(ylim)
        else:
            self.plot_figure = plot(workspaces, wksp_indices=[0], window_title=title, plot_kwargs={'distribution': True,
                                    'autoscale_on_update': False}, errors=True)
            self.set_x_lim(domain)

        self.plot_figure.canvas.set_window_title(window_title)
        self.plot_figure.gca().set_title(title)

        self.plot_figure.canvas.window().closing.connect(self._clear_plot_references)

        workspaces_to_remove = [workspace for workspace in self.plotted_workspaces if workspace not in workspace_list]
        for workspace in workspaces_to_remove:
            self.remove_workpace_from_plot(workspace)

        self.plotted_workspaces = workspace_list
Exemplo n.º 7
0
 def wrapper(*args, **kwargs):
     ads = AnalysisDataService.Instance()
     names_before = set(ads.getObjectNames())
     try:
         return func(*args, **kwargs)
     except Exception as exc:
         added_names = set(ads.getObjectNames()) - names_before
         for name in added_names:
             ads.remove(name)
         raise exc
    def test_fit_result_workspaces_are_added_to_browser_when_fitting_done(self):
        name = "ws"
        fig, canvas, _ = self._create_and_plot_matrix_workspace(name)
        property_browser = self._create_widget(canvas=canvas)
        property_browser.setOutputName(name)

        # create fake fit output results
        matrixWorkspace = WorkspaceFactory.Instance().create("Workspace2D", NVectors=3, YLength=5, XLength=5)
        tableWorkspace = WorkspaceFactory.createTable()
        AnalysisDataService.Instance().addOrReplace(name + "_Workspace", matrixWorkspace)
        AnalysisDataService.Instance().addOrReplace(name + "_Parameters", tableWorkspace)
        AnalysisDataService.Instance().addOrReplace(name + "_NormalisedCovarianceMatrix", tableWorkspace)

        property_browser.fitting_done_slot(name + "_Workspace")
        workspaceList = property_browser.getWorkspaceList()

        self.assertEqual(3, workspaceList.count())
        self.assertEqual(name + "_NormalisedCovarianceMatrix", workspaceList.item(0).text())
        self.assertEqual(name + "_Parameters", workspaceList.item(1).text())
        self.assertEqual(name + "_Workspace", workspaceList.item(2).text())
Exemplo n.º 9
0
    def test_that_plot_can_accept_workspace_names(self):
        ws_name1 = "some_workspace"
        AnalysisDataService.Instance().addOrReplace(ws_name1, self._test_ws)

        try:
            result_workspaces = workspace_names_dummy_func([ws_name1])
        except ValueError:
            self.fail("Passing workspace names should not raise a value error.")
        else:
            # The list of workspace names we pass in should have been converted
            # to a list of workspaces
            self.assertNotEqual(result_workspaces, [ws_name1])
Exemplo n.º 10
0
def _get_peaksworkspace(name):
    """Return a handle to a PeaksWorkspace
    :param name: The string name of a workspace in the ADS that should be a PeaksWorkspace
    :raises ValueError: if the workspace exists but is not a PeaksWorkspace
    :raises KeyError: if the workspace does not exist
    :return: A workspace handle for a PeaksWorkspace
    """
    workspace = AnalysisDataService.Instance()[name]
    if not hasattr(workspace, 'getNumberPeaks'):
        raise ValueError("Requested workspace {} is not a PeaksWorkspace. Type={}".format(
            name, type(workspace)))
    return workspace
 def create_table_workspace(self, table_name):
     table = WorkspaceFactory.createTable()
     table.addColumn('double', X_COLUMN_LABEL, 1)
     table.addColumn('double', Y_COLUMN_LABEL, 2)
     for i in range(1, 10):
         table.addRow([0.1 * i, 5])
     AnalysisDataService.Instance().addOrReplace(table_name, table)
     self.fit_browser.getXColumnName.return_value = X_COLUMN_LABEL
     self.fit_browser.getYColumnName.return_value = Y_COLUMN_LABEL
     self.fit_browser.getErrColumnName.return_value = None
     self.fit_browser.startX.return_value = 0.15
     self.fit_browser.endX.return_value = 0.95
Exemplo n.º 12
0
    def test_fit_curves_removed_when_workspaces_deleted(self):
        fig, canvas, _ = self._create_and_plot_matrix_workspace(name="ws")
        property_browser = self._create_widget(canvas=canvas)

        manager_mock = Mock()
        manager_mock.canvas = canvas
        observer = FigureManagerADSObserver(manager=manager_mock)  # noqa: F841

        for plot_diff in [True, False]:
            # create fake fit output results
            matrixWorkspace = WorkspaceFactory.Instance().create("Workspace2D",
                                                                 NVectors=3,
                                                                 YLength=5,
                                                                 XLength=5)
            tableWorkspace = WorkspaceFactory.createTable()
            AnalysisDataService.Instance().addOrReplace("ws_Workspace", matrixWorkspace)
            AnalysisDataService.Instance().addOrReplace("ws_Parameters", tableWorkspace)
            AnalysisDataService.Instance().addOrReplace("ws_NormalisedCovarianceMatrix",
                                                        tableWorkspace)

            property_browser.plotDiff = Mock(return_value=plot_diff)
            property_browser.fitting_done_slot("ws_Workspace")

            if plot_diff:
                self.assertEqual(3, len(fig.get_axes()[0].lines))
            else:
                self.assertEqual(2, len(fig.get_axes()[0].lines))

            AnalysisDataService.Instance().remove("ws_Workspace")
            AnalysisDataService.Instance().remove("ws_Parameters")
            AnalysisDataService.Instance().remove("ws_NormalisedCovarianceMatrix")

            self.assertEqual(1, len(fig.get_axes()[0].lines))
Exemplo n.º 13
0
    def replace_workspace_plot(self, workspace_name, axis):
        """
        Replace workspace from plot
        :param workspace_name: Name of workspace to update in plot
        :param axis: the axis that contains the workspace
        :return:
        """
        try:
            workspace = AnalysisDataService.Instance().retrieve(workspace_name)
        except RuntimeError:
            return

        axis.replace_workspace_artists(workspace)
Exemplo n.º 14
0
    def test_fit_result_matrix_workspace_in_browser_is_viewed_when_clicked(self):
        from mantidqt.widgets.workspacedisplay.table.presenter import TableWorkspaceDisplay

        name = "ws"
        fig, canvas, _ = self._create_and_plot_matrix_workspace(name)
        property_browser = self._create_widget(canvas=canvas)
        property_browser.setOutputName(name)

        # create fake fit output results
        matrixWorkspace = WorkspaceFactory.Instance().create("Workspace2D", NVectors=3, YLength=5, XLength=5)
        AnalysisDataService.Instance().addOrReplace(name + "_Workspace", matrixWorkspace)
        tableWorkspace = WorkspaceFactory.createTable()
        AnalysisDataService.Instance().addOrReplace(name + "_Parameters", tableWorkspace)

        property_browser.fitting_done_slot(name + "_Workspace")
        wsList = property_browser.getWorkspaceList()
        TableWorkspaceDisplay.show_view = Mock()

        # click on table workspace
        item = wsList.item(0).text()
        property_browser.workspaceClicked.emit(item)
        self.assertEqual(1, TableWorkspaceDisplay.show_view.call_count)
Exemplo n.º 15
0
 def remove_workpace_from_plot(self, workspace_name):
     """
     :param workspace_name: Name of workspace to remove from plot
     :return:
     """
     try:
         workspace = AnalysisDataService.Instance().retrieve(workspace_name)
     except RuntimeError:
         return
     self.plot_figure.gca().remove_workspace_artists(workspace)
     self.plotted_workspaces = [item for item in self.plotted_workspaces if item != workspace_name]
     self.plotted_fit_workspaces = [item for item in self.plotted_fit_workspaces if item != workspace_name]
     if workspace_name in self.plotted_workspaces_inverse_binning:
         self.plotted_workspaces_inverse_binning.pop(workspace_name)
Exemplo n.º 16
0
def _validate_workspace_names(workspaces):
    """
    Checks if the workspaces passed into a plotting function are workspace names, and
    retrieves the workspaces if they are.
    This function assumes that we do not have a mix of workspaces and workspace names.
    :param workspaces: A list of workspaces or workspace names
    :return: A list of workspaces
    """
    try:
        raise_if_not_sequence(workspaces, 'workspaces', string_types)
    except ValueError:
        return workspaces
    else:
        return AnalysisDataService.Instance().retrieveWorkspaces(workspaces, unrollGroups=True)
Exemplo n.º 17
0
 def calculate_vanadium_correction(vanadium_path):
     """
     Runs the vanadium correction algorithm.
     :param vanadium_path: The path to the vanadium data.
     :return: The integrated workspace and the curves generated by the algorithm.
     """
     try:
         Load(Filename=vanadium_path,
              OutputWorkspace=VANADIUM_INPUT_WORKSPACE_NAME)
     except Exception as e:
         logger.error(
             "Error when loading vanadium sample data. "
             "Could not run Load algorithm with vanadium run number: " +
             str(vanadium_path) + ". Error description: " + str(e))
         raise RuntimeError
     EnggVanadiumCorrections(
         VanadiumWorkspace=VANADIUM_INPUT_WORKSPACE_NAME,
         OutIntegrationWorkspace=INTEGRATED_WORKSPACE_NAME,
         OutCurvesWorkspace=CURVES_WORKSPACE_NAME)
     Ads.remove(VANADIUM_INPUT_WORKSPACE_NAME)
     integrated_workspace = Ads.Instance().retrieve(
         INTEGRATED_WORKSPACE_NAME)
     curves_workspace = Ads.Instance().retrieve(CURVES_WORKSPACE_NAME)
     return integrated_workspace, curves_workspace
Exemplo n.º 18
0
    def add_workspace_to_plot(self, workspace, specNum, label):
        """
        Adds a plot line to the specified subplot
        :param workspace: Name of workspace to get plot data from
        :param specNum: Spectrum number to plot from workspace
        :return:
        """
        try:
            workspaces = AnalysisDataService.Instance().retrieveWorkspaces([workspace], unrollGroups=True)
        except RuntimeError:
            return

        self.plot_figure = plot(workspaces, spectrum_nums=[specNum], fig=self.plot_figure, overplot=True,
                                plot_kwargs={'distribution': True, 'zorder': 4, 'autoscale_on_update': False, 'label': label})

        self.plotted_fit_workspaces.append(workspace)
    def test_plot_guess_plots_for_table_workspaces(self):
        table = WorkspaceFactory.createTable()
        table.addColumn('double', 'X', 1)
        table.addColumn('double', 'Y', 2)
        for i in range(1, 10):
            table.addRow([0.1 * i, 5])
        name = "table_name"
        AnalysisDataService.Instance().addOrReplace(name, table)
        property_browser = self._create_widget()
        property_browser.getFittingFunction = Mock(
            return_value='name=FlatBackground')
        property_browser.workspaceName = Mock(return_value=name)
        property_browser.startX = Mock(return_value=0.15)
        property_browser.endX = Mock(return_value=0.95)
        property_browser.plot_guess()

        self.assertEqual(1, property_browser.get_axes().plot.call_count)
Exemplo n.º 20
0
 def test_output_workspace_name_changes_if_more_than_one_plot_of_same_workspace(self, figure_labels_mock):
     # create a workspace
     ws = WorkspaceFactory.Instance().create("Workspace2D", NVectors=2, YLength=5, XLength=5)
     AnalysisDataService.Instance().addOrReplace("workspace", ws)
     ws_window_names = ["workspace-1", "workspace-2"]
     figure_labels_mock.return_value = ws_window_names
     output_name = []
     # plot it twice
     for i in [0, 1]:
         fig = plot([ws], spectrum_nums=[1])
         fig.canvas.get_window_title = Mock(return_value=ws_window_names[i])
         browser = self._create_widget(canvas=fig.canvas)
         # don't want the widget to actually show in test
         QDockWidget.show = Mock()
         browser.show()
         output_name.append(browser.outputName())
     self.assertNotEqual(output_name[0], output_name[1])
Exemplo n.º 21
0
def create_test_workspacegroup(group_name=None, size=None, items=None):
    if size is not None and items is not None:
        raise ValueError("Provide either size or items not both.")

    group_name = group_name if group_name is not None else 'fitting_context_testgroup'
    group = WorkspaceGroup()
    if size is not None:
        for i in range(size):
            ws_name = '{}_{}'.format(group_name, i)
            fake_ws = create_test_workspace(ws_name)
            group.addWorkspace(fake_ws)
    elif items is not None:
        for item in items:
            group.addWorkspace(item)

    ads = AnalysisDataService.Instance()
    ads.addOrReplace(group_name, group)
    return group
Exemplo n.º 22
0
    def _do_plot_from_names_test(self, get_spectra_selection_mock, expected_labels,
                                 wksp_indices, errors, overplot, target_fig=None):
        ws_name = 'test_plot_from_names-1'
        AnalysisDataService.Instance().addOrReplace(ws_name, self._test_ws)

        selection = SpectraSelection([self._test_ws])
        selection.wksp_indices = wksp_indices
        get_spectra_selection_mock.return_value = selection
        fig = plot_from_names([ws_name], errors, overplot, target_fig)
        if target_fig is not None:
            self.assertEqual(target_fig, fig)

        plotted_lines = fig.gca().get_legend().get_lines()
        self.assertEqual(len(expected_labels), len(plotted_lines))
        for label_part, line in zip(expected_labels, plotted_lines):
            if label_part is not None:
                self.assertTrue(label_part in line.get_label(),
                                msg="Label fragment '{}' not found in line label".format(label_part))
        return fig
Exemplo n.º 23
0
    def add_workspace_to_plot(self, workspace_name, workspace_index, label):
        """
        Adds a plot line to the specified subplot
        :param workspace: Name of workspace to get plot data from
        :param workspace_index: workspace index to plot from workspace
        :return:
        """
        try:
            workspaces = AnalysisDataService.Instance().retrieveWorkspaces([workspace_name], unrollGroups=True)
        except RuntimeError:
            return

        if all([workspace.getNumberHistograms() == 4 for workspace in workspaces]) and workspace_index == 1:
            workspace_index = 3

        self.plot_figure = plot(workspaces, wksp_indices=[workspace_index], fig=self.plot_figure, overplot=True,
                                plot_kwargs={'distribution': True, 'zorder': 4, 'autoscale_on_update': False, 'label': label})

        if workspace_name not in self._plotted_fit_workspaces:
            self._plotted_fit_workspaces.append(workspace_name)
Exemplo n.º 24
0
    def __init__(self, parent):
        super(WorkspaceWidget, self).__init__(parent)

        self._ads = AnalysisDataService.Instance()

        # layout
        self.workspacewidget = WorkspaceTreeWidget()
        layout = QVBoxLayout()
        layout.addWidget(self.workspacewidget)
        self.setLayout(layout)

        # behaviour
        self.workspacewidget.plotSpectrumClicked.connect(
            partial(self._do_plot_spectrum, errors=False, overplot=False))
        self.workspacewidget.plotBinClicked.connect(
            partial(self._do_plot_bin, errors=False, overplot=False))
        self.workspacewidget.overplotSpectrumClicked.connect(
            partial(self._do_plot_spectrum, errors=False, overplot=True))
        self.workspacewidget.plotSpectrumWithErrorsClicked.connect(
            partial(self._do_plot_spectrum, errors=True, overplot=False))
        self.workspacewidget.overplotSpectrumWithErrorsClicked.connect(
            partial(self._do_plot_spectrum, errors=True, overplot=True))
        self.workspacewidget.plotColorfillClicked.connect(
            self._do_plot_colorfill)
        self.workspacewidget.sampleLogsClicked.connect(self._do_sample_logs)
        self.workspacewidget.sliceViewerClicked.connect(self._do_slice_viewer)
        self.workspacewidget.showDataClicked.connect(self._do_show_data)
        self.workspacewidget.showInstrumentClicked.connect(
            self._do_show_instrument)
        self.workspacewidget.showAlgorithmHistoryClicked.connect(
            self._do_show_algorithm_history)
        self.workspacewidget.showDetectorsClicked.connect(
            self._do_show_detectors)
        self.workspacewidget.plotAdvancedClicked.connect(
            partial(self._do_plot_spectrum,
                    errors=False,
                    overplot=False,
                    advanced=True))

        self.workspacewidget.workspaceDoubleClicked.connect(
            self._action_double_click_workspace)
Exemplo n.º 25
0
    def _assert_table_matches_expected(self, expected_cols, expected_content,
                                       table, table_name):
        self.assertTrue(isinstance(table, ITableWorkspace))
        self.assertTrue(table_name in AnalysisDataService.Instance())
        self.assertEqual(len(expected_content), table.rowCount())
        self.assertEqual(len(list(expected_cols)), table.columnCount())
        actual_col_names = table.getColumnNames()
        for index, (expected_name, expected_type) in enumerate(expected_cols):
            self.assertEqual(expected_name, actual_col_names[index])
            self.assertEqual(expected_type.value, table.getPlotType(index))

        for row_index, (expected_row,
                        actual_row) in enumerate(zip(expected_content, table)):
            self.assertEqual(len(expected_row), len(actual_row))
            for col_index, expected in enumerate(expected_row):
                actual = table.cell(row_index, col_index)
                if isinstance(expected, str):
                    self.assertEqual(expected, actual)
                else:
                    # Fit pushes things back/forth through strings so exact match is not possible
                    self.assertAlmostEqual(expected, actual, places=3)
Exemplo n.º 26
0
def plot_from_names(names,
                    errors,
                    overplot,
                    fig=None,
                    show_colorfill_btn=False):
    """
    Given a list of names of workspaces, raise a dialog asking for the
    a selection of what to plot and then plot it.

    :param names: A list of workspace names
    :param errors: If true then error bars will be plotted on the points
    :param overplot: If true then the add to the current figure if one
                     exists and it is a compatible figure
    :param fig: If not None then use this figure object to plot
    :return: The figure containing the plot or None if selection was cancelled
    """
    workspaces = AnalysisDataService.Instance().retrieveWorkspaces(
        names, unrollGroups=True)
    try:
        selection = get_spectra_selection(
            workspaces,
            show_colorfill_btn=show_colorfill_btn,
            overplot=overplot)
    except Exception as exc:
        LOGGER.warning(format(str(exc)))
        selection = None

    if selection is None:
        return None
    elif selection == 'colorfill':
        return pcolormesh_from_names(names)

    return plot(selection.workspaces,
                spectrum_nums=selection.spectra,
                wksp_indices=selection.wksp_indices,
                errors=errors,
                overplot=overplot,
                fig=fig,
                tiled=selection.plot_type == selection.Tiled,
                waterfall=selection.plot_type == selection.Waterfall)
Exemplo n.º 27
0
    def add_workspace_to_plot(self, ax, workspace_name, workspace_indices,
                              errors, plot_kwargs):
        """
            Adds a plot line to the specified axis
            :param ax: Axis to plot the workspace on
            :param workspace_name: Name of workspace to get plot data from
            :param workspace_indices: workspace indices to plot from workspace
            :param errors: Plotting workspace errors
            :param plot_kwargs, arguments to Mantid axis plotting
            :return:
            """
        # check workspace exists -
        # retrieveWorkspaces expects a list of workspace names
        try:
            workspace = AnalysisDataService.Instance().retrieveWorkspaces(
                [workspace_name], unrollGroups=True)
        except RuntimeError:
            return

        self._do_single_plot(ax, workspace, workspace_indices, errors,
                             plot_kwargs)
        self._update_legend(ax)
Exemplo n.º 28
0
 def update(self):
     """
         Update data members according to reduction results
     """
     if IS_IN_MANTIDPLOT:
         from reduction_workflow.command_interface import ReductionSingleton
         self.log_text = ReductionSingleton().log_text
         try:
             if hasattr(ReductionSingleton(), "output_workspaces") \
             and len(ReductionSingleton().output_workspaces)>0:
                 for item in ReductionSingleton().output_workspaces:
                     mantidplot.plotSpectrum(item, 0, True)
             else:
                 iq_plots = []
                 for item in ReductionSingleton()._data_files.keys():
                     for ws in AnalysisDataService.Instance(
                     ).getObjectNames():
                         if ws.startswith(item) and ws.endswith('_Iq'):
                             iq_plots.append(ws)
                 if len(iq_plots) > 0:
                     mantidplot.plotSpectrum(iq_plots, 0, True)
         except:
             raise RuntimeError, "Could not plot resulting output\n  %s" % sys.exc_value
Exemplo n.º 29
0
    def test_fit_result_matrix_workspace_in_browser_is_viewed_when_clicked(self):
        if not PYQT5:
            self.skipTest("MatrixWorkspaceDisplay and TableWorkspaceDisplay cannot be "
                          "imported in qt4 so the test fails with an error.")
        from mantidqt.widgets.workspacedisplay.matrix.presenter import MatrixWorkspaceDisplay

        name = "ws"
        fig, canvas = self._create_and_plot_matrix_workspace(name)
        property_browser = self._create_widget(canvas=canvas)
        property_browser.setOutputName(name)

        # create fake fit output results
        matrixWorkspace = WorkspaceFactory.Instance().create("Workspace2D", NVectors=3, YLength=5, XLength=5)
        AnalysisDataService.Instance().addOrReplace(name + "_Workspace", matrixWorkspace)

        property_browser.fitting_done_slot(name + "_Workspace")
        wsList = property_browser.getWorkspaceList()

        # click on matrix workspace
        MatrixWorkspaceDisplay.show_view = Mock()
        item = wsList.item(0).text()
        property_browser.workspaceClicked.emit(item)
        self.assertEqual(1, MatrixWorkspaceDisplay.show_view.call_count)
Exemplo n.º 30
0
    def log_value(self, log_name):
        """
        Compute and return the log value for the named log.
        If the log is a string then the value is converted to a float
        if possible. If the log is a time series then the time-average
        value is computed. If multiple workspaces are part of the fit
        then the values computed above are averaged over each workspace.
        It is assumed that all logs have been checked for existence.
        :param log_name: The name of an existing log
        :return: A single double value
        """
        ads = AnalysisDataService.Instance()

        def value_from_workspace(wksp_name):
            run = ads.retrieve(wksp_name).run()
            prop = run.getProperty(log_name)
            if hasattr(prop, 'timeAverageValue'):
                return prop.timeAverageValue()
            else:
                try:
                    return float(prop.value)
                except ValueError:
                    return prop.valueAsStr

        values = [
            value_from_workspace(wksp_name)
            for wksp_name in self.output_workspace_names
        ]
        try:
            return np.mean(values)
        except TypeError:
            # This will be a string
            if len(values) == 1:
                return values[0]
            elif len(values) > 1:
                return str(values[0]) + " to " + str(values[-1])