예제 #1
0
 def __init_image_view__(self):
     self.image_view = Basic2DImageWidget(
         self.get_lower_connector('Basic2DImageWidget'))
     dock = Dock('Image')
     dock.addWidget(self.image_view)
     self.addDock(dock, size=(1000, 1000))
     self.image_view_dock = dock
예제 #2
0
 def __init_crystal_image_widget(self):
     self.crystal_image_viewer = CrystalImageWidget(self)
     self.crystal_controller.connect_image_widget(self.crystal_image_viewer)
     dock = Dock('Crystal Image Viewer')
     dock.addWidget(self.crystal_image_viewer)
     self.addDock(dock, position='right')
     self.crystal_image_viewer_dock = dock
예제 #3
0
파일: UI.py 프로젝트: queezz/AXUV
class UIWindow(object):
    def __init__(self):
        super().__init__()
        pg.setConfigOptions(imageAxisOrder='row-major')

        self.MainWindow = QtGui.QMainWindow()
        self.tabwidg = QtGui.QTabWidget()
        self.area = DockArea()
        self.plotDock = Dock("Plots", size=(400, 400))
        self.surfaceDock = Dock("Contour", size=(250, 400))
        self.controlDock = ControlDock()
        self.controlDock.setStretch(*(10, 100))
        self.graph = Graph()
        self.contour = Contour()

        self.MainWindow.setGeometry(20, 50, 1200, 600)
        self.MainWindow.setObjectName("Monitor")
        self.MainWindow.setWindowTitle("AXUV tool")
        self.MainWindow.statusBar().showMessage('')
        self.MainWindow.setAcceptDrops(True)
        self.__setLayout()

    def __setLayout(self):
        self.MainWindow.setCentralWidget(self.tabwidg)
        self.tabwidg.addTab(self.area, "Data")

        self.area.addDock(self.plotDock, "right")
        self.area.addDock(self.controlDock, "left")
        self.area.addDock(self.surfaceDock, "bottom", self.controlDock)

        self.plotDock.addWidget(self.graph)
        self.surfaceDock.addWidget(self.contour)

    def showMain(self):
        self.MainWindow.show()
예제 #4
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')
예제 #5
0
    def __init__(self, *args, **kwargs):
        self.tab = kwargs.pop("tab", None)
        self.main = kwargs.pop("main", None)
        self.automaticDraw = True

        Dock.__init__(self, *args, **kwargs)

        self._axialPlot = pg.PlotWidget()
        self._axialPlot.addLegend()

        self._axialControls = QtGui.QWidget(self)
        self._axialControlsLayout = QtGui.QGridLayout(self._axialControls)

        self._axialButtons = QtGui.QWidget(self._axialControls)
        self._axialButtonsLayout = QtGui.QHBoxLayout(self._axialButtons)

        self._calibButton = QtGui.QPushButton("Calibrate", self._axialButtons)
        self._calibButton.setIcon(QtGui.QIcon(":/16x16/16x16/Play_16x16.png"))
        self._calibButton.pressed.connect(self._CalibrateAxialPosition)

        self._calibDelButton = QtGui.QPushButton("Clear", self._axialButtons)
        self._calibDelButton.setIcon(
            QtGui.QIcon(":/16x16/16x16/Delete_16x16.png"))
        self._calibDelButton.pressed.connect(self._DeleteAxialCalibration)

        self._axialButtonsLayout.addWidget(self._calibButton)
        self._axialButtonsLayout.addWidget(self._calibDelButton)

        self._axialControlsLayout.addWidget(self._axialPlot, 0, 0, 1, 1)
        self._axialControlsLayout.addWidget(self._axialButtons, 1, 0, 1, 1)

        self.addWidget(self._axialControls)
예제 #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 set_point_list(self):
        dock_list = Dock('List of points')
        self.area.addDock(dock_list, 'right')
        params = [{'title': 'Positions', 'name': 'tabular_table', 'type': 'table_view',
                   'delegate': gutils.SpinBoxDelegate, 'menu': True}, ]
        self.settings_tree = ParameterTree()
        self.settings = Parameter.create(name='settings', title='Settings', type='group', children=params)
        self.settings_tree.setParameters(self.settings, showTop=False)
        dock_list.addWidget(self.settings_tree)

        init_data = [[0., 0., 0.]]
        self.table_model = TableModelTabular(init_data, ['x', 'y', 'data'])
        self.table_view = pymodaq.daq_utils.parameter.utils.get_widget_from_tree(self.settings_tree, custom_tree.TableViewCustom)[0]
        self.settings.child(('tabular_table')).setValue(self.table_model)

        self.table_view.horizontalHeader().setResizeMode(QtWidgets.QHeaderView.ResizeToContents)
        self.table_view.horizontalHeader().setStretchLastSection(True)
        self.table_view.setSelectionBehavior(QtWidgets.QTableView.SelectRows)
        self.table_view.setSelectionMode(QtWidgets.QTableView.SingleSelection)
        styledItemDelegate = QtWidgets.QStyledItemDelegate()
        styledItemDelegate.setItemEditorFactory(gutils.SpinBoxDelegate())
        self.table_view.setItemDelegate(styledItemDelegate)

        self.table_view.setDragEnabled(True)
        self.table_view.setDropIndicatorShown(True)
        self.table_view.setAcceptDrops(True)
        self.table_view.viewport().setAcceptDrops(True)
        self.table_view.setDefaultDropAction(Qt.MoveAction)
        self.table_view.setDragDropMode(QtWidgets.QTableView.InternalMove)
        self.table_view.setDragDropOverwriteMode(False)

        self.table_view.add_data_signal[int].connect(self.table_model.add_data)
        self.table_view.remove_row_signal[int].connect(self.table_model.remove_data)
        self.table_view.load_data_signal.connect(self.table_model.load_txt)
        self.table_view.save_data_signal.connect(self.table_model.save_txt)
예제 #8
0
def gui_docks_p2_04_02(d_area, _, title=None):
    d1 = Dock(title, size=(1, 1), closable=True)
    tab_1 = pg.TableWidget()
    d1.addWidget(tab_1)
    d_area.addDock(d1, 'right')

    c = np.arange(2.0, 0.0, -0.1)

    def solve_for_r(conc, start_r):
        return root(
            lambda r: -r + 1.5 * (conc - 0.8 * r) /
            (1 + 0.3 * np.sqrt(conc - 0.8 * r) + 0.1 * (conc - 0.8 * r))**2.0,
            np.array([start_r])).x

    r_calc = np.array([solve_for_r(conc, 0.1) for conc in c]).flatten()
    simple_t = -np.gradient(c) * 1 / r_calc
    simple_t[0] = 0
    simple_t = np.cumsum(simple_t)
    quad_t = np.array([
        quad(lambda conc: 1 / solve_for_r(conc, 0.1), c_min, 2.0)
        for c_min in c
    ])[:, 0]
    data = np.array([c, 1 / r_calc, simple_t, quad_t]).T
    tab_1.setData(data)
    tab_1.setHorizontalHeaderLabels(['c', '1/r', 't_simple', 't_quadfunc'])
    tab_1.sortByColumn(2, QtCore.Qt.AscendingOrder)
    tab_1.horizontalHeader().setResizeMode(QtGui.QHeaderView.ResizeToContents)
예제 #9
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')
예제 #10
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)
예제 #11
0
 def __init_control_widget__(self):
     self.control_widget = ControlWidget(
         self.get_lower_connector('ControlWidget'), self)
     control_dock = Dock('Segments')
     control_dock.addWidget(self.control_widget)
     self.addDock(control_dock, position='right')
     self.control_dock = control_dock
예제 #12
0
def gui_docks_p4_03_01(d_area, timer, title=None):
    d1 = Dock(title, size=(1, 1), closable=True)
    p1 = pg.PlotWidget(name='Plot 1')
    d1.addWidget(p1)
    d_area.addDock(d1, 'right')
    timer.stop()
    if timer.connected:
        # Qt objects can have several connected slots.
        # Not disconnecting them all causes previously
        # running processes to continue when restarted.
        timer.timeout.disconnect()

    time_interval = [0, 10]

    # noinspection PyUnusedLocal
    def g(t, y):
        b1, b2, b3, b4, b5 = \
            0.949, 3.439, 18.72, 37.51, 1.169
        y1, y2, y3, y4 = y  # len(y) == 4
        return [
            b1 * y1 * (1 - y1 / b2),
            b3 * y1 * y4 / (b4 + y4) - 0.9802 * b5 * y2, b5 * y2,
            -1.011 * b3 * y1 * y4 / (b4 + y4)
        ]

    p1.setLabel('bottom', text='t, h')

    y0 = [0.5, 0, 0, 50.0]
    y_t = np.empty([20, len(y0)])
    time_series = [time_interval[0]]
    y_t[0, :] = y0

    r = ode(lambda t, y: g(t, y))
    r.set_initial_value(y0, time_interval[0])
    r.set_integrator('dopri5', nsteps=1)
    # Add the legend before plotting, for it to pick up
    # all the curves names and properties.
    p1.setLimits(xMin=0, yMin=0, yMax=60)
    p1.addLegend()

    curves = [None] * len(y0)
    curve_names = ['y' + str(it) for it in range(len(y0))]
    for j, item_j in enumerate(y0):
        pen_color = random_color()
        symbol_color = random_color()
        symbol = random_symbol()
        curves[j] = p1.plot(name=curve_names[j],
                            pen=pen_color,
                            symbolBrush=symbol_color,
                            symbol=symbol,
                            size=0.2)

    # For updating, pass y_t and time_series by reference
    # y_t: Already a mutable object (numpy array)
    # time_series: Mutable object also
    r.set_solout(lambda t_l, y_l: plot_successful_integration_step(
        t_l, y_l, curves, y_t, time_series, time_interval[1], timer))
    timer.timeout.connect(lambda: r.integrate(time_interval[1]))
    timer.connected = True
    timer.start(50)
    def __init__(self, pid_controller):
        super().__init__(pid_controller)
        self.running = False
        self.det_done_flag = False
        self.move_done_flag = False
        self.timeout_scan_flag = False

        self.curr_time = time.perf_counter()

        self.lsqe = LSqEllipse()

        self.phases = np.zeros((100, ))
        self.curr_phase = 0
        self.curr_position = 0

        self.dock_calib = Dock('Calibration')
        widget_calib = QtWidgets.QWidget()
        self.viewer_calib = Viewer1D(widget_calib)
        widget_ellipse = QtWidgets.QWidget()
        self.viewer_ellipse = Viewer1D(widget_ellipse)
        self.viewer_ellipse.show_data([np.zeros((10, )), np.zeros((10, ))])
        self.dock_calib.addWidget(widget_calib)
        self.dock_calib.addWidget(widget_ellipse, row=0, col=1)
        self.pid_controller.dock_area.addDock(self.dock_calib)
        self.dock_calib.float()

        self.timer = QTimer()
        self.timer.setSingleShot(True)
        self.timer.timeout.connect(self.timeout)
예제 #14
0
 def __init__(self, *args, **kwargs):
     self.tab = kwargs.pop("tab", None)
     self.main = kwargs.pop("main", None)
     self.automaticDraw = True
     Dock.__init__(self, *args, **kwargs) 
     
     self.dockArea = GoodnessDock.GoodnessTab(main = self.main, tab = self, tabName = "goodnessTab")  
     self.addWidget(self.dockArea)
예제 #15
0
 def __init_radial_widget__(self):
     self.radial_profile = RadialProfileWidget(
         self.get_lower_connector('RadialProfileWidget'), self)
     dock = Dock('Radial Profile')
     dock.addWidget(self.radial_profile)
     self.addDock(dock, position='bottom')
     self.radial_profile.update_image()
     self.radial_profile_dock = dock
예제 #16
0
 def __init_angular_widget__(self):
     self.angular_profile = AngularProfileWidget(
         self.get_lower_connector('AngularProfileWidget'), self)
     dock = Dock('Angular Profile')
     dock.addWidget(self.angular_profile)
     self.addDock(dock, position='bottom')
     self.angular_profile.update_profile()
     self.angular_profile_dock = dock
예제 #17
0
 def __init_interpolate_widget__(self):
     self.interpolate_view = InterpolateImageWidget(
         self.get_lower_connector('InterpolateImageWidget'), self)
     dock = Dock('Interpolate')
     dock.addWidget(self.interpolate_view)
     self.addDock(dock, position='right')
     self.interpolate_view.update_image()
     self.interpolation_dock = dock
예제 #18
0
    def __init__(self, *args, **kwargs):
        self.tab = kwargs.pop("tab", None)
        self.main = kwargs.pop("main", None)
        self.automaticDraw = True

        Dock.__init__(self, self.name(), **kwargs)
        self.imv = MyImageView()
        self.imv.setContentsMargins(2, 2, 2, 2)
        self.addWidget(self.imv)
예제 #19
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)
예제 #20
0
 def __init__(self, *args, **kwargs):
     self.tab = kwargs.pop("tab", None)
     self.main = kwargs.pop("main", None)
     self.automaticDraw = True
     
     Dock.__init__(self, *args, **kwargs)
     
     self._dockarea = IterationsDock.Tab(main = self.main, tab = self, tabName = "IterationsTab")  
     self.addWidget(self._dockarea)
예제 #21
0
def gui_docks_p4_03_04(d_area, timer, title=None):
    d1 = Dock('A<<==>>B<<==>>C', size=(1, 1), closable=True)
    p1 = pg.PlotWidget(name='Plot 1')
    d1.addWidget(p1)
    d_area.addDock(d1, 'right')
    timer.stop()
    if timer.connected:
        # Qt objects can have several connected slots.
        # Not disconnecting them all causes previously
        # running processes to continue when restarted.
        timer.timeout.disconnect()

    time_interval = [0, 25000]

    # noinspection PyUnusedLocal
    def g(t, y):
        k1, k2, kc1, kc2 = 0.001, 0.01, 0.8, 0.6
        ca, cb, cc = y  # len(y) == 3
        return [
            -k1 * (ca - cb / kc1),
            +k1 * (ca - cb / kc1) - k2 * (cb - cc / kc2), +k2 * (cb - cc / kc2)
        ]

    p1.setLabel('bottom', text='t, h')

    y0 = [1.0, 0, 0]
    y_t = np.empty([20, len(y0)])
    time_series = [time_interval[0]]
    y_t[0, :] = y0

    r = ode(lambda t, y: g(t, y))
    r.set_initial_value(y0, time_interval[0])
    r.set_integrator('dopri5', nsteps=1)
    # Add the legend before plotting, for it to pick up
    # all the curves names and properties.
    p1.setLimits(xMin=0, yMin=0, yMax=1)
    p1.addLegend()

    curves = [None] * len(y0)
    for j, item_j in enumerate(y0):
        pen_color = random_color()
        symbol_color = random_color()
        symbol = random_symbol()
        curves[j] = p1.plot(name=string.ascii_uppercase[j],
                            pen=pen_color,
                            symbolBrush=symbol_color,
                            symbol=symbol,
                            size=0.2)

    # For updating, pass y_t and time_series by reference
    # y_t: Already a mutable object (numpy array)
    # time_series: Mutable object also
    r.set_solout(lambda t_l, y_l: plot_successful_integration_step(
        t_l, y_l, curves, y_t, time_series, time_interval[1], timer))
    timer.timeout.connect(lambda: r.integrate(time_interval[1]))
    timer.connected = True
    timer.start(50)
예제 #22
0
 def __init__(self, *args, **kwargs):
     self.tab = kwargs.pop("tab", None)
     self.main = kwargs.pop("main", None)
     self.automaticDraw = True
     
     Dock.__init__(self, self.name(), **kwargs)   
     self.imv = MyImageView()
     self.imv.setContentsMargins(2, 2, 2, 2)
     self.addWidget(self.imv)
예제 #23
0
        def __init__(self, area):
            self.area = area
            self.detector_modules = None
            self.ui = UI()
            self.dock = Dock('2D scan', size=(500, 300), closable=False)

            form = QtWidgets.QWidget()
            self.ui.scan2D_graph = Viewer2D(form)
            self.dock.addWidget(form)
            self.area.addDock(self.dock)
예제 #24
0
 def onAddPlot(self):
     name, ok = QtGui.QInputDialog.getText(self, 'Plot Name', 'Please enter a plot name: ')
     if ok and name!= 'Autoload':
         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}
예제 #25
0
 def create_dock(self):
     area = DockArea()
     self.obj_graph['param']['dock'] = Dock("setting parameters")
     self.obj_graph['plot']['dock'] = Dock("graphic 1")
     self.obj_graph['plot2']['dock'] = Dock("graphic 2")
     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)
    def _add_btn_layout(self):
        # add a DockArea for buttons
        area = DockArea()
        dock = Dock("Functions")
        area.addDock(dock)
        area.show()

        self.vlayout.addWidget(area, 1, 1)
        btn_layout = pg.LayoutWidget()
        dock.addWidget(btn_layout)
        self.btn_layout = btn_layout
 def add_image_plot_with_axes(self, dock_name, diag_name, func, x_axis,
                              y_axis):
     dock = Dock(dock_name, size=(400, 400))
     self.addDock(dock)
     dock.addWidget(
         ImagePlot(self.server,
                   diag_name,
                   self.base_path,
                   func,
                   x_axis=x_axis,
                   y_axis=y_axis))
예제 #28
0
    def test_dockarea(self, qtbot):
        area = gutils.DockArea()
        dock1 = Dock('test1')
        dock2 = Dock('tes2')
        area.addDock(dock1)
        area.addDock(dock2)

        area.dock_signal.connect(self.track_signal)
        area.moveDock(dock2, 'below', dock1)
        QtWidgets.QApplication.processEvents()
        assert self.moved is True
예제 #29
0
 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 )
예제 #30
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)
    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)
예제 #32
0
파일: test.py 프로젝트: Simske/exostriker
 def __init__(self, window, dock_area):
     self.testing = 0
     self.pen = pg.mkPen(color='y')
     """Setup the UI"""
     self.window = window
     self.dock_area = dock_area
     self.window.setCentralWidget(self.dock_area)
     self.spec_dock = []
     self.spec_dock.append(
         Dock("Spectro 1", size=(1200, 600), autoOrientation=False))
     self.spec_dock.append(
         Dock("Spectro 2", size=(1200, 600), autoOrientation=False))
     self.dock_area.addDock(self.spec_dock[0], "top")
     self.dock_area.addDock(self.spec_dock[1], "below", self.spec_dock[0])
예제 #33
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_())
예제 #34
0
 def __init__(self, *args, **kwargs):
     self.tab = kwargs.pop("tab", None)
     self.main = kwargs.pop("main", None)
     self.automaticDraw = True
     
     Dock.__init__(self, *args, **kwargs)   
     self.plt = pg.PlotWidget()
     self.plt.addLegend()
     
     wrapWidget = QtGui.QWidget(self)
     wrapLayout = QtGui.QGridLayout(wrapWidget)
     wrapLayout.addWidget(self.plt, 0, 0, 1, 1)
     wrapWidget.setContentsMargins(2, 2, 2, 2)
     self.addWidget(wrapWidget)
예제 #35
0
    def add_plot_dock(self, depth, widget):
        dock = Dock(depth, size=(1,1), closable=False, autoOrientation=False)
        split_dock_widget = SplitDockWidget(widget)

        ### Connect signals ###
        self.s.x_range_updated.connect(widget.set_x_range)
        self.s.y_range_updated.connect(widget.set_y_range)
        widget.s.title_updated.connect(dock.setTitle)

        if settings.annotation_on:
            self.toggle_annotation.toggled.connect(split_dock_widget.toggle_second_widget)

        dock.addWidget(split_dock_widget)
        self.selected_depths[depth] = dock       
예제 #36
0
 def __init__(self, *args, **kwargs):
     self.tab = kwargs.pop("tab", None)
     self.main = kwargs.pop("main", None)
     self.automaticDraw = False
     Dock.__init__(self, *args, **kwargs)   
     self.plt = pg.PlotWidget()
     
     self._controlsWidget = QtGui.QWidget(self)
     self._controlsLayout = QtGui.QVBoxLayout(self._controlsWidget)
     self._buttonsWidget = QtGui.QWidget(self._controlsWidget)
     self._buttonsLayout = QtGui.QHBoxLayout(self._buttonsWidget)
     self._processFramesButton = QtGui.QPushButton("Process frames", self._buttonsWidget)
     self._processFramesButton.setIcon(QtGui.QIcon(":/16x16/16x16/Play_16x16.png"))
     self._processFramesButton.pressed.connect(self.tab._ProcessFramesPressed)
     self._framesFrom = QtGui.QSpinBox(self._buttonsWidget)
     self._framesFrom.setEnabled(False)
     self._framesTo = QtGui.QSpinBox(self._buttonsWidget)
     self._studyName = QtGui.QLineEdit(self._buttonsWidget)
     self._studyName.setText("test study")
     self._studyName.setFixedWidth(120)
     self._saveResultsButton = QtGui.QPushButton("Save", self._buttonsWidget)
     self._saveResultsButton.setIcon(QtGui.QIcon(":/16x16/16x16/Save_16x16.png"))
     self._saveResultsButton.pressed.connect(self.tab._SaveResults)
     
     self._buttonsLayout.addWidget(QtGui.QLabel("Study name: "))
     self._buttonsLayout.addWidget(self._studyName)
     self._buttonsLayout.addWidget(QtGui.QLabel("From: "))
     self._buttonsLayout.addWidget(self._framesFrom)
     self._buttonsLayout.addWidget(QtGui.QLabel("To: "))
     self._buttonsLayout.addWidget(self._framesTo)
     self._buttonsLayout.addWidget(self._processFramesButton)
     self._buttonsLayout.addWidget(self._saveResultsButton)
     spacerItem = QtGui.QSpacerItem(20, 20, QtGui.QSizePolicy.Expanding, \
                                        QtGui.QSizePolicy.Minimum)
     self._buttonsLayout.addItem(spacerItem)
     
     # Progress bar
     self._resultsProgressBar = QtGui.QProgressBar(self._controlsWidget)
     self._resultsProgressBar.setEnabled(True)
     self._resultsProgressBar.setProperty("value", 0)
     
     # Parent layout
     self._controlsLayout.addWidget(self._buttonsWidget)
     self._controlsLayout.addWidget(self.plt)
     self._controlsLayout.addWidget(self._resultsProgressBar)
     self.addWidget(self._controlsWidget)
     
     # Variables
     self._allLocsNotPostprocessed = []
예제 #37
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}
예제 #38
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}
예제 #39
0
 def check_dock(self):
     if self.plot is not None:
         self.plot.setParent(None)
     self.plot = self.plot_type()()
     if self.dock is None:
         self.dock = Dock(self.name(), widget=self.plot)
         win.outputs_dock_area.addDock(self.dock)
     else:
         self.dock.addWidget(self.plot)
예제 #40
0
 def __init__(self, *args, **kwargs):
     self.tab = kwargs.pop("tab", None)
     self.main = kwargs.pop("main", None)
     self.automaticDraw = False
     Dock.__init__(self, *args, **kwargs)   
     self.plt = pg.PlotWidget()
     
     self._controlsWidget = QtGui.QWidget(self)
     self._controlsLayout = QtGui.QGridLayout(self._controlsWidget)
     self._buttonsWidget = QtGui.QWidget(self._controlsWidget)
     self._buttonsLayout = QtGui.QHBoxLayout(self._buttonsWidget)
     self._processFramesButton = QtGui.QPushButton("Update", self._buttonsWidget)
     self._processFramesButton.setIcon(QtGui.QIcon(":/16x16/16x16/Play_16x16.png"))
     self._processFramesButton.pressed.connect(self._ProcessFramesPressed)
     self._buttonsLayout.addWidget(self._processFramesButton)
     spacerItem = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Expanding, \
                                        QtGui.QSizePolicy.Minimum)
     self._buttonsLayout.addItem(spacerItem)
     self._controlsLayout.addWidget(self._buttonsWidget, 0, 0, 1, 1)
     self._controlsLayout.addWidget(self.plt, 1, 0, 1, 1)
     self.addWidget(self._controlsWidget)
    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)))
예제 #42
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        
예제 #43
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)
예제 #44
0
	def load_protocol(self, path):
		lua = lupa.LuaRuntime(attribute_handlers=(getter, setter))
		self.lua = lua
		lua.globals()["flow"] = flow
		lua.globals()["channels"] = self.context.get_channels()
		lua.globals()["context"] = self.context
		source = open(path).read()

		try:
			lua.execute(source)
			self.guiBlocks = lua.eval('setup()')
			#lua.eval('gui()')
		except Exception as e:
			print ('Lua Exception occured: ', e, type(e))
			raise

		for block in self.guiBlocks:
			dock = Dock(block.name)
			dock.addWidget(block.widget())
			self.dockarea.addDock(dock)

		if 'doc_config' in lua.globals():
			self.restore_layout()
예제 #45
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
예제 #46
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
예제 #47
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
    def setup_widgets(self, parent, name):
        dock_area = DockArea()
        parent.addTab(dock_area, name)

        # Occupancy Docks
        self.occupancy_images = []

        for plane in range(3):  # Loop over 3 * 2 plot widgets
            # Dock left
            dock_occcupancy = Dock("Occupancy plane %d" % 2 * plane, size=(100, 200))
            dock_area.addDock(dock_occcupancy)
            occupancy_graphics = pg.GraphicsLayoutWidget()  # Plot docks
            occupancy_graphics.show()
            view = occupancy_graphics.addViewBox()
            self.occupancy_images.append(pg.ImageItem(border='w'))
            view.addItem(self.occupancy_images[2 * plane])
            view.setRange(QtCore.QRectF(0, 0, 80, 336))
            dock_occcupancy.addWidget(occupancy_graphics)

            # Dock right
            dock_occcupancy_2 = Dock("Occupancy plane %d" % (2 * plane + 1), size=(100, 200))
            dock_area.addDock(dock_occcupancy_2, 'right', dock_occcupancy)  
            occupancy_graphics = pg.GraphicsLayoutWidget()  # Plot docks
            occupancy_graphics.show()
            view = occupancy_graphics.addViewBox()
            self.occupancy_images.append(pg.ImageItem(border='w'))
            view.addItem(self.occupancy_images[2 * plane + 1])
            view.setRange(QtCore.QRectF(0, 0, 80, 336))
            dock_occcupancy_2.addWidget(occupancy_graphics)

        # dock_event_status = Dock("Event status", size=(400, 400))
        # dock_trigger_status = Dock("Trigger status", size=(400, 400))

        # dock_area.addDock(dock_trigger_status, 'above', dock_service_records)
        # dock_area.addDock(dock_event_status, 'above', dock_trigger_status)
        dock_status = Dock("Status", size=(800, 40))
        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')
        self.noisy_checkbox = QtGui.QCheckBox('Mask noisy pixels')
        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.noisy_checkbox, 0, 7, 0, 1)
        layout.addWidget(self.reset_button, 0, 8, 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)))
        self.noisy_checkbox.stateChanged.connect(lambda value: self.send_command('MASK %d' % value))

#         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)

        self.plot_delay = 0
예제 #49
0
class OutputItem(GroupItemChild):
    def __init__(self, group):
        super(OutputItem, self).__init__("Output_1", [
            ("simulation", group.setup.sims_item, group.setup.sims_item.items_list()[0].name()),
            ("mode", group.setup.modes_item, group.setup.modes_item.items_list()[0].name()),
            ("report type", ["Wigner", "Expect-XYZ"], "Wigner"),
            ("wigner range", float, 5),
            ("wigner resolution", int, 100),
        ], group)

        self.context_menu.add_action("Re-Compute", self.compute)
        self.data = None
        self.dock = None
        self.plot = None

    def compute(self):
        win.set_status("Computing Output %s" % self.name())
        output_steps = []
        if self.report_type == "Wigner":
            dx = self.wigner_range
            nx = self.wigner_resolution
            axis = linspace(-dx, dx, nx)
            step_function = lambda state: wigner(state, axis, axis)
        else:
            dim = self.mode.dimension
            a = destroy(dim)
            ad = a.dag()
            ops = [a + ad, 1j*(a - ad), a*ad]
            step_function = lambda state: [expect(op, state) for op in ops]

        n_states = len(self.simulation.states)
        for i, s in enumerate(self.simulation.states):
            output_steps.append(step_function(s.ptrace(self.mode.tensor_index())))
            win.set_progress(100*float(i)/n_states)
        win.set_progress(0)
        win.set_status("")

        if output_steps:
            self.data = np.array(output_steps)
            if self.report_type == "Wigner":
                self.plot_wigner()
            elif self.report_type == "Expect-XYZ":
                self.plot_xyz()

    def plot_type(self):
        return {
            "Wigner": MyImageView,
            "Expect-XYZ": TimePlot,
        }[self.report_type]

    def check_dock(self):
        if self.plot is not None:
            self.plot.setParent(None)
        self.plot = self.plot_type()()
        if self.dock is None:
            self.dock = Dock(self.name(), widget=self.plot)
            win.outputs_dock_area.addDock(self.dock)
        else:
            self.dock.addWidget(self.plot)

    def plot_wigner(self):
        if not isinstance(self.plot, ImageView):
            self.check_dock()
        self.plot.setImage(self.data, xvals=array(self.simulation.times))

    # TODO: Bloch/XYZ plot output implementation
    def plot_xyz(self):
        if not isinstance(self.plot, PlotWidget):
            self.check_dock()
        self.plot.clear()
        self.plot.add_line()
        self.plot.addLegend()
        for trace, name, pen in zip(self.data.transpose(), 'XYZ', pen_generator()):
            self.plot.plot(self.simulation.times, trace, pen=pen, name=name)
예제 #50
0
class OnlineMonitorApplication(pg.Qt.QtGui.QMainWindow):
    app_name = 'Online Monitor'

    def __init__(self, config_file, loglevel='INFO'):
        super(OnlineMonitorApplication, self).__init__()
        utils.setup_logging(loglevel)
        logging.debug("Initialize online monitor with configuration in %s", config_file)
        self.configuration = utils.parse_config_file(config_file, expect_receiver=True)
        self.setup_style()
        self.setup_widgets()
        self.receivers = self.start_receivers()

    def closeEvent(self, event):
        super(OnlineMonitorApplication, self).closeEvent(event)
        self.stop_receivers()
        settings.set_window_geometry(self.geometry().getRect())

    def setup_style(self):
        self.setWindowTitle(self.app_name)
        stored_windows_geometry = settings.get_window_geometry()
        if stored_windows_geometry:
            self.setGeometry(pg.Qt.QtCore.QRect(*stored_windows_geometry))
        # Fore/Background color
        pg.setConfigOption('background', 'w')
        pg.setConfigOption('foreground', 'k')
        # Enable antialiasing for prettier plots
        pg.setConfigOptions(antialias=True)

    def start_receivers(self):
        receivers = []
        try:
            self.configuration['receiver']
        except KeyError:
            return receivers
        if self.configuration['receiver']:
            logging.info('Starting %d receivers', len(self.configuration['receiver']))
            for (receiver_name, receiver_settings) in self.configuration['receiver'].items():
                receiver_settings['name'] = receiver_name
                receiver = utils.load_receiver(receiver_settings['kind'], base_class_type=Receiver, *(), **receiver_settings)
                receiver.setup_widgets(self.tab_widget, name=receiver_name)
                receiver.start()
                receivers.append(receiver)
            return receivers

    def on_tab_changed(self, value):
        for index, actual_receiver in enumerate(self.receivers, start=1):  # First index is status tab widget
            actual_receiver.active(True if index == value else False)

    def stop_receivers(self):
        if self.receivers:
            logging.info('Stopping %d receivers', len(self.receivers))
            for receiver in self.receivers:
                receiver.shutdown()

    def setup_widgets(self):
        # Main window with Tab widget
        self.tab_widget = Qt.QTabWidget()
        self.setCentralWidget(self.tab_widget)
        self.setup_status_widget(self.tab_widget)
        self.tab_widget.currentChanged.connect(self.on_tab_changed)

    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
예제 #51
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
import numpy as np
import pyqtgraph as pg
from pyqtgraph.ptime import time
from pyqtgraph.dockarea import DockArea, Dock

pg.setConfigOption('background', 'w')
pg.setConfigOption('foreground', 'k')

app = QtGui.QApplication([])
win = QtGui.QMainWindow()
area = DockArea()
win.setCentralWidget(area)
win.resize(1000,500)
win.setWindowTitle('pyqtgraph example: dockarea')

d1 = Dock("Dock 1", size=(500,300))
d2 = Dock("Dock 2", size=(500,300))

area.addDock(d1, 'left')      ## place d1 at left edge of dock area (it will fill the whole space since there are no other docks yet)
area.addDock(d2, 'right')   

for e in sorted(dir(pg.PlotWidget().plotItem)):
    print e
    
# p=pg.plot()
# for e in sorted(dir(p)):
#     print e
    
w=pg.PlotWidget()
w.setWindowTitle('pyqtgraph example: PlotSpeedTest')
w.setRange(QtCore.QRectF(0, -20, 5000, 30)) 
예제 #53
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)
예제 #54
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
예제 #55
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)
예제 #56
0
class SegmentInfoDockArea(DockArea):
    segid2treenode = WeakValueDictionary()

    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

    def updatePropertiesTableData(self, objwithprops, cleartable=False):
        if cleartable:
            self.properties_table.clear()
            self.properties_table.horizontalHeader().setResizeMode(
                QtGui.QHeaderView.Stretch)
            self.properties_table.setData(objwithprops.propertiesTableData())
        else:
            i=0
            for v in objwithprops.propertiesTableData().values():
                self.properties_table.setRow(i,v)
                i+=1

    #
    # Signal Handlers
    #

    def handleProjectChange(self, project):
        self.project_tree.clear()
        self.segid2treenode.clear()
        # Create Project Tree Node
        projecttreeitem = QtGui.QTreeWidgetItem([project.name])
        projecttreeitem._pydat = proxy(project.segmenttree)
        self.segid2treenode[project.segmenttree.id] = projecttreeitem
        self.project_tree.addTopLevelItem(projecttreeitem)

        for seg in project.segmenttree.children:
            self.handleSegmentCreated(seg)


    def handleSegmentCreated(self, segment):
        #print '>>TREE.handleSegmentCreated:',segment
        self.doNotSetActiveObject = True
        segindex = segment.parent.getChildIndex(segment)
        parent_tree_node = self.segid2treenode[segment.parent.id]
        #parent_tree_node = self.project_tree.topLevelItem(0)
        segtreeitem = QtGui.QTreeWidgetItem([segment.name])
        self.segid2treenode[segment.id] = segtreeitem
        segtreeitem._pydat = proxy(segment)
        parent_tree_node.insertChild(segindex, segtreeitem)
        #for i in self.project_tree.selectedItems():
        #    i.setSelected(False)
        #segtreeitem.setSelected(True)
        self.project_tree.setCurrentItem(segtreeitem)
        #print '<< TREE.handleSegmentCreated'
        self.doNotSetActiveObject = False

        for seg in segment.children:
            self.handleSegmentCreated(seg)

    def handleSegmentRemoved(self, segment, segment_index):
        self.doNotSetActiveObject = True
        parent_tree_node = self.segid2treenode[segment.parent.id]
        segmenttreeitem = parent_tree_node.child(segment_index)
        parent_tree_node.removeChild(segmenttreeitem)
        self.doNotSetActiveObject = False
        if MarkWriteMainWindow.instance():
            MarkWriteMainWindow.instance().setActiveObject(segment.parent)

    def handleActiveObjectChanged(self,activeobj, prevactiveobj):
        #if activeobj != prevactiveobj:
        #    print "Active Obj Changed:",activeobj, prevactiveobj
        if activeobj:
            self.updatePropertiesTableData(activeobj, activeobj!=prevactiveobj)

        if activeobj != prevactiveobj:
            if not isinstance(activeobj,PenDataSegmentCategory):
                #print "Deselecting Tree Node.."
                # set root node as current, otherwise if user tries to press on
                # prev selected segment, tree change event will not fire.
                if self.segid2treenode.has_key(0):
                    self.project_tree.setCurrentItem(self.segid2treenode[0])
                self.project_tree.clearSelection()
                #self.project_tree.setCurrentItem(None)
            else:
                #print "Settting tree node",activeobj,self.segid2treenode[activeobj.id]
                self.project_tree.setCurrentItem(self.segid2treenode[activeobj.id])

    def rightClickTreeEvent(self, *args, **kwargs):
        # Show Segment name editing dialog
        segment = MarkWriteMainWindow.instance().activeobject
        #print "rightClickTreeEvent:",segment
        if segment:
            if isinstance(segment, PenDataSegmentCategory):
                if segment.locked is False:
                    tag, ok = showSegmentNameDialog(
                        MarkWriteMainWindow.instance().predefinedtags, default=segment.name)
                    if len(tag) > 0 and ok:
                        segment.name = tag
                        self.project_tree.selectedItems()[0].setText(0,
                                                                     segment.name)


    def currentTreeItemChangedEvent(self, *args, **kwargs):
        current_tree_item, old_tree_widget = args
        #print ">> currentTreeItemChangedEvent:",current_tree_item, old_tree_widget
#        print "  selected items:",self.project_tree.selectedItems()
        try:
            if current_tree_item is None:
                #passing in not obj sets activeObject to project.selectedtimeregion
                MarkWriteMainWindow.instance().setActiveObject()
            elif self.doNotSetActiveObject is False:
                self.project_tree.setCurrentItem(current_tree_item)
                selectedsegment = current_tree_item._pydat
                if selectedsegment.isRoot():
                    ao=MarkWriteMainWindow.instance().setActiveObject()
                else:
                    ao=MarkWriteMainWindow.instance().setActiveObject(selectedsegment)
                #print "Set active object:",ao
        except Exception, e:
            #import traceback
            #traceback.print_exc()
            self.properties_table.clear()