def __init__(self, hostname, port=9998, interval=.1, alarm=None):
        # run the base class constructor
        super().__init__()

        # initialize the connection
        self.hostname = hostname
        self.port = port
        self.initialize()

        # set some properties
        self.setWindowTitle(hostname)
        self.hasData = False
        self.alarm = alarm
#        self.waiting_for_frame = False
#        self.latest_request = time.time()

        # a periodic timer triggers the update
        self.timer = qt.QTimer(self)
        self.timer.setInterval(interval * 1000.0)
        self.timer.timeout.connect(self._update)
        self.timer.start()

        # a periodic timer triggers the update
        self.timer = qt.QTimer(self)
        self.timer.setInterval(interval * 1000.0)
        self.timer.timeout.connect(self._update)
        self.timer.start()
    def __init__(self, hostname, port=9998, interval=.1, alarm=None):
        # run the base class constructor
        super().__init__()

        # initialize the connection
        self.hostname = hostname
        self.port = port
        self.initialize()

        # set some properties
        self.setWindowTitle(hostname)
        self.setKeepDataAspectRatio(True)
        self.setColormap(normalization='log')
        self.setYAxisInverted(True)
        self.hasImage = False
        self.alarm = alarm
        self.waiting_for_frame = False
        self.latest_request = time.time()

        # a periodic timer triggers the update
        self.timer = qt.QTimer(self)
        self.timer.setInterval(interval * 1000.0)
        self.timer.timeout.connect(self._update)
        self.timer.start()

        # Display mouseover position info
        posInfo = [
            ('X', lambda x, y: int(x)),
            ('Y', lambda x, y: int(y)),
            ('Data', self._getActiveImageValue)]
        self._positionWidget = tools.PositionInfo(plot=self, converters=posInfo)
        self.statusBar().addWidget(self._positionWidget)
Exemple #3
0
 def __init__(self, parent=None, timeout=14):
     super(TimerMessageBox, self).__init__(parent)
     self.setWindowTitle("Dark Current")
     self.time_to_wait = timeout
     self.setText(
         "Measuring dark current (Done in {0} secondes.)".format(timeout))
     self.setStandardButtons(qt.QMessageBox.NoButton)
     self.timer = qt.QTimer(self)
     self.timer.setInterval(1000)
     self.timer.timeout.connect(self.changeContent)
     self.timer.start()
Exemple #4
0
def mainQtApp(options):
    """Part of the main application depending on Qt"""
    try:
        # it should be loaded before h5py
        import hdf5plugin  # noqa
    except ImportError:
        _logger.debug("Backtrace", exc_info=True)
    import h5py

    import silx
    import silx.utils.files
    from silx.gui import qt

    # Make sure matplotlib is configured
    # Needed for Debian 8: compatibility between Qt4/Qt5 and old matplotlib
    from silx.gui.plot import matplotlib

    _logger.info('Starting application')
    app = qt.QApplication([])
    qt.QLocale.setDefault(qt.QLocale.c())

    def sigintHandler(*args):
        """Handler for the SIGINT signal."""
        qt.QApplication.quit()

    signal.signal(signal.SIGINT, sigintHandler)
    sys.excepthook = qt.exceptionHandler

    timer = qt.QTimer()
    timer.start(500)
    # Application have to wake up Python interpreter, else SIGINT is not
    # catched
    timer.timeout.connect(lambda: None)

    from .window import RixsAppWindow as MainWindow

    window = MainWindow(with_ipykernel=True)
    window.setAttribute(qt.Qt.WA_DeleteOnClose, True)

    window.show()
    _logger.info('Finished initialization')

    # Very important, IPython-specific step: this gets GUI event loop
    # integration going, and it replaces calling app.exec_()
    _logger.info('Starting the IPython kernel')
    window._ipykernel.kernel.start()

    result = app.exec_()
    # remove ending warnings relative to QTimer
    app.deleteLater()
    return result
Exemple #5
0
    def __init__(self, parent, plot3d=None):
        super(RotateViewport, self).__init__(parent, plot3d)

        self._previousTime = None

        self._timer = qt.QTimer(self)
        self._timer.setInterval(self._TIMEOUT_MS)  # 20fps
        self._timer.timeout.connect(self._rotate)

        self.setIcon(getQIcon('cube-rotate'))
        self.setText('Rotate scene')
        self.setToolTip('Rotate the 3D scene around the vertical axis')
        self.setCheckable(True)
        self.triggered[bool].connect(self._triggered)
Exemple #6
0
    def __mergeStart(self):
        self.__bn_box.rejected.disconnect(self.reject)
        self.__bn_box.rejected.connect(self.__onAbort)
        self.__bn_box.button(Qt.QDialogButtonBox.Ok).setEnabled(False)
        self.__bn_box.button(Qt.QDialogButtonBox.Cancel).setText('Abort')

        self.__qtimer = Qt.QTimer()
        self.__qtimer.timeout.connect(self.__onProgress)
        self.__merger.merge(overwrite=True,
                            blocking=False,
                            callback=self.__sigMergeDone.emit)
        self.__onProgress()
        self.__qtimer.start(1000)

        self.__time = time.time()
Exemple #7
0
    def __init__(self,
                 pv,
                 scaler_pv=None,
                 moving_pv=None,
                 moving_val=0,
                 precision=3,
                 limit_hi=9,
                 *args,
                 **kwargs):

        super().__init__(*args, **kwargs)

        if scaler_pv:
            self.count_mode = epics.PV(scaler_pv + '.CONT')
            self.count_time = epics.PV(scaler_pv + '.TP')
            self.auto_count_time = epics.PV(scaler_pv + '.TP1')

        self.setMinimumSize(qt.QSize(120, 30))
        self.setMaximumSize(qt.QSize(120, 30))

        self.precision = precision
        self.setFrameShape(qt.QFrame.Panel)
        self.setFrameShadow(qt.QFrame.Sunken)
        self.setAlignment(qt.Qt.AlignCenter)
        self.setText("not connected")

        self.formatStr = "{:." + str(self.precision) + "f}"

        self.moving_val = moving_val

        self.pv = epics.PV(pv, auto_monitor=True)
        self.pv.add_callback(self.update_value)

        if moving_pv is not None:
            self.moving_pv = epics.PV(moving_pv, auto_monitor=True)
            self.moving_pv.add_callback(self.update_color)

        self.limit_hi = limit_hi
        self._dummyIndex = 0

        self.notifyTimer = qt.QTimer()
        self.notifyTimer.timeout.connect(self._notifyColor)
        self.notifyTimer.start(1000)
Exemple #8
0
    def __init__(self, converter, parent=None, **kwargs):
        """
        Simple widget displaying a progress bar and a info label during the
            conversion process.
        :param converter:
        :param parent:
        :param kwargs:
        """
        super(_ConversionProcessDialog, self).__init__(parent)
        layout = Qt.QVBoxLayout(self)

        progress_bar = Qt.QProgressBar()
        layout.addWidget(progress_bar)
        status_lab = Qt.QLabel('<font color="blue">Conversion '
                               'in progress</font>')
        status_lab.setFrameStyle(Qt.QFrame.Panel | Qt.QFrame.Sunken)
        layout.addWidget(status_lab)

        bn_box = Qt.QDialogButtonBox(Qt.QDialogButtonBox.Abort)
        layout.addWidget(bn_box)
        bn_box.accepted.connect(self.accept)
        bn_box.rejected.connect(self.__onAbort)

        self.__sigConvertDone.connect(self.__convertDone)

        self.__bn_box = bn_box
        self.__progress_bar = progress_bar
        self.__status_lab = status_lab
        self.__converter = converter
        self.__aborted = False

        self.__qtimer = Qt.QTimer()
        self.__qtimer.timeout.connect(self.__onProgress)

        converter.convert(blocking=False,
                          overwrite=True,
                          callback=self.__sigConvertDone.emit,
                          **kwargs)

        self.__qtimer.start(1000)
Exemple #9
0
    def __init__(self, signal, delay=0.3, rateLimit=0, slot=None):
        """Initialization arguments:
        signal - a bound Signal or pyqtSignal instance
        delay - Time (in seconds) to wait for signals to stop before emitting (default 0.3s)
        slot - Optional function to connect sigDelayed to.
        rateLimit - (signals/sec) if greater than 0, this allows signals to stream out at a
                    steady rate while they are being received.
        """

        qt.QObject.__init__(self)
        signal.connect(self.signalReceived)
        self.signal = signal
        self.delay = delay
        self.rateLimit = rateLimit
        self.args = None
        self.timer = qt.QTimer()
        self.timer.timeout.connect(self.flush)
        self.blockSignal = False
        self.slot = weakref.ref(slot)
        self.lastFlushTime = None
        if slot is not None:
            self.sigDelayed.connect(slot)
Exemple #10
0
    def __init__(self, pv, *args, **kwargs):
        super(EpicsStringLabel, self).__init__(*args, **kwargs)

        self._dummyIndex = 0

        self.setMinimumSize(qt.QSize(130, 30))
        self.setMaximumSize(qt.QSize(130, 30))
        self.setFrameShape(qt.QFrame.Panel)
        self.setFrameShadow(qt.QFrame.Sunken)
        self.setAlignment(qt.Qt.AlignCenter)
        self.setText("not connected")

        self.pv = epics.PV(pv, auto_monitor=True)
        self.pv.add_callback(self.update_value)

        self.notifyTimer = qt.QTimer()
        self.notifyTimer.timeout.connect(self._notifyColor)
        self.notifyTimer.start(1000)

        # Set initial value from pv
        if self.pv.connected:
            if self.pv.get():
                _submit(self.setText, str("On"))
Exemple #11
0
    def __slotRunClicked(self):

        # TODO : put some safeguards
        self.__lock(True)

        self.__progBar.setValue(0)
        fitType = FitWidget.FitTypes[self.__fitTypeCb.currentText()]

        if self.__roiWidget.isActive():
            x0, x1 = self.__roiWidget.xSlider().getSliderIndices()
            y0, y1 = self.__roiWidget.ySlider().getSliderIndices()
            z0, z1 = self.__roiWidget.zSlider().getSliderIndices()
            roiIndices = [[x0, x1 + 1], [y0, y1 + 1], [z0, z1 + 1]]
        else:
            roiIndices = None

        self.__fitter = fitter = PeakFitter(self.__qspaceH5.filename,
                                            fit_type=fitType,
                                            roi_indices=roiIndices,
                                            n_peaks=self.__nPeaks)
        self.__statusLabel.setText('Running...')

        self.__progTimer = timer = Qt.QTimer()
        timer.setSingleShot(True)
        timer.timeout.connect(self.__slotProgTimer)

        try:
            self.sigProcessStarted.emit()
            fitter.peak_fit(blocking=False, callback=self.__sigFitDone.emit)
            timer.start(self.__progressDelay)
        except Exception as ex:
            # TODO : popup
            self.__statusLabel.setText('ERROR')
            print('ERROR : {0}.'.format(ex))
            self.__lock(False)
            self.sigProcessDone.emit(None)
Exemple #12
0
def main(argv):
    """
    Main function to launch the viewer as an application

    :param argv: Command line arguments
    :returns: exit status
    """
    parser = createParser()
    options = parser.parse_args(argv[1:])

    if options.debug:
        logging.root.setLevel(logging.DEBUG)

    #
    # Import most of the things here to be sure to use the right logging level
    #

    try:
        # it should be loaded before h5py
        import hdf5plugin  # noqa
    except ImportError:
        _logger.debug("Backtrace", exc_info=True)

    try:
        import h5py
    except ImportError:
        _logger.debug("Backtrace", exc_info=True)
        h5py = None

    if h5py is None:
        message = "Module 'h5py' is not installed but is mandatory."\
            + " You can install it using \"pip install h5py\"."
        _logger.error(message)
        return -1

    #
    # Run the application
    #

    app = qt.QApplication([])
    qt.QLocale.setDefault(qt.QLocale.c())

    signal.signal(signal.SIGINT, sigintHandler)
    sys.excepthook = qt.exceptionHandler

    timer = qt.QTimer()
    timer.start(500)
    # Application have to wake up Python interpreter, else SIGINT is not
    # catched
    timer.timeout.connect(lambda: None)

    settings = qt.QSettings(qt.QSettings.IniFormat, qt.QSettings.UserScope,
                            "silx", "silx-view", None)
    if options.fresh_preferences:
        settings.clear()

    from .Viewer import Viewer
    window = Viewer(parent=None, settings=settings)
    window.setAttribute(qt.Qt.WA_DeleteOnClose, True)

    if options.use_opengl_plot:
        # It have to be done after the settings (after the Viewer creation)
        silx.config.DEFAULT_PLOT_BACKEND = "opengl"

    for filename in options.files:
        try:
            window.appendFile(filename)
        except IOError as e:
            _logger.error(e.args[0])
            _logger.debug("Backtrace", exc_info=True)

    window.show()
    result = app.exec_()
    # remove ending warnings relative to QTimer
    app.deleteLater()
    return result
Exemple #13
0
def mainQt(options):
    """Part of the main depending on Qt"""
    if options.debug:
        logging.root.setLevel(logging.DEBUG)

    #
    # Import most of the things here to be sure to use the right logging level
    #

    # Use max opened files hard limit as soft limit
    try:
        import resource
    except ImportError:
        _logger.debug("No resource module available")
    else:
        if hasattr(resource, 'RLIMIT_NOFILE'):
            try:
                hard_nofile = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
                resource.setrlimit(resource.RLIMIT_NOFILE,
                                   (hard_nofile, hard_nofile))
            except (ValueError, OSError):
                _logger.warning(
                    "Failed to retrieve and set the max opened files limit")
            else:
                _logger.debug("Set max opened files to %d", hard_nofile)

    # This needs to be done prior to load HDF5
    hdf5_file_locking = 'TRUE' if options.hdf5_file_locking else 'FALSE'
    _logger.info('Set HDF5_USE_FILE_LOCKING=%s', hdf5_file_locking)
    os.environ['HDF5_USE_FILE_LOCKING'] = hdf5_file_locking

    try:
        # it should be loaded before h5py
        import hdf5plugin  # noqa
    except ImportError:
        _logger.debug("Backtrace", exc_info=True)

    import h5py

    import silx
    import silx.utils.files
    from silx.gui import qt
    # Make sure matplotlib is configured
    # Needed for Debian 8: compatibility between Qt4/Qt5 and old matplotlib
    import silx.gui.utils.matplotlib  # noqa

    app = qt.QApplication([])
    qt.QLocale.setDefault(qt.QLocale.c())

    def sigintHandler(*args):
        """Handler for the SIGINT signal."""
        qt.QApplication.quit()

    signal.signal(signal.SIGINT, sigintHandler)
    sys.excepthook = qt.exceptionHandler

    timer = qt.QTimer()
    timer.start(500)
    # Application have to wake up Python interpreter, else SIGINT is not
    # catched
    timer.timeout.connect(lambda: None)

    settings = qt.QSettings(qt.QSettings.IniFormat, qt.QSettings.UserScope,
                            "silx", "silx-view", None)
    if options.fresh_preferences:
        settings.clear()

    window = createWindow(parent=None, settings=settings)
    window.setAttribute(qt.Qt.WA_DeleteOnClose, True)

    if options.use_opengl_plot:
        # It have to be done after the settings (after the Viewer creation)
        silx.config.DEFAULT_PLOT_BACKEND = "opengl"

    # NOTE: under Windows, cmd does not convert `*.tif` into existing files
    options.files = silx.utils.files.expand_filenames(options.files)

    for filename in options.files:
        # TODO: Would be nice to add a process widget and a cancel button
        try:
            window.appendFile(filename)
        except IOError as e:
            _logger.error(e.args[0])
            _logger.debug("Backtrace", exc_info=True)

    window.show()
    result = app.exec()
    # remove ending warnings relative to QTimer
    app.deleteLater()
    return result
def mainQt(options):
    """Part of the main depending on Qt"""
    if options.debug:
        logging.root.setLevel(logging.DEBUG)

    #
    # Import most of the things here to be sure to use the right logging level
    #

    try:
        # it should be loaded before h5py
        import hdf5plugin  # noqa
    except ImportError:
        _logger.debug("Backtrace", exc_info=True)

    import h5py

    import silx
    import silx.utils.files
    from silx.gui import qt
    # Make sure matplotlib is configured
    # Needed for Debian 8: compatibility between Qt4/Qt5 and old matplotlib
    from silx.gui.plot import matplotlib

    app = qt.QApplication([])
    qt.QLocale.setDefault(qt.QLocale.c())

    def sigintHandler(*args):
        """Handler for the SIGINT signal."""
        qt.QApplication.quit()

    signal.signal(signal.SIGINT, sigintHandler)
    sys.excepthook = qt.exceptionHandler

    timer = qt.QTimer()
    timer.start(500)
    # Application have to wake up Python interpreter, else SIGINT is not
    # catched
    timer.timeout.connect(lambda: None)

    settings = qt.QSettings(qt.QSettings.IniFormat, qt.QSettings.UserScope,
                            "silx", "silx-view", None)
    if options.fresh_preferences:
        settings.clear()

    from .Viewer import Viewer
    window = Viewer(parent=None, settings=settings)
    window.setAttribute(qt.Qt.WA_DeleteOnClose, True)

    if options.use_opengl_plot:
        # It have to be done after the settings (after the Viewer creation)
        silx.config.DEFAULT_PLOT_BACKEND = "opengl"

    # NOTE: under Windows, cmd does not convert `*.tif` into existing files
    options.files = silx.utils.files.expand_filenames(options.files)

    for filename in options.files:
        # TODO: Would be nice to add a process widget and a cancel button
        try:
            window.appendFile(filename)
        except IOError as e:
            _logger.error(e.args[0])
            _logger.debug("Backtrace", exc_info=True)

    window.show()
    result = app.exec_()
    # remove ending warnings relative to QTimer
    app.deleteLater()
    return result
Exemple #15
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # PV names
        self.pv_names = loadPV()

        # ZMQ Ports
        self.zmqSendPort = 5301
        self.zmqRecvPort = 5201

        try:
            self.zmqSendSock = CONTEXT.socket(zmq.PUB)
            self.zmqSendSock.bind("tcp://*:" + str(self.zmqSendPort))
        except:
            self.zmqSendSock = None
            print("Failed to bind to socket : {}".format(self.zmqSendPort))

        # MainWindow Title
        self.setWindowTitle("DataViewer")

        # Initialize
        self._dragging = False
        self._last_y_axis_type = 0
        self._last_tab_index = 0
        self.plot_type = 'measure'
        self.start_timer = 0

        self.settings = {}
        self.settings['E0'] = 8333
        self.settings['sdd'] = False
        self.settings['ratio'] = 0.7
        self.settings['plot_type'] = 'measure'
        self.settings['blink'] = False
        self.settings['scanCounts'] = 1

        # DataBroker
        self.dbv1 = Broker.from_config(config)
        self.db = self.dbv1.v2

        # Main QWidget
        main_panel = qt.QWidget(self)
        main_panel.setLayout(qt.QVBoxLayout())
        self.setCentralWidget(main_panel)

        # Status Widget
        self.status = StatusWidget(self)
        self.status.setSizePolicy(qt.QSizePolicy.Expanding,
                                  qt.QSizePolicy.Fixed)

        # Intialize plot
        self.plot = Plot1DCustom(self, 'mpl')
        self.plot.getLegendsDockWidget().show()
        self.plot.setBackgroundColor('#FCF9F6')
        self.plot.setGraphXLabel("Energy [eV]")
        self.plot.setGraphYLabel("Counts [Arbs.]")
        self.plot.setDataMargins(0.01, 0.01, 0.01, 0.01)

        # Layout
        main_panel.layout().addWidget(self.status)
        main_panel.layout().addWidget(self.plot)

        # Adjust operation graph's margin(left, bottom, width height)
        self.plot._backend.ax.set_position([0.1, 0.05, 0.83, 0.93])
        self.plot._backend.ax2.set_position([0.1, 0.05, 0.83, 0.93])

        # self.updatePlotThread = UpdatePlotThread(self)
        # self.updatePlotThread.daemon = True
        # self.updatePlotThread.start()

        self.updatePlotThread = TestThread(self)
        self.updatePlotThread.daemon = True
        self.updatePlotThread.start()

        # Upper pannel for safety
        self.status.abortButton.clicked.connect(self.abortScan)

        # Manage zoom history of plot
        self.status.x_axis_type_combo_box.currentIndexChanged.connect(
            self.clearZoomHistory)
        self.status.y_axis_type_combo_box.currentIndexChanged.connect(
            self.clearZoomHistory)

        # Start ZMQ Recv Thread
        self.zmqRecvThread = QThreadFuture(self.receiveZmq)
        self.zmqRecvThread.start()

        if self.status:
            # RunEngine Notifier
            self._dummyIndex = 0
            self.notifyTimer = qt.QTimer()
            self.notifyTimer.timeout.connect(self._notifyColor)
            self.notifyTimer.start(1000)

        # As a thread that monitors the DCM moving state, check the case
        # that it is normally located but is displaying as moving
        # self.checkDcmThread = CheckDcmThread()
        # self.checkDcmThread.daemon = True
        # self.checkDcmThread.start()

        # Connections
        self.status.num_of_history_spin_box.valueChanged.connect(
            self.updatePlotThread.trigger)
        self.status.x_axis_type_combo_box.currentIndexChanged.connect(
            self.updatePlotThread.trigger)
        self.status.y_axis_type_combo_box.currentIndexChanged.connect(
            self.updatePlotThread.trigger)
        self.status.derivativeCB.stateChanged.connect(
            self.updatePlotThread.trigger)

        # Check for dragging
        self.plot.sigPlotSignal.connect(self.checkDragging)

        # Initial query
        self.sendZmq('ViewerInitialized')
Exemple #16
0
 def __setThread(self, function, period):
     self.__timer = qt.QTimer()
     self.__timer.timeout[()].connect(function)
     self.__timer.start(period)
Exemple #17
0
 def __init__(self, function=None, period=1000):
     self.__timer = qt.QTimer()
     if function is None: function = self.test
     self._function = function
     self.__setThread(function, period)