Beispiel #1
0
    def action_show_minor_ticks_changed(self, state):
        ConfigService.setString(PlotProperties.SHOW_MINOR_TICKS.value,
                                "On" if state == Qt.Checked else "Off")
        self.view.show_minor_gridlines.setEnabled(state == Qt.Checked)

        if not self.view.show_minor_gridlines.isEnabled():
            self.view.show_minor_gridlines.setChecked(False)
Beispiel #2
0
    def __init__(self,
                 view,
                 exit_code: str,
                 application: str,
                 traceback: Optional[str] = None):
        """
        :param view: A reference to the view managed by this presenter
        :param exit_code: A string containing the exit_code of the failing application
        :param application: A string containing the failing application name
        :param traceback: An optional string containing a traceback dumped as JSON-encoded string
        """
        self.error_log = Logger("errorreports")
        self._view = view
        self._exit_code = exit_code
        self._application = application
        self._traceback = traceback if traceback else ''
        self._view.set_report_callback(self.error_handler)
        self._view.moreDetailsButton.clicked.connect(self.show_more_details)

        if not traceback:
            traceback_file_path = os.path.join(
                ConfigService.getAppDataDirectory(),
                '{}_stacktrace.txt'.format(application))
            try:
                if os.path.isfile(traceback_file_path):
                    with open(traceback_file_path, 'r') as file:
                        self._traceback = file.readlines()
                    new_workspace_name = os.path.join(
                        ConfigService.getAppDataDirectory(),
                        '{}_stacktrace_sent.txt'.format(application))
                    os.rename(traceback_file_path, new_workspace_name)
            except OSError:
                pass
Beispiel #3
0
    def __init__(self,
                 view,
                 exit_code,
                 application='mantidplot',
                 traceback=''):
        self.error_log = Logger("error")
        self._view = view
        self._exit_code = exit_code
        self._application = application
        self._traceback = traceback
        self._view.set_report_callback(self.error_handler)

        if not traceback:
            traceback_file_path = os.path.join(
                ConfigService.getAppDataDirectory(),
                '{}_stacktrace.txt'.format(application))
            try:
                if os.path.isfile(traceback_file_path):
                    with open(traceback_file_path, 'r') as file:
                        self._traceback = file.readlines()
                    new_workspace_name = os.path.join(
                        ConfigService.getAppDataDirectory(),
                        '{}_stacktrace_sent.txt'.format(application))
                    os.rename(traceback_file_path, new_workspace_name)
            except OSError:
                pass
Beispiel #4
0
    def load_current_setting_values(self):
        background = ConfigService.getString(self.AUTO_BACKGROUND).split(
            " ", 1)
        if self.view.auto_bkg.findText(background[0], Qt.MatchExactly) != -1:
            self.view.auto_bkg.setCurrentText(background[0])
        else:
            self.view.auto_bkg.setCurrentText("LinearBackground")
        if len(background) > 1:
            self.view.background_args.setText(background[1])

        default_peak = ConfigService.getString(self.DEFAULT_PEAK)
        if self.view.default_peak.findText(default_peak,
                                           Qt.MatchExactly) != -1:
            self.view.default_peak.setCurrentText(default_peak)
        else:
            self.view.auto_bkg.setCurrentText("Gaussian")

        fwhm = ConfigService.getString(self.FWHM)
        if fwhm == "":
            self.view.findpeaks_fwhm.setValue(7)
        else:
            self.view.findpeaks_fwhm.setValue(int(fwhm))

        tolerance = ConfigService.getString(self.TOLERANCE)
        if tolerance == "":
            self.view.findpeaks_tol.setValue(4)
        else:
            self.view.findpeaks_tol.setValue(int(tolerance))
Beispiel #5
0
    def __init__(self, multifileinterpreter, main_window=None, globalfiguremanager=None):
        """
        Project Recovery class is aimed at allowing you to recovery your workbench project should you crash for whatever
         reason
        :param multifileinterpreter: MultiPythonFileInterpreter; An object that is used in workbench to represent the
        python script editor
        :param main_window: A reference to the main window object to be used as a parent to the project recovery GUIs
        :param globalfiguremanager: Based on the globalfiguremanager object expects an object with a dictionary on
        cls/self.figs for the object passed here which contains all of the plots open/needed to be saved
        """
        self._recovery_directory = os.path.join(ConfigService.getAppDataDirectory(),
                                                self.recovery_workbench_recovery_name)
        self._recovery_directory_hostname = os.path.join(self.recovery_directory, socket.gethostname())
        self._recovery_directory_pid = os.path.join(self.recovery_directory_hostname, str(os.getpid()))

        self._recovery_order_workspace_history_file = os.path.join(ConfigService.getAppDataDirectory(),
                                                                   self.recovery_ordered_recovery_file_name)

        self.recovery_enabled = ("true" == ConfigService[RECOVERY_ENABLED_KEY].lower())
        self.maximum_num_checkpoints = int(ConfigService[NO_OF_CHECKPOINTS_KEY])
        self.time_between_saves = int(ConfigService[SAVING_TIME_KEY])  # seconds

        # The recovery GUI's presenter is set when needed
        self.recovery_presenter = None

        self.thread_on = False

        # Set to true by workbench on close to kill the thread on completion of project save
        self.closing_workbench = False

        # Recovery loader and saver
        self.loader = ProjectRecoveryLoader(self, multi_file_interpreter=multifileinterpreter, main_window=main_window)
        self.saver = ProjectRecoverySaver(self, globalfiguremanager)
Beispiel #6
0
def pcolormesh_on_axis(ax, ws, color_norm=None, normalize_by_bin_width=None):
    """
    Plot a pcolormesh plot of the given workspace on the given axis
    :param ax: A matplotlib axes instance
    :param ws: A mantid workspace instance
    :param color_norm: A matplotlib.colours Normalize instance (or any of its subclasses)
    :param normalize_by_bin_width: Optional keyword argument to pass to imshow in the event of a plot restoration
    :return:
    """
    ax.clear()
    ax.set_title(ws.name())
    scale = _get_colorbar_scale() if not color_norm else color_norm

    if use_imshow(ws):
        pcm = ax.imshow(ws,
                        cmap=ConfigService.getString("plots.images.Colormap"),
                        aspect='auto',
                        origin='lower',
                        norm=scale,
                        normalize_by_bin_width=normalize_by_bin_width)
        # remove normalize_by_bin_width from cargs if present so that this can be toggled in future
        for cargs in pcm.axes.creation_args:
            cargs.pop('normalize_by_bin_width')
    else:
        pcm = ax.pcolormesh(
            ws,
            cmap=ConfigService.getString("plots.images.Colormap"),
            norm=scale)

    return pcm
Beispiel #7
0
 def action_background_args_changed(self):
     if self.view.auto_bkg.currentText() == "None":
         ConfigService.setString(self.AUTO_BACKGROUND, "")
     else:
         background_string = self.view.auto_bkg.currentText(
         ) + " " + self.view.background_args.text()
         ConfigService.setString(self.AUTO_BACKGROUND, background_string)
Beispiel #8
0
    def setup_facilities_group(self):
        facilities = ConfigService.getFacilityNames()
        if not facilities:
            return
        self.view.facility.addItems(facilities)

        try:
            default_facility = ConfigService.getFacility().name()
        except RuntimeError:
            default_facility = facilities[0]
        self.view.facility.setCurrentIndex(
            self.view.facility.findText(default_facility))
        self.action_facility_changed(default_facility)
        self.view.facility.currentTextChanged.connect(
            self.action_facility_changed)

        try:
            default_instrument = ConfigService.getInstrument().name()
            self.view.instrument.setCurrentIndex(
                self.view.instrument.findText(default_instrument))
        except RuntimeError:
            default_instrument = self.view.instrument.itemText(0)
        self.action_instrument_changed(default_instrument)
        self.view.instrument.currentTextChanged.connect(
            self.action_instrument_changed)
    def __init__(self, multifileinterpreter, main_window=None, globalfiguremanager=None):
        """
        Project Recovery class is aimed at allowing you to recovery your workbench project should you crash for whatever
         reason
        :param multifileinterpreter: MultiPythonFileInterpreter; An object that is used in workbench to represent the
        python script editor
        :param main_window: A reference to the main window object to be used as a parent to the project recovery GUIs
        :param globalfiguremanager: Based on the globalfiguremanager object expects an object with a dictionary on
        cls/self.figs for the object passed here which contains all of the plots open/needed to be saved
        """
        self._recovery_directory = os.path.join(ConfigService.getAppDataDirectory(),
                                                self.recovery_workbench_recovery_name)
        self._recovery_directory_hostname = os.path.join(self.recovery_directory, socket.gethostname())
        self._recovery_directory_pid = os.path.join(self.recovery_directory_hostname, str(os.getpid()))

        self._recovery_order_workspace_history_file = os.path.join(ConfigService.getAppDataDirectory(),
                                                                   self.recovery_ordered_recovery_file_name)

        self.recovery_enabled = ("true" == ConfigService[RECOVERY_ENABLED_KEY].lower())
        self.maximum_num_checkpoints = int(ConfigService[NO_OF_CHECKPOINTS_KEY])
        self.time_between_saves = int(ConfigService[SAVING_TIME_KEY])  # seconds

        # The recovery GUI's presenter is set when needed
        self.recovery_presenter = None

        self.thread_on = False

        # Set to true by workbench on close to kill the thread on completion of project save
        self.closing_workbench = False

        # Recovery loader and saver
        self.loader = ProjectRecoveryLoader(self, multi_file_interpreter=multifileinterpreter, main_window=main_window)
        self.saver = ProjectRecoverySaver(self, globalfiguremanager)
Beispiel #10
0
    def load_general_setting_values(self):
        normalize_to_bin_width = "on" == ConfigService.getString(
            self.NORMALIZATION).lower()
        show_title = "on" == ConfigService.getString(self.SHOW_TITLE).lower()

        self.view.normalize_to_bin_width.setChecked(normalize_to_bin_width)
        self.view.show_title.setChecked(show_title)
Beispiel #11
0
    def should_show_on_startup():
        """ Determines if the first time dialog should be shown
        :return: True if the dialog should be shown
        """
        # first check the facility and instrument
        facility = ConfigService.getString(AboutPresenter.FACILITY)
        instrument = ConfigService.getString(AboutPresenter.INSTRUMENT)
        if not facility:
            return True
        else:
            # check we can get the facility and instrument
            try:
                facilityInfo = ConfigService.getFacility(facility)
                instrumentInfo = ConfigService.getInstrument(instrument)
                logger.information("Default facility '{0}', instrument '{1}'\n".format(facilityInfo.name(),
                                                                                       instrumentInfo.name()))
            except RuntimeError:
                # failed to find the facility or instrument
                logger.error("Could not find your default facility '{0}' or instrument '{1}' in facilities.xml, "
                             + "showing please select again.\n".format(facility, instrument))
                return True

        settings = QSettings()
        settings.beginGroup(AboutPresenter.DO_NOT_SHOW_GROUP)
        doNotShowUntilNextRelease =int(settings.value(AboutPresenter.DO_NOT_SHOW, '0'))
        lastVersion = settings.value(AboutPresenter.LAST_VERSION, "")
        settings.endGroup()

        if not doNotShowUntilNextRelease:
            return True

        # Now check if the version has changed since last time
        version = release_notes_url()
        return version != lastVersion
    def setUpClass(cls):
        ConfigService.Instance().setString("default.facility", "ISIS")
        # A small workspace for general tests
        test_workspace = LoadNexusProcessed(Filename="LOQ48127")
        cls.immutable_test_workspace = test_workspace

        # A full workspace on which we can test region of interest selection
        region_of_interest_workspace = Load(Filename="LOQ74044")
        cls.region_of_interest_workspace = region_of_interest_workspace

        # A region of interest xml file
        roi_content = ("<?xml version=\"1.0\"?>\n"
                       "\t<detector-masking>\n"
                       "\t\t<group>\n"
                       "\t\t\t<detids>6990-6996</detids>\n"
                       "\t\t</group>\n"
                       "\t</detector-masking>\n")
        cls.roi_file_path = cls._get_path(cls.roi_file)
        cls._save_file(cls.roi_file_path, roi_content)

        # A mask file
        mask_content = ("<?xml version=\"1.0\"?>\n"
                        "\t<detector-masking>\n"
                        "\t\t<group>\n"
                        "\t\t\t<detids>6991</detids>\n"
                        "\t\t</group>\n"
                        "\t</detector-masking>\n")
        cls.mask_file_path = cls._get_path(cls.mask_file)
        cls._save_file(cls.mask_file_path, mask_content)
        ConfigService.Instance().setString("default.facility", " ")
Beispiel #13
0
    def setup_facilities_group(self):
        facilities = sorted(ConfigService.getFacilityNames())
        if not facilities:
            return
        self.view.facility.addItems(facilities)
        self.view.instrument = instrumentselector.InstrumentSelector()
        self.view.horizontalLayout_4.replaceWidget(self.view.instrument_dummy,
                                                   self.view.instrument)
        self.view.instrument_dummy.setVisible(False)

        try:
            default_facility = ConfigService.getFacility().name()
        except RuntimeError:
            default_facility = facilities[0]
        self.view.facility.setCurrentIndex(
            self.view.facility.findText(default_facility))
        self.action_facility_changed(default_facility)
        self.view.facility.currentTextChanged.connect(
            self.action_facility_changed)

        try:
            default_instrument = ConfigService.getInstrument().name()
        except RuntimeError:
            default_instrument = self.view.instrument.itemText(0)
        self.action_instrument_changed(default_instrument)
        self.view.instrument.currentTextChanged.connect(
            self.action_instrument_changed)
    def test_constructor_settings_are_set(self):
        # Test the paths set in the constructor that are generated.
        self.assertEqual(
            self.pr.recovery_directory,
            os.path.join(ConfigService.getAppDataDirectory(),
                         "workbench-recovery"))
        self.assertEqual(
            self.pr.recovery_directory_hostname,
            os.path.join(ConfigService.getAppDataDirectory(),
                         "workbench-recovery", socket.gethostname()))
        self.assertEqual(
            self.pr.recovery_directory_pid,
            os.path.join(ConfigService.getAppDataDirectory(),
                         "workbench-recovery", socket.gethostname(),
                         str(os.getpid())))
        self.assertEqual(
            self.pr.recovery_order_workspace_history_file,
            os.path.join(ConfigService.getAppDataDirectory(),
                         "ordered_recovery.py"))

        # Test config service values
        self.assertEqual(self.pr.time_between_saves,
                         int(ConfigService[SAVING_TIME_KEY]))
        self.assertEqual(self.pr.maximum_num_checkpoints,
                         int(ConfigService[NO_OF_CHECKPOINTS_KEY]))
        self.assertEqual(
            self.pr.recovery_enabled,
            ("true" == ConfigService[RECOVERY_ENABLED_KEY].lower()))
Beispiel #15
0
def get_plot_fig(overplot=None,
                 ax_properties=None,
                 window_title=None,
                 axes_num=1,
                 fig=None):
    """
    Create a blank figure and axes, with configurable properties.
    :param overplot: If true then plotting on figure will plot over previous plotting. If an axis object the overplotting
    will be done on the axis passed in
    :param ax_properties: A dict of axes properties. E.g. {'yscale': 'log'} for log y-axis
    :param window_title: A string denoting the name of the GUI window which holds the graph
    :param axes_num: The number of axes to create on the figure
    :param fig: An optional figure object
    :return: Matplotlib fig and axes objects
    """
    import matplotlib.pyplot as plt

    if fig and overplot:
        fig = fig
    elif fig:
        fig, _, _, _ = create_subplots(axes_num, fig)
    elif overplot:
        # The create subplot below assumes no figure was passed in, this is ensured by the elif above
        # but add an assert which prevents a future refactoring from breaking this assumption
        assert not fig
        fig = plt.gcf()
        if not fig.axes:
            plt.close(fig)
            # The user is likely trying to overplot on a non-existent plot, create one for them
            fig, _, _, _ = create_subplots(axes_num)
    else:
        fig, _, _, _ = create_subplots(axes_num)

    if not ax_properties and not overplot:
        ax_properties = {}
        if ConfigService.getString("plots.xAxesScale").lower() == 'log':
            ax_properties['xscale'] = 'log'
        else:
            ax_properties['xscale'] = 'linear'
        if ConfigService.getString("plots.yAxesScale").lower() == 'log':
            ax_properties['yscale'] = 'log'
        else:
            ax_properties['yscale'] = 'linear'
    if ax_properties:
        for axis in fig.axes:
            axis.set(**ax_properties)
    if window_title:
        fig.canvas.set_window_title(window_title)

    if not overplot:
        if ConfigService.getString("plots.ShowMinorTicks").lower() == "on":
            for ax in fig.axes:
                ax.minorticks_on()

        for ax in fig.axes:
            ax.show_minor_gridlines = ConfigService.getString(
                "plots.ShowMinorGridlines").lower() == "on"

    return fig, fig.axes
Beispiel #16
0
    def setup_layout(self, load_last=False):
        """
            Sets up the instrument-specific part of the UI layout
        """
        # Clean up the widgets that have already been created
        self.tabWidget.clear()
        self.progress_bar.hide()

        if self._instrument == '' or self._instrument is None:
            return self._change_instrument()

        self._update_file_menu()

        if self._interface is not None:
            self._interface.destroy()

        self.general_settings.instrument_name = self._instrument
        # Find corresponding facility
        if self._facility is None:
            for facility in INSTRUMENT_DICT.keys():
                if self._instrument in INSTRUMENT_DICT[facility].keys():
                    self._facility = facility
                    break
        if self._facility is None:
            self._facility = ConfigService.Instance().getFacility().name()

        self.general_settings.facility_name = self._facility
        self._interface = instrument_factory(self._instrument, settings=self.general_settings)

        if self._interface is not None:
            tab_list = self._interface.get_tabs()
            for tab in tab_list:
                self.tabWidget.addTab(tab[1], tab[0])
            self._set_window_title()

            # Show the "advanced interface" check box if needed
            if self._interface.has_advanced_version():
                self.interface_chk.show()
            else:
                self.interface_chk.hide()

            # Show the parallel reduction button if enabled
            if self._interface.is_cluster_enabled() and IS_IN_MANTIDPLOT \
            and CLUSTER_ENABLED:
                config = ConfigService.Instance()
                if config.hasProperty("cluster.submission") \
                and config.getString("cluster.submission").lower()=='on':
                    self.cluster_button.show()
                    self.connect(self.cluster_button, QtCore.SIGNAL("clicked()"), self.cluster_clicked)
            else:
                self.cluster_button.hide()

            if load_last:
                self._interface.load_last_reduction()
        else:
            print "Could not generate an interface for instrument %s" % self._instrument
            self.close()

        return True
 def test_update_and_set_facility(self):
     self.assertFalse("TEST" in config.getFacilityNames())
     ConfigService.updateFacilities(
         os.path.join(ConfigService.getInstrumentDirectory(),
                      "IDFs_for_UNIT_TESTING/UnitTestFacilities.xml"))
     ConfigService.setFacility("TEST")
     self.assertEquals(config.getFacility().name(), "TEST")
     self.assertRaises(RuntimeError, config.getFacility, "SNS")
Beispiel #18
0
 def action_auto_background_changed(self, item_name):
     if item_name == "None":
         ConfigService.setString(FittingProperties.AUTO_BACKGROUND.value,
                                 "")
         return
     background_string = item_name + " " + self.view.background_args.text()
     ConfigService.setString(FittingProperties.AUTO_BACKGROUND.value,
                             background_string)
 def test_update_and_set_facility(self):
     self.assertFalse("TEST" in config.getFacilityNames())
     ConfigService.updateFacilities(
         os.path.join(ConfigService.getInstrumentDirectory(), "IDFs_for_UNIT_TESTING/UnitTestFacilities.xml")
     )
     ConfigService.setFacility("TEST")
     self.assertEquals(config.getFacility().name(), "TEST")
     self.assertRaises(RuntimeError, config.getFacility, "SNS")
    def __init__(self):
        super(PythonInterfacesStartupTest, self).__init__()

        self._app = get_application()

        self._interface_directory = ConfigService.getString('mantidqt.python_interfaces_directory')
        self._interface_scripts = [interface.split("/")[1] for interface in
                                   ConfigService.getString('mantidqt.python_interfaces').split()
                                   if interface.split("/")[1] not in EXCLUDED_SCRIPTS]
Beispiel #21
0
 def setup_legend_group(self):
     legend_location = ConfigService.getString(
         PlotProperties.LEGEND_LOCATION.value)
     self.view.legend_location.addItems(self.LEGEND_LOCATION_LIST)
     if legend_location in self.LEGEND_LOCATION_LIST:
         self.view.legend_location.setCurrentIndex(
             self.view.legend_location.findText(legend_location))
     legend_font_size = float(
         ConfigService.getString(PlotProperties.LEGEND_FONT_SIZE.value))
     self.view.legend_font_size.setValue(legend_font_size)
Beispiel #22
0
 def action_facility_changed(self, new_facility):
     """
     When the facility is changed, refreshes all available instruments that can be selected in the dropdown.
     :param new_facility: The name of the new facility that was selected
     """
     ConfigService.setFacility(new_facility)
     # refresh the instrument selection to contain instruments about the selected facility only
     self.view.instrument.clear()
     self.view.instrument.addItems(
         [instr.name() for instr in ConfigService.getFacility(new_facility).instruments()])
Beispiel #23
0
 def save_on_closing(self):
     # make sure the Last Version is updated on closing
     settings = QSettings()
     settings.beginGroup(self.DO_NOT_SHOW_GROUP)
     settings.setValue(self.LAST_VERSION, release_notes_url())
     settings.endGroup()
     self.store_facility(self.view.cb_facility.currentText())
     self.action_instrument_changed(self.view.cb_instrument.currentText())
     ConfigService.saveConfig(ConfigService.getUserFilename())
     self.parent.config_updated()
Beispiel #24
0
    def action_close(self):
        # make sure the Last Version is updated on closing
        settings = QSettings()
        settings.beginGroup(self.DO_NOT_SHOW_GROUP)
        settings.setValue(self.LAST_VERSION, release_notes_url())
        settings.endGroup()

        ConfigService.saveConfig(ConfigService.getUserFilename())
        self.parent.config_updated()
        self.view.close()
Beispiel #25
0
    def setup_error_bar_group(self):
        error_width = float(ConfigService.getString(self.ERROR_WIDTH))
        capsize = float(ConfigService.getString(self.CAPSIZE))
        cap_thickness = float(ConfigService.getString(self.CAP_THICKNESS))
        error_every = int(ConfigService.getString(self.ERROR_EVERY))

        self.view.error_width.setValue(error_width)
        self.view.capsize.setValue(capsize)
        self.view.cap_thickness.setValue(cap_thickness)
        self.view.error_every.setValue(error_every)
Beispiel #26
0
    def test_that_load_dead_time_from_filename_places_table_in_ADS(self):
        ConfigService.Instance().setString("default.facility", "ISIS")
        filename = 'MUSR00022725.nsx'

        name = utils.load_dead_time_from_filename(filename)
        dead_time_table = AnalysisDataService.retrieve('MUSR00022725.nsx_deadtime_table')

        self.assertEqual(name, 'MUSR00022725.nsx_deadtime_table')
        self.assertTrue(isinstance(dead_time_table, ITableWorkspace))
        ConfigService.Instance().setString("default.facility", " ")
Beispiel #27
0
def _add_default_plot_kwargs_from_settings(plot_kwargs, errors):
    if 'linestyle' not in plot_kwargs:
        plot_kwargs['linestyle'] = ConfigService.getString("plots.line.Style")
    if 'drawstyle' not in plot_kwargs:
        plot_kwargs['drawstyle'] = ConfigService.getString(
            "plots.line.DrawStyle")
    if 'linewidth' not in plot_kwargs:
        plot_kwargs['linewidth'] = float(
            ConfigService.getString("plots.line.Width"))
    if 'marker' not in plot_kwargs:
        plot_kwargs['marker'] = MARKER_MAP[ConfigService.getString(
            "plots.marker.Style")]
    if 'markersize' not in plot_kwargs:
        plot_kwargs['markersize'] = float(
            ConfigService.getString("plots.marker.Size"))
    if errors:
        if 'capsize' not in plot_kwargs:
            plot_kwargs['capsize'] = float(
                ConfigService.getString("plots.errorbar.Capsize"))
        if 'capthick' not in plot_kwargs:
            plot_kwargs['capthick'] = float(
                ConfigService.getString("plots.errorbar.CapThickness"))
        if 'errorevery' not in plot_kwargs:
            plot_kwargs['errorevery'] = int(
                ConfigService.getString("plots.errorbar.errorEvery"))
        if 'elinewidth' not in plot_kwargs:
            plot_kwargs['elinewidth'] = float(
                ConfigService.getString("plots.errorbar.Width"))
Beispiel #28
0
    def action_usage_data_changed(self, checkedState):
        if not checkedState:
            response = self.usage_reporting_verification_view.exec()

            if not response:
                # No was clicked, or no button was clicked
                # set the checkbox back to checked
                checkedState = Qt.Checked
                self.view.chkAllowUsageData.setCheckState(checkedState)

        ConfigService.setString(self.USAGE_REPORTING, "1" if checkedState == Qt.Checked else "0")
Beispiel #29
0
    def test_load_workspace_from_filename_for_existing_file(self):
        ConfigService.Instance().setString("default.facility", "ISIS")
        filename = 'MUSR00022725.nsx'
        load_result, run, filename, _ = utils.load_workspace_from_filename(filename)

        self.assertEqual(load_result['DeadTimeTable'], None)
        self.assertEqual(load_result['FirstGoodData'], 0.106)
        self.assertEqual(load_result['MainFieldDirection'], 'Transverse')
        self.assertAlmostEqual(load_result['TimeZero'], 0.55000, 5)
        self.assertEqual(run, 22725)
        ConfigService.Instance().setString("default.facility", " ")
Beispiel #30
0
    def setup_line_group(self):
        line_style = ConfigService.getString(self.LINE_STYLE)
        self.view.line_style.addItems(VALID_LINE_STYLE)
        if line_style in VALID_LINE_STYLE:
            self.view.line_style.setCurrentIndex(
                self.view.line_style.findText(line_style))
        else:
            self.view.line_style.setCurrentIndex(0)

        line_width = float(ConfigService.getString(self.LINE_WIDTH))
        self.view.line_width.setValue(line_width)
Beispiel #31
0
    def setup_marker_group(self):
        marker_style = ConfigService.getString(self.MARKER_STYLE)
        self.view.marker_style.addItems(MARKER_STYLES)
        if marker_style in MARKER_STYLES:
            self.view.marker_style.setCurrentIndex(
                self.view.marker_style.findText(marker_style))
        else:
            self.view.marker_style.setCurrentIndex(0)

        marker_size = float(ConfigService.getString(self.MARKER_SIZE))
        self.view.marker_size.setValue(marker_size)
Beispiel #32
0
 def action_facility_changed(self, new_facility):
     """
     When the facility is changed, refreshes all available instruments that can be selected in the dropdown.
     :param new_facility: The name of the new facility that was selected
     """
     current_value = ConfigService.getFacility().name()
     if new_facility != current_value:
         ConfigService.setFacility(new_facility)
     # refresh the instrument selection to contain instruments about the selected facility only
     self.view.instrument.facility = new_facility
     if new_facility != current_value:
         self.view.instrument.setCurrentIndex(0)
Beispiel #33
0
    def setup_marker_group(self):
        marker_style = ConfigService.getString(
            PlotProperties.MARKER_STYLE.value)
        if marker_style in MARKER_STYLES.keys():
            self.view.marker_style.setCurrentIndex(
                self.view.marker_style.findText(marker_style))
        else:
            self.view.marker_style.setCurrentIndex(0)

        marker_size = float(
            ConfigService.getString(PlotProperties.MARKER_SIZE.value))
        self.view.marker_size.setValue(marker_size)
Beispiel #34
0
    def load_current_setting_values(self):
        self.view.prompt_save_on_close.setChecked(CONF.get(self.PROMPT_SAVE_ON_CLOSE))
        self.view.prompt_save_editor_modified.setChecked(CONF.get(self.PROMPT_SAVE_EDITOR_MODIFIED))

        # compare lower-case, because MantidPlot will save it as lower case,
        # but Python will have the bool's first letter capitalised
        pr_enabled = ("true" == ConfigService.getString(self.PR_RECOVERY_ENABLED).lower())
        pr_time_between_recovery = int(ConfigService.getString(self.PR_TIME_BETWEEN_RECOVERY))
        pr_number_checkpoints = int(ConfigService.getString(self.PR_NUMBER_OF_CHECKPOINTS))

        self.view.project_recovery_enabled.setChecked(pr_enabled)
        self.view.time_between_recovery.setValue(pr_time_between_recovery)
        self.view.total_number_checkpoints.setValue(pr_number_checkpoints)
Beispiel #35
0
    def setup_facilities_group(self):
        facilities = ConfigService.getFacilityNames()
        self.view.facility.addItems(facilities)

        default_facility = ConfigService.getFacility().name()
        self.view.facility.setCurrentIndex(self.view.facility.findText(default_facility))
        self.action_facility_changed(default_facility)
        self.view.facility.currentTextChanged.connect(self.action_facility_changed)

        default_instrument = ConfigService.getInstrument().name()
        self.view.instrument.setCurrentIndex(self.view.instrument.findText(default_instrument))
        self.action_instrument_changed(default_instrument)
        self.view.instrument.currentTextChanged.connect(self.action_instrument_changed)
def remove_output_files(list_of_names=None):
    """Removes output files created during a test."""

    # import ConfigService here to avoid:
    # RuntimeError: Pickling of "mantid.kernel._kernel.ConfigServiceImpl"
    # instances is not enabled (http://www.boost.org/libs/python/doc/v2/pickle.html)

    from mantid.kernel import ConfigService

    if not isinstance(list_of_names, list):
        raise ValueError("List of names is expected.")
    if not all(isinstance(i, str) for i in list_of_names):
        raise ValueError("Each name should be a string.")

    save_dir_path = ConfigService.getString("defaultsave.directory")
    if save_dir_path != "":  # default save directory set
        all_files = os.listdir(save_dir_path)
    else:
        all_files = os.listdir(os.getcwd())

    for filename in all_files:
        for name in list_of_names:
            if name in filename:
                full_path = os.path.join(save_dir_path, filename)
                if os.path.isfile(full_path):
                    os.remove(full_path)
                break
    def test_constructor_settings_are_set(self):
        # Test the paths set in the constructor that are generated.
        self.assertEqual(self.pr.recovery_directory,
                         os.path.join(ConfigService.getAppDataDirectory(), "workbench-recovery"))
        self.assertEqual(self.pr.recovery_directory_hostname,
                         os.path.join(ConfigService.getAppDataDirectory(), "workbench-recovery", socket.gethostname()))
        self.assertEqual(self.pr.recovery_directory_pid,
                         os.path.join(ConfigService.getAppDataDirectory(), "workbench-recovery", socket.gethostname(),
                                      str(os.getpid())))
        self.assertEqual(self.pr.recovery_order_workspace_history_file,
                         os.path.join(ConfigService.getAppDataDirectory(), "ordered_recovery.py"))

        # Test config service values
        self.assertEqual(self.pr.time_between_saves, int(ConfigService[SAVING_TIME_KEY]))
        self.assertEqual(self.pr.maximum_num_checkpoints, int(ConfigService[NO_OF_CHECKPOINTS_KEY]))
        self.assertEqual(self.pr.recovery_enabled, ("true" == ConfigService[RECOVERY_ENABLED_KEY].lower()))
Beispiel #38
0
    def setup_checkbox_signals(self):
        self.view.show_invisible_workspaces.setChecked(
            "true" == ConfigService.getString(self.SHOW_INVISIBLE_WORKSPACES).lower())

        self.view.show_invisible_workspaces.stateChanged.connect(self.action_show_invisible_workspaces)
        self.view.project_recovery_enabled.stateChanged.connect(self.action_project_recovery_enabled)
        self.view.time_between_recovery.valueChanged.connect(self.action_time_between_recovery)
        self.view.total_number_checkpoints.valueChanged.connect(self.action_total_number_checkpoints)
 def test_timezones(self):
     # verify that all of the timezones can get converted by pytz
     for facility in ConfigService.getFacilities():
         if len(facility.timezone()) == 0:
             continue # don't test empty strings
         tz = pytz.timezone(facility.timezone())
         print(facility.name(), tz)
         self.assertEquals(str(tz), facility.timezone())
 def get_number_of_checkpoints():
     """
     :return: int; The maximum number of checkpoints project recovery should allow
     """
     try:
         return int(ConfigService.getString("projectRecovery.numberOfCheckpoints"))
     except Exception as e:
         if isinstance(e, KeyboardInterrupt):
             raise
         # Fail silently and return 5 (the default)
         return DEFAULT_NUM_CHECKPOINTS
Beispiel #41
0
    def getValidInstruments(self):
        instruments = ['']

        for name in ['SNS', 'HFIR']:
            facility = ConfigService.getFacility(name)
            facilityInstruments = sorted([item.shortName()
                                          for item in facility.instruments()
                                          if item != 'DAS'])
            instruments.extend(facilityInstruments)

        return instruments
def get_default_grouping(instrument, main_field_direction):
    parameter_name = "Default grouping file"
    if instrument == "MUSR":
        parameter_name += " - " + main_field_direction
    try:
        grouping_file = ConfigService.getInstrument(instrument).getStringParameter(parameter_name)[0]
    except IndexError:
        return [], []
    instrument_directory = ConfigServiceImpl.Instance().getInstrumentDirectory()
    filename = instrument_directory + grouping_file
    new_groups, new_pairs = load_utils.load_grouping_from_XML(filename)
    return new_groups, new_pairs
Beispiel #43
0
    def closeEvent(self, event):
        # Check whether or not to save project
        if not self.project.saved:
            # Offer save
            if self.project.offer_save(self):
                # Cancel has been clicked
                event.ignore()
                return

        # Close editors
        if self.editor.app_closing():
            # write out any changes to the mantid config file
            ConfigService.saveConfig(ConfigService.getUserFilename())
            # write current window information to global settings object
            self.writeSettings(CONF)
            # Close all open plots
            # We don't want this at module scope here
            import matplotlib.pyplot as plt  # noqa
            plt.close('all')

            app = QApplication.instance()
            if app is not None:
                app.closeAllWindows()

            # Kill the project recovery thread and don't restart should a save be in progress and clear out current
            # recovery checkpoint as it is closing properly
            self.project_recovery.stop_recovery_thread()
            self.project_recovery.closing_workbench = True
            self.project_recovery.remove_current_pid_folder()

            self.interface_manager.closeHelpWindow()

            event.accept()
        else:
            # Cancel was pressed when closing an editor
            event.ignore()
Beispiel #44
0
    def __init__(self, input_filename=None, group_name=None):

        if isinstance(input_filename, str):

            self._input_filename = input_filename
            try:
                self._hash_input_filename = self.calculate_ab_initio_file_hash()
            except IOError as err:
                logger.error(str(err))
            except ValueError as err:
                logger.error(str(err))

            # extract name of file from the full path in the platform independent way
            filename = os.path.basename(self._input_filename)

            if filename.strip() == "":
                raise ValueError("Name of the file cannot be an empty string.")

        else:
            raise ValueError("Invalid name of input file. String was expected.")

        if isinstance(group_name, str):
            self._group_name = group_name
        else:
            raise ValueError("Invalid name of the group. String was expected.")

        core_name = filename[0:filename.rfind(".")]
        save_dir_path = ConfigService.getString("defaultsave.directory")
        self._hdf_filename = os.path.join(save_dir_path, core_name + ".hdf5")  # name of hdf file

        try:
            self._advanced_parameters = self._get_advanced_parameters()
        except IOError as err:
            logger.error(str(err))
        except ValueError as err:
            logger.error(str(err))

        self._attributes = {}  # attributes for group

        # data  for group; they are expected to be numpy arrays or
        # complex data sets which have the form of Python dictionaries or list of Python
        # dictionaries
        self._data = {}
    def __updateAlignAndFocusArgs(self, wkspname):
        self.log().debug('__updateAlignAndFocusArgs(%s)' % wkspname)
        # if the files are missing, there is nothing to do
        if (CAL_FILE not in self.kwargs) and (GROUP_FILE not in self.kwargs):
            self.log().debug('--> Nothing to do')
            return
        self.log().debug('--> Updating')

        # delete the files from the list of kwargs
        if CAL_FILE in self.kwargs:
            del self.kwargs[CAL_FILE]
        if CAL_FILE in self.kwargs:
            del self.kwargs[GROUP_FILE]

        # get the instrument name
        instr = mtd[wkspname].getInstrument().getName()
        instr = ConfigService.getInstrument(instr).shortName()

        # use the canonical names if they weren't specifed
        for key, ext in zip((CAL_WKSP, GRP_WKSP, MASK_WKSP),
                            ('_cal', '_group', '_mask')):
            if key not in self.kwargs:
                self.kwargs[key] = instr + ext
 def instrument(self):
     return ConfigService.getString('default.instrument')
Beispiel #47
0
 def action_show_invisible_workspaces(self, state):
     ConfigService.setString(self.SHOW_INVISIBLE_WORKSPACES, str(bool(state)))
 def _get_test_facility(self):
     return ConfigService.getFacility("ISIS")
 def instrument(self):
     inst = ConfigService.getInstrument()
     return inst
 def _get_test_instrument(self):
     facility = ConfigService.getFacility("ISIS")
     return facility.instrument("CRISP")
Beispiel #51
0
 def _get_test_listener(self):
     facility = ConfigService.getFacility("ISIS")
     return facility.instrument("CRISP").liveListenerInfo()
Beispiel #52
0
 def action_total_number_checkpoints(self, value):
     ConfigService.setString(self.PR_NUMBER_OF_CHECKPOINTS, str(value))
Beispiel #53
0
 def get_ipf_for_rule_2(path):
     # Check if can be found in the instrument folder
     directory = ConfigService.getInstrumentDirectory()
     return check_for_files(directory, path)
Beispiel #54
0
    def __init__(self, Ion, Symmetry, **kwargs):
        """
        Constructor.

        @param Ion: A rare earth ion. Possible values:
                    Ce, Pr, Nd, Pm, Sm, Eu, Gd, Tb, Dy, Ho, Er, Tm, Yb

        @param Symmetry: Symmetry of the field. Possible values:
                         C1, Ci, C2, Cs, C2h, C2v, D2, D2h, C4, S4, C4h, D4, C4v, D2d, D4h, C3,
                         S6, D3, C3v, D3d, C6, C3h, C6h, D6, C6v, D3h, D6h, T, Td, Th, O, Oh

        @param kwargs: Other field parameters and attributes. Acceptable values include:
                        ToleranceEnergy:     energy tolerance,
                        ToleranceIntensity:  intensity tolerance,
                        ResolutionModel:     A resolution model.
                        FWHMVariation:       Absolute value of allowed variation of a peak width during a fit.
                        FixAllPeaks:         A boolean flag that fixes all parameters of the peaks.

                        Field parameters:

                        BmolX: The x-component of the molecular field,
                        BmolY: The y-component of the molecular field,
                        BmolZ: The z-component of the molecular field,
                        BextX: The x-component of the external field,
                        BextY: The y-component of the external field,
                        BextZ: The z-component of the external field,
                        B20: Real part of the B20 field parameter,
                        B21: Real part of the B21 field parameter,
                        B22: Real part of the B22 field parameter,
                        B40: Real part of the B40 field parameter,
                        B41: Real part of the B41 field parameter,
                        B42: Real part of the B42 field parameter,
                        B43: Real part of the B43 field parameter,
                        B44: Real part of the B44 field parameter,
                        B60: Real part of the B60 field parameter,
                        B61: Real part of the B61 field parameter,
                        B62: Real part of the B62 field parameter,
                        B63: Real part of the B63 field parameter,
                        B64: Real part of the B64 field parameter,
                        B65: Real part of the B65 field parameter,
                        B66: Real part of the B66 field parameter,
                        IB21: Imaginary part of the B21 field parameter,
                        IB22: Imaginary part of the B22 field parameter,
                        IB41: Imaginary part of the B41 field parameter,
                        IB42: Imaginary part of the B42 field parameter,
                        IB43: Imaginary part of the B43 field parameter,
                        IB44: Imaginary part of the B44 field parameter,
                        IB61: Imaginary part of the B61 field parameter,
                        IB62: Imaginary part of the B62 field parameter,
                        IB63: Imaginary part of the B63 field parameter,
                        IB64: Imaginary part of the B64 field parameter,
                        IB65: Imaginary part of the B65 field parameter,
                        IB66: Imaginary part of the B66 field parameter,


                        Each of the following parameters can be either a single float or an array of floats.
                        They are either all floats or all arrays of the same size.

                        IntensityScaling: A scaling factor for the intensity of each spectrum.
                        FWHM: A default value for the full width at half maximum of the peaks.
                        Temperature: A temperature "of the spectrum" in Kelvin
        """
        # This is to make sure that Lorentzians get evaluated properly
        ConfigService.setString('curvefitting.peakRadius', str(100))

        from .function import PeaksFunction
        self._ion = Ion
        self._symmetry = Symmetry
        self._toleranceEnergy = 1e-10
        self._toleranceIntensity = 1e-1
        self._fieldParameters = {}
        self._fieldTies = {}
        self._fieldConstraints = []
        self._temperature = None
        self._FWHM = None
        self._intensityScaling = 1.0
        self._resolutionModel = None
        self._fwhmVariation = None
        self._fixAllPeaks = False

        for key in kwargs:
            if key == 'ToleranceEnergy':
                self._toleranceEnergy = kwargs[key]
            elif key == 'ToleranceIntensity':
                self._toleranceIntensity = kwargs[key]
            elif key == 'IntensityScaling':
                self._intensityScaling = kwargs[key]
            elif key == 'FWHM':
                self._FWHM = kwargs[key]
            elif key == 'ResolutionModel':
                self.ResolutionModel = kwargs[key]
            elif key == 'Temperature':
                self._temperature = kwargs[key]
            elif key == 'FWHMVariation':
                self._fwhmVariation = kwargs[key]
            elif key == 'FixAllPeaks':
                self._fixAllPeaks = kwargs[key]
            else:
                # Crystal field parameters
                self._fieldParameters[key] = kwargs[key]

        if isinstance(self._temperature, list) or isinstance(self._temperature, np.ndarray):
            self.peaks = [PeaksFunction(firstIndex=1) for _ in self._temperature]
        else:
            self.peaks = PeaksFunction()
        self.background = None

        # Eigensystem
        self._dirty_eigensystem = True
        self._eigenvalues = None
        self._eigenvectors = None
        self._hamiltonian = None

        # Peak lists
        self._dirty_peaks = True
        self._peakList = None

        # Spectra
        self._dirty_spectra = True
        self._spectra = {}
        self._plot_window = {}

        self._setDefaultTies()
        self.chi2 = None
Beispiel #55
0
 def action_project_recovery_enabled(self, state):
     ConfigService.setString(self.PR_RECOVERY_ENABLED, str(bool(state)))
Beispiel #56
0
 def action_time_between_recovery(self, value):
     ConfigService.setString(self.PR_TIME_BETWEEN_RECOVERY, str(value))
 def __init__(self, initial_type):
     self._save_directory = ConfigService.getString('defaultsave.directory')
     self._type_factory_dict = {BinningType.SaveAsEventData: SaveAsEventData(),
                                BinningType.Custom: CustomBinning(),
                                BinningType.FromMonitors: BinningFromMonitors()}
     self._settings, self._type = self._settings_from_type(initial_type)
Beispiel #58
0
 def action_instrument_changed(self, new_instrument):
     ConfigService.setString(self.INSTRUMENT, new_instrument)
 def save_directory(self):
     return ConfigService.getString('defaultsave.directory')
    def test_properties_documented(self):
        # location of the rst file relative to this file this will break if either moves
        doc_filename = os.path.split(inspect.getfile(self.__class__))[0]
        doc_filename = os.path.join(doc_filename, '../../../../../../docs/source/concepts/PropertiesFile.rst')
        doc_filename = os.path.abspath(doc_filename)

        # read in the user documentation
        print ('Parsing', doc_filename)
        documented_keys = []
        with open(doc_filename) as handle:
            text = handle.read()

        # these will be ignored - the list should get shorter over time
        hidden_prefixes = ['CheckMantidVersion.DownloadURL',  # shouldn't be changed by users
                           'CheckMantidVersion.GitHubReleaseURL', # shouldn't be changed by users
                           'UpdateInstrumentDefinitions.URL', # shouldn't be changed by users
                           'docs.html.root', # shouldn't be changed by users
                           'errorreports.rooturl', # shouldn't be changed by users
                           'usagereports.rooturl', # shouldn't be changed by users
                           'workspace.sendto.SansView.arguments', 'workspace.sendto.SansView.saveusing', # related to SASview in menu
                           'workspace.sendto.SansView.target', 'workspace.sendto.SansView.visible', # related to SASview in menu
                           'workspace.sendto.name.SansView', # related to SASview in menu
                           'catalog.oncat.token.accessToken', 'catalog.oncat.token.expiresIn', 'catalog.oncat.token.refreshToken', 'catalog.oncat.token.scope', 'catalog.oncat.token.tokenType', # Shouldn't be changed by users.

                           ########## TODO should be documented!
                           'filefinder.casesensitive',
                           'graph1d.autodistribution',
                           'groupingFiles.directory',
                           'icatDownload.directory', 'icatDownload.mountPoint',
                           'instrument.view.geometry',
                           'interfaces.categories.hidden',
                           'loading.multifile', 'loading.multifilelimit',
                           'maskFiles.directory',
                           'pythonalgorithms.refresh.allowed',
                           'sliceviewer.nonorthogonal',
                           'usersearch.directories',

                           ########## TODO should these be documented?
                           'curvefitting.defaultPeak', 'curvefitting.findPeaksFWHM', 'curvefitting.findPeaksTolerance', 'curvefitting.guiExclude',
                           'logging.channels.consoleChannel.class', 'logging.channels.consoleChannel.formatter', 'logging.formatters.f1.class', 'logging.formatters.f1.pattern', 'logging.formatters.f1.times', 'logging.loggers.root.channel.channel1', 'logging.loggers.root.channel.class',
                           'MantidOptions.ReusePlotInstances',
                           'mantidqt.python_interfaces', 'mantidqt.python_interfaces_directory',
                           'paraview.ignore', 'paraview.path', 'paraview.pythonpaths', 'pvplugins.directory',
                           'python.plugins.directories',
                       ]

        # create the list of things
        undocumented = []
        properties_defined = ConfigService.keys()
        for property in properties_defined:
            property_tag = '``{}``'.format(property)

            if property_tag not in text:
                for hidden in hidden_prefixes:
                    if property.startswith(hidden):
                        break
                else:
                    undocumented.append(property)

        # everything should be documented
        if len(undocumented) > 0:
            raise AssertionError('{} undocumented properties: {}'.format(len(undocumented), undocumented))