예제 #1
0
    def __init__(self, fit: chisurf.fitting.fit.FitGroup, *args, **kwargs):
        super(ParameterScanPlot, self).__init__(fit)

        self.layout = QtWidgets.QVBoxLayout(self)
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.layout.setSpacing(0)

        self.data_x, self.data_y = None, None

        self.pltControl = ParameterScanWidget(model=fit.model, parent=self)

        area = DockArea()
        self.layout.addWidget(area)
        hide_title = plot_settings['hideTitle']
        d2 = Dock("Chi2-Surface", hideTitle=hide_title)

        self.p1 = QtWidgets.QPlainTextEdit()
        p2 = pg.PlotWidget()

        d2.addWidget(p2)

        area.addDock(d2, 'top')

        distribution_plot = p2.getPlotItem()

        self.distribution_plot = distribution_plot
        self.distribution_curve = distribution_plot.plot(x=[0.0],
                                                         y=[0.0],
                                                         pen=pg.mkPen(
                                                             colors['data'],
                                                             width=lw),
                                                         name='Data')
    def setup_widgets(self, parent, name):
        dock_area = DockArea()
        parent.addTab(dock_area, name)

        dock_position = Dock("Position")
        dock_area.addDock(dock_position)

        # Position 2d plot
        position_graphics = pg.GraphicsLayoutWidget()
        position_graphics.show()
        view = position_graphics.addViewBox()
        self.position_img = pg.ImageItem(border='w')
        view.addItem(self.position_img)
        dock_position.addWidget(position_graphics)

        # Status widget
        dock_status = Dock("Status", size=(800, 1))
        dock_area.addDock(dock_status, 'top')
        cw = QtGui.QWidget()
        cw.setStyleSheet("QWidget {background-color:white}")
        layout = QtGui.QGridLayout()
        cw.setLayout(layout)
        self.spin_box = Qt.QSpinBox(value=1)
        self.spin_box.setMaximum(10)
        self.spin_box.setSuffix(" Threshold")

        layout.addWidget(self.spin_box, 0, 6, 0, 1)
        dock_status.addWidget(cw)

        self.spin_box.valueChanged.connect(lambda value: self.send_command(str(value)))
예제 #3
0
    def create_graph_views(self):
        """
        Creates the window containing the graph views.
        :return: None
        """
        dock_area = DockArea()
        self.setCentralWidget(dock_area)

        dock_3d = Dock('3D')
        dock_area.addDock(dock_3d)

        dock_1d = Dock('1D')
        dock_area.addDock(dock_1d, 'above', dock_3d)

        dock_2d = Dock('2D')
        dock_area.addDock(dock_2d, 'above', dock_3d)

        self.plot_3d = Plot3DWidget(self.model_wrapper, dock_3d)
        dock_3d.addWidget(self.plot_3d)

        self.plot_2d = Plot2DWidget(self.model_wrapper, self.statusBar(),
                                    dock_2d)
        dock_2d.addWidget(self.plot_2d)

        self.plot_1d = Plot1DWidget(self.model_wrapper, self.statusBar(),
                                    dock_1d)
        dock_1d.addWidget(self.plot_1d)

        # TODO: move away from this function
        dock_list = Dock('integration')
        dock_area.addDock(dock_list)
        dock_list.addWidget(IntegrationList(self.model_wrapper, dock_list))
예제 #4
0
    def __init__(self, parent=None):
        DockArea.__init__(self, parent=parent)
        self._status_dict = defaultdict(lambda: True)
        self.app = App()
        self.crystal_controller = CrystalsController(
            self.app.crystals_database, self, self)
        self.crystal_viewer = MainCrystalViewer(self.crystal_controller, self)

        self.__init_image_viewer()
        self.__init_polar_viewer()
        # self.__init_control_widget__()
        self.__init_radial_widget()
        self.__init_file_widget()
        self.__init_angular_widget()
        self.__init_crystal_image_widget()

        self._DOCK_DICT = {
            'image_view': self.image_viewer_dock,
            'polar': self.polar_viewer_dock,
            'radial_profile': self.radial_profile_dock,
            'file_widget': self.file_dock,
            'angular_profile': self.angular_profile_dock,
            'crystal_image': self.crystal_image_viewer_dock
        }
        self._apply_default_view()
        self._fit_widget = None

        self.app.image_holder.sigFitOpen.connect(self._open_fit_widget)
예제 #5
0
    def __init__(self, scan_z, webcam_focus_lock, *args, **kwargs):

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

        self.scan_z = scan_z

        self.filewarning = FileWarning()

        # Dock widget
        dockArea = DockArea()

        # Focus lock widget
        focusDock = Dock("Focus lock", size=(500, 500))
        self.focusWidget = focus.FocusWidget(self.scan_z, webcam_focus_lock)
        focusDock.addWidget(self.focusWidget)
        dockArea.addDock(focusDock, "left")

        self.setWindowTitle('Tempesta - Focus lock edition')
        self.cwidget = QtGui.QWidget()
        self.setCentralWidget(self.cwidget)

        # Widgets' layout
        layout = QtGui.QGridLayout()
        self.cwidget.setLayout(layout)
        layout.addWidget(dockArea, 0, 0, 1, 1)
예제 #6
0
    def __init__(self, imgFName='img', parent=None):
        QWidget.__init__(self, parent=None)
        self.palette = QPalette()
        self.cwd = os.getcwd()
        self.setup = Setup(os.path.join(self.cwd, 'SetupData'))
        self.detectors = self.setup.detectors
        self.motors = self.setup.motors
        self.scalers = self.setup.scalers
        self.imgFName = imgFName
        self.vblayout = QVBoxLayout(self)
        self.mainDock = DockArea(self, parent)
        self.vblayout.addWidget(self.mainDock)
        self.imageFlag = 0

        self.pdIn = False
        self.beamIn = False
        self.mirrorIn = False
        self.align = True
        self.delay = 0.1
        self.detPV = 'None'

        self.detParDock = Dock('Detector Parameters', size=(1, 1))
        self.imgDock = Dock('Image', size=(1, 10))
        self.mainDock.addDock(self.imgDock, 'left')
        self.mainDock.addDock(self.detParDock, 'left')
        self.mainDock.moveDock(self.imgDock, 'bottom', self.detParDock)

        self.create_imgDock()
        self.create_detParDock()

        self.fileWatcher = FileWatcher()
예제 #7
0
    def __init__(self, fit: chisurf.fitting.fit.FitGroup,
                 parent: QtWidgets.QWidget, **kwargs):
        super().__init__(fit=fit, parent=parent)
        self.layout = QtWidgets.QVBoxLayout(self)
        self.data_x, self.data_y = None, None

        self.pltControl = DistributionPlotControl(self, parent=self, **kwargs)

        area = DockArea()
        self.layout.addWidget(area)
        hide_title = plot_settings['hideTitle']
        d2 = Dock("Fit", size=(500, 400), hideTitle=hide_title)

        self.p1 = QtWidgets.QPlainTextEdit()
        p2 = pg.PlotWidget(useOpenGL=pyqtgraph_settings['useOpenGL'])

        d2.addWidget(p2)

        area.addDock(d2, 'top')

        distribution_plot = p2.getPlotItem()

        self.distribution_plot = distribution_plot
        self.distribution_curve = distribution_plot.plot(x=[0.0],
                                                         y=[0.0],
                                                         pen=pg.mkPen(
                                                             colors['data'],
                                                             width=lw),
                                                         name='Data')
예제 #8
0
    def add_widgets(self):
        # Main window with dock area
        self.dock_area = DockArea()
        self.setCentralWidget(self.dock_area)
        dock_run_config = Dock("Run configuration", size=(400, 400))
        # Docks
        dock_occcupancy = Dock("Occupancy", size=(400, 400))
        #dock_tti = Dock("tti",size=(400, 400))
        self.dock_area.addDock(dock_occcupancy)
        # Status widget
        cw = QtGui.QWidget()
        cw.setStyleSheet("QWidget {background-color:white}")
        layout = QtGui.QGridLayout()
        cw.setLayout(layout)

        # Run config dock
        self.run_conf_list_widget = Qt.QListWidget()
        dock_run_config.addWidget(self.run_conf_list_widget)

        # Global config dock
        self.global_conf_list_widget = Qt.QListWidget()

        # Different plot docks
        occupancy_graphics = pg.GraphicsLayoutWidget()
        occupancy_graphics.show()
        view = occupancy_graphics.addViewBox()
        self.occupancy_img = pg.ImageItem(border='w')

        view.addItem(self.occupancy_img)
        view.setRange(QtCore.QRectF(0, 0, 80, 336))
        dock_occcupancy.addWidget(occupancy_graphics)
예제 #9
0
    def __init__(self, fit):
        super().__init__(fit=fit)

        self.trajectory = fit.model
        self.source = fit.model

        self.layout = QtWidgets.QVBoxLayout(self)
        area = DockArea()
        self.layout.addWidget(area)
        hide_title = chisurf.settings.gui['plot']['hideTitle']
        d1 = Dock("RMSD")
        d2 = Dock("dRMSD")
        d3 = Dock("Energy")
        d4 = Dock("FRET")

        p1 = pg.PlotWidget()
        p2 = pg.PlotWidget()
        p3 = pg.PlotWidget()
        p4 = pg.PlotWidget()

        d1.addWidget(p1)
        d2.addWidget(p2)
        d3.addWidget(p3)
        d4.addWidget(p4)

        area.addDock(d1, 'top')
        area.addDock(d2, 'right', d1)
        area.addDock(d3, 'bottom')
        area.addDock(d4, 'right', d3)

        # RMSD - Curves
        self.rmsd_plot = p1.getPlotItem()
        self.drmsd_plot = p2.getPlotItem()
        self.energy_plot = p3.getPlotItem()
        self.fret_plot = p4.getPlotItem()

        lw = chisurf.settings.gui['plot']['line_width']
        self.rmsd_curve = self.rmsd_plot.plot(x=[0.0],
                                              y=[0.0],
                                              pen=pg.mkPen(colors['irf'],
                                                           width=lw),
                                              name='rmsd')
        self.drmsd_curve = self.drmsd_plot.plot(x=[0.0],
                                                y=[0.0],
                                                pen=pg.mkPen(colors['data'],
                                                             width=lw),
                                                name='drmsd')
        self.energy_curve = self.energy_plot.plot(x=[0.0],
                                                  y=[0.0],
                                                  pen=pg.mkPen(
                                                      colors['models'],
                                                      width=lw),
                                                  name='energy')
        self.fret_curve = self.fret_plot.plot(x=[0.0],
                                              y=[0.0],
                                              pen=pg.mkPen(colors['models'],
                                                           width=lw),
                                              name='fret')
    def __init_gui(self):
        self.graphs = {}
        self.area = DockArea()

        self.__create_graph(
            graph_id='std',
            pos='top',
            widget=pyqtgraph.PlotWidget(
                title='Std participation vs % Yes votes'),
        )

        self.std_mean_plot = self.graphs['std']['widget'].plot()
        self.std_mean_plot.setZValue(10)

        self.__create_graph(
            graph_id='taiko',
            pos='right',
            widget=pyqtgraph.PlotWidget(
                title='Taiko participation vs % Yes votes'),
        )

        self.taiko_mean_plot = self.graphs['taiko']['widget'].plot()
        self.taiko_mean_plot.setZValue(10)

        self.__create_graph(
            graph_id='catch',
            pos='bottom',
            widget=pyqtgraph.PlotWidget(
                title='Catch participation vs % Yes votes'),
        )

        self.catch_mean_plot = self.graphs['catch']['widget'].plot()

        self.__create_graph(
            graph_id='mania',
            pos='right',
            relative_to=self.graphs['catch']['dock'],
            widget=pyqtgraph.PlotWidget(
                title='Mania participation vs % Yes votes'),
        )

        self.mania_mean_plot = self.graphs['mania']['widget'].plot()
        self.mania_mean_plot.setZValue(10)

        self.graphs['std']['widget'].setLabel('left', '% Yes')
        self.graphs['std']['widget'].setLabel('bottom', '# Total Votes')

        self.graphs['taiko']['widget'].setLabel('left', '% Yes')
        self.graphs['taiko']['widget'].setLabel('bottom', '# Total Votes')

        self.graphs['catch']['widget'].setLabel('left', '% Yes')
        self.graphs['catch']['widget'].setLabel('bottom', '# Total Votes')

        self.graphs['mania']['widget'].setLabel('left', '% Yes')
        self.graphs['mania']['widget'].setLabel('bottom', '# Total Votes')

        self.setCentralWidget(self.area)
예제 #11
0
 def ui_setup(self):
     '''Calls all functions needed to set up UI programmatically.
     This object is called from :meth:`setup`'''
     self.ui = DockArea()
     self.layout = QtWidgets.QVBoxLayout()
     self.ui.show()
     self.ui.setWindowTitle('ALD Control Panel')
     self.ui.setLayout(self.layout)
     self.widget_setup()
     self.dockArea_setup()
예제 #12
0
 def addTempArea(self):
     if self.home is None:
         area = DockArea(temporary=True, home=self)
         self.tempAreas.append(area)
         win = TempAreaWindow(area)
         area.win = win
         win.show()
     else:
         area = self.home.addTempArea()
     # print "added temp area", area, area.window()
     return area
예제 #13
0
class MainWindow(QtWidgets.QMainWindow):
    """The only window of the application."""
    def __init__(self, settings):
        super(MainWindow, self).__init__()
        self.settings = settings

        self.setupUi()

        self.dock_area = DockArea()
        self.setCentralWidget(self.dock_area)

        self.createDocks()

        self.loadSettings()
        self.setWindowTitle('Rb Lock')

    def setupUi(self):
        pass

    def createDocks(self):
        self.rb_lock_widget = RbLockWidget(self.settings, self)
        self.rb_lock_widget_dock = Dock('Rb Lock', widget=self.rb_lock_widget)
        self.dock_area.addDock(self.rb_lock_widget_dock)

    def loadSettings(self):
        """Load window state from self.settings"""

        self.settings.beginGroup('mainwindow')
        geometry = self.settings.value('geometry')
        state = self.settings.value('windowstate')
        dock_string = str(self.settings.value('dockstate'))
        if dock_string is not "":
            dock_state = eval(dock_string)
            self.dock_area.restoreState(dock_state)
        self.settings.endGroup()

        self.restoreGeometry(geometry)
        self.restoreState(state)

    def saveSettings(self):
        """Save window state to self.settings."""
        self.settings.beginGroup('mainwindow')
        self.settings.setValue('geometry', self.saveGeometry())
        self.settings.setValue('windowstate', self.saveState())
        dock_state = self.dock_area.saveState()
        # dock_state returned here is a python dictionary. Coundn't find a good
        # way to save dicts in QSettings, hence just using representation
        # of it.
        self.settings.setValue('dockstate', repr(dock_state))
        self.settings.endGroup()

    def closeEvent(self, event):
        self.rb_lock_widget.saveSettings()
        self.saveSettings()
예제 #14
0
 def addTempArea(self):
     if self.home is None:
         area = DockArea(temporary=True, home=self)
         self.tempAreas.append(area)
         win = TempAreaWindow(area, self)
         area.win = win
         win.show()
     else:
         area = self.home.addTempArea()
     #print 'added temp area', area, area.window()
     return area
예제 #15
0
 def addTempArea(self):
     if self.home is None:
         area = DockArea(temporary=True, home=self)
         self.tempAreas.append(area)
         win = TempAreaWindow(area)
         win.setWindowFlags(Qt.Qt.WindowMinimizeButtonHint)
         area.win = win
         win.show()
     else:
         area = self.home.addTempArea()
     #print "added temp area", area, area.window()
     return area
예제 #16
0
    def __init__(self, settings):
        super(MainWindow, self).__init__()
        self.settings = settings

        self.setupUi(self)

        self.dock_area = DockArea()
        self.setCentralWidget(self.dock_area)

        self.createDocks()

        self.loadSettings()
예제 #17
0
 def addTempArea(self):
     if self.home is None:
         area = DockArea(temporary=True, home=self)
         self.tempAreas.append(area)
         win = TempAreaWindow(area)
         win.setWindowFlags(Qt.Qt.WindowMinimizeButtonHint)
         area.win = win
         win.show()
     else:
         area = self.home.addTempArea()
     #print "added temp area", area, area.window()
     return area
예제 #18
0
class MainWindow(QMainWindow, Ui_MainWindow):
    """The only window of the application."""

    def __init__(self, settings):
        super(MainWindow, self).__init__()
        self.settings = settings

        self.setupUi(self)

        self.dock_area = DockArea()
        self.setCentralWidget(self.dock_area)

        self.createDocks()

        self.loadSettings()

    def createDocks(self):
        self.zmq_subscriber = ZMQSubscriber(self.settings, self)
        self.zmq_subscriber_dock = Dock('Subscriber',
                                        widget=self.zmq_subscriber)
        self.dock_area.addDock(self.zmq_subscriber_dock)

    def loadSettings(self):
        """Load window state from self.settings"""

        self.settings.beginGroup('mainwindow')
        geometry = self.settings.value('geometry').toByteArray()
        state = self.settings.value('windowstate').toByteArray()
        dock_string = str(self.settings.value('dockstate').toString())
        if dock_string is not "":
            dock_state = eval(dock_string)
            self.dock_area.restoreState(dock_state)
        self.settings.endGroup()

        self.restoreGeometry(geometry)
        self.restoreState(state)

    def saveSettings(self):
        """Save window state to self.settings."""
        self.settings.beginGroup('mainwindow')
        self.settings.setValue('geometry', self.saveGeometry())
        self.settings.setValue('windowstate', self.saveState())
        dock_state = self.dock_area.saveState()
        # dock_state returned here is a python dictionary. Coundn't find a good
        # way to save dicts in QSettings, hence just using representation
        # of it.
        self.settings.setValue('dockstate', repr(dock_state))
        self.settings.endGroup()

    def closeEvent(self, event):
        self.zmq_subscriber.saveSettings()
        self.saveSettings()
예제 #19
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setWindowTitle('Scripting')

        # Actions in menubar
        menuBar = self.menuBar()
        file = menuBar.addMenu('&File')

        self.newFileAction = QtWidgets.QAction('New…', self)
        self.newFileAction.setShortcut('Ctrl+N')
        self.newFileAction.triggered.connect(self.sigNewFile)
        file.addAction(self.newFileAction)
        self.openFileAction = QtWidgets.QAction('Open…', self)
        self.openFileAction.setShortcut('Ctrl+O')
        self.openFileAction.triggered.connect(self.sigOpenFile)
        file.addAction(self.openFileAction)
        self.saveFileAction = QtWidgets.QAction('Save', self)
        self.saveFileAction.setShortcut('Ctrl+S')
        self.saveFileAction.triggered.connect(self.sigSaveFile)
        file.addAction(self.saveFileAction)
        self.saveAsFileAction = QtWidgets.QAction('Save as…', self)
        self.saveAsFileAction.setShortcut('Ctrl+Shift+S')
        self.saveAsFileAction.triggered.connect(self.sigSaveAsFile)
        file.addAction(self.saveAsFileAction)

        # Main layout
        self.dockArea = DockArea()
        self.setCentralWidget(self.dockArea)

        self.editor = EditorView()
        self.editorDock = Dock('Script Editor')
        self.editorDock.addWidget(self.editor)
        self.dockArea.addDock(self.editorDock)

        self.files = FilesView()
        self.filesDock = Dock('Files')
        self.filesDock.addWidget(self.files)
        self.dockArea.addDock(self.filesDock, 'left', self.editorDock)

        self.console = ConsoleView()
        self.consoleDock = Dock('Console')
        self.consoleDock.addWidget(self.console)
        self.dockArea.addDock(self.consoleDock, 'right', self.editorDock)

        self.output = OutputView()
        self.outputDock = Dock('Output')
        self.outputDock.addWidget(self.output)
        self.dockArea.addDock(self.outputDock, 'bottom', self.editorDock)

        self.editorDock.setStretch(20, 30)

        self.showMaximized()
예제 #20
0
    def __init__(self, parent=None, hideHistograms=False) -> None:
        BaseClassTemplate.__init__(self, parent=parent)

        self.uiBase = BaseWidgetTemplate()
        self.uiBase.setupUi(self)

        #############################################################
        #                   ATTRIBUTES                              #
        #############################################################

        self.gui_timer = QTimer()  # type: QTimer
        self.gui_timer.timeout.connect(self.updateDisplay)
        if self.uiBase.wao_Display.isChecked():
            self.gui_timer.start(1000. / self.uiBase.wao_frameRate.value())
        self.loopLock = threading.Lock(
        )  # type: Threading.Lock # Asynchronous loop / display safe-threading
        self.hideHistograms = hideHistograms
        #############################################################
        #               PYQTGRAPH DockArea INIT                     #
        #############################################################

        self.area = DockArea()
        self.uiBase.wao_DisplayDock.setWidget(self.area)
        self.gridSH = []

        #############################################################
        #                 CONNECTED BUTTONS                         #
        #############################################################
        # Default path for config files
        self.defaultParPath = "."
        self.defaultAreaPath = "."
        self.uiBase.wao_loadConfig.clicked.connect(self.loadConfig)
        self.uiBase.wao_loadArea.clicked.connect(self.loadArea)
        self.uiBase.wao_saveArea.clicked.connect(self.saveArea)
        self.uiBase.wao_init.clicked.connect(self.initConfig)
        self.uiBase.wao_configFromFile.clicked.connect(self.addConfigFromFile)

        self.uiBase.wao_Display.stateChanged.connect(self.gui_timer_config)
        self.uiBase.wao_frameRate.setValue(2)

        self.uiBase.wao_loadConfig.setDisabled(False)
        self.uiBase.wao_init.setDisabled(True)

        self.disp_checkboxes = []
        self.docks = {}  # type: Dict[str, pg.dockarea.Dock]
        self.viewboxes = {}  # type: Dict[str, pg.ViewBox]
        self.imgs = {}  # type: Dict[str, pg.ImageItem]
        self.hists = {}  # type: Dict[str, pg.HistogramLUTItem]

        self.PupilLines = None
        self.adjustSize()
예제 #21
0
    def setup_widgets(self, parent, name):
        dock_area = DockArea()
        parent.addTab(dock_area, name)

        dock_position = Dock("Position")
        dock_area.addDock(dock_position)

        # Position 2d plot
        position_graphics = pg.GraphicsLayoutWidget()
        position_graphics.show()
        view = position_graphics.addViewBox()
        self.position_img = pg.ImageItem(border='w')
        view.addItem(self.position_img)
        dock_position.addWidget(position_graphics)
예제 #22
0
    def _InitDocks(self):

        # Define docking area
        if hasattr(self, "_dockArea"):
            self._dockArea.setParent(None)
        self._dockArea = DockArea()

        self._plotDocks = self._defaultDockPos.keys()

        # Add dock to area
        for dock, pos in self._defaultDockPos.iteritems():
            self._dockArea.addDock(dock, *pos)

        self._layout.addWidget(self._dockArea, 0, 0, 1, 1)
    def setup_plots(self, parent, name):
        dock_area = DockArea()
        parent.addTab(dock_area, name)

        dock_position = Dock("Position Correlation")
        dock_area.addDock(dock_position)

        # Position 2d plot
        position_graphics = pg.GraphicsLayoutWidget()
        position_graphics.show()
        view = position_graphics.addViewBox()
        self.position_img = pg.ImageItem(border='w')
        view.addItem(self.position_img)
        dock_position.addWidget(position_graphics)
예제 #24
0
def main():
    app = QtWidgets.QApplication(sys.argv)
    win = QtWidgets.QMainWindow()
    area = DockArea()
    win.setCentralWidget(area)
    win.show()

    dock = Dock(name='Test Dock', area=area)
    area.addDock(dock)

    QtCore.QThread.sleep(2)
    dock.close()
    QtWidgets.QApplication.processEvents()
    sys.exit(app.exec_())
예제 #25
0
파일: main.py 프로젝트: wsonv/Wonjun
    def realinit(self):

        self.docklist = [
            'self.drho', 'self.dlamb', 'self.dalpha', 'self.dbeta',
            'self.dphase', 'self.dcontrols'
        ]
        self.area = DockArea()
        self.drho = Dock("Particle Density \u2374", closable=True)
        self.dlamb = Dock("Hopping Rate \u03bb", closable=True)
        self.dphase = Dock("Phase Diagram", closable=True)
        self.dcontrols = Dock("Controls", closable=True)
        self.dalpha = Dock(
            "Current J and average density \u27e8\u2374\u27e9 as a function of \u03b1",
            closable=True)
        self.dbeta = Dock(
            "Current J and average density \u27e8\u2374\u27e9 as a function of \u03b2",
            closable=True)

        self.layout = QtGui.QHBoxLayout()
        self.layout.addWidget(self.area)
        self.mainframe.setLayout(self.layout)
        self.mainframe.setFrameStyle(QtGui.QFrame.Box | QtGui.QFrame.Raised)
        self.mainframe.setLineWidth(8)

        pg.setConfigOptions(antialias=True)

        self.rh = rho.rho(self.drho)
        self.jalph = jalpha.jalpha(self.dalpha, self.rh)
        self.jbet = jbeta.jbeta(self.dbeta, self.rh)
        self.phas = phase.phase(self.dphase)
        self.lamb_po = lamb_pol.lamb_pol(self.dlamb)
        self.slid = slider.Widget(self.dcontrols, self.lamb_po, self.phas,
                                  self.rh, self.jbet, self.jalph)
        self.lamb_po.receive(self.slid)

        # default values to restore is input
        self.savedlambdas = glo_var.lambdas[:]
        self.savedalpha = glo_var.alpha
        self.savedbeta = glo_var.beta
        self.savedl = glo_var.l

        self.pltlist = [['Lambda_fig', self.lamb_po.p1],
                        ['Density_fig', self.rh.p2],
                        ['Current_alpha_fig', self.jalph.plotitemtoexport],
                        ['Current_beta_fig', self.jbet.plotitemtoexport],
                        ['Phase_fig', self.phas.p5]]

        self.grid_view_1()

        self.setCentralWidget(self.area)
예제 #26
0
 def setupPlots(self):
     self.area = DockArea()
     self.setCentralWidget(self.area)
     self.plotDict = dict()
     # initialize all the plot windows we want
     plotNames = self.config.get( 'PlotNames', ['Scan'] )
     if len(plotNames)<1:
         plotNames.append('Scan')
     for name in plotNames:
         dock = Dock(name)
         widget = CoordinatePlotWidget(self)
         view = widget._graphicsView
         self.area.addDock(dock, "bottom")
         dock.addWidget(widget)
         self.plotDict[name] = {"dock":dock, "widget":widget, "view":view}
예제 #27
0
    def makeLayout(self):

        self.dock_area = DockArea()
        self.setCentralWidget(self.dock_area)

        # self.setupUi(self)
        # self.qsettings = QtCore.QSettings('DemsarLabs','StepScanMeter')
        # geometry = self.qsettings.value('geometry', '')

        self.scan_area = ScanAreaWidget()
        self.scan_area_docker = QtWidgets.QDockWidget()
        self.scan_area_docker.setObjectName("docker")
        # self.plot_area_docker.setAllowedAreas(QtCore.Qt.TopDockWidgetArea)
        self.scan_area_docker.setWidget(self.scan_area)

        self.scan_setup_area = ScanSetupWidget()
        self.scan_setup_area_docker = QtWidgets.QDockWidget()
        self.scan_setup_area_docker.setObjectName('Scan Setup Area')
        # self.scan_setup_area_docker.setAllowedAreas(QtCore.Qt.LeftDockWidgetArea)
        self.scan_setup_area_docker.setWidget(self.scan_setup_area)

        self.scan_setup_area.set_scan_settings.connect(
            self.scan_area.acceptScanSettings)
        self.instrument_monitor = DockInstrumentMonitor()

        self.addDockWidget(QtCore.Qt.LeftDockWidgetArea,
                           self.scan_setup_area_docker)
        self.addDockWidget(QtCore.Qt.TopDockWidgetArea, self.scan_area_docker)
        self.addDockWidget(QtCore.Qt.RightDockWidgetArea,
                           self.instrument_monitor)
예제 #28
0
    def __init__(self, settings):
        super(MainWindow, self).__init__()
        self.settings = settings
        self.setupUi(self)

        # MainWindow is a collection of widgets in their respective docks.
        # We make DockArea our central widget
        self.dock_area = DockArea()
        self.setCentralWidget(self.dock_area)

        self.createDocks()
        self.initAfterCreatingDockWidgets()
        self.loadSettings()

        self.connectSignalsToSlots()

        # all signals in place, send out the first image
        # self.image_browser.populateAndEmitImageInfo()
        self.image_browser.initialEmit()
        self.roi_editor_h.initialEmit()
        self.roi_editor_v.initialEmit()
        self.roi_editor_int.initialEmit()
        self.roi_editor_err.initialEmit()

        self.loadPlugins()
예제 #29
0
 def create_dock(self):
     area = DockArea()
     self.obj_graph['param']['dock'] = Dock("setting parameters")
     self.obj_graph['plot']['dock'] = Dock("R (V) function of current (mA)")
     self.obj_graph['plot2']['dock'] = Dock("Phi (deg) function of current (mA)")
     area.addDock(self.obj_graph['param']['dock'], 'left')
     area.addDock(self.obj_graph['plot']['dock'],'right')
     area.addDock(self.obj_graph['plot2']['dock'],'bottom',self.obj_graph['plot']['dock'])
     self.setCentralWidget(area)
예제 #30
0
 def start(self):
     self.win = QtGui.QMainWindow()
     self.win.resize(1000, 500)
     self.win.setWindowTitle(title)
     self.area = DockArea()
     self.visualizeDock = Dock("Visualization", size=(800, 500))
     self.visualizePlt = pg.PlotWidget(background=(255, 255, 255))
     self.visualizePlt.setTitle(title=opt.input, color=(0, 0, 0))
     self.visualizePlt.showGrid(x=True, y=True)
     self.visualizePlt.getAxis("left").setPen((0, 0, 0))
     self.visualizePlt.getAxis("top").setPen((0, 0, 0))
     self.visualizePlt.getAxis("bottom").setPen((0, 0, 0))
     self.visualizePlt.getAxis("right").setPen((0, 0, 0))
     self.buttonDock = Dock("Buttons", size=(100, 500))
     self.bottonScroll = QtGui.QScrollArea()
     self.buttonGroup = QtGui.QGroupBox()
     self.bottonVBox = QtGui.QVBoxLayout()
예제 #31
0
 def setupPlots(self):
     self.area = DockArea()
     self.setCentralWidget(self.area)
     self.plotDict = SequenceDict()
     # initialize all the plot windows we want
     plotNames = self.config.get(self.configName+'.PlotNames', ['Plot'])
     if len(plotNames) < 1:
         plotNames.append('Plot')
     if 'Autoload' not in plotNames:
         plotNames.append('Autoload')
     for name in plotNames:
         dock = Dock(name)
         widget = DateTimePlotWidget(self, name=name)
         view = widget._graphicsView
         self.area.addDock(dock, "bottom")
         dock.addWidget(widget)
         self.plotDict[name] = {"dock":dock, "widget":widget, "view":view}
    def __init_gui(self):
        self.graphs = {}
        self.area = DockArea()

        self.__create_graph(
            graph_id='std',
            pos='top',
            widget=pyqtgraph.PlotWidget(
                title='% of Maps Loved vs % Yes Threashold'),
        )

        self.__create_graph(
            graph_id='taiko',
            pos='right',
            widget=pyqtgraph.PlotWidget(
                title='% of Maps Loved vs % Yes Threashold'),
        )

        self.__create_graph(
            graph_id='catch',
            pos='bottom',
            widget=pyqtgraph.PlotWidget(
                title='% of Maps Loved vs % Yes Threashold'),
        )

        self.__create_graph(
            graph_id='mania',
            pos='right',
            relative_to=self.graphs['catch']['dock'],
            widget=pyqtgraph.PlotWidget(
                title='% of Maps Loved vs % Yes Threashold'),
        )

        self.graphs['std']['widget'].setLabel('left', '% of Maps Loved')
        self.graphs['std']['widget'].setLabel('bottom', '% Yes Threshold')

        self.graphs['taiko']['widget'].setLabel('left', '% of Maps Loved')
        self.graphs['taiko']['widget'].setLabel('bottom', '% Yes Threshold')

        self.graphs['catch']['widget'].setLabel('left', '% of Maps Loved')
        self.graphs['catch']['widget'].setLabel('bottom', '% Yes Threshold')

        self.graphs['mania']['widget'].setLabel('left', '% of Maps Loved')
        self.graphs['mania']['widget'].setLabel('bottom', '% Yes Threshold')

        self.setCentralWidget(self.area)
예제 #33
0
class Tab(QWidget):
    def __init__(self, num_tabs=3):
        super().__init__()
        self.num_tabs = num_tabs

        self.initUI()

    def initUI(self):
        self.layout = QGridLayout(self)
        self.dock_area = DockArea()
        self.layout.addWidget(self.dock_area)
        self.add_docks()

    def add_docks(self):
        self.d1 = QDockWidget('d1')
        self.d2 = QDockWidget('d2')
        self.dock_area.addDock(self.d1.dock)
예제 #34
0
파일: window.py 프로젝트: lowks/liveplot
 def __init__(self):
     super(MainWindow, self).__init__()
     self.setWindowTitle("Liveplot")
     self.dockarea = DockArea()
     self.setCentralWidget(self.dockarea)
     self.namelist = NameList(self)
     self.addDockWidget(QtConst.LeftDockWidgetArea, self.namelist)
     self.server = QLocalServer()
     self.server.removeServer('LivePlot')
     self.server.listen('LivePlot')
     self.server.newConnection.connect(self.accept)
     self.bytes = bytearray()
     self.target_size = 0
     self.meta = None
     self.insert_dock_right = True
     self.conns = []
     self.shared_mems = []
     signal.signal(signal.SIGINT, self.close)
예제 #35
0
    def initDialog(self,results=None,KData=None,bDrawText=False):
        # 1) creates layouts
        dialog = QtGui.QDialog()   
        mainLayout = QtGui.QHBoxLayout()
        rightLayout = QtGui.QVBoxLayout()
        mainLayout.addLayout(rightLayout)
        dialog.setLayout(mainLayout)        
        dialog.setWindowTitle(('Strategy Results'))
        # 2) creates widgets         
        from Widgets.pgCandleWidgetCross import pgCandleWidgetCross
        from Widgets.pgCrossAddition import pgCrossAddition
        from pyqtgraph.dockarea import DockArea,Dock     
        
    

        area = DockArea()
        ## Create docks, place them into the window one at a time.
        ## Note that size arguments are only a suggestion; docks will still have to
        ## fill the entire dock area and obey the limits of their internal widgets.
        d1 = Dock("price", size=(200,100))
        d2 = Dock("position", size=(200,100))


        area.addDock(d1, 'bottom')  
        area.addDock(d2, 'bottom')  

        rightLayout.addWidget(area)
       
       
       
        
        pgCandleView = pgCandleWidgetCross(dataForCandle=KData)            
        PyqtGraphindicators = pgCrossAddition()
        toShow = pgCandleView
        self.pricePlot(toShow) 
        d1.addWidget(toShow)   
        
        PyqtGraphPosition = pgCrossAddition()
        self.positionPlot(PyqtGraphPosition)        
        d2.addWidget(PyqtGraphPosition)
        PyqtGraphPosition.showGrid(x=True, y=True)
        
        PyqtGraphPosition.setXLink(toShow)        
        return dialog
예제 #36
0
 def __init__(self):
     logging.debug('Creating main window.')
     QtGui.QMainWindow.__init__(self)
     self.setWindowTitle("colorgraphs dock")
     self.dockarea = DockArea()
     self.setCentralWidget(self.dockarea)
     self.resize(*_MAIN_WINDOW_SIZE)
     self.initUI()
     self.show()
     self.raise_()
예제 #37
0
파일: fluxi.py 프로젝트: JayFF/lab_fluxi
    def __init__(self, parent=None, title="fluxi window"):
        QtGui.QMainWindow.__init__(self, parent)
        self.setWindowTitle(title)
        self.area = area = DockArea()
        self.setCentralWidget(area)

        def close_function():
            pass

        self.close_function = close_function
예제 #38
0
    def __init__(self):
        DockArea.__init__(self)

        self.project_tree_dock = Dock(u"Project Tree", hideTitle=True)
        self.addDock(self.project_tree_dock,
                     'top')  #'above', self.flowcharts_dock)

        self.project_tree = SegmentTreeWidget()

        self.project_tree_dock.addWidget(self.project_tree)

        self.properties_table = TableWidget(sortable=False, editable=False)
        self.properties_table.setFormat("%.3f",1)
        self.properties_table.setColumnCount(1)
        self.properties_table.contextMenu.clear()
        self.properties_table.horizontalHeader().hide()

        self.properties_dock = Dock("Selected Object Properties",
                                    widget=self.properties_table,
                                    hideTitle=True)
        self.addDock(self.properties_dock, 'bottom')

        MarkWriteMainWindow.instance().sigProjectChanged.connect(
            self.handleProjectChange)
        MarkWriteMainWindow.instance().sigSegmentCreated.connect(
            self.handleSegmentCreated)
        MarkWriteMainWindow.instance().sigSegmentRemoved.connect(
            self.handleSegmentRemoved)
        MarkWriteMainWindow.instance().sigActiveObjectChanged.connect(
            self.handleActiveObjectChanged)

        self.project_tree.currentItemChanged.connect(
            self.currentTreeItemChangedEvent)
        self.project_tree.itemDoubleClicked.connect(
            self.treeItemDoubleClickedEvent)
        self.project_tree.customContextMenuRequested.connect(
            self.rightClickTreeEvent)
 #       self.project_tree.itemSelectionChanged.connect(self.handleItemSelectionChanged)

        self.project_tree.setExpandsOnDoubleClick(False)

        self.doNotSetActiveObject=False
예제 #39
0
    def __init__(self, settings):
        super(MainWindow, self).__init__()
        self.settings = settings

        self.setupUi(self)

        self.dock_area = DockArea()
        self.setCentralWidget(self.dock_area)

        self.createDocks()

        self.loadSettings()
예제 #40
0
    def __init__(self, deviceClass, config, parent=None):
        Base.__init__(self, parent)
        Form.__init__(self)
        Form.setupUi(self, self)
        self.config = config
        self.configname = "AWGOptimizer"
        self.setWindowTitle("AWG Optimizer")
        guiState = self.config.get(self.configname+".guiState")
        state = self.config.get(self.configname+'.state')
        pos = self.config.get(self.configname+'.pos')
        size = self.config.get(self.configname+'.size')
        isMaximized = self.config.get(self.configname+'.isMaximized')
        restoreGuiState(self, self.config.get(self.configname+".guiState"))
        if state: self.restoreState(state)
        if pos: self.move(pos)
        if size: self.resize(size)
        if isMaximized: self.showMaximized()

        self.show()
        self.awgUi = AWGUi(deviceClass, config, dict())
        self.awgUi.setupUi(self.awgUi)
        self.splitter.insertWidget(1, self.awgUi)

        #oscilloscope plot window
        name = "Oscilloscope Trace"
        self.scopeDock = Dock(name)
        self.scopePlot = CoordinatePlotWidget(self, name=name)
        self.scopeView = self.scopePlot._graphicsView
        self.scopeDock.addWidget(self.scopePlot)
        self.area = DockArea()
        self.area.addDock(self.scopeDock)
        self.plotDict ={name: {"dock":self.scopeDock, "widget":self.scopePlot, "view":self.scopeView}}
        self.verticalLayout.insertWidget(0, self.area)

        #trace ui
        self.penicons = pens.penicons().penicons()
        self.traceui = Traceui.Traceui(self.penicons, self.config, self.configname, self.plotDict, hasMeasurementLog=False, highlightUnsaved=False)
        self.traceui.setupUi(self.traceui)
        traceDock = Dock("Traces")
        traceDock.addWidget(self.traceui)
        self.area.addDock(traceDock, 'left')
        self.device = self.awgUi.device

        self.measureWaveformButton.clicked.connect(self.onMeasureWaveform)
        self.optimizeButton.clicked.connect(self.onOptimize)

        dockAreaState = self.config.get(self.configname+'.dockAreaState')
        try:
            if dockAreaState: self.area.restoreState(dockAreaState)
        except Exception as e:
            print(e)
예제 #41
0
 def setup_status_widget(self, parent):  # Visualizes the nodes + their connections + CPU usage
     # Status dock area showing setup
     dock_area = DockArea()
     parent.addTab(dock_area, 'Status')
     self.status_dock = Dock("Status")
     dock_area.addDock(self.status_dock)
     # GraphicsLayout to align graphics
     status_graphics_widget = pg.GraphicsLayoutWidget()
     status_graphics_widget.show()
     self.status_dock.addWidget(status_graphics_widget)
     try:
         self.configuration['receiver']
     except KeyError:
         return
     # Create nodes with links from configuration file for converter/receiver
     for receiver_index, (receiver_name, receiver_settings) in enumerate(self.configuration['receiver'].items()):
         # Add receiver info
         view = status_graphics_widget.addViewBox(row=receiver_index, col=5, lockAspect=True, enableMouse=False)
         text = pg.TextItem('Receiver\n%s' % receiver_name, border='b', fill=(0, 0, 255, 100), anchor=(0.5, 0.5), color=(0, 0, 0, 200))
         text.setPos(0.5, 0.5)
         view.addItem(text)
         # Add corresponding producer info
         try:
             if self.configuration['converter']:
                 try:
                     actual_converter = self.configuration['converter'][receiver_name]
                     view = status_graphics_widget.addViewBox(row=receiver_index, col=1, lockAspect=True, enableMouse=False)
                     text = pg.TextItem('Producer\n%s' % receiver_name, border='b', fill=(0, 0, 255, 100), anchor=(0.5, 0.5), color=(0, 0, 0, 200))
                     text.setPos(0.5, 0.5)
                     view.addItem(text)
                     view = status_graphics_widget.addViewBox(row=receiver_index, col=3, lockAspect=True, enableMouse=False)
                     text = pg.TextItem('Converter\n%s' % receiver_settings, border='b', fill=(0, 0, 255, 100), anchor=(0.5, 0.5), color=(0, 0, 0, 200))
                     text.setPos(0.5, 0.5)
                     view.addItem(text)
                 except KeyError:  # no converter for receiver
                     pass
         except KeyError:  # No converter defined in configruation
             pass
예제 #42
0
    def _InitDocks(self):
        
        # Define docking area
        if hasattr(self, "_dockArea"):
            self._dockArea.setParent(None)
        self._dockArea = DockArea()

        self._plotDocks = self._defaultDockPos.keys()
        
        # Add dock to area
        for dock, pos in self._defaultDockPos.iteritems():
            self._dockArea.addDock(dock, *pos)
        
        self._layout.addWidget(self._dockArea, 0, 0, 1, 1)
예제 #43
0
 def __init__(self):
     super(MainWindow, self).__init__()
     self.setWindowTitle("Liveplot")
     self.dockarea = DockArea()
     self.setCentralWidget(self.dockarea)
     self.namelist = NameList(self)
     self.addDockWidget(QtConst.LeftDockWidgetArea, self.namelist)
     self.ctx = zmq.Context()
     sock = self.ctx.socket(zmq.SUB)
     sock.bind('tcp://127.0.0.1:7755')
     sock.setsockopt(zmq.SUBSCRIBE, '')
     self.conn = ZMQSocket(sock)
     self.conn.readyRead.connect(lambda: self.read_from(self.conn))
     self.bytes = bytearray()
     self.target_size = 0
     self.meta = None
     self.insert_dock_right = True
     self.conns = []
예제 #44
0
    def add_widgets(self):
        # Main window with dock area
        self.dock_area = DockArea()
        self.setCentralWidget(self.dock_area)

        # Docks
        dock_waveform = Dock("Waveform", size=(600, 400))
        dock_histogram = Dock("Histogram", size=(600, 400))
        dock_status = Dock("Status", size=(1200, 40))
        self.dock_area.addDock(dock_waveform, 'left')
        self.dock_area.addDock(dock_histogram, 'right', dock_waveform)
        self.dock_area.addDock(dock_status, 'top')

        # Status widget
        cw = QtGui.QWidget()
        cw.setStyleSheet("QWidget {background-color:white}")
        layout = QtGui.QGridLayout()
        layout.setColumnStretch(2, 1)
        cw.setLayout(layout)
        self.event_rate_label = QtGui.QLabel("Event Rate\n0 Hz")
        self.total_events_label = QtGui.QLabel("Total Events\n0")
        self.spin_box = Qt.QSpinBox(value=20, maximum=1000)
        self.reset_button = Qt.QPushButton('Reset', self)
        self.reset_button.clicked.connect(self.reset_plots)
        layout.addWidget(self.event_rate_label, 0, 1, 1, 1)
        layout.addWidget(self.total_events_label, 1, 1, 1, 1)
        layout.addWidget(self.spin_box, 0, 3, 1, 1)
        layout.addWidget(self.reset_button, 1, 3, 1, 1)
        
        dock_status.addWidget(cw)

        # Different plot docks
        waveform_widget = pg.PlotWidget(background="w")
        self.waveform_plot = waveform_widget.plot(range(0, 200), np.zeros(shape=(200)))
        self.thr_line = pg.InfiniteLine(pos=1000, angle=0, pen={'color':0.0, 'style':QtCore.Qt.DashLine})
        waveform_widget.addItem(self.thr_line)
        dock_waveform.addWidget(waveform_widget)

        histogram_widget = pg.PlotWidget(background="w")
        self.histogram_plot = histogram_widget.plot(range(0, 2**14 + 1), np.zeros(shape=(2**14)), stepMode=True)
        histogram_widget.showGrid(y=True)
        self.thr_line_hist = pg.InfiniteLine(pos=1000, angle=90, pen={'color':0.0, 'style':QtCore.Qt.DashLine})
        histogram_widget.addItem(self.thr_line_hist)
        dock_histogram.addWidget(histogram_widget)
예제 #45
0
    def initDialogSummary(self,result,KData=None):
        # 1) creates layouts
        dialog = QtGui.QDialog()   
        mainLayout = QtGui.QHBoxLayout()
        rightLayout = QtGui.QVBoxLayout()
        mainLayout.addLayout(rightLayout)
        dialog.setLayout(mainLayout)        
        dialog.setWindowTitle(('Strategy Results'))

        import os,sys        
        xpower = os.path.abspath(os.path.join(os.path.dirname(__file__),os.pardir,os.pardir,os.pardir,'midProjects','histdataUI'))
        sys.path.append(xpower)

        from Widgets.pgCandleWidgetCross import pgCandleWidgetCross
        from Widgets.pgCrossAddition import pgCrossAddition
        from pyqtgraph.dockarea import DockArea,Dock 
        area = DockArea()   
        rightLayout.addWidget(area)


        # 2) creates widgets 
        #  2.1)candle        
        pgCandleView = pgCandleWidgetCross(dataForCandle=KData)        
        dCandle = Dock("candles",closable=True, size=(200,300))     ## give this dock the minimum possible size
        area.addDock(dCandle, 'bottom') 
        dCandle.addWidget(pgCandleView)       
        # 2) creates widgets 
        # 2.3)position_cost 
        if(True):
            PyqtGraphPositionCost = pgCrossAddition()
            self.availableCashPlot(PyqtGraphPositionCost)
            dAvailableCash = Dock("available_cash",closable=True, size=(200,100))
            area.addDock(dAvailableCash, 'bottom')        
            dAvailableCash.addWidget(PyqtGraphPositionCost)             
            PyqtGraphPositionCost.setXLink(pgCandleView)         
        # 2.3)position_cost 
        if(True):
            PyqtGraphPositionCost = pgCrossAddition()
            self.portfolioPlot(PyqtGraphPositionCost)
            dPortfolioValue = Dock("portfolio_value",closable=True, size=(200,100))
            area.addDock(dPortfolioValue, 'bottom')        
            dPortfolioValue.addWidget(PyqtGraphPositionCost)             
            PyqtGraphPositionCost.setXLink(pgCandleView) 
        return dialog        
예제 #46
0
    def __init__(self, file):
        super(H5Plotter, self).__init__()
        view_box = SearchableH5View(H5File(file))
        self.view = view_box.tree_view
        self.match_model = self.view.model()
        self.model = self.match_model.sourceModel()
        self.dock_area = DockArea()

        self.layout = QtGui.QSplitter(Qt.Horizontal)
        self.setCentralWidget(self.layout)
        self.view.activated.connect(self.load_plot)
        self.layout.addWidget(view_box)
        self.layout.addWidget(self.dock_area)
        self.layout.setStretchFactor(0, 0)
        self.layout.setStretchFactor(1, 1)

        self.setWindowIcon(QtGui.QIcon("icon.ico"))

        QtGui.QShortcut(QtGui.QKeySequence(Qt.CTRL | Qt.Key_N), self,
                        lambda: self.move_view_cursor(QtGui.QAbstractItemView.MoveDown))
        QtGui.QShortcut(QtGui.QKeySequence(Qt.CTRL | Qt.Key_P), self,
                        lambda: self.move_view_cursor(QtGui.QAbstractItemView.MoveUp))
        QtGui.QShortcut(QtGui.QKeySequence(Qt.CTRL | Qt.Key_F), self,
                        lambda: self.move_view_cursor(QtGui.QAbstractItemView.MoveRight))
        QtGui.QShortcut(QtGui.QKeySequence(Qt.CTRL | Qt.Key_B), self,
                        lambda: self.move_view_cursor(QtGui.QAbstractItemView.MoveLeft))
        QtGui.QShortcut(QtGui.QKeySequence(Qt.CTRL | Qt.Key_S), self, view_box.search_box.setFocus)

        view_menu = self.menuBar().addMenu("View")

        toggle_attrs_action = QtGui.QAction("Attributes Visible", view_menu)
        toggle_attrs_action.setCheckable(True)
        toggle_attrs_action.triggered.connect(self.match_model.toggle_attrs_visible)
        view_menu.addAction(toggle_attrs_action)

        toggle_junk_action = QtGui.QAction("Junk Visible", view_menu)
        toggle_junk_action.setCheckable(True)
        toggle_junk_action.triggered.connect(self.match_model.toggle_junk_visible)
        view_menu.addAction(toggle_junk_action)
예제 #47
0
class DigitalLockUi(WidgetContainerBase, WidgetContainerForm):
    levelNameList = ["debug", "info", "warning", "error", "critical"]
    levelValueList = [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL]
    plotConfigurationChanged = QtCore.pyqtSignal( object )
    def __init__(self, config, project):
        self.config = config
        self.project = project
        super(DigitalLockUi, self).__init__()
        self.settings = SettingsDialog.Settings()
        self.deviceSerial = config.get('Settings.deviceSerial')
        self.deviceDescription = config.get('Settings.deviceDescription')
        self.loggingLevel = config.get('Settings.loggingLevel', logging.INFO)
        self.consoleMaximumLines = config.get('Settings.consoleMaximumLines', 0)
        self.dockWidgetList = list()
        if self.loggingLevel not in self.levelValueList: self.loggingLevel = logging.INFO
        self.plotDict = dict()
        
    def __enter__(self):
        self.pulser = Controller()
        return self
    
    def __exit__(self, excepttype, value, traceback):
        self.pulser.shutdown()
        return False
    
    def setupUi(self, parent):
        super(DigitalLockUi, self).setupUi(parent)
        self.dockWidgetConsole.hide()
        self.loggerUi = LoggerLevelsUi(self.config)
        self.loggerUi.setupUi(self.loggerUi)
        self.setupAsDockWidget(self.loggerUi, "Logging", QtCore.Qt.NoDockWidgetArea)
                
        logger = logging.getLogger()        
        self.toolBar.addWidget(ExceptionLogButton())
        
        # Setup Console Dockwidget
        self.levelComboBox.addItems(self.levelNameList)
#        self.levelComboBox.currentIndexChanged[int].connect( self.setLoggingLevel )            
        self.levelComboBox.setCurrentIndex( self.levelValueList.index(self.loggingLevel) )
#        self.consoleClearButton.clicked.connect( self.onClearConsole )
#        self.linesSpinBox.valueChanged.connect( self.onConsoleMaximumLinesChanged )
        
        self.parent = parent
        self.tabList = list()
        self.tabDict = dict()
               
        # initialize FPGA settings
        self.settingsDialog = SettingsDialog.SettingsDialog(self.pulser, self.config, self.parent)
        self.settingsDialog.setupUi()
        self.settings = self.settingsDialog.settings

        try:
            configFile = os.path.splitext(self.settings.bitfile)[0] + '.yml'
            with open(configFile, 'r') as f:
                lockConfig = yaml.load(f)
            self.settings.onBoardADCEncoding = lockConfig['onBoardADCEncoding']
        except Exception as e:
            logger.error('unable to load config file: {0}'.format(e))
            self.settings.onBoardADCEncoding = None

        self.setupPlots()

        # Traceui
        self.penicons = pens.penicons().penicons()
        self.traceui = Traceui.Traceui(self.penicons, self.config, "Main", self.plotDict)
        self.traceui.setupUi(self.traceui)
        self.setupAsDockWidget(self.traceui, "Traces", QtCore.Qt.LeftDockWidgetArea)

        # lock status
        self.lockStatus = LockStatus(self.pulser, self.config, self.traceui, self.plotDict, self.settings, self.parent)
        self.lockStatus.setupUi()
        self.setupAsDockWidget(self.lockStatus, "Status", QtCore.Qt.RightDockWidgetArea)
        self.plotConfigurationChanged.connect( self.lockStatus.onPlotConfigurationChanged )

        # Trace control
        self.traceControl = TraceControl(self.pulser, self.config, self.traceui, self.plotDict, self.parent)
        self.traceControl.setupUi()
        self.setupAsDockWidget(self.traceControl, "Trace Control", QtCore.Qt.RightDockWidgetArea)
        self.plotConfigurationChanged.connect( self.traceControl.onPlotConfigurationChanged )

        # Lock control
        self.lockControl = LockControl(self.pulser, self.config, self.settings, self.parent)
        self.lockControl.dataChanged.connect( self.lockStatus.onControlChanged )
        self.lockControl.dataChanged.connect( self.traceControl.onControlChanged )
        self.lockControl.setupUi() 
        self.lockStatus.newDataAvailable.connect( self.lockControl.onStreamData )
        self.traceControl.newDataAvailable.connect( self.lockControl.onTraceData )
        self.setupAsDockWidget(self.lockControl, "Control", QtCore.Qt.RightDockWidgetArea)
        
        self.actionSave.triggered.connect(self.onSave)
        self.actionSettings.triggered.connect(self.onSettings)
        self.actionExit.triggered.connect(self.onClose)
        self.actionProject.triggered.connect( self.onProjectSelection)

        self.addPlot = QtWidgets.QAction( QtGui.QIcon(":/openicon/icons/add-plot.png"), "Add new plot", self)
        self.addPlot.setToolTip("Add new plot")
        self.addPlot.triggered.connect(self.onAddPlot)
        self.toolBar.addAction(self.addPlot)
        
        self.removePlot = QtWidgets.QAction( QtGui.QIcon(":/openicon/icons/remove-plot.png"), "Remove a plot", self)
        self.removePlot.setToolTip("Remove a plot")
        self.removePlot.triggered.connect(self.onRemovePlot)
        self.toolBar.addAction(self.removePlot)

        self.renamePlot = QtWidgets.QAction( QtGui.QIcon(":/openicon/icons/rename-plot.png"), "Rename a plot", self)
        self.renamePlot.setToolTip("Rename a plot")
        self.renamePlot.triggered.connect(self.onRenamePlot)
        self.toolBar.addAction(self.renamePlot)

        self.setWindowTitle( "Digital Lock ({0})".format(self.project) )
        if 'MainWindow.State' in self.config:
            self.parent.restoreState(self.config['MainWindow.State'])
        self.initMenu()
        try:
            if 'pyqtgraph-dockareastate' in self.config:
                self.area.restoreState(self.config['pyqtgraph-dockareastate'])
        except Exception as e:
            logger.error("Cannot restore dock state in experiment {0}. Exception occurred: ".format(self.experimentName) + str(e))
        QtCore.QTimer.singleShot(300000, self.onCommitConfig )      
       
    def onCommitConfig(self):
        self.saveConfig()
        self.config.saveConfig() 
        QtCore.QTimer.singleShot(300000, self.onCommitConfig )      
            
        
    def setupPlots(self):
        self.area = DockArea()
        self.setCentralWidget(self.area)
        self.plotDict = dict()
        # initialize all the plot windows we want
        plotNames = self.config.get( 'PlotNames', ['History', 'Scope'] )
        if len(plotNames)<1:
            plotNames.append('History')
        for name in plotNames:
            dock = Dock(name)
            widget = CoordinatePlotWidget(self)
            view = widget._graphicsView
            self.area.addDock(dock, "bottom")
            dock.addWidget(widget)
            self.plotDict[name] = {"dock":dock, "widget":widget, "view":view}
        
    def setupAsDockWidget(self, widget, name, area=QtCore.Qt.RightDockWidgetArea, stackAbove=None, stackBelow=None ):
        dock = QtWidgets.QDockWidget(name)
        dock.setObjectName(name)
        dock.setWidget( widget )
        self.addDockWidget(area, dock )
        self.dockWidgetList.append( dock )
        if stackAbove is not None:
            self.tabifyDockWidget( stackAbove, dock )
        elif stackBelow is not None:
            self.tabifyDockWidget( dock, stackBelow )
        return dock           

    def onAddPlot(self):
        name, ok = QtWidgets.QInputDialog.getText(self, 'Plot Name', 'Please enter a plot name: ')
        if ok:
            name = str(name)
            dock = Dock(name)
            widget = CoordinatePlotWidget(self)
            view = widget._graphicsView
            self.area.addDock(dock, "bottom")
            dock.addWidget(widget)
            self.plotDict[name] = {"dock":dock, "widget":widget, "view":view}
            self.plotConfigurationChanged.emit( self.plotDict )
            
    def onRemovePlot(self):
        logger = logging.getLogger(__name__)
        if len(self.plotDict) > 0:
            name, ok = QtWidgets.QInputDialog.getItem(self, "Select Plot", "Please select which plot to remove: ", list(self.plotDict.keys()), editable=False)
            if ok:
                name = str(name)
                self.plotDict[name]["dock"].close()
                del self.plotDict[name]
                self.plotConfigurationChanged.emit( self.plotDict )
        else:
            logger.info("There are no plots which can be removed")
                
    def onRenamePlot(self):
        logger = logging.getLogger(__name__)
        if len(self.plotDict) > 0:
            name, ok = QtWidgets.QInputDialog.getItem(self, "Select Plot", "Please select which plot to rename: ", list(self.plotDict.keys()), editable=False)
            if ok:
                newName, newOk = QtWidgets.QInputDialog.getText(self, 'New Plot Name', 'Please enter a new plot name: ')
                if newOk:
                    name = str(name)
                    newName = str(newName)
                    self.plotDict[name]["dock"].label.setText(str(newName))
                    self.plotDict[newName] = self.plotDict[name]
                    del self.plotDict[name]
                    self.plotConfigurationChanged.emit( self.plotDict )
        else:
            logger.info("There are no plots which can be renamed")

    def onProjectSelection(self):
        ui = ProjectInfoUi(self.project)
        ui.show()
        ui.exec_()

    def onSettings(self):
        self.settingsDialog.show()
        
    def onSave(self):
        logger = logging.getLogger(__name__)
        logger.info( "Saving config" )
        filename, _ = DataDirectory.DataDirectory().sequencefile("digitalLock-configuration.db")
        self.saveConfig()
        self.config.saveConfig(filename)
    
    def onMessageWrite(self,message,level=logging.DEBUG):
        if level>= self.loggingLevel:
            cursor = self.textEditConsole.textCursor()
            cursor.movePosition(QtGui.QTextCursor.End)
            if level < logging.ERROR:
                self.textEditConsole.setTextColor(QtCore.Qt.black)
            else:
                self.textEditConsole.setTextColor(QtCore.Qt.red)
            cursor.insertText(message)
            self.textEditConsole.setTextCursor(cursor)
            self.textEditConsole.ensureCursorVisible()

    def onClose(self):
        self.parent.close()
        
    def closeEvent(self, e):
        logger = logging.getLogger("")
        logger.debug( "Saving Configuration" )
        self.saveConfig()
        self.settingsDialog.done(0)
        self.lockControl.closeEvent(e)

    def initMenu(self):
        self.menuView.clear()
        for dock in self.dockWidgetList:
            self.menuView.addAction(dock.toggleViewAction())

    def saveConfig(self):
        self.config['MainWindow.State'] = self.parent.saveState()
        for tab in self.tabList:
            tab.saveConfig()
        self.config['Settings.deviceSerial'] = self.settings.deviceSerial
        self.config['Settings.deviceDescription'] = self.settings.deviceDescription
        self.config['MainWindow.pos'] = self.pos()
        self.config['MainWindow.size'] = self.size()
        self.config['Settings.loggingLevel'] = self.loggingLevel
        self.config['Settings.consoleMaximumLines'] = self.consoleMaximumLines
        self.config['PlotNames'] = list(self.plotDict.keys())
        self.config['pyqtgraph-dockareastate'] = self.area.saveState()
        self.settingsDialog.saveConfig()
        self.loggerUi.saveConfig()
        self.lockControl.saveConfig()
        self.lockStatus.saveConfig()
        self.traceControl.saveConfig()
예제 #48
0
    def initDialogSymbol(self,results=None,KData=None,bDrawText=False,InKLine = False):
        # 1) creates layouts
        dialog = QtGui.QDialog()   
        mainLayout = QtGui.QHBoxLayout()
        rightLayout = QtGui.QVBoxLayout()
        mainLayout.addLayout(rightLayout)
        dialog.setLayout(mainLayout)        
        dialog.setWindowTitle(('Strategy Results'))

        import os,sys        
        xpower = os.path.abspath(os.path.join(os.path.dirname(__file__),os.pardir,os.pardir,os.pardir,'midProjects','histdataUI'))
        sys.path.append(xpower)

        from Widgets.pgCandleWidgetCross import pgCandleWidgetCross
        from Widgets.pgCrossAddition import pgCrossAddition
        from pyqtgraph.dockarea import DockArea,Dock 
        area = DockArea()   
        rightLayout.addWidget(area)

        # 2) creates widgets 
        #  2.1)candle        
        pgCandleView = pgCandleWidgetCross(dataForCandle=KData)        
        self.pricePlot(pgCandleView) 
        if(InKLine):
            self.indicatorsPlot(pgCandleView) 
        #self.signalPlot(pgCandleView,yBuy = KData.take([1],axis=1),ySell = KData.take([1],axis=1))
        self.signalPlot(pgCandleView)
        dCandle = Dock("candles",closable=True, size=(200,300))     ## give this dock the minimum possible size
        area.addDock(dCandle, 'bottom') 
        dCandle.addWidget(pgCandleView)        

        #  2.2)long_pnl 当前position_pnl曲线
        if(True):
            PyqtGraphPnl = pgCrossAddition()
            self.longPnlPlot(PyqtGraphPnl,bDrawText=bDrawText)
            long_pnl = np.array(self.results.long_pnl)
            self.signalPlot(PyqtGraphPnl,yBuy = long_pnl,ySell = long_pnl)
            dPnl = Dock("long_pnl", closable=True, size=(200,100))
            area.addDock(dPnl, 'bottom')    
            dPnl.addWidget(PyqtGraphPnl)           
            PyqtGraphPnl.setXLink(pgCandleView)
        # 2.3)long_cost 
        if(True):
            PyqtGraphPositionCost = pgCrossAddition()
            self.longCostPlot(PyqtGraphPositionCost)
            dPositionCost = Dock("long_cost",closable=True, size=(200,100))
            area.addDock(dPositionCost, 'bottom')        
            dPositionCost.addWidget(PyqtGraphPositionCost)             
            PyqtGraphPositionCost.setXLink(pgCandleView)         
        
        #  2.2)long_pnl 当前position_pnl曲线
        if(True):
            PyqtGraphPnl = pgCrossAddition()
            self.shortPnlPlot(PyqtGraphPnl,bDrawText=bDrawText)
            short_pnl = np.array(self.results.short_pnl)
            self.signalPlot(PyqtGraphPnl,yBuy = short_pnl,ySell = short_pnl)
            dPnl = Dock("short_pnl", closable=True, size=(200,100))
            area.addDock(dPnl, 'bottom')    
            dPnl.addWidget(PyqtGraphPnl)           
            PyqtGraphPnl.setXLink(pgCandleView)
        # 2.3)long_cost 
        if(True):
            PyqtGraphPositionCost = pgCrossAddition()
            self.shortCostPlot(PyqtGraphPositionCost)
            dPositionCost = Dock("short_cost",closable=True, size=(200,100))
            area.addDock(dPositionCost, 'bottom')        
            dPositionCost.addWidget(PyqtGraphPositionCost)             
            PyqtGraphPositionCost.setXLink(pgCandleView)          
        
        #  2.3)position_volume
        if(False):
            PyqtGraphPosition = pgCrossAddition()
            self.positionVolumePlot(PyqtGraphPosition)
            dPosition = Dock("position_volume",closable=True, size=(200,100))
            area.addDock(dPosition, 'bottom')        
            dPosition.addWidget(PyqtGraphPosition)             
            PyqtGraphPosition.setXLink(pgCandleView)
        #  2.4)portfolio  总资产变动曲线 cash + equity
        if(True):
            PyqtGraphPortfolio = pgCrossAddition()
            self.positionValuePlot(PyqtGraphPortfolio)
            dPortfolio = Dock("portfolio", closable=True,size=(200,100))
            area.addDock(dPortfolio, 'bottom')     
            dPortfolio.addWidget(PyqtGraphPortfolio)        
            PyqtGraphPortfolio.setXLink(pgCandleView)
        #  2.5)indicator
        if(True):
            PyqtGraphindicators = pgCrossAddition()
            self.pricePlot(PyqtGraphindicators)    
            self.indicatorsPlot(PyqtGraphindicators)
            
            self.signalPlot(PyqtGraphindicators)
            
            dIndicator = Dock("indicator",closable=True, size=(200,100))
            dIndicator.addWidget(PyqtGraphindicators)
            area.addDock(dIndicator, 'bottom', dCandle)  
            PyqtGraphindicators.setXLink(pgCandleView)
        #  2.2)position_pnl 当前position_pnl曲线
        if(False):
            PyqtGraphPortfolioInstruments = pgCrossAddition()
            self.instrumentPnlPlot(PyqtGraphPortfolioInstruments,bDrawText=bDrawText)
            position_pnl = np.array(self.results.position_pnl)
            self.signalPlot(PyqtGraphPortfolioInstruments,yBuy = position_pnl,ySell = position_pnl)
            dPnl = Dock("instrumentsPNL", closable=True, size=(200,100))
            area.addDock(dPnl, 'bottom',dPositionCost)    
            dPnl.addWidget(PyqtGraphPortfolioInstruments)           
            PyqtGraphPortfolioInstruments.setXLink(pgCandleView)            
        return dialog
예제 #49
0
    def __init__(self, scanZ, recWidget=None, *args, **kwargs):

        super().__init__(*args, **kwargs)
        self.setMinimumSize(2, 350)

        self.mainRec = recWidget

        self.webcam = instruments.Webcam()

        self.z = scanZ
        self.z.zHostPosition = 'left'
        self.z.zobject.HostBackLashEnable = False

        self.setPoint = 0

        self.V = Q_(1, 'V')
        self.um = Q_(1, 'um')
        self.nm = Q_(1, 'nm')

        self.setFrameStyle(QtGui.QFrame.Panel | QtGui.QFrame.Raised)

        self.scansPerS = 10
        self.ProcessData = ProcessData(self.webcam)

        # Focus lock widgets
        self.kpEdit = QtGui.QLineEdit('4')
        self.kpEdit.setFixedWidth(60)
        self.kpEdit.textChanged.connect(self.unlockFocus)
        self.kpLabel = QtGui.QLabel('kp')
        self.kiEdit = QtGui.QLineEdit('0.01')
        self.kiEdit.setFixedWidth(60)
        self.kiEdit.textChanged.connect(self.unlockFocus)
        self.kiLabel = QtGui.QLabel('ki')
        self.lockButton = QtGui.QPushButton('Lock')
        self.lockButton.setCheckable(True)
        self.lockButton.clicked.connect(self.toggleFocus)
        self.lockButton.setSizePolicy(QtGui.QSizePolicy.Preferred,
                                      QtGui.QSizePolicy.Expanding)
        moveLabel = QtGui.QLabel('Move [nm]')
        moveLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.moveEdit = QtGui.QLineEdit('0')
        self.moveEdit.setFixedWidth(60)
        self.moveEdit.returnPressed.connect(self.zMoveEdit)

        self.focusDataBox = QtGui.QCheckBox('Save focus data')
        self.focusPropertiesDisplay = QtGui.QLabel(' st_dev = 0  max_dev = 0')

        self.graph = FocusLockGraph(self, self.mainRec)

        self.focusTime = 1000 / self.scansPerS
        self.focusTimer = QtCore.QTimer()
        self.focusTimer.timeout.connect(self.update)
        self.focusTimer.start(self.focusTime)

        self.locked = False
        self.n = 1
        self.max_dev = 0

        self.focusCalib = FocusCalibration(self)
        self.focusCalibThread = QtCore.QThread(self)
        self.focusCalib.moveToThread(self.focusCalibThread)
        self.focusCalibButton = QtGui.QPushButton('Calibrate')
        self.focusCalibButton.clicked.connect(self.focusCalib.start)
        self.focusCalibThread.start()

        try:
            prevCal = np.around(np.loadtxt('calibration')[0]/10)
            text = '1 px --> {} nm'.format(prevCal)
            self.calibrationDisplay = QtGui.QLineEdit(text)
        except:
            self.calibrationDisplay = QtGui.QLineEdit('0 px --> 0 nm')

        self.calibrationDisplay.setReadOnly(False)

        self.webcamgraph = WebcamGraph(self)

        dockArea = DockArea()
        graphDock = Dock("Focus laser graph", size=(400, 200))
        graphDock.addWidget(self.graph)
        dockArea.addDock(graphDock)
        webcamDock = Dock("Focus laser view", size=(200, 200))
        webcamDock.addWidget(self.webcamgraph)
        dockArea.addDock(webcamDock, 'right', graphDock)

        # GUI layout
        grid = QtGui.QGridLayout()
        self.setLayout(grid)
        grid.addWidget(dockArea, 0, 0, 1, 6)
        grid.addWidget(self.focusCalibButton, 1, 0)
        grid.addWidget(self.calibrationDisplay, 2, 0)
        grid.addWidget(self.focusDataBox, 1, 1)
        grid.addWidget(moveLabel, 1, 2)
        grid.addWidget(self.moveEdit, 2, 2)
        grid.addWidget(self.kpLabel, 1, 3)
        grid.addWidget(self.kpEdit, 1, 4)
        grid.addWidget(self.kiLabel, 2, 3)
        grid.addWidget(self.kiEdit, 2, 4)
        grid.addWidget(self.lockButton, 1, 5, 2, 1)
        grid.setColumnMinimumWidth(5, 170)
예제 #50
0
    def setup_widgets(self, parent, name):
        dock_area = DockArea()
        parent.addTab(dock_area, name)

        # Docks
        dock_occcupancy = Dock("Occupancy", size=(400, 400))
        dock_run_config = Dock("Run configuration", size=(400, 400))
        dock_global_config = Dock("Global configuration", size=(400, 400))
        dock_tot = Dock("Time over threshold values (TOT)", size=(400, 400))
        dock_tdc = Dock("Time digital converter values (TDC)", size=(400, 400))
        dock_event_status = Dock("Event status", size=(400, 400))
        dock_trigger_status = Dock("Trigger status", size=(400, 400))
        dock_service_records = Dock("Service records", size=(400, 400))
        dock_hit_timing = Dock("Hit timing (rel. BCID)", size=(400, 400))
        dock_status = Dock("Status", size=(800, 40))
        dock_area.addDock(dock_global_config, 'left')
        dock_area.addDock(dock_run_config, 'above', dock_global_config)
        dock_area.addDock(dock_occcupancy, 'above', dock_run_config)
        dock_area.addDock(dock_tdc, 'right', dock_occcupancy)
        dock_area.addDock(dock_tot, 'above', dock_tdc)
        dock_area.addDock(dock_service_records, 'bottom', dock_occcupancy)
        dock_area.addDock(dock_trigger_status, 'above', dock_service_records)
        dock_area.addDock(dock_event_status, 'above', dock_trigger_status)
        dock_area.addDock(dock_hit_timing, 'bottom', dock_tot)
        dock_area.addDock(dock_status, 'top')

        # Status dock on top
        cw = QtGui.QWidget()
        cw.setStyleSheet("QWidget {background-color:white}")
        layout = QtGui.QGridLayout()
        cw.setLayout(layout)
        self.rate_label = QtGui.QLabel("Readout Rate\n0 Hz")
        self.hit_rate_label = QtGui.QLabel("Hit Rate\n0 Hz")
        self.event_rate_label = QtGui.QLabel("Event Rate\n0 Hz")
        self.timestamp_label = QtGui.QLabel("Data Timestamp\n")
        self.plot_delay_label = QtGui.QLabel("Plot Delay\n")
        self.scan_parameter_label = QtGui.QLabel("Scan Parameters\n")
        self.spin_box = Qt.QSpinBox(value=0)
        self.spin_box.setMaximum(1000000)
        self.spin_box.setSuffix(" Readouts")
        self.reset_button = QtGui.QPushButton('Reset')
        layout.addWidget(self.timestamp_label, 0, 0, 0, 1)
        layout.addWidget(self.plot_delay_label, 0, 1, 0, 1)
        layout.addWidget(self.rate_label, 0, 2, 0, 1)
        layout.addWidget(self.hit_rate_label, 0, 3, 0, 1)
        layout.addWidget(self.event_rate_label, 0, 4, 0, 1)
        layout.addWidget(self.scan_parameter_label, 0, 5, 0, 1)
        layout.addWidget(self.spin_box, 0, 6, 0, 1)
        layout.addWidget(self.reset_button, 0, 7, 0, 1)
        dock_status.addWidget(cw)

        # Connect widgets
        self.reset_button.clicked.connect(lambda: self.send_command('RESET'))
        self.spin_box.valueChanged.connect(lambda value: self.send_command(str(value)))

        # Run config dock
        self.run_conf_list_widget = Qt.QListWidget()
        dock_run_config.addWidget(self.run_conf_list_widget)

        # Global config dock
        self.global_conf_list_widget = Qt.QListWidget()
        dock_global_config.addWidget(self.global_conf_list_widget)

        # Different plot docks
        occupancy_graphics = pg.GraphicsLayoutWidget()
        occupancy_graphics.show()
        view = occupancy_graphics.addViewBox()
        self.occupancy_img = pg.ImageItem(border='w')
        view.addItem(self.occupancy_img)
        view.setRange(QtCore.QRectF(0, 0, 80, 336))
        dock_occcupancy.addWidget(occupancy_graphics)

        tot_plot_widget = pg.PlotWidget(background="w")
        self.tot_plot = tot_plot_widget.plot(np.linspace(-0.5, 15.5, 17), np.zeros((16)), stepMode=True)
        tot_plot_widget.showGrid(y=True)
        dock_tot.addWidget(tot_plot_widget)

        tdc_plot_widget = pg.PlotWidget(background="w")
        self.tdc_plot = tdc_plot_widget.plot(np.linspace(-0.5, 4095.5, 4097), np.zeros((4096)), stepMode=True)
        tdc_plot_widget.showGrid(y=True)
        tdc_plot_widget.setXRange(0, 800, update=True)
        dock_tdc.addWidget(tdc_plot_widget)

        event_status_widget = pg.PlotWidget()
        self.event_status_plot = event_status_widget.plot(np.linspace(-0.5, 15.5, 17), np.zeros((16)), stepMode=True)
        event_status_widget.showGrid(y=True)
        dock_event_status.addWidget(event_status_widget)

        trigger_status_widget = pg.PlotWidget()
        self.trigger_status_plot = trigger_status_widget.plot(np.linspace(-0.5, 7.5, 9), np.zeros((8)), stepMode=True)
        trigger_status_widget.showGrid(y=True)
        dock_trigger_status.addWidget(trigger_status_widget)

        service_record_widget = pg.PlotWidget()
        self.service_record_plot = service_record_widget.plot(np.linspace(-0.5, 31.5, 33), np.zeros((32)), stepMode=True)
        service_record_widget.showGrid(y=True)
        dock_service_records.addWidget(service_record_widget)

        hit_timing_widget = pg.PlotWidget()
        self.hit_timing_plot = hit_timing_widget.plot(np.linspace(-0.5, 15.5, 17), np.zeros((16)), stepMode=True)
        hit_timing_widget.showGrid(y=True)
        dock_hit_timing.addWidget(hit_timing_widget)

        self.plot_delay = 0
예제 #51
0
class InstrumentLoggingUi(WidgetContainerBase, WidgetContainerForm):
    levelNameList = ["debug", "info", "warning", "error", "critical"]
    levelValueList = [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL]
    plotConfigurationChanged = QtCore.pyqtSignal( object )
    def __init__(self, project, config):
        super(InstrumentLoggingUi, self).__init__()
        self.config = config
        self.project = project
        self.dockWidgetList = list()
        self.plotDict = dict()
        self.instrument = ""
        self.loggingLevel = config.get('Settings.loggingLevel', logging.INFO)
        self.consoleMaximumLines = config.get('Settings.consoleMaximumLinesNew', 100)
        self.consoleEnable = config.get('Settings.consoleEnable', False)
        self.printMenu = None
        if self.loggingLevel not in self.levelValueList: self.loggingLevel = logging.INFO
        
    def __enter__(self):
        return self
    
    def __exit__(self, excepttype, value, traceback):
        return False
    
    def setupUi(self, parent):
        super(InstrumentLoggingUi, self).setupUi(parent)
                
        self.dockWidgetConsole.hide()
        self.loggerUi = LoggerLevelsUi(self.config)
        self.loggerUi.setupUi(self.loggerUi)
        self.loggerDock = QtWidgets.QDockWidget("Logging")
        self.loggerDock.setWidget(self.loggerUi)
        self.loggerDock.setObjectName("_LoggerDock")
        self.addDockWidget( QtCore.Qt.RightDockWidgetArea, self.loggerDock)
        self.loggerDock.hide()

        logger = logging.getLogger()        
        self.toolBar.addWidget(ExceptionLogButton())
            
        # Setup Console Dockwidget
        self.levelComboBox.addItems(self.levelNameList)
        self.levelComboBox.currentIndexChanged[int].connect( self.setLoggingLevel )            
        self.levelComboBox.setCurrentIndex( self.levelValueList.index(self.loggingLevel) )
        self.consoleClearButton.clicked.connect( self.onClearConsole )
        self.linesSpinBox.valueChanged.connect( self.onConsoleMaximumLinesChanged )
        self.linesSpinBox.setValue( self.consoleMaximumLines )
        self.checkBoxEnableConsole.stateChanged.connect( self.onEnableConsole )
        self.checkBoxEnableConsole.setChecked( self.consoleEnable )

        self.parent = parent
        self.tabDict = SequenceDict()
               
        self.setupPlots()     
        
        self.preferencesUi = PreferencesUi(config, self)
        self.preferencesUi.setupUi(self.preferencesUi)
        self.preferencesUiDock = QtWidgets.QDockWidget("Print Preferences")
        self.preferencesUiDock.setWidget(self.preferencesUi)
        self.preferencesUiDock.setObjectName("_preferencesUi")
        self.addDockWidget( QtCore.Qt.RightDockWidgetArea, self.preferencesUiDock)

          
        # Traceui
        self.penicons = pens.penicons().penicons()
        self.traceui = Traceui.Traceui(self.penicons, self.config, "Main", self.plotDict)
        self.traceui.setupUi(self.traceui)
        setattr(self.traceui, 'autoSaveTraces', self.config.get('autoSaveTraces', False))
        self.traceui.autoSaveAction = QtWidgets.QAction('Autosave traces', self.traceui)
        self.traceui.autoSaveAction.setCheckable(True)
        self.traceui.autoSaveAction.setChecked(self.traceui.autoSaveTraces)
        self.traceui.autoSaveAction.triggered.connect(lambda checked: setattr(self.traceui, 'autoSaveTraces', checked))
        self.traceui.addAction(self.traceui.autoSaveAction)
        traceuiDock = self.setupAsDockWidget(self.traceui, "Traces", QtCore.Qt.LeftDockWidgetArea)

        # new fit widget
        self.fitWidget = FitUi(self.traceui, self.config, "Main")
        self.fitWidget.setupUi(self.fitWidget)
        self.fitWidgetDock = self.setupAsDockWidget(self.fitWidget, "Fit", QtCore.Qt.LeftDockWidgetArea, stackBelow=traceuiDock)

        self.instrumentLoggingHandler = InstrumentLoggingHandler(self.traceui, self.plotDict, self.config, 'externalInput')

        self.ExternalParametersSelectionUi = InstrumentLoggingSelection(self.config, classdict=LoggingInstruments, plotNames=list(self.plotDict.keys()),
                                                                        instrumentLoggingHandler=self.instrumentLoggingHandler )
        self.ExternalParametersSelectionUi.setupUi( self.ExternalParametersSelectionUi )
        self.ExternalParameterSelectionDock = QtWidgets.QDockWidget("Params Selection")
        self.ExternalParameterSelectionDock.setObjectName("_ExternalParameterSelectionDock")
        self.ExternalParameterSelectionDock.setWidget(self.ExternalParametersSelectionUi)
        self.addDockWidget( QtCore.Qt.RightDockWidgetArea, self.ExternalParameterSelectionDock)
        self.instrumentLoggingHandler.paramTreeChanged.connect( self.ExternalParametersSelectionUi.refreshParamTree)
        self.instrumentLoggingHandler.setInputChannels( self.ExternalParametersSelectionUi.inputChannels() )
        self.ExternalParametersSelectionUi.inputChannelsChanged.connect( self.instrumentLoggingHandler.setInputChannels )
    
        self.instrumentLoggingDisplay = InstrumentLoggingDisplay(self.config)
        self.instrumentLoggingDisplay.setupUi( self.ExternalParametersSelectionUi.inputChannels(), self.instrumentLoggingDisplay )
        self.instrumentLoggingDisplayDock = QtWidgets.QDockWidget("Params Reading")
        self.instrumentLoggingDisplayDock.setObjectName("_ExternalParameterDisplayDock")
        self.instrumentLoggingDisplayDock.setWidget(self.instrumentLoggingDisplay)
        self.addDockWidget( QtCore.Qt.RightDockWidgetArea, self.instrumentLoggingDisplayDock)
        self.ExternalParametersSelectionUi.inputChannelsChanged.connect( self.instrumentLoggingDisplay.setupParameters )
        self.instrumentLoggingHandler.newData.connect( self.instrumentLoggingDisplay.update )

        self.instrumentLoggingQueryUi = InstrumentLoggerQueryUi(self.config, self.traceui, self.plotDict )
        self.instrumentLoggingQueryUi.setupUi( self.instrumentLoggingQueryUi )
        self.instrumentLoggingQueryUiDock = self.setupAsDockWidget(self.instrumentLoggingQueryUi, "Query", QtCore.Qt.LeftDockWidgetArea)
    
        self.addPlot = QtWidgets.QAction( QtGui.QIcon(":/openicon/icons/add-plot.png"), "Add new plot", self)
        self.addPlot.setToolTip("Add new plot")
        self.addPlot.triggered.connect(self.onAddPlot)
        self.toolBar.addAction(self.addPlot)
        
        self.removePlot = QtWidgets.QAction( QtGui.QIcon(":/openicon/icons/remove-plot.png"), "Remove a plot", self)
        self.removePlot.setToolTip("Remove a plot")
        self.removePlot.triggered.connect(self.onRemovePlot)
        self.toolBar.addAction(self.removePlot)

        self.renamePlot = QtWidgets.QAction( QtGui.QIcon(":/openicon/icons/rename-plot.png"), "Rename a plot", self)
        self.renamePlot.setToolTip("Rename a plot")
        self.renamePlot.triggered.connect(self.onRenamePlot)
        self.toolBar.addAction(self.renamePlot)

        self.setWindowTitle( "Instrument Logger ({0})".format(self.project) )
        if 'MainWindow.State' in self.config:
            self.parent.restoreState(self.config['MainWindow.State'])
        try:
            if 'pyqtgraph-dockareastate' in self.config:
                self.area.restoreState(self.config['pyqtgraph-dockareastate'])
        except Exception as e:
            logger.error("Cannot restore dock state in experiment {0}. Exception occurred: ".format(self.experimentName) + str(e))
        self.initMenu()
        self.actionProject.triggered.connect( self.onProjectSelection)
        self.actionExit.triggered.connect(self.onClose)

    def onProjectSelection(self):
        ui = ProjectInfoUi(self.project)
        ui.show()
        ui.exec_()

    def onEnableConsole(self, state):
        self.consoleEnable = state==QtCore.Qt.Checked
                
    def onClearConsole(self):
        self.textEditConsole.clear()
        
    def onConsoleMaximumLinesChanged(self, maxlines):
        self.consoleMaximumLines = maxlines
        self.textEditConsole.document().setMaximumBlockCount(maxlines)

    def setLoggingLevel(self, index):
        self.loggingLevel = self.levelValueList[index]
                   
    def setupPlots(self):
        self.area = DockArea()
        self.setCentralWidget(self.area)
        self.plotDict = dict()
        # initialize all the plot windows we want
        plotNames = self.config.get( 'PlotNames', ['Scan'] )
        if len(plotNames)<1:
            plotNames.append('Scan')
        for name in plotNames:
            dock = Dock(name)
            widget = DateTimePlotWidget(self, name=name)
            view = widget._graphicsView
            self.area.addDock(dock, "bottom")
            dock.addWidget(widget)
            self.plotDict[name] = {"dock":dock, "widget":widget, "view":view}
        
    def setupAsDockWidget(self, widget, name, area=QtCore.Qt.RightDockWidgetArea, stackAbove=None, stackBelow=None ):
        dock = QtWidgets.QDockWidget(name)
        dock.setObjectName(name)
        dock.setWidget( widget )
        self.addDockWidget(area, dock )
        self.dockWidgetList.append( dock )
        if stackAbove is not None:
            self.tabifyDockWidget( stackAbove, dock )
        elif stackBelow is not None:
            self.tabifyDockWidget( dock, stackBelow )
        return dock           

    def onAddPlot(self):
        name, ok = QtWidgets.QInputDialog.getText(self, 'Plot Name', 'Please enter a plot name: ')
        if ok:
            name = str(name)
            dock = Dock(name)
            widget = DateTimePlotWidget(self)
            view = widget._graphicsView
            self.area.addDock(dock, "bottom")
            dock.addWidget(widget)
            self.plotDict[name] = {"dock":dock, "widget":widget, "view":view}
            self.plotConfigurationChanged.emit( self.plotDict )
            
    def onRemovePlot(self):
        logger = logging.getLogger(__name__)
        if len(self.plotDict) > 0:
            name, ok = QtWidgets.QInputDialog.getItem(self, "Select Plot", "Please select which plot to remove: ", list(self.plotDict.keys()), editable=False)
            if ok:
                name = str(name)
                self.plotDict[name]["dock"].close()
                del self.plotDict[name]
                self.plotConfigurationChanged.emit( self.plotDict )
        else:
            logger.info("There are no plots which can be removed")
                
    def onRenamePlot(self):
        logger = logging.getLogger(__name__)
        if len(self.plotDict) > 0:
            name, ok = QtWidgets.QInputDialog.getItem(self, "Select Plot", "Please select which plot to rename: ", list(self.plotDict.keys()), editable=False)
            if ok:
                newName, newOk = QtWidgets.QInputDialog.getText(self, 'New Plot Name', 'Please enter a new plot name: ')
                if newOk:
                    name = str(name)
                    newName = str(newName)
                    self.plotDict[name]["dock"].label.setText(str(newName))
                    self.plotDict[newName] = self.plotDict[name]
                    del self.plotDict[name]
                    self.plotConfigurationChanged.emit( self.plotDict )
        else:
            logger.info("There are no plots which can be renamed")

    def onSave(self):
        logger = logging.getLogger(__name__)
        logger.info( "Saving config" )
        filename, _ = DataDirectory.DataDirectory().sequencefile("InstrumentLogger-configuration.db")
        self.saveConfig()
        self.config.saveConfig(filename)
    
    def onClose(self):
        self.parent.close()
        
    def onMessageWrite(self,message,level=logging.DEBUG):
        if self.consoleEnable and level>= self.loggingLevel:
            cursor = self.textEditConsole.textCursor()
            cursor.movePosition(QtGui.QTextCursor.End)
            if level < logging.ERROR:
                self.textEditConsole.setTextColor(QtCore.Qt.black)
            else:
                self.textEditConsole.setTextColor(QtCore.Qt.red)
            cursor.insertText(message)
            self.textEditConsole.setTextCursor(cursor)
            self.textEditConsole.ensureCursorVisible()

    def closeEvent(self, e):
        logger = logging.getLogger(__name__)
        logger.info( "Close Event" )
        logger = logging.getLogger("")
        logger.debug( "Saving Configuration" )
        self.saveConfig()

    def saveConfig(self):
        self.config['MainWindow.State'] = self.parent.saveState()
        for tab in list(self.tabDict.values()):
            tab.saveConfig()
        self.config['MainWindow.pos'] = self.pos()
        self.config['MainWindow.size'] = self.size()
        self.config['PlotNames'] = list(self.plotDict.keys())
        self.config['pyqtgraph-dockareastate'] = self.area.saveState()
        self.config['Settings.loggingLevel'] = self.loggingLevel
        self.config['Settings.consoleMaximumLinesNew'] = self.consoleMaximumLines
        self.config['Settings.consoleEnable'] = self.consoleEnable
        self.config['autoSaveTraces'] = self.traceui.autoSaveTraces
        self.ExternalParametersSelectionUi.saveConfig()
        self.instrumentLoggingHandler.saveConfig()
        self.instrumentLoggingQueryUi.saveConfig()
        self.preferencesUi.saveConfig()

    def onPrint(self, target):
        printer = QtPrintSupport.QPrinter(mode=QtPrintSupport.QPrinter.ScreenResolution)
        if self.preferencesUi.preferences().printPreferences.doPrint:
            dialog = QtPrintSupport.QPrintDialog(printer, self)
            dialog.setWindowTitle("Print Document")
            if dialog.exec_() != QtWidgets.QDialog.Accepted:
                return;    
        printer.setResolution(self.preferencesUi.preferences().printPreferences.printResolution)

        pdfPrinter = QtPrintSupport.QPrinter()
        pdfPrinter.setOutputFormat(QtPrintSupport.QPrinter.PdfFormat);
        pdfPrinter.setOutputFileName(DataDirectory.DataDirectory().sequencefile(target+".pdf")[0])
        self.doPrint(target, printer, pdfPrinter, self.preferencesUi.preferences().printPreferences)

    def doPrint(self, target, printer, pdfPrinter, preferences):
        widget = self.plotDict[target]['widget']
        if preferences.savePdf:
            with SceneToPrint(widget):
                painter = QtGui.QPainter(pdfPrinter)
                widget.render( painter )
                del painter
        
        # create an exporter instance, as an argument give it
        # the item you wish to export
        with SceneToPrint(widget, preferences.gridLinewidth, preferences.curveLinewidth):
            exporter = ImageExporter(widget._graphicsView.scene()) 
      
            # set export parameters if needed
            pageWidth = printer.pageRect().width()
            pageHeight = printer.pageRect().height()
            exporter.parameters()['width'] = pageWidth*preferences.printWidth   # (note this also affects height parameter)
              
            # save to file
            png = exporter.export(toBytes=True)
            if preferences.savePng:
                png.save(DataDirectory.DataDirectory().sequencefile(target+".png")[0])
            
            if preferences.doPrint:
                painter = QtGui.QPainter( printer )
                painter.drawImage(QtCore.QPoint(pageWidth*preferences.printX, pageHeight*preferences.printY), png)

    def initMenu(self):
        """Initialize print menu and view menu"""
        #View menu
        self.menuView.clear()
        dockList = self.findChildren(QtWidgets.QDockWidget)
        for dock in dockList:
            self.menuView.addAction(dock.toggleViewAction())

        # Print menu
        if self.printMenu is not None:
            self.printMenu.clear()
        else:
            self.printMenu = self.menuFile.addMenu("Print")
        for plot in list(self.plotDict.keys()):
            action = self.printMenu.addAction( plot )
            action.triggered.connect( partial(self.onPrint, plot ))
예제 #52
0
    def add_widgets(self):
        # Main window with dock area
        self.dock_area = DockArea()
        self.setCentralWidget(self.dock_area)

        # Docks
        dock_occcupancy = Dock("Occupancy", size=(400, 400))
        dock_run_config = Dock("Configuration", size=(400, 400))
        dock_tot = Dock("Time over threshold values (TOT)", size=(400, 400))
        dock_tdc = Dock("Time digital converter values (TDC)", size=(400, 400))
        dock_event_status = Dock("Event status", size=(400, 400))
        dock_trigger_status = Dock("Trigger status", size=(400, 400))
        dock_service_records = Dock("Service records", size=(400, 400))
        dock_hit_timing = Dock("Hit timing (rel. BCID)", size=(400, 400))
        dock_status = Dock("Status", size=(800, 40))
        self.dock_area.addDock(dock_run_config, 'left')
        self.dock_area.addDock(dock_occcupancy, 'above', dock_run_config)
        self.dock_area.addDock(dock_tdc, 'right', dock_occcupancy)
        self.dock_area.addDock(dock_tot, 'above', dock_tdc)
        self.dock_area.addDock(dock_service_records, 'bottom', dock_occcupancy)
        self.dock_area.addDock(dock_trigger_status, 'above', dock_service_records)
        self.dock_area.addDock(dock_event_status, 'above', dock_trigger_status)
        self.dock_area.addDock(dock_hit_timing, 'bottom', dock_tot)
        self.dock_area.addDock(dock_status, 'top')

        # Status widget
        cw = QtGui.QWidget()
        cw.setStyleSheet("QWidget {background-color:white}")
        layout = QtGui.QGridLayout()
        cw.setLayout(layout)
        self.rate_label = QtGui.QLabel("Readout Rate\n0 Hz")
        self.hit_rate_label = QtGui.QLabel("Hit Rate\n0 Hz")
        self.event_rate_label = QtGui.QLabel("Event Rate\n0 Hz")
        self.timestamp_label = QtGui.QLabel("Data Timestamp\n")
        self.plot_delay_label = QtGui.QLabel("Plot Delay\n")
        self.scan_parameter_label = QtGui.QLabel("Scan Parameters\n")
        self.spin_box = Qt.QSpinBox(value=1)
        layout.addWidget(self.timestamp_label, 0, 0, 0, 1)
        layout.addWidget(self.plot_delay_label, 0, 1, 0, 1)
        layout.addWidget(self.rate_label, 0, 2, 0, 1)
        layout.addWidget(self.hit_rate_label, 0, 3, 0, 1)
        layout.addWidget(self.event_rate_label, 0, 4, 0, 1)
        layout.addWidget(self.scan_parameter_label, 0, 5, 0, 1)
        layout.addWidget(self.spin_box, 0, 6, 0, 1)
        dock_status.addWidget(cw)

        # Config dock
        self.run_conf_list_widget = Qt.QListWidget()
        dock_run_config.addWidget(self.run_conf_list_widget)

        # Different plot docks

        occupancy_graphics = pg.GraphicsLayoutWidget()
        occupancy_graphics.show()
        view = occupancy_graphics.addViewBox()
        self.occupancy_img = pg.ImageItem(border='w')
        view.addItem(self.occupancy_img)
        view.setRange(QtCore.QRectF(0, 0, 80, 336))
        dock_occcupancy.addWidget(occupancy_graphics)

        tot_plot_widget = pg.PlotWidget(background="w")
        self.tot_plot = tot_plot_widget.plot(np.linspace(-0.5, 15.5, 17), np.zeros((16)), stepMode=True)
        tot_plot_widget.showGrid(y=True)
        dock_tot.addWidget(tot_plot_widget)

        tdc_plot_widget = pg.PlotWidget(background="w")
        self.tdc_plot = tdc_plot_widget.plot(np.linspace(-0.5, 4095.5, 4097), np.zeros((4096)), stepMode=True)
        tdc_plot_widget.showGrid(y=True)
        tdc_plot_widget.setXRange(0, 800, update=True)
        dock_tdc.addWidget(tdc_plot_widget)

        event_status_widget = pg.PlotWidget()
        self.event_status_plot = event_status_widget.plot(np.linspace(-0.5, 15.5, 17), np.zeros((16)), stepMode=True)
        event_status_widget.showGrid(y=True)
        dock_event_status.addWidget(event_status_widget)

        trigger_status_widget = pg.PlotWidget()
        self.trigger_status_plot = trigger_status_widget.plot(np.linspace(-0.5, 7.5, 9), np.zeros((8)), stepMode=True)
        trigger_status_widget.showGrid(y=True)
        dock_trigger_status.addWidget(trigger_status_widget)

        service_record_widget = pg.PlotWidget()
        self.service_record_plot = service_record_widget.plot(np.linspace(-0.5, 31.5, 33), np.zeros((32)), stepMode=True)
        service_record_widget.showGrid(y=True)
        dock_service_records.addWidget(service_record_widget)

        hit_timing_widget = pg.PlotWidget()
        self.hit_timing_plot = hit_timing_widget.plot(np.linspace(-0.5, 15.5, 17), np.zeros((16)), stepMode=True)
        hit_timing_widget.showGrid(y=True)
        dock_hit_timing.addWidget(hit_timing_widget)
예제 #53
0
class OnlineMonitorApplication(QtGui.QMainWindow):

    def __init__(self, socket_addr):
        super(OnlineMonitorApplication, self).__init__()
        self.setup_plots()
        self.add_widgets()
        self.fps = 0  # data frames per second
        self.hps = 0  # hits per second
        self.eps = 0  # events per second
        self.plot_delay = 0
        self.updateTime = ptime.time()
        self.total_hits = 0
        self.total_events = 0
        self.setup_data_worker_and_start(socket_addr)

    def closeEvent(self, event):
        super(OnlineMonitorApplication, self).closeEvent(event)
        # wait for thread
        self.worker.stop()
#         self.thread.wait()

    def setup_data_worker_and_start(self, socket_addr):
        self.thread = QtCore.QThread()  # no parent
        self.worker = DataWorker()  # no parent
        self.worker.meta_data.connect(self.on_meta_data)
        self.worker.interpreted_data.connect(self.on_interpreted_data)
        self.worker.run_start.connect(self.on_run_start)
        self.worker.config_data.connect(self.on_config_data)
        self.spin_box.valueChanged.connect(self.worker.on_set_integrate_readouts)
        self.worker.moveToThread(self.thread)
        self.worker.connect(socket_addr)
#         self.aboutToQuit.connect(self.worker.stop)  # QtGui.QApplication
        self.thread.started.connect(self.worker.process_data)
        self.worker.finished.connect(self.thread.quit)
#         self.worker.finished.connect(self.worker.deleteLater)
#         self.thread.finished.connect(self.thread.deleteLater)
        self.thread.start()

    def setup_plots(self):
        pg.setConfigOption('background', 'w')
        pg.setConfigOption('foreground', 'k')

    def add_widgets(self):
        # Main window with dock area
        self.dock_area = DockArea()
        self.setCentralWidget(self.dock_area)

        # Docks
        dock_occcupancy = Dock("Occupancy", size=(400, 400))
        dock_run_config = Dock("Configuration", size=(400, 400))
        dock_tot = Dock("Time over threshold values (TOT)", size=(400, 400))
        dock_tdc = Dock("Time digital converter values (TDC)", size=(400, 400))
        dock_event_status = Dock("Event status", size=(400, 400))
        dock_trigger_status = Dock("Trigger status", size=(400, 400))
        dock_service_records = Dock("Service records", size=(400, 400))
        dock_hit_timing = Dock("Hit timing (rel. BCID)", size=(400, 400))
        dock_status = Dock("Status", size=(800, 40))
        self.dock_area.addDock(dock_run_config, 'left')
        self.dock_area.addDock(dock_occcupancy, 'above', dock_run_config)
        self.dock_area.addDock(dock_tdc, 'right', dock_occcupancy)
        self.dock_area.addDock(dock_tot, 'above', dock_tdc)
        self.dock_area.addDock(dock_service_records, 'bottom', dock_occcupancy)
        self.dock_area.addDock(dock_trigger_status, 'above', dock_service_records)
        self.dock_area.addDock(dock_event_status, 'above', dock_trigger_status)
        self.dock_area.addDock(dock_hit_timing, 'bottom', dock_tot)
        self.dock_area.addDock(dock_status, 'top')

        # Status widget
        cw = QtGui.QWidget()
        cw.setStyleSheet("QWidget {background-color:white}")
        layout = QtGui.QGridLayout()
        cw.setLayout(layout)
        self.rate_label = QtGui.QLabel("Readout Rate\n0 Hz")
        self.hit_rate_label = QtGui.QLabel("Hit Rate\n0 Hz")
        self.event_rate_label = QtGui.QLabel("Event Rate\n0 Hz")
        self.timestamp_label = QtGui.QLabel("Data Timestamp\n")
        self.plot_delay_label = QtGui.QLabel("Plot Delay\n")
        self.scan_parameter_label = QtGui.QLabel("Scan Parameters\n")
        self.spin_box = Qt.QSpinBox(value=1)
        layout.addWidget(self.timestamp_label, 0, 0, 0, 1)
        layout.addWidget(self.plot_delay_label, 0, 1, 0, 1)
        layout.addWidget(self.rate_label, 0, 2, 0, 1)
        layout.addWidget(self.hit_rate_label, 0, 3, 0, 1)
        layout.addWidget(self.event_rate_label, 0, 4, 0, 1)
        layout.addWidget(self.scan_parameter_label, 0, 5, 0, 1)
        layout.addWidget(self.spin_box, 0, 6, 0, 1)
        dock_status.addWidget(cw)

        # Config dock
        self.run_conf_list_widget = Qt.QListWidget()
        dock_run_config.addWidget(self.run_conf_list_widget)

        # Different plot docks

        occupancy_graphics = pg.GraphicsLayoutWidget()
        occupancy_graphics.show()
        view = occupancy_graphics.addViewBox()
        self.occupancy_img = pg.ImageItem(border='w')
        view.addItem(self.occupancy_img)
        view.setRange(QtCore.QRectF(0, 0, 80, 336))
        dock_occcupancy.addWidget(occupancy_graphics)

        tot_plot_widget = pg.PlotWidget(background="w")
        self.tot_plot = tot_plot_widget.plot(np.linspace(-0.5, 15.5, 17), np.zeros((16)), stepMode=True)
        tot_plot_widget.showGrid(y=True)
        dock_tot.addWidget(tot_plot_widget)

        tdc_plot_widget = pg.PlotWidget(background="w")
        self.tdc_plot = tdc_plot_widget.plot(np.linspace(-0.5, 4095.5, 4097), np.zeros((4096)), stepMode=True)
        tdc_plot_widget.showGrid(y=True)
        tdc_plot_widget.setXRange(0, 800, update=True)
        dock_tdc.addWidget(tdc_plot_widget)

        event_status_widget = pg.PlotWidget()
        self.event_status_plot = event_status_widget.plot(np.linspace(-0.5, 15.5, 17), np.zeros((16)), stepMode=True)
        event_status_widget.showGrid(y=True)
        dock_event_status.addWidget(event_status_widget)

        trigger_status_widget = pg.PlotWidget()
        self.trigger_status_plot = trigger_status_widget.plot(np.linspace(-0.5, 7.5, 9), np.zeros((8)), stepMode=True)
        trigger_status_widget.showGrid(y=True)
        dock_trigger_status.addWidget(trigger_status_widget)

        service_record_widget = pg.PlotWidget()
        self.service_record_plot = service_record_widget.plot(np.linspace(-0.5, 31.5, 33), np.zeros((32)), stepMode=True)
        service_record_widget.showGrid(y=True)
        dock_service_records.addWidget(service_record_widget)

        hit_timing_widget = pg.PlotWidget()
        self.hit_timing_plot = hit_timing_widget.plot(np.linspace(-0.5, 15.5, 17), np.zeros((16)), stepMode=True)
        hit_timing_widget.showGrid(y=True)
        dock_hit_timing.addWidget(hit_timing_widget)

    @pyqtSlot()
    def on_run_start(self):
        # clear config data widget
        self.run_conf_list_widget.clear()
        self.run_conf_list_widget.addItem(Qt.QListWidgetItem("No run configuration"))

    @pyqtSlot(dict)
    def on_config_data(self, config_data):
        self.setup_config_text(**config_data)

    def setup_config_text(self, conf):
        for key, value in conf.iteritems():
            item = Qt.QListWidgetItem("%s: %s" % (key, value))
            self.run_conf_list_widget.addItem(item)

    @pyqtSlot(dict)
    def on_interpreted_data(self, interpreted_data):
        self.update_plots(**interpreted_data)

    def update_plots(self, occupancy, tot_hist, tdc_counters, error_counters, service_records_counters, trigger_error_counters, rel_bcid_hist):
        self.occupancy_img.setImage(occupancy[:, ::-1, 0], autoDownsample=True)
        self.tot_plot.setData(x=np.linspace(-0.5, 15.5, 17), y=tot_hist, fillLevel=0, brush=(0, 0, 255, 150))
        self.tdc_plot.setData(x=np.linspace(-0.5, 4096.5, 4097), y=tdc_counters, fillLevel=0, brush=(0, 0, 255, 150))
        self.event_status_plot.setData(x=np.linspace(-0.5, 15.5, 17), y=error_counters, stepMode=True, fillLevel=0, brush=(0, 0, 255, 150))
        self.service_record_plot.setData(x=np.linspace(-0.5, 31.5, 33), y=service_records_counters, stepMode=True, fillLevel=0, brush=(0, 0, 255, 150))
        self.trigger_status_plot.setData(x=np.linspace(-0.5, 7.5, 9), y=trigger_error_counters, stepMode=True, fillLevel=0, brush=(0, 0, 255, 150))
        self.hit_timing_plot.setData(x=np.linspace(-0.5, 15.5, 17), y=rel_bcid_hist, stepMode=True, fillLevel=0, brush=(0, 0, 255, 150))

    @pyqtSlot(dict)
    def on_meta_data(self, meta_data):
        self.update_monitor(**meta_data)

    def update_monitor(self, timestamp_start, timestamp_stop, readout_error, scan_parameters, n_hits, n_events):
        self.timestamp_label.setText("Data Timestamp\n%s" % time.asctime(time.localtime(timestamp_stop)))
        self.scan_parameter_label.setText("Scan Parameters\n%s" % ', '.join('%s: %s' % (str(key), str(val)) for key, val in scan_parameters.iteritems()))
        now = ptime.time()
        recent_total_hits = n_hits
        recent_total_events = n_events
        self.plot_delay = self.plot_delay * 0.9 + (now - timestamp_stop) * 0.1
        self.plot_delay_label.setText("Plot Delay\n%s" % ((time.strftime('%H:%M:%S', time.gmtime(self.plot_delay))) if self.plot_delay > 5 else "%1.2f ms" % (self.plot_delay * 1.e3)))
        recent_fps = 1.0 / (now - self.updateTime)  # calculate FPS
        recent_hps = (recent_total_hits - self.total_hits) / (now - self.updateTime)
        recent_eps = (recent_total_events - self.total_events) / (now - self.updateTime)
        self.updateTime = now
        self.total_hits = recent_total_hits
        self.total_events = recent_total_events
        self.fps = self.fps * 0.7 + recent_fps * 0.3
        self.hps = self.hps + (recent_hps - self.hps) * 0.3 / self.fps
        self.eps = self.eps + (recent_eps - self.eps) * 0.3 / self.fps
        self.rate_label.setText("Readout Rate\n%d Hz" % self.fps)
        if self.spin_box.value() == 0:  # show number of hits, all hits are integrated
            self.hit_rate_label.setText("Total Hits\n%d" % int(recent_total_hits))
        else:
            self.hit_rate_label.setText("Hit Rate\n%d Hz" % int(self.hps))
        if self.spin_box.value() == 0:  # show number of events
            self.event_rate_label.setText("Total Events\n%d" % int(recent_total_events))
        else:
            self.event_rate_label.setText("Event Rate\n%d Hz" % int(self.eps))
예제 #54
0
    def __init__(self, instance):
        super(GUIBuilder, self).__init__()
        self.setCentralWidget(QWidget())
        layout = QVBoxLayout(self.centralWidget())
        self.plots_layout = DockArea()
        layout.addWidget(self.plots_layout)
        self.form_layout = QFormLayout()
        self.form_layout.setFieldGrowthPolicy(QFormLayout.ExpandingFieldsGrow)
        layout.addLayout(self.form_layout)
        self.buttons_layout = QHBoxLayout()
        layout.addLayout(self.buttons_layout)

        self.instance = instance
        self.plot_widgets = {}
        self.plot_data_items = {}
        self.plot_color_generators = {}

        seen_form_items = []
        seen_plot_items = []

        for node in ast.walk(ast.parse(getsource(type(instance)))):
            if isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
                if node.func.id.startswith('gb_get_') or node.func.id.startswith('gb_set_'):
                    segs = node.func.id.split('_')
                    caster = __builtins__[segs[2]]
                    name = "_".join(segs[3:])

                    if name in seen_form_items:
                        continue
                    seen_form_items.append(name)

                    if caster is bool:
                        editor = QCheckBox()
                        if node.func.id.startswith('gb_get_') and node.args:
                            editor.setChecked(node.args[0].id == 'True')
                        get_fn = lambda e=editor: e.isChecked()
                        set_fn = lambda v, e=editor: e.setChecked(v)
                    else:
                        editor = QLineEdit()
                        if node.func.id.startswith('gb_get_') and node.args:
                            if isinstance(node.args[0], ast.Num):
                                init = node.args[0].n
                            else:
                                init = node.args[0].s
                            editor.setText(str(caster(init)))
                        get_fn = lambda e=editor, c=caster: c(e.text())
                        set_fn = lambda val, e=editor: e.setText(str(val))

                    base_name = "_".join(segs[2:])
                    get_name = "gb_get_" + base_name
                    set_name = "gb_set_" + base_name
                    __builtins__[get_name] = lambda init=0, get_fn=get_fn: get_fn()
                    __builtins__[set_name] = lambda val, set_fn=set_fn: set_fn(val)

                    self.form_layout.addRow(prettify(name), editor)

                if node.func.id.startswith('gb_plot_'):
                    segs = node.func.id.split("_")
                    plot_type = segs[2]
                    plot_name = segs[3]
                    if len(segs) >= 5:
                        data_item_name = "_".join(segs[4:])
                    else:
                        data_item_name = ""

                    if (plot_name, data_item_name) in seen_plot_items:
                        continue
                    seen_plot_items.append((plot_name, data_item_name))

                    if plot_name not in self.plot_widgets:
                        if plot_type in ['y', 'xy']:
                            pw = PlotWidget()
                            self.plot_widgets[plot_name] = pw
                            self.plot_color_generators[plot_name] = itertools.cycle('rgb')
                            pw.addLegend()
                        else:
                            raise ValueError("Unknown plot type in {}: {}".format(node.func.id, plot_type))
                        dock = Dock(name=prettify(plot_name), widget=pw)
                        self.plots_layout.addDock(dock, 'above')

                    self.add_plot_item(node.func.id, plot_name, data_item_name)

            if isinstance(node, ast.FunctionDef):
                if node.name.endswith("_gb_button"):
                    name = "_".join(node.name.split("_")[:-2])
                    button = QPushButton(prettify(name))
                    button.clicked.connect(getattr(instance, node.name))
                    self.buttons_layout.addWidget(button)
예제 #55
0
class PicoampMeterUi(WidgetContainerBase, WidgetContainerForm):
    levelNameList = ["debug", "info", "warning", "error", "critical"]
    levelValueList = [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL]
    plotConfigurationChanged = QtCore.pyqtSignal( object )
    def __init__(self, config):
        self.config = config
        super(PicoampMeterUi, self).__init__()
        self.loggingLevel = config.get('Settings.loggingLevel', logging.INFO)
        self.consoleMaximumLines = config.get('Settings.consoleMaximumLines', 0)
        self.dockWidgetList = list()
        if self.loggingLevel not in self.levelValueList: self.loggingLevel = logging.INFO
        self.plotDict = dict()
        self.meter = None
        self.instrument = ""
        
    def __enter__(self):
        self.meter = PicoampMeter()
        self.meter_2 = PicoampMeter()
        self.meter_3 = PicoampMeter()
        return self
    
    def __exit__(self, excepttype, value, traceback):
        self.meter.close()
        self.meter_2.close()
        self.meter_3.close()
        return False
    
    def setupUi(self, parent):
        super(PicoampMeterUi, self).setupUi(parent)
        self.dockWidgetConsole.hide()
        self.loggerUi = LoggerLevelsUi(self.config)
        self.loggerUi.setupUi(self.loggerUi)
        self.setupAsDockWidget(self.loggerUi, "Logging", QtCore.Qt.NoDockWidgetArea)
                
        logger = logging.getLogger()        
        self.toolBar.addWidget(ExceptionLogButton())
            
        self.parent = parent
        self.tabList = list()
        self.tabDict = dict()
               
        self.setupPlots()       
        # Traceui
        self.penicons = pens.penicons().penicons()
        self.traceui = Traceui.Traceui(self.penicons, self.config, "Main", self.plotDict)
        self.traceui.setupUi(self.traceui)
        self.setupAsDockWidget(self.traceui, "Traces", QtCore.Qt.LeftDockWidgetArea)

        # PicoampMeter Control
        self.meterControl = PicoampMeterControl(self.config, self.traceui, self.plotDict, self.parent, self.meter, self.meter_2, self.meter_3)
        self.meterControl.setupUi(self.meterControl)
        self.setupAsDockWidget(self.meterControl, "Control", QtCore.Qt.RightDockWidgetArea)
    
        self.actionSave.triggered.connect(self.onSave)
        #self.actionSettings.triggered.connect(self.onSettings)
        self.actionExit.triggered.connect(self.onClose)
        self.actionProject.triggered.connect( self.onProjectSelection)
        
        self.actionStart.triggered.connect(self.meterControl.onScan)
        self.actionStop.triggered.connect(self.meterControl.onStop)

        self.addPlot = QtWidgets.QAction( QtGui.QIcon(":/openicon/icons/add-plot.png"), "Add new plot", self)
        self.addPlot.setToolTip("Add new plot")
        self.addPlot.triggered.connect(self.onAddPlot)
        self.toolBar.addAction(self.addPlot)
        
        self.removePlot = QtWidgets.QAction( QtGui.QIcon(":/openicon/icons/remove-plot.png"), "Remove a plot", self)
        self.removePlot.setToolTip("Remove a plot")
        self.removePlot.triggered.connect(self.onRemovePlot)
        self.toolBar.addAction(self.removePlot)

        self.renamePlot = QtWidgets.QAction( QtGui.QIcon(":/openicon/icons/rename-plot.png"), "Rename a plot", self)
        self.renamePlot.setToolTip("Rename a plot")
        self.renamePlot.triggered.connect(self.onRenamePlot)
        self.toolBar.addAction(self.renamePlot)

        self.setWindowTitle("Digital Lock ({0})".format(project) )
        if 'MainWindow.State' in self.config:
            self.parent.restoreState(self.config['MainWindow.State'])
        self.initMenu()
        try:
            if 'pyqtgraph-dockareastate' in self.config:
                self.area.restoreState(self.config['pyqtgraph-dockareastate'])
        except Exception as e:
            logger.error("Cannot restore dock state in experiment {0}. Exception occurred: ".format(self.experimentName) + str(e))
       
        
    def setupPlots(self):
        self.area = DockArea()
        self.setCentralWidget(self.area)
        self.plotDict = dict()
        # initialize all the plot windows we want
        plotNames = self.config.get( 'PlotNames', ['Scan'] )
        if len(plotNames)<1:
            plotNames.append('Scan')
        for name in plotNames:
            dock = Dock(name)
            widget = CoordinatePlotWidget(self)
            view = widget._graphicsView
            self.area.addDock(dock, "bottom")
            dock.addWidget(widget)
            self.plotDict[name] = {"dock":dock, "widget":widget, "view":view}
        
    def setupAsDockWidget(self, widget, name, area=QtCore.Qt.RightDockWidgetArea, stackAbove=None, stackBelow=None ):
        dock = QtWidgets.QDockWidget(name)
        dock.setObjectName(name)
        dock.setWidget( widget )
        self.addDockWidget(area, dock )
        self.dockWidgetList.append( dock )
        if stackAbove is not None:
            self.tabifyDockWidget( stackAbove, dock )
        elif stackBelow is not None:
            self.tabifyDockWidget( dock, stackBelow )
        return dock           

    def onAddPlot(self):
        name, ok = QtWidgets.QInputDialog.getText(self, 'Plot Name', 'Please enter a plot name: ')
        if ok:
            name = str(name)
            dock = Dock(name)
            widget = CoordinatePlotWidget(self)
            view = widget._graphicsView
            self.area.addDock(dock, "bottom")
            dock.addWidget(widget)
            self.plotDict[name] = {"dock":dock, "widget":widget, "view":view}
            self.plotConfigurationChanged.emit( self.plotDict )
            
    def onRemovePlot(self):
        logger = logging.getLogger(__name__)
        if len(self.plotDict) > 0:
            name, ok = QtWidgets.QInputDialog.getItem(self, "Select Plot", "Please select which plot to remove: ", list(self.plotDict.keys()), editable=False)
            if ok:
                name = str(name)
                self.plotDict[name]["dock"].close()
                del self.plotDict[name]
                self.plotConfigurationChanged.emit( self.plotDict )
        else:
            logger.info("There are no plots which can be removed")
                
    def onRenamePlot(self):
        logger = logging.getLogger(__name__)
        if len(self.plotDict) > 0:
            name, ok = QtWidgets.QInputDialog.getItem(self, "Select Plot", "Please select which plot to rename: ", list(self.plotDict.keys()), editable=False)
            if ok:
                newName, newOk = QtWidgets.QInputDialog.getText(self, 'New Plot Name', 'Please enter a new plot name: ')
                if newOk:
                    name = str(name)
                    newName = str(newName)
                    self.plotDict[name]["dock"].label.setText(str(newName))
                    self.plotDict[newName] = self.plotDict[name]
                    del self.plotDict[name]
                    self.plotConfigurationChanged.emit( self.plotDict )
        else:
            logger.info("There are no plots which can be renamed")

    def onProjectSelection(self):
        ProjectSelectionUi.GetProjectSelection()

    def onSettings(self):
        self.settingsDialog.show()
        
    def onSave(self):
        logger = logging.getLogger(__name__)
        logger.info( "Saving config" )
        filename, _ = DataDirectory.DataDirectory().sequencefile("digitalLock-configuration.db")
        self.saveConfig()
        self.config.saveConfig(filename)
    
    def onMessageWrite(self,message,level=logging.DEBUG):
        if level>= self.loggingLevel:
            cursor = self.textEditConsole.textCursor()
            cursor.movePosition(QtGui.QTextCursor.End)
            if level < logging.ERROR:
                self.textEditConsole.setTextColor(QtCore.Qt.black)
            else:
                self.textEditConsole.setTextColor(QtCore.Qt.red)
            cursor.insertText(message)
            self.textEditConsole.setTextCursor(cursor)
            self.textEditConsole.ensureCursorVisible()

    def onClose(self):
        self.parent.close()
        
    def closeEvent(self, e):
        logger = logging.getLogger("")
        logger.debug( "Saving Configuration" )
        self.saveConfig()

    def initMenu(self):
        self.menuView.clear()
        for dock in self.dockWidgetList:
            self.menuView.addAction(dock.toggleViewAction())

    def saveConfig(self):
        self.config['MainWindow.State'] = self.parent.saveState()
        for tab in self.tabList:
            tab.saveConfig()
        self.config['MainWindow.pos'] = self.pos()
        self.config['MainWindow.size'] = self.size()
        self.config['Settings.loggingLevel'] = self.loggingLevel
        self.config['Settings.consoleMaximumLines'] = self.consoleMaximumLines
        self.config['PlotNames'] = list(self.plotDict.keys())
        self.config['pyqtgraph-dockareastate'] = self.area.saveState()
        self.loggerUi.saveConfig()
        self.meterControl.saveConfig()
예제 #56
0
class DockAreaTabWidgetBase(QtGui.QWidget):
    
    def __init__(self, *args, **kwargs):
        self.main = kwargs.pop("main")
        tabName = kwargs.pop("tabName")
        QtGui.QWidget.__init__(self, *args, **kwargs)
        self.setObjectName(tabName)
        self._layout = QtGui.QGridLayout(self)
            
    def _InitDocks(self):
        
        # Define docking area
        if hasattr(self, "_dockArea"):
            self._dockArea.setParent(None)
        self._dockArea = DockArea()

        self._plotDocks = self._defaultDockPos.keys()
        
        # Add dock to area
        for dock, pos in self._defaultDockPos.iteritems():
            self._dockArea.addDock(dock, *pos)
        
        self._layout.addWidget(self._dockArea, 0, 0, 1, 1)
    
    def Shown(self):
        self.DrawFrame()
    
    def DrawFrame(self, clear = True):   
        if clear:
            self.ClearPlots()
            
        for dock in self._plotDocks:
            if not dock.automaticDraw:
                continue
            dock.DrawPlot()
        
    def ClearPlots(self):
        for dock in self._plotDocks:
            if not dock.automaticDraw:
                continue
            dock.ClearPlot()
            
    def AutoscalePlots(self):
        for dock in self._plotDocks:
            if not dock.automaticDraw:
                continue
            dock.Autoscale()
            
    def SaveState(self):
        res = {}
        res["dockingState"] = self._dockArea.saveState()
        for dock in self._plotDocks:
            res["dock_" + dock.name()] = dock.SaveState()
        return res
    
    def SetState(self, state):
        try:    
            if "dockingState" in state:
                self._dockArea.restoreState(state["dockingState"])           
        except:
            print "Docking area restore failed, restoring defaults:"
            traceback.print_exc()
            print "Restore defaults"
            self._InitDocks()
 
        for dock in self._plotDocks:
            stateName = "dock_" + dock.name()
            if stateName in state:
                dock.SetState(state[stateName])
예제 #57
0
class H5Plotter(QtGui.QMainWindow):
    def __init__(self, file):
        super(H5Plotter, self).__init__()
        view_box = SearchableH5View(H5File(file))
        self.view = view_box.tree_view
        self.match_model = self.view.model()
        self.model = self.match_model.sourceModel()
        self.dock_area = DockArea()

        self.layout = QtGui.QSplitter(Qt.Horizontal)
        self.setCentralWidget(self.layout)
        self.view.activated.connect(self.load_plot)
        self.layout.addWidget(view_box)
        self.layout.addWidget(self.dock_area)
        self.layout.setStretchFactor(0, 0)
        self.layout.setStretchFactor(1, 1)

        self.setWindowIcon(QtGui.QIcon("icon.ico"))

        QtGui.QShortcut(QtGui.QKeySequence(Qt.CTRL | Qt.Key_N), self,
                        lambda: self.move_view_cursor(QtGui.QAbstractItemView.MoveDown))
        QtGui.QShortcut(QtGui.QKeySequence(Qt.CTRL | Qt.Key_P), self,
                        lambda: self.move_view_cursor(QtGui.QAbstractItemView.MoveUp))
        QtGui.QShortcut(QtGui.QKeySequence(Qt.CTRL | Qt.Key_F), self,
                        lambda: self.move_view_cursor(QtGui.QAbstractItemView.MoveRight))
        QtGui.QShortcut(QtGui.QKeySequence(Qt.CTRL | Qt.Key_B), self,
                        lambda: self.move_view_cursor(QtGui.QAbstractItemView.MoveLeft))
        QtGui.QShortcut(QtGui.QKeySequence(Qt.CTRL | Qt.Key_S), self, view_box.search_box.setFocus)

        view_menu = self.menuBar().addMenu("View")

        toggle_attrs_action = QtGui.QAction("Attributes Visible", view_menu)
        toggle_attrs_action.setCheckable(True)
        toggle_attrs_action.triggered.connect(self.match_model.toggle_attrs_visible)
        view_menu.addAction(toggle_attrs_action)

        toggle_junk_action = QtGui.QAction("Junk Visible", view_menu)
        toggle_junk_action.setCheckable(True)
        toggle_junk_action.triggered.connect(self.match_model.toggle_junk_visible)
        view_menu.addAction(toggle_junk_action)

    def move_view_cursor(self, cursor_action):
        self.view.setFocus(Qt.OtherFocusReason)
        self.view.setCurrentIndex(self.view.moveCursor(cursor_action, Qt.NoModifier))


    def load_plot(self, index):
        'given an index referring to an H5Dataset, puts a plot corresponding to that dataset in the plot area'
        source_index = self.match_model.mapToSource(index)
        item = self.model.itemFromIndex(source_index)
        if isinstance(item.row, H5DatasetRow) and item.row.plot is None:
            labels = []
            axes = []
            for d in item.group.dims:
                try:
                    label, ds = d.items()[0]
                    labels.append(label)
                    axes.append(ds[:])
                except IndexError:
                    print 'Could not find axis in item', item
                    labels.append('')
                    axes.append(None)
                except RuntimeError:
                    print 'Mac bug? Probably no axis available'

            dock = self.make_dock(item.name, item.group[:], labels, axes)
            self.dock_area.addDock(dock)
            item.plot = dock
            dock.closeClicked.connect(lambda: item.__setattr__('plot', None))

    def make_dock(self, name, array, labels=None, axes=None):
        'returns a dockable plot widget'
        labels = {pos: l for l, pos in zip(labels, ('bottom', 'left'))}
        if len(array.shape) in (2, 3):
            if len(array.shape) == 2:
                d = CrossSectionDock(name=name, area=self.dock_area)
            if len(array.shape) == 3:
                d = MoviePlotDock(array, name=name, area=self.dock_area)
            pos, scale = None, None
            if axes is not None:
                pos = [0, 0]
                scale = [1, 1]
                if axes[0] is not None:
                    pos[0] = axes[0][0]
                    scale[0] = axes[0][1] - axes[0][0]
                if axes[1] is not None:
                    pos[1] = axes[1][0]
                    scale[1] = axes[1][1] - axes[1][0]
            d.setImage(array, pos=pos, scale=scale)
            if labels is not None:
                d.setLabels(labels['bottom'], labels['left'], name)

        if len(array.shape) == 1:
            w = CrosshairPlotWidget(labels=labels)
            if axes and axes[0] is not None:
                w.plot(axes[0], array)
            else:
                w.plot(array)
            d = CloseableDock(name=name, widget=w, area=self.dock_area)

        return d