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", " ")
Exemple #2
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_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", " ")
    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", " ")
 def _create_flat_background_test_workspace(workspace_name):
     ConfigService.Instance().setString("default.facility", "ISIS")
     LoadNexusProcessed(Filename="LOQ48127", OutputWorkspace=workspace_name)
     ConfigService.Instance().setString("default.facility", " ")
     workspace = AnalysisDataService.retrieve(workspace_name)
     # Rebin to only have four values at 11, 31, 51, 70.5
     workspace = Rebin(workspace, "1,20,80")
     # For each spectrum we set the first two entries to 2 and the other two entries to 4.
     for index in range(workspace.getNumberHistograms()):
         data_y = workspace.dataY(index)
         data_y[0] = 2.
         data_y[1] = 2.
         data_y[2] = 4.
         data_y[3] = 4.
     return workspace
Exemple #6
0
 def set_output_directory(self, directory):
     if not directory:
         directory = ConfigService.Instance().getString(
             "defaultsave.directory")
     self.save_directory = directory
     self._view.set_out_file_directory(directory)
     return directory
Exemple #7
0
    def initialize_content(self):
        # Add functionality to copy and paste
        self.copyAction = QtGui.QAction("Copy", self)
        self.copyAction.setShortcut("Ctrl+C")
        self.addAction(self.copyAction)
        self.connect(self.copyAction, QtCore.SIGNAL("triggered()"),
                     self.copyCells)
        self._content.job_table.setContextMenuPolicy(
            QtCore.Qt.CustomContextMenu)
        self.connect(self._content.job_table,
                     QtCore.SIGNAL("customContextMenuRequested(QPoint)"),
                     self.tableWidgetContext)

        self.connect(self._content.refresh_button, QtCore.SIGNAL("clicked()"),
                     self._update_content)

        # Set the time of the oldest displayed job to 2 days ago
        self._content.date_time_edit.setDateTime(
            QtCore.QDateTime().currentDateTime().addDays(-2))

        compute_resources = ConfigService.Instance().getFacility(
        ).computeResources()
        self._content.resource_combo.clear()
        for res in compute_resources:
            self._content.resource_combo.addItem(
                QtGui.QApplication.translate("Dialog", res, None,
                                             QtGui.QApplication.UnicodeUTF8))

        self._clear_table()
    def _init_sub_presenters(self, view):
        self._run_selector_presenter = self._init_run_selector_presenter(
            view.run_selector_view(), self._handle_selection_changed, view)

        self._summation_settings_presenter = \
            self._init_run_summations_settings_presenter(view.summation_settings_view(),
                                                         view, ConfigService.Instance().getString("default.instrument"))
Exemple #9
0
 def setUp(self):
     self.config = ConfigService.Instance()
     self._search_directories = self.config.getString(
         "datasearch.directories")
     self._default_save_directory = self.config.getString(
         "defaultsave.directory")
     self._retained_algorithms = self.config.getString(
         "algorithms.retained")
Exemple #10
0
 def set_data_path(self, path):
     """
         Set the path for data files
         @param path: data file path
     """
     path = os.path.normcase(path)
     if os.path.isdir(path):
         self._data_path = path
         ConfigService.Instance().appendDataSearchDir(path)
     else:
         raise RuntimeError, "Reducer.set_data_path: provided path is not a directory (%s)" % path
    def test_calls_for_default_save_change(self):
        onValueChangedMock = mock.Mock()

        class FakeConfigObserver(ConfigObserver):
            def onValueChanged(self, name, new, old):
                onValueChangedMock(name, new, old)

        observer = FakeConfigObserver()
        ConfigService.Instance().setString("defaultsave.directory", "/dev/null")
        onValueChangedMock.assert_any_call("defaultsave.directory", mock.ANY, mock.ANY)
        onValueChangedMock.assert_any_call("datasearch.directories", mock.ANY, mock.ANY)
Exemple #12
0
    def _exec_alg(log_type: str) -> str:
        config = ConfigService.Instance()
        original_conf = config['algorithms.deprecated']
        with RedirectStdOut() as log_file:
            alg = MyOldAlg()
            alg.initialize()
            alg.setProperty("Meaning", 42)
            config['algorithms.deprecated'] = log_type
            alg.execute()

        config['algorithms.deprecated'] = original_conf
        return str(log_file)
Exemple #13
0
 def add_directories_to_config_service(self, file_list):
     """
     Parses file_list into the unique directories containing the files, and adds these
     to the global config service. These directories will then be automatically searched in
     all subsequent Load calls.
     """
     dirs = [os.path.dirname(filename) for filename in file_list]
     dirs = [path if os.path.isdir(path) else "" for path in dirs]
     dirs = list(set(dirs))
     if dirs:
         for directory in dirs:
             ConfigService.Instance().appendDataSearchDir(directory.encode('ascii', 'ignore'))
Exemple #14
0
 def __init__(self, name="", facility=""):
     self.instrument_name = name
     self.facility_name = facility
     self._observers = []
     self._output_directory = os.path.expanduser('~')
     if HAS_MANTID:
         config = ConfigService.Instance()
         try:
             head, _tail = os.path.split(config.getUserFilename())
             if os.path.isdir(head):
                 self._output_directory = head
         except (StopIteration, StandardError, Warning):
             Logger("scripter").debug("Could not get user filename")
    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()

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

        return True
Exemple #16
0
 def __init__(self, name="", facility=""):
     self.instrument_name = name
     self.facility_name = facility
     self._observers = []
     self._output_directory = os.path.expanduser('~')
     if HAS_MANTID:
         config = ConfigService.Instance()
         #register startup
         if HAS_MANTID:
             UsageService.registerFeatureUsage(FeatureType.Interface, "Reduction_gui:{0:.5}-{1:.10}".format(facility, name), False)
         try:
             head, _tail = os.path.split(config.getUserFilename())
             if os.path.isdir(head):
                 self._output_directory = head
         except (StopIteration, AttributeError, ImportError, NameError, TypeError, ValueError, Warning):
             Logger("scripter").debug("Could not get user filename")
Exemple #17
0
def find_file(filename=None, startswith=None, data_dir=None):
    """
        Returns a list of file paths for the search criteria.
        @param filename: exact name of a file. The first file found will be returned.
        @param startswith: string that files should start with.
        @param data_dir: additional directory to search
    """
    # Files found
    files_found = []
    filename = str(filename).strip()

    # List of directory to look into
    # The preferred way to operate is to have a symbolic link in a work directory,
    # so look in the current working directory first
    search_dirs = [os.getcwd()]
    # The second best location would be with the data itself
    if data_dir is not None:
        search_dirs.append(data_dir)
    # The standard place would be the location of the configuration files on the SNS mount
    search_dirs.append("/SNS/EQSANS/shared/instrument_configuration/")
    search_dirs.extend(ConfigService.Instance().getDataSearchDirs())

    # Look for specific file
    if filename is not None:
        for d in search_dirs:
            if not os.path.isdir(d):
                continue
            file_path = os.path.join(os.path.normcase(d), filename)
            if os.path.isfile(file_path):
                files_found.append(file_path)
                # If we are looking for a specific file, return right after we find the first
                if startswith is None:
                    return files_found

    # Look for files that starts with a specific string
    if startswith is not None:
        for d in search_dirs:
            if not os.path.isdir(d):
                continue
            files = os.listdir(d)
            for file in files:
                if file.startswith(startswith):
                    file_path = os.path.join(os.path.normcase(d), file)
                    files_found.append(file_path)

    return files_found
Exemple #18
0
def capture_logs(level=None) -> io.StringIO:
    r"""
    A context manager that redirects logging messages to string buffer
    and returns a StringIO buffer.

    Usage:
        with capture_logs(level='debug') as logs:
            some code that outputs messages with mantid.kernel.logger
            assert 'some query message' in logs.getvalue()

    Can be used to assert if an algorithm emitted a particular log message by one of its
    methods not exposed to the python API. This is an indirect way of testing those private
    methods.

    @param str level: set a particular logging level within the scope of the context manager. If
        ``None``, the level's unchanged. One of 'debug', 'information', 'notice',
        'warning', 'error'. If ``level`` is specified, the pre-existing level in
         configuration option 'logging.loggers.root.level' is reinstated upon leaving the
         scope of the context manager. If this option was unset, the 'notice' level is set.

    @return io.StringIO: A reference to the temporary StringIO buffer object
    """
    try:
        # backup the logging channel and sys.stdout
        config = ConfigService.Instance()
        backup = dict(channel=config['logging.channels.consoleChannel.class'],
                      stdout=sys.stdout)
        # backup the logging level?
        if level:
            assert level.lower() in [
                'debug', 'information', 'notice', 'warning', 'error'
            ]
            current_level = config['logging.loggers.root.level']
            backup['level'] = current_level if current_level else 'notice'
            config['logging.loggers.root.level'] = level
        # redirect messages to log_file
        config['logging.channels.consoleChannel.class'] = 'PythonStdoutChannel'
        str_buffer = io.StringIO()
        sys.stdout = str_buffer
        yield str_buffer
    finally:
        str_buffer.close()
        config['logging.channels.consoleChannel.class'] = backup['channel']
        if level:
            config['logging.loggers.root.level'] = backup['level']
        sys.stdout = backup['stdout']
Exemple #19
0
    def test_capture_logs(self):

        with capture_logs() as logs:
            logger.error('Error message')
            self.assertTrue('Error message' in logs.getvalue())

        with temporary_config():
            config = ConfigService.Instance()
            config['logging.loggers.root.level'] = 'information'
            with capture_logs(level='error') as logs:
                self.assertTrue(
                    config['logging.loggers.root.level'] == 'error')
                logger.error('Error-message')
                logger.debug('Debug-message')
                self.assertTrue('Error-message' in logs.getvalue())
                self.assertFalse('Debug-message' in logs.getvalue())

            self.assertTrue(
                config['logging.loggers.root.level'] == 'information')
Exemple #20
0
    def __init__(self, sum_runs, make_run_selector_presenter,
                 make_run_summation_presenter, view, parent_view):

        self._view = view
        self._parent_view = parent_view
        self._sum_runs = sum_runs
        self._use_generated_file_name = True
        self._run_selector_presenter = \
            make_run_selector_presenter(view.run_selector_view(),
                                        self._handle_selection_changed, view)
        self._summation_settings_presenter = \
            make_run_summation_presenter(view.summation_settings_view(),
                                         view, ConfigService.Instance().getString("default.instrument"))

        self.save_directory = ""
        self._connect_to_view(view)

        self.gui_properties_handler = SANSGuiPropertiesHandler(
            {"add_runs_output_directory": (self.set_output_directory, str)})
Exemple #21
0
    def remote_resources_available(self):
        """
            Returns whether or not the application is cluster-enabled.
            The Remote algorithms have to be available and the
            cluster submission property has to be ON.
        """
        # Check whether Mantid is available
        try:
            from mantid.kernel import ConfigService
            from mantid.api import AlgorithmFactory

            if "SubmitRemoteJob" in AlgorithmFactory.getRegisteredAlgorithms(True):
                config = ConfigService.Instance()
                if config.hasProperty("cluster.submission") \
                        and config.getString("cluster.submission").lower()=='on':
                    return True

            return False
        except:
            return False
Exemple #22
0
def log_to_python(level='debug'):
    r"""
    Modify Mantid's logger to forward messages to Python's logging framework instead
    of outputting them itself. This allows users to configure the logger from Python
    and merge logs from different sources.

    Note that this function does not configure Python's logging system.

    @param str level: Logging level for the *Mantid* logger. Should be set to a low value
        to forward all potentially relevant messages to Python and let *Python's* logger
        filter out undesired messages. Possible values: 'trace', 'debug' (default),
        'information', 'notice', 'warning', 'error', 'critical', 'fatal'.
    """
    config = ConfigService.Instance()
    config['logging.loggers.root.level'] = level
    config['logging.channels.consoleChannel.formatter'] = 'f1'
    # Output only the message text and let Python take care of formatting.
    config['logging.formatters.f1.class'] = 'PatternFormatter'
    config['logging.formatters.f1.pattern'] = '%t'
    # Important: Do this one last because it triggers re-init of logging system!
    config['logging.channels.consoleChannel.class'] = 'PythonLoggingChannel'
    def __init__(self, parent=None):
        """ Intialization and set up
        """
        # Base class
        QtGui.QMainWindow.__init__(self, parent)

        # Mantid configuration
        config = ConfigService.Instance()
        self._instrument = config["default.instrument"]

        # Central widget
        self.centralwidget = QtGui.QWidget(self)

        # UI Window (from Qt Designer)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.mainplot = self.ui.graphicsView.getPlot()

        # Do initialize plotting
        vecx, vecy, xlim, ylim = self.computeMock()

        self.mainline = self.ui.mainplot.plot(vecx, vecy, 'r-')

        leftx = [xlim[0], xlim[0]]
        lefty = [ylim[0], ylim[1]]
        self.leftslideline = self.ui.mainplot.plot(leftx, lefty, 'b--')
        rightx = [xlim[1], xlim[1]]
        righty = [ylim[0], ylim[1]]
        self.rightslideline = self.ui.mainplot.plot(rightx, righty, 'g--')
        upperx = [xlim[0], xlim[1]]
        uppery = [ylim[1], ylim[1]]
        self.upperslideline = self.ui.mainplot.plot(upperx, uppery, 'b--')
        lowerx = [xlim[0], xlim[1]]
        lowery = [ylim[0], ylim[0]]
        self.lowerslideline = self.ui.mainplot.plot(lowerx, lowery, 'g--')

        self.ui.graphicsView.mpl_connect('button_press_event',
                                         self.on_mouseDownEvent)

        # Set up horizontal slide (integer) and string value
        self._leftSlideValue = 0
        self._rightSlideValue = 99

        self.ui.horizontalSlider.setRange(0, 100)
        self.ui.horizontalSlider.setValue(self._leftSlideValue)
        self.ui.horizontalSlider.setTracking(True)
        self.ui.horizontalSlider.setTickPosition(QSlider.NoTicks)
        self.connect(self.ui.horizontalSlider, SIGNAL('valueChanged(int)'),
                     self.move_leftSlider)

        self.ui.horizontalSlider_2.setRange(0, 100)
        self.ui.horizontalSlider_2.setValue(self._rightSlideValue)
        self.ui.horizontalSlider_2.setTracking(True)
        self.ui.horizontalSlider_2.setTickPosition(QSlider.NoTicks)
        self.connect(self.ui.horizontalSlider_2, SIGNAL('valueChanged(int)'),
                     self.move_rightSlider)

        # self.connect(self.ui.lineEdit_3, QtCore.SIGNAL("textChanged(QString)"),
        #         self.set_startTime)
        self.ui.lineEdit_3.setValidator(
            QtGui.QDoubleValidator(self.ui.lineEdit_3))
        self.connect(self.ui.pushButton_setT0, QtCore.SIGNAL("clicked()"),
                     self.set_startTime)
        # self.connect(self.ui.lineEdit_4, QtCore.SIGNAL("textChanged(QString)"),
        #         self.set_stopTime)
        self.ui.lineEdit_4.setValidator(
            QtGui.QDoubleValidator(self.ui.lineEdit_4))
        self.connect(self.ui.pushButton_setTf, QtCore.SIGNAL("clicked()"),
                     self.set_stopTime)

        # File loader
        self.scanEventWorkspaces()
        self.connect(self.ui.pushButton_refreshWS, SIGNAL('clicked()'),
                     self.scanEventWorkspaces)
        self.connect(self.ui.pushButton_browse, SIGNAL('clicked()'),
                     self.browse_File)
        self.connect(self.ui.pushButton_load, SIGNAL('clicked()'),
                     self.load_File)
        self.connect(self.ui.pushButton_3, SIGNAL('clicked()'),
                     self.use_existWS)

        # Set up time
        self.ui.lineEdit_3.setValidator(
            QtGui.QDoubleValidator(self.ui.lineEdit_3))
        self.ui.lineEdit_4.setValidator(
            QtGui.QDoubleValidator(self.ui.lineEdit_4))

        # Filter by time
        self.connect(self.ui.pushButton_filterTime, SIGNAL('clicked()'),
                     self.filterByTime)

        # Filter by log value
        self.ui.lineEdit_5.setValidator(
            QtGui.QDoubleValidator(self.ui.lineEdit_5))
        self.ui.lineEdit_6.setValidator(
            QtGui.QDoubleValidator(self.ui.lineEdit_6))
        self.ui.lineEdit_7.setValidator(
            QtGui.QDoubleValidator(self.ui.lineEdit_7))
        self.ui.lineEdit_8.setValidator(
            QtGui.QDoubleValidator(self.ui.lineEdit_8))
        self.ui.lineEdit_9.setValidator(
            QtGui.QDoubleValidator(self.ui.lineEdit_9))

        self.connect(self.ui.lineEdit_5, QtCore.SIGNAL("textChanged(QString)"),
                     self.set_minLogValue)
        self.connect(self.ui.lineEdit_6, QtCore.SIGNAL("textChanged(QString)"),
                     self.set_maxLogValue)

        dirchangeops = ["Both", "Increase", "Decrease"]
        self.ui.comboBox_4.addItems(dirchangeops)

        logboundops = ["Centre", "Left"]
        self.ui.comboBox_5.addItems(logboundops)

        self.connect(self.ui.pushButton_4, SIGNAL('clicked()'),
                     self.plotLogValue)

        self.connect(self.ui.pushButton_filterLog, SIGNAL('clicked()'),
                     self.filterByLogValue)

        #Set up help button
        self.connect(self.ui.helpBtn, QtCore.SIGNAL('clicked()'),
                     self.helpClicked)

        # Set up vertical slide
        self._upperSlideValue = 99
        self._lowerSlideValue = 0

        self.ui.verticalSlider.setRange(0, 100)
        self.ui.verticalSlider.setValue(self._upperSlideValue)
        self.ui.verticalSlider.setTracking(True)
        self.connect(self.ui.verticalSlider, SIGNAL('valueChanged(int)'),
                     self.move_upperSlider)

        self.ui.verticalSlider_2.setRange(0, 100)
        self.ui.verticalSlider_2.setValue(self._lowerSlideValue)
        self.ui.verticalSlider_2.setTracking(True)
        self.connect(self.ui.verticalSlider_2, SIGNAL('valueChanged(int)'),
                     self.move_lowerSlider)

        # Set up for filtering (advanced setup)
        self._tofcorrection = False
        self.ui.checkBox_fastLog.setChecked(False)
        self.ui.checkBox_filterByPulse.setChecked(False)
        self.ui.checkBox_from1.setChecked(False)
        self.ui.checkBox_groupWS.setChecked(True)

        self.connect(self.ui.comboBox_tofCorr,
                     SIGNAL('currentIndexChanged(int)'), self.showHideEi)
        self.connect(self.ui.pushButton_refreshCorrWSList, SIGNAL('clicked()'),
                     self._searchTableWorkspaces)

        self.ui.lineEdit_Ei.setValidator(
            QtGui.QDoubleValidator(self.ui.lineEdit_Ei))

        self.ui.label_Ei.hide()
        self.ui.lineEdit_Ei.hide()
        self.ui.label_Ei_2.hide()
        self.ui.comboBox_corrWS.hide()
        self.ui.pushButton_refreshCorrWSList.hide()

        # Error message
        # self.connect(self.ui.pushButton_clearerror, SIGNAL('clicked()'), self._clearErrorMsg)
        # self.ui.plainTextEdit_ErrorMsg.setReadOnly(True)
        # self.ui.label_error.hide()

        # Set up for workspaces
        self._dataWS = None
        self._sampleLogNames = []
        self._sampleLog = None

        # Side information
        self.ui.label_mean.hide()
        self.ui.label_meanvalue.hide()
        self.ui.label_avg.hide()
        self.ui.label_timeAvgValue.hide()
        self.ui.label_freq.hide()
        self.ui.label_freqValue.hide()
        self.ui.label_logname.hide()
        self.ui.label_lognamevalue.hide()
        self.ui.label_logsize.hide()
        self.ui.label_logsizevalue.hide()

        # Default
        self._defaultdir = os.getcwd()

        # self.ui.InputVal.setValidator(QtGui.QDoubleValidator(self.ui.InputVal))

        # QtCore.QObject.connect(self.ui.convert, QtCore.SIGNAL("clicked()"), self.convert )
        # QtCore.QObject.connect(self.ui.inputUnits, QtCore.SIGNAL("currentIndexChanged(QString)"), self.setInstrumentInputs )
        # QtCore.QObject.connect(self.ui.outputUnits, QtCore.SIGNAL("currentIndexChanged(QString)"), self.setInstrumentInputs )
        # self.setInstrumentInputs()

        ##defaults

        #register startup
        mantid.UsageService.registerFeatureUsage("Interface", "EventFilter",
                                                 False)

        return
Exemple #24
0
    def __init__(self, instrument=None, instrument_list=None):
        QtGui.QMainWindow.__init__(self)

        if REDUCTION_WARNING:
            message = "The reduction application has problems starting:\n\n"
            message += WARNING_MESSAGE
            QtGui.QMessageBox.warning(self, "WARNING", message)

        # Application settings
        settings = QtCore.QSettings()

        # Name handle for the instrument
        if instrument is None:
            instrument = unicode(settings.value("instrument_name", ''))
            if instrument_list is not None and instrument not in instrument_list:
                instrument = None

        self._instrument = instrument
        self._facility = None

        # List of allowed instrument
        self._instrument_list = instrument_list

        # Reduction interface
        self._interface = None

        # Recent files
        self._recent_files = settings.value("recent_files", [])
        if self._recent_files is None:  # An empty list saved to QSettings comes back as 'None'
            self._recent_files = []

        # Folder to open files in
        self._last_directory = unicode(settings.value("last_directory", '.'))
        self._last_export_directory = unicode(settings.value("last_export_directory", '.'))

        # Current file name
        self._filename = None

        # Cluster credentials and options
        self._cluster_details_set = False
        self._number_of_nodes = 1
        self._cores_per_node = 16
        self._compute_resources = ['Fermi']
        if IS_IN_MANTIDPLOT \
        and hasattr(ConfigService.Instance().getFacility(), "computeResources"):
            self._compute_resources = ConfigService.Instance().getFacility().computeResources()

        # Internal flag for clearing all settings and restarting the application
        self._clear_and_restart = False

        # General settings shared by all widgets
        self.general_settings = GeneralSettings(settings)

        self.setupUi(self)

        # Event connections
        if not IS_IN_MANTIDPLOT:
            self.reduce_button.hide()
        self.cluster_button.hide()
        self.connect(self.export_button, QtCore.SIGNAL("clicked()"), self._export)
        self.connect(self.reduce_button, QtCore.SIGNAL("clicked()"), self.reduce_clicked)
        self.connect(self.save_button, QtCore.SIGNAL("clicked()"), self._save)
        self.connect(self.interface_chk, QtCore.SIGNAL("clicked(bool)"), self._interface_choice)

        self.interface_chk.setChecked(self.general_settings.advanced)

        # Of the widgets that are part of the application, one is the ApplicationWindow.
        # The ApplicationWindow will send a shutting_down() signal when quitting,
        # after which we should close this window.
        # Note: there is no way to identify which Widget is the ApplicationWindow.
        for w in QtCore.QCoreApplication.instance().topLevelWidgets():
            self.connect(w, QtCore.SIGNAL("shutting_down()"), self.close)

        self.general_settings.progress.connect(self._progress_updated)
Exemple #25
0
 def __init__(self):
     self._stdout = None
     self._string_io = None
     self._original_config = None
     self._config = ConfigService.Instance()
Exemple #26
0
# The full version, including alpha/beta/rc tags.
release = version_str

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# -- Options for doctest --------------------------------------------------

# Store certain config options so they can be restored to initial
# settings after each test.
mantid_init_config_keys = ('datasearch.directories', 'defaultsave.directory',
                           'default.facility', 'default.instrument')

# With the default facility changed from ISIS to nothing (EMPTY),
# the following setting is put in place to avoid failure of tests
ConfigService.Instance().setString("default.facility", "ISIS")

mantid_config_reset = [
    "_cfg['{0}'] = '{1}'".format(k,
                                 ConfigService.Instance()[k])
    for k in mantid_init_config_keys
]
mantid_config_reset = '\n'.join(mantid_config_reset)

# Run this before each test is executed
doctest_global_setup = """
from mantid.simpleapi import *
from mantid.kernel import ConfigService as _cfg
{0}

# doctest.py examines the global scope for future imports
Exemple #27
0
# The full version, including alpha/beta/rc tags.
release = version_str

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# -- Options for doctest --------------------------------------------------

# Store certain config options so they can be restored to initial
# settings after each test.
mantid_init_config_keys = ('datasearch.directories', 'defaultsave.directory', 'default.facility',
                           'default.instrument')

# With the default facility changed from ISIS to nothing (EMPTY),
# the following setting is put in place to avoid failure of tests
ConfigService.Instance().setString("default.facility", "ISIS")

mantid_config_reset = [
    "_cfg['{0}'] = '{1}'".format(k,
                                 ConfigService.Instance()[k]) for k in mantid_init_config_keys
]
mantid_config_reset = '\n'.join(mantid_config_reset)

# Run this before each test is executed
doctest_global_setup = """
from mantid.simpleapi import *
from mantid.kernel import ConfigService as _cfg
{0}

# doctest.py examines the global scope for future imports
# and uses the sames ones in the executing scope. We don't want the
 def _connect_to_view(self, view):
     view.sum.connect(self._handle_sum)
     view.outFileChanged.connect(self._handle_out_file_changed)
     self._view.set_out_file_directory(
         ConfigService.Instance().getString("defaultsave.directory"))
Exemple #29
0
version = ".".join(version_str.split(".")[:2])
# The full version, including alpha/beta/rc tags.
release = version_str

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# -- Options for doctest --------------------------------------------------

# Store certain config options so they can be restored to initial
# settings after each test.
mantid_init_config_keys = ('datasearch.directories', 'defaultsave.directory',
                           'default.facility', 'default.instrument')
mantid_config_reset = [
    "_cfg['{0}'] = '{1}'".format(k,
                                 ConfigService.Instance()[k])
    for k in mantid_init_config_keys
]
mantid_config_reset = '\n'.join(mantid_config_reset)

# Run this before each test is executed
doctest_global_setup = """
from mantid.simpleapi import *
from mantid.kernel import ConfigService as _cfg
{0}

# doctest.py examines the global scope for future imports
# and uses the sames ones in the executing scope. We don't want the
# Python-3 style behaviour in the docs yet.
try:
    del print_function
    def __init__(self, parent=None, window_flags=None, instrument=None, instrument_list=None):
        QMainWindow.__init__(self, parent)
        if window_flags:
            self.setWindowFlags(window_flags)
        self.ui = load_ui(__file__, 'ui/reduction_main.ui', baseinstance=self)

        if STARTUP_WARNING:
            message = "The reduction application has problems starting:\n\n"
            message += STARTUP_WARNING
            QMessageBox.warning(self, "WARNING", message)

        # Application settings
        settings = QSettings()

        # Name handle for the instrument
        if instrument is None:
            instrument = unicode(settings.value("instrument_name", ''))
            if instrument_list is not None and instrument not in instrument_list:
                instrument = None

        self._instrument = instrument
        self._facility = None

        # List of allowed instrument
        self._instrument_list = instrument_list

        # Reduction interface
        self._interface = None

        # Recent files
        self._recent_files = settings.value("recent_files", [])
        if self._recent_files is None:  # An empty list saved to QSettings comes back as 'None'
            self._recent_files = []

        # Folder to open files in
        self._last_directory = unicode(settings.value("last_directory", '.'))
        self._last_export_directory = unicode(settings.value("last_export_directory", '.'))

        # Current file name
        self._filename = None

        # Cluster credentials and options
        self._cluster_details_set = False
        self._number_of_nodes = 1
        self._cores_per_node = 16
        self._compute_resources = ['Fermi']
        if CAN_REDUCE and hasattr(ConfigService.Instance().getFacility(), "computeResources"):
            self._compute_resources = ConfigService.Instance().getFacility().computeResources()

        # Internal flag for clearing all settings and restarting the application
        self._clear_and_restart = False

        # General settings shared by all widgets
        self.general_settings = GeneralSettings(settings)

        # Event connections
        if not CAN_REDUCE:
            self.reduce_button.hide()
        self.export_button.clicked.connect(self._export)
        self.reduce_button.clicked.connect(self.reduce_clicked)
        self.save_button.clicked.connect(self._save)
        self.interface_chk.clicked.connect(self._interface_choice)

        self.interface_chk.setChecked(self.general_settings.advanced)

        self.general_settings.progress.connect(self._progress_updated)