示例#1
0
    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:
                QAppThreadCall(self.plot_loader.load_plots)(
                    self.project_reader.plot_list)

            # Load interfaces
            if self.project_reader.interface_list is not None:
                QAppThreadCall(self.load_interfaces)(directory)

        return workspace_success
示例#2
0
def apply_calibration(workspace: WorkspaceTypes, calibration_table: InputTable,
                      output_workspace: Optional[str] = None, show_instrument: bool = False) -> Workspace2D:
    r"""
    Calibrate the detector positions with an input table, and open the instrument view if so requested.

    :param workspace: input Workspace2D containing total neutron counts per pixel
    :param calibration_table: a TableWorskpace containing one column for detector ID and one column
    for its calibrated XYZ coordinates, in meters
    :param output_workspace: name of the output workspace containing calibrated detectors. If `None`, then
        the output workspace name will be the input workspace plus the suffix `_calibrated`
    :param show_instrument: open the instrument view for `output_workspace`

    :raises AssertionError: either `workspace` or `calibration_table` are not found
    """
    assert AnalysisDataService.doesExist(str(workspace)), f'No worksapce {str(workspace)} found'
    assert AnalysisDataService.doesExist(str(calibration_table)), f'No table {str(calibration_table)} found'
    if output_workspace is None:
        output_workspace = str(workspace) + '_calibrated'

    CloneWorkspace(InputWorkspace=workspace, OutputWorkspace=output_workspace)
    ApplyCalibration(Workspace=output_workspace, CalibrationTable=calibration_table)

    if show_instrument is True and None not in (InstrumentViewPresenter, InstrumentViewPresenter):
        instrument_presenter = QAppThreadCall(InstrumentViewPresenter)(mtd[output_workspace])
        QAppThreadCall(instrument_presenter.show_view)()

    return mtd[output_workspace]
示例#3
0
    def __init__(self, on_replace, on_rename, on_clear, on_delete):
        super(SliceViewerADSObserver, self).__init__()

        self.on_replace_workspace = QAppThreadCall(on_replace, blocking=False)
        self.on_rename_workspace = QAppThreadCall(on_rename, blocking=False)
        self.on_clear = QAppThreadCall(on_clear, blocking=False)
        self.on_delete_workspace = QAppThreadCall(on_delete, blocking=False)

        self.observeClear(True)
        self.observeDelete(True)
        self.observeReplace(True)
        self.observeRename(True)
示例#4
0
    def _save(self):
        self.__is_saving = True
        try:
            workspaces_to_save = self._get_workspace_names_to_save()

            if self.save_altered_workspaces_only:
                workspaces_to_save = self._filter_unaltered_workspaces(workspaces_to_save)

            # Calculate the size of the workspaces in the project.
            project_size = self._get_project_size(workspaces_to_save)
            warning_size = int(ConfigService.getString("projectSaving.warningSize"))
            # If a project is > the value in the properties file, question the user if they want to continue.
            result = None
            if project_size > warning_size:
                # we have to create the message box in the main thread
                result = QAppThreadCall(self._offer_large_size_confirmation)()

            if result is None or result != QMessageBox.Cancel:
                plots_to_save = self.plot_gfm.figs

                if self.save_altered_workspaces_only:
                    plots_to_save = self._filter_plots_with_unaltered_workspaces(plots_to_save, workspaces_to_save)

                interfaces_to_save = self.interface_populating_function()
                project_saver = ProjectSaver(self.project_file_ext)
                project_saver.save_project(file_name=self.last_project_location, workspace_to_save=workspaces_to_save,
                                           plots_to_save=plots_to_save, interfaces_to_save=interfaces_to_save)
                self.__saved = True
        finally:
            self.__is_saving = False
示例#5
0
    def __init__(self, *args, **kwargs):
        """
        A constructor matching that of RichJupyterWidget
        :param args: Positional arguments passed directly to RichJupyterWidget
        :param kwargs: Keyword arguments. The following keywords are understood by this widget:

          - startup_code: A code snippet to run on startup.

        the rest are passed to RichJupyterWidget
        """
        startup_code = kwargs.pop("startup_code", "")
        super(InProcessJupyterConsole, self).__init__(*args, **kwargs)

        # create an in-process kernel
        kernel_manager = QtInProcessKernelManager()
        kernel_manager.start_kernel()
        kernel = kernel_manager.kernel
        kernel.gui = 'qt'

        # use a separate thread for execution
        shell = kernel.shell
        shell.run_code = async_wrapper(shell.run_code, shell)

        # attach channels, start kernel and run any startup code
        kernel_client = kernel_manager.client()
        kernel_client.start_channels()
        if startup_code:
            shell.ex(startup_code)

        self.kernel_manager = kernel_manager
        self.kernel_client = kernel_client

        # Override python input to raise a QInputDialog.
        kernel.raw_input = QAppThreadCall(input_qinputdialog)
示例#6
0
 def __init__(self):
     super(Observable, self).__init__()
     self._subscribers = []
     self.thread_safe_update_call = QAppThreadCall(
         self._notify_subscribers_impl)
     self.arg = None
     self.kwargs = {}
示例#7
0
    def __init__(self, notifyee):
        """
        :param notifyee: An instance of a type with a refresh instance
        """
        super().__init__()
        self._refresh_widget = QAppThreadCall(notifyee.refresh)

        self.observeUpdate(True)
示例#8
0
def new_figure_manager_given_figure(num, figure):
    """Create a new manager from a num & figure """

    def _new_figure_manager_given_figure_impl(num: int, figure):
        """Create a new figure manager instance for the given figure.
        Forces all public and non-dunder method calls onto the QApplication thread.
        """
        canvas = MantidFigureCanvas(figure)
        return force_method_calls_to_qapp_thread(FigureManagerWorkbench(canvas, num))

    # figure manager & canvas must be created on the QApplication thread
    return QAppThreadCall(_new_figure_manager_given_figure_impl)(int(num), figure)
示例#9
0
 def override_python_input(self):
     """Replace python input with a call to a qinputdialog"""
     builtins.input = QAppThreadCall(input_qinputdialog)
示例#10
0
def get_instrumentview(workspace):
    """Return a handle to the instrument view of given workspace
    :param ws: input workspace
    """
    def _wrappper(ws):
        return force_method_calls_to_qapp_thread(InstrumentViewPresenter(ws))

    # need to do some duck-typing here
    ivp = QAppThreadCall(_wrappper)(workspace)
    # link nested method to top level
    # NOTE: setMin and setMax still leads to segfault, need to force
    #       wrapped in QAppThreadCall again
    ivp.reset_view = ivp.get_render_tab().resetView
    ivp.select_tab = ivp.container.select_tab
    ivp.select_surface_type = ivp.get_render_tab().setSurfaceType
    ivp.set_auto_scaling = ivp.get_render_tab().setColorMapAutoscaling
    ivp.set_axis = ivp.get_render_tab().setAxis
    ivp.set_bin_range = safe_qthread(ivp.container.widget.setBinRange)
    ivp.set_color_min = safe_qthread(ivp.get_render_tab().setMinValue)
    ivp.set_color_max = safe_qthread(ivp.get_render_tab().setMaxValue)
    ivp.set_color_range = safe_qthread(ivp.get_render_tab().setRange)
    ivp.set_color_scale = ivp.get_render_tab().setLegendScaleType
    return ivp
示例#11
0
 def _wrapped(*args, **kwargs):
     return QAppThreadCall(func)(*args, **kwargs)
示例#12
0
    def __init__(self, canvas, num):
        assert QAppThreadCall.is_qapp_thread(
        ), "FigureManagerWorkbench cannot be created outside of the QApplication thread"
        QObject.__init__(self)

        parent, flags = get_window_config()
        self.window = FigureWindow(canvas, parent=parent, window_flags=flags)
        self.window.activated.connect(self._window_activated)
        self.window.closing.connect(canvas.close_event)
        self.window.closing.connect(self.destroy)
        self.window.visibility_changed.connect(self.fig_visibility_changed)

        self.window.setWindowTitle("Figure %d" % num)
        canvas.figure.set_label("Figure %d" % num)

        FigureManagerBase.__init__(self, canvas, num)
        # Give the keyboard focus to the figure instead of the
        # manager; StrongFocus accepts both tab and click to focus and
        # will enable the canvas to process event w/o clicking.
        # ClickFocus only takes the focus is the window has been
        # clicked
        # on. http://qt-project.org/doc/qt-4.8/qt.html#FocusPolicy-enum or
        # http://doc.qt.digia.com/qt/qt.html#FocusPolicy-enum
        canvas.setFocusPolicy(Qt.StrongFocus)
        canvas.setFocus()

        self.window._destroying = False

        # add text label to status bar
        self.statusbar_label = QLabel()
        self.window.statusBar().addWidget(self.statusbar_label)

        self.plot_options_dialog = None
        self.toolbar = self._get_toolbar(canvas, self.window)
        if self.toolbar is not None:
            self.window.addToolBar(self.toolbar)
            self.toolbar.message.connect(self.statusbar_label.setText)
            self.toolbar.sig_grid_toggle_triggered.connect(self.grid_toggle)
            self.toolbar.sig_toggle_fit_triggered.connect(self.fit_toggle)
            self.toolbar.sig_toggle_superplot_triggered.connect(
                self.superplot_toggle)
            self.toolbar.sig_copy_to_clipboard_triggered.connect(
                self.copy_to_clipboard)
            self.toolbar.sig_plot_options_triggered.connect(
                self.launch_plot_options)
            self.toolbar.sig_plot_help_triggered.connect(self.launch_plot_help)
            self.toolbar.sig_generate_plot_script_clipboard_triggered.connect(
                self.generate_plot_script_clipboard)
            self.toolbar.sig_generate_plot_script_file_triggered.connect(
                self.generate_plot_script_file)
            self.toolbar.sig_home_clicked.connect(
                self.set_figure_zoom_to_display_all)
            self.toolbar.sig_waterfall_reverse_order_triggered.connect(
                self.waterfall_reverse_line_order)
            self.toolbar.sig_waterfall_offset_amount_triggered.connect(
                self.launch_waterfall_offset_options)
            self.toolbar.sig_waterfall_fill_area_triggered.connect(
                self.launch_waterfall_fill_area_options)
            self.toolbar.sig_waterfall_conversion.connect(
                self.update_toolbar_waterfall_plot)
            self.toolbar.sig_change_line_collection_colour_triggered.connect(
                self.change_line_collection_colour)
            self.toolbar.setFloatable(False)
            tbs_height = self.toolbar.sizeHint().height()
        else:
            tbs_height = 0

        # resize the main window so it will display the canvas with the
        # requested size:
        cs = canvas.sizeHint()
        sbs = self.window.statusBar().sizeHint()
        self._status_and_tool_height = tbs_height + sbs.height()
        height = cs.height() + self._status_and_tool_height
        self.window.resize(cs.width(), height)

        self.fit_browser = FitPropertyBrowser(
            canvas, ToolbarStateManager(self.toolbar))
        self.fit_browser.closing.connect(self.handle_fit_browser_close)
        self.window.setCentralWidget(canvas)
        self.window.addDockWidget(Qt.LeftDockWidgetArea, self.fit_browser)

        self.superplot = None

        # Need this line to stop the bug where the dock window snaps back to its original size after resizing.
        # 0 argument is arbitrary and has no effect on fit widget size
        # This is a qt bug reported at (https://bugreports.qt.io/browse/QTBUG-65592)
        if QT_VERSION >= LooseVersion("5.6"):
            self.window.resizeDocks([self.fit_browser], [1], Qt.Horizontal)
        self.fit_browser.hide()

        if matplotlib.is_interactive():
            self.window.show()
            canvas.draw_idle()

        def notify_axes_change(fig):
            # This will be called whenever the current axes is changed
            if self.toolbar is not None:
                self.toolbar.update()

        canvas.figure.add_axobserver(notify_axes_change)

        # Register canvas observers
        self._fig_interaction = FigureInteraction(self)
        self._ads_observer = FigureManagerADSObserver(self)

        self.window.raise_()
示例#13
0
 def task(self):
     qappthread_wrap = QAppThreadCall(self.raises_exception)
     qappthread_wrap()
示例#14
0
    def test_correct_exception_is_raised_when_called_on_main_thread(self):
        qappthread_wrap = QAppThreadCall(self.raises_exception)

        self.assertRaises(CustomException, qappthread_wrap)
示例#15
0
文件: view.py 项目: ethoeng/mantid
    def __init__(self, presenter, parent=None):
        """
        Initialise a new instance of PlotSelectorWidget
        :param presenter: The presenter controlling this view
        :param parent: Optional - the parent QWidget
        running as a unit test, in which case skip file dialogs
        """
        super(PlotSelectorView, self).__init__(parent)
        self.presenter = presenter

        # This mutex prevents multiple operations on the table at the
        # same time. Wrap code in - with QMutexLocker(self.mutex):
        self.mutex = QMutex()
        self.active_plot_number = -1

        self.show_button = QPushButton('Show')
        self.hide_button = QPushButton('Hide')
        # Note this button is labeled delete, but for consistency
        # with matplotlib 'close' is used in the code
        self.close_button = QPushButton('Delete')
        self.select_all_button = QPushButton('Select All')
        self.sort_button = self._make_sort_button()
        self.export_button = self._make_export_button()
        self.filter_box = self._make_filter_box()
        self.table_widget = self._make_table_widget()

        # Add the context menu
        self.table_widget.setContextMenuPolicy(Qt.CustomContextMenu)
        self.context_menu, self.export_menu = self._make_context_menu()
        self.table_widget.customContextMenuRequested.connect(
            self.context_menu_opened)

        buttons_layout = FlowLayout()
        buttons_layout.setSpacing(1)
        buttons_layout.addWidget(self.show_button)
        buttons_layout.addWidget(self.hide_button)
        buttons_layout.addWidget(self.close_button)
        buttons_layout.addWidget(self.select_all_button)
        buttons_layout.addWidget(self.sort_button)
        buttons_layout.addWidget(self.export_button)

        filter_layout = QHBoxLayout()
        filter_layout.addWidget(self.filter_box)

        layout = QVBoxLayout()
        layout.addLayout(buttons_layout)
        layout.addLayout(filter_layout)
        layout.addWidget(self.table_widget)
        # todo: Without the sizeHint() call the minimum size is not set correctly
        #       This needs some investigation as to why this is.
        layout.sizeHint()
        self.setLayout(layout)

        # Any updates that originate from the matplotlib figure
        # windows must be wrapped in a QAppThreadCall. Not doing this
        # WILL result in segfaults.
        self.set_plot_list_orig = self.set_plot_list
        self.set_plot_list = QAppThreadCall(self.set_plot_list_orig)
        self.append_to_plot_list_orig = self.append_to_plot_list
        self.append_to_plot_list = QAppThreadCall(
            self.append_to_plot_list_orig)
        self.remove_from_plot_list_orig = self.remove_from_plot_list
        self.remove_from_plot_list = QAppThreadCall(
            self.remove_from_plot_list_orig)
        self.rename_in_plot_list_orig = self.rename_in_plot_list
        self.rename_in_plot_list = QAppThreadCall(
            self.rename_in_plot_list_orig)
        self.set_active_font_orig = self.set_active_font
        self.set_active_font = QAppThreadCall(self.set_active_font_orig)
        self.set_visibility_icon_orig = self.set_visibility_icon
        self.set_visibility_icon = QAppThreadCall(
            self.set_visibility_icon_orig)
        self.set_last_active_values_orig = self.set_last_active_values
        self.set_last_active_values = QAppThreadCall(
            self.set_last_active_values_orig)
        self.sort_type_orig = self.sort_type
        self.sort_type = QAppThreadCall(self.sort_type_orig)

        # Connect presenter methods to things in the view
        self.show_button.clicked.connect(self.presenter.show_multiple_selected)
        self.hide_button.clicked.connect(self.presenter.hide_selected_plots)
        self.close_button.clicked.connect(self.presenter.close_action_called)
        self.select_all_button.clicked.connect(self.table_widget.selectAll)
        self.table_widget.doubleClicked.connect(
            self.presenter.show_single_selected)
        self.filter_box.textChanged.connect(self.presenter.filter_text_changed)
        self.deleteKeyPressed.connect(self.presenter.close_action_called)

        if DEBUG_MODE:
            self.table_widget.clicked.connect(self.show_debug_info)
示例#16
0
 def _generate_script_from_workspaces(self):
     script = "from mantid.simpleapi import *\n\n" + get_all_workspace_history_from_ads(
     )
     QAppThreadCall(self.editor.open_script_in_new_tab)(script)
示例#17
0
    def __init__(self, canvas, num):
        QObject.__init__(self)
        FigureManagerBase.__init__(self, canvas, num)
        # Patch show/destroy to be thread aware
        self._destroy_orig = self.destroy
        self.destroy = QAppThreadCall(self._destroy_orig)
        self._show_orig = self.show
        self.show = QAppThreadCall(self._show_orig)
        self._window_activated_orig = self._window_activated
        self._window_activated = QAppThreadCall(self._window_activated_orig)
        self.set_window_title_orig = self.set_window_title
        self.set_window_title = QAppThreadCall(self.set_window_title_orig)
        self.fig_visibility_changed_orig = self.fig_visibility_changed
        self.fig_visibility_changed = QAppThreadCall(self.fig_visibility_changed_orig)

        self.window = FigureWindow(canvas)
        self.window.activated.connect(self._window_activated)
        self.window.closing.connect(canvas.close_event)
        self.window.closing.connect(self.destroy)
        self.window.visibility_changed.connect(self.fig_visibility_changed)

        self.window.setWindowTitle("Figure %d" % num)
        canvas.figure.set_label("Figure %d" % num)

        # Give the keyboard focus to the figure instead of the
        # manager; StrongFocus accepts both tab and click to focus and
        # will enable the canvas to process event w/o clicking.
        # ClickFocus only takes the focus is the window has been
        # clicked
        # on. http://qt-project.org/doc/qt-4.8/qt.html#FocusPolicy-enum or
        # http://doc.qt.digia.com/qt/qt.html#FocusPolicy-enum
        canvas.setFocusPolicy(Qt.StrongFocus)
        canvas.setFocus()

        self.window._destroying = False

        # add text label to status bar
        self.statusbar_label = QLabel()
        self.window.statusBar().addWidget(self.statusbar_label)

        self.plot_options_dialog = None
        self.toolbar = self._get_toolbar(canvas, self.window)
        if self.toolbar is not None:
            self.window.addToolBar(self.toolbar)
            self.toolbar.message.connect(self.statusbar_label.setText)
            self.toolbar.sig_grid_toggle_triggered.connect(self.grid_toggle)
            self.toolbar.sig_toggle_fit_triggered.connect(self.fit_toggle)
            self.toolbar.sig_plot_options_triggered.connect(self.launch_plot_options)
            self.toolbar.setFloatable(False)
            tbs_height = self.toolbar.sizeHint().height()
        else:
            tbs_height = 0

        # resize the main window so it will display the canvas with the
        # requested size:
        cs = canvas.sizeHint()
        sbs = self.window.statusBar().sizeHint()
        self._status_and_tool_height = tbs_height + sbs.height()
        height = cs.height() + self._status_and_tool_height
        self.window.resize(cs.width(), height)

        self.fit_browser = FitPropertyBrowser(canvas,
                                              ToolbarStateManager(self.toolbar))
        self.fit_browser.closing.connect(self.handle_fit_browser_close)
        self.window.setCentralWidget(canvas)
        self.window.addDockWidget(Qt.LeftDockWidgetArea, self.fit_browser)
        self.fit_browser.hide()

        if matplotlib.is_interactive():
            self.window.show()
            canvas.draw_idle()

        def notify_axes_change(fig):
            # This will be called whenever the current axes is changed
            if self.toolbar is not None:
                self.toolbar.update()

        canvas.figure.add_axobserver(notify_axes_change)

        # Register canvas observers
        self._fig_interaction = FigureInteraction(self)
        self._ads_observer = FigureManagerADSObserver(self)

        self.window.raise_()