Ejemplo n.º 1
0
    def setup(self):

        self.settings.New('rebin', dtype=bool, initial=False)
        self.settings.New('rebin_time',
                          dtype=int,
                          initial=4,
                          unit='ps',
                          choices=tuple(4 * 2**np.arange(0, 10)))

        self.settings.rebin.add_listener(self.on_rebin)
        self.settings.rebin_time.add_listener(self.on_rebin)

        # settings from file
        self.settings.New('sample', dtype=str, ro=True)
        self.settings.New('elapsed_meas_time', dtype=float, unit='ms', ro=True)
        self.settings.New('Tacq', dtype=float, unit='s', ro=True)
        self.settings.New('Resolution', dtype=float, unit='ps', ro=True)
        self.settings.New('count_rate0', dtype=float, unit='Hz', ro=True)
        self.settings.New('count_rate1', dtype=float, unit='Hz', ro=True)

        self.ui = self.dockarea = dockarea.DockArea()

        self.setdock = self.dockarea.addDock(name='Settings',
                                             position='left',
                                             widget=self.settings.New_UI())

        self.graph_layout = pg.GraphicsLayoutWidget()
        self.plotdock = self.dockarea.addDock(name='Picoharp Histogram',
                                              position='right',
                                              widget=self.graph_layout)

        self.plot = self.graph_layout.addPlot()
        self.plotdata = self.plot.plot(pen='r')
        self.plot.setLogMode(False, True)
Ejemplo n.º 2
0
    def __init__(self, model, parent=None):
        QtWidgets.QDialog.__init__(self, parent)
        self.model = model

        loadUi(get_resource("gacos_correction.ui"), baseinstance=self)
        self.closeButton.setIcon(self.style().standardIcon(
            QtWidgets.QStyle.SP_DialogCloseButton))

        self.gacos_plot = self.GACOSPlot(model, self)
        self.dockarea = dockarea.DockArea(self)

        self.dockarea.addDock(
            dockarea.Dock(
                "GACOS.get_correction()",
                widget=self.gacos_plot,
                size=(4, 4),
                autoOrientation=False,
            ),
            position="left",
        )

        self.horizontalLayoutPlot.addWidget(self.dockarea)
        self.loadGrids.released.connect(self.load_grids)
        self.toggleGACOS.released.connect(self.toggle_gacos)
        self.update_widgets()
    def setup_figure(self):
        self.ui = self.dockarea = dockarea.DockArea()
        self.settings_dock = self.dockarea.addDock(
            name='Settings', position='top', widget=self.settings.New_UI())

        self.graph_layout = pg.GraphicsLayoutWidget()
        self.graph_dock = self.dockarea.addDock(
            name='plot',
            #position='below',
            relativeTo=self.settings_dock,
            widget=self.graph_layout)

        self.plot = self.graph_layout.addPlot(title='power history',
                                              labels={
                                                  'left':
                                                  'present/set voltage',
                                                  'bottom': 'time (a.u)'
                                              })

        self.plot_line = self.plot.plot([1, 2, 3])

        self.graph_layout.nextRow()

        self.plot_err = self.graph_layout.addPlot(title='err')
        self.err_plotline = self.plot_err.plot()

        self.graph_layout.nextRow()

        self.plot_pos = self.graph_layout.addPlot(title='pos')
        self.pos_plotline = self.plot_pos.plot()
Ejemplo n.º 4
0
    def _add_dock(self, title="Dock", size=(500, 200), position="bottom"):
        if self.area is None:
            self.area = dockarea.DockArea()
            self.win.setCentralWidget(self.area)

        d = dockarea.Dock(title, size=size)
        self.area.addDock(d, position)
        logger.debug("Function _add_dock: " + repr(d))
Ejemplo n.º 5
0
 def __init__(self, vehicle):
     super(PlotHandler, self).__init__()
     pg.setConfigOptions(antialias=True)
     self.vehicle = vehicle
     self.app = qtgqt.QtGui.QApplication([])
     self.area = darea.DockArea()
     self.win = qtgqt.QtGui.QMainWindow()
     self.rospack = rospkg.RosPack()
     self.win.move
Ejemplo n.º 6
0
    def setup(self):
        self.ui = self.dockarea = dockarea.DockArea()

        self.iv_layout = pg.GraphicsLayoutWidget()
        self.iv_dock = self.dockarea.addDock(name='IV curve',
                                             widget=self.iv_layout)

        self.iv_plot = self.iv_layout.addPlot()
        self.iv_plot.setLabel('bottom', 'Voltage', units='V')
        self.iv_plot.setLabel('left', 'Current', units='Amps')
        self.iv_plotdata = self.iv_plot.plot(y=[0, 2, 1, 3, 2])
Ejemplo n.º 7
0
    def __init__(self, *args, **kwargs):
        self._attrs.update({"servers": GUIServerLite})

        self.win = QtGui.QMainWindow()
        self.area = dock.DockArea()
        self.win.setCentralWidget(self.area)
        self.win.setWindowTitle("Super-duper Python Wavemeter Viewer!")

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

        self.place_channels()
        self.create_toolbars()
Ejemplo n.º 8
0
    def init_dock(self):
        '''Initialize the dock window.'''
        dock = QtGui.QDockWidget('Graphs', self)
        dock.setAllowedAreas(QtCore.Qt.BottomDockWidgetArea
                             | QtCore.Qt.LeftDockWidgetArea
                             | QtCore.Qt.RightDockWidgetArea)

        # .. Prepare the DockArea to be used with pyqtgraph.
        self.dock_area = da.DockArea()
        self.dock_area.setMinimumSize(QtCore.QSize(600, 500))

        dock.setWidget(self.dock_area)
        self.addDockWidget(QtCore.Qt.BottomDockWidgetArea, dock)
Ejemplo n.º 9
0
    def __init__(self):

        self.args = args = get_argparser().parse_args()
        init_logger_from_args(args)

        if args.log_to_file:
            log_file = pkg_resources.resource_filename("wand", "log.txt")
            fh = logging.FileHandler(log_file, mode="wt")
            fh.setLevel(logger.getEffectiveLevel())
            logger.addHandler(fh)
            logging.getLogger("qasync").addHandler(fh)
            sys.excepthook = lambda exc_type, exc_value, exc_traceback: \
                logger.exception("".join(
                    traceback.format_exception(exc_type,
                                               exc_value,
                                               exc_traceback)))

        self.config = load_config(args, "_gui")

        self.laser_db = {}
        self.freq_db = {}
        self.osa_db = {}
        self.subscribers = {}

        self.qapp = QtWidgets.QApplication(["WAnD"])
        self.loop = QEventLoop(self.qapp)
        asyncio.set_event_loop(self.loop)
        atexit.register(self.loop.close)

        # set program icon
        icon = QtGui.QIcon()
        icon.addFile(pkg_resources.resource_filename("wand", "wand.svg"))
        self.qapp.setWindowIcon(icon)

        # create main window
        self.win = MainWindow()
        self.area = dock.DockArea()
        self.win.setCentralWidget(self.area)
        self.win.setWindowTitle("Super-duper Python Wavemeter Viewer!")

        # populate GUI
        self.laser_displays = {}
        for row in self.config["layout"]:
            prev = None
            pos = 'bottom'
            for display_name in row:
                display = LaserDisplay(display_name, self)
                self.laser_displays.update({display.laser: display})
                self.area.addDock(display.dock, position=pos, relativeTo=prev)
                pos = 'right'
                prev = display.dock
Ejemplo n.º 10
0
 def setup(self):
     self.ui = self.dockarea = dockarea.DockArea()
     self.settings.New('sample', dtype=str, initial='', ro=True)
     self.settings.New('spec_min', dtype=float, initial=0, ro=True)
     self.settings.New('spec_max', dtype=float, initial=1, ro=True)
     self.settings.spec_max.add_listener(self.update_display)
     self.settings.spec_min.add_listener(self.update_display)
     self.settings_ui = self.settings.New_UI()
     self.dockarea.addDock(name='settings',
                           position='top',
                           widget=self.settings_ui)
     self.plot = pg.PlotWidget(title="Spectrum")
     self.dockarea.addDock(name='plot', widget=self.plot)
     self.plot_setup()
Ejemplo n.º 11
0
    def __init__(self, model, parent=None):
        QtWidgets.QDialog.__init__(self, parent)

        loadUi(get_resource("noise_dialog.ui"), baseinstance=self)
        self.closeButton.setIcon(self.style().standardIcon(
            QtWidgets.QStyle.SP_DialogCloseButton))
        self.setWindowFlags(QtCore.Qt.Window)

        self.noise_patch = self.NoisePlot(model)
        self.noise_synthetic = self.NoiseSyntheticPlot(model)

        colormap = KiteToolColormap(self.noise_patch)
        self.noise_synthetic.setGradientEditor(colormap)

        self.dockarea = dockarea.DockArea(self)

        self.dockarea.addDock(
            dockarea.Dock(
                "Covariance.noise_data",
                widget=self.noise_patch,
                size=(6, 6),
                autoOrientation=False,
            ),
            position="top",
        )

        self.dockarea.addDock(
            dockarea.Dock(
                "Covariance.syntheticNoise",
                widget=self.noise_synthetic,
                size=(6, 6),
                autoOrientation=False,
            ),
            position="bottom",
        )

        self.dockarea.addDock(
            dockarea.Dock(
                "Colormap",
                widget=colormap,
                size=(1, 1),
                autoOrientation=False,
            ),
            position="right",
        )
        self.horizontalLayoutPlot.addWidget(self.dockarea)

        self.resetSizeButton.released.connect(self.noise_synthetic.resetSize)
        self.anisotropicCB.toggled.connect(
            lambda b: self.noise_synthetic.enableAnisotropic(b))
Ejemplo n.º 12
0
 def addTempArea(self):
     """
     Re-implemenation using a subclass of QMainWindow to prevent
     closing of the docks
     """
     if self.home is None:
         area = da.DockArea(temporary=True, home=self)
         self.tempAreas.append(area)
         win = QMainWindow_unclosable()
         win.setCentralWidget(area)
         area.win = win
         win.show()
     else:
         area = self.home.addTempArea()
     #print "added temp area", area, area.window()
     return area
Ejemplo n.º 13
0
    def __init__(self, scene_proxy, parent=None):
        QtGui.QDialog.__init__(self, parent)

        cov_ui = path.join(path.dirname(path.realpath(__file__)),
                           'ui/covariance_matrix.ui')
        loadUi(cov_ui, baseinstance=self)
        self.closeButton.setIcon(self.style().standardPixmap(
                                 QtGui.QStyle.SP_DialogCloseButton))

        self.weight_matrix = self.MatrixPlot(scene_proxy)
        self.dockarea = dockarea.DockArea(self)
        self.dockarea.addDock(
            dockarea.Dock('Covariance.weight_matrix_focal',
                          widget=self.weight_matrix,
                          size=(4, 4),
                          autoOrientation=False,),
            position='left')
        self.horizontalLayoutPlot.addWidget(self.dockarea)
Ejemplo n.º 14
0
    def __init__(self, model, parent=None):
        QtGui.QDialog.__init__(self, parent)

        loadUi(get_resource('covariance_matrix.ui'), baseinstance=self)
        self.closeButton.setIcon(self.style().standardPixmap(
            QtGui.QStyle.SP_DialogCloseButton))

        self.weight_matrix = self.MatrixPlot(model)
        self.dockarea = dockarea.DockArea(self)

        self.dockarea.addDock(dockarea.Dock(
            'Covariance.weight_matrix_focal',
            widget=self.weight_matrix,
            size=(4, 4),
            autoOrientation=False,
        ),
                              position='left')

        self.horizontalLayoutPlot.addWidget(self.dockarea)
Ejemplo n.º 15
0
    def setup(self):
        
        #self.ui = self.splitter = QtWidgets.QSplitter()
        #self.ui.setLayout(QtWidgets.QVBoxLayout())
        self.ui = self.dockarea = dockarea.DockArea()
        self.imview = pg.ImageView()
        self.imview.getView().invertY(False) # lower left origin
        #self.splitter.addWidget(self.imview)
        self.dockarea.addDock(name='Image', widget=self.imview)
        self.graph_layout = pg.GraphicsLayoutWidget()
        #self.splitter.addWidget(self.graph_layout)
        self.dockarea.addDock(name='Spec Plot', widget=self.graph_layout)

        self.spec_plot = self.graph_layout.addPlot()
        self.rect_plotdata = self.spec_plot.plot()
        self.point_plotdata = self.spec_plot.plot(pen=(0,9))
        
        
        # Rectangle ROI
        self.rect_roi = pg.RectROI([20, 20], [20, 20], pen=(0,9))
        self.rect_roi.addTranslateHandle((0.5,0.5))        
        self.imview.getView().addItem(self.rect_roi)        
        self.rect_roi.sigRegionChanged[object].connect(self.on_change_rect_roi)
        
        # Point ROI
        self.circ_roi = pg.CircleROI( (0,0), (2,2) , movable=True, pen=(0,9))
        #self.circ_roi.removeHandle(self.circ_roi.getHandles()[0])
        h = self.circ_roi.addTranslateHandle((0.5,.5))
        h.pen = pg.mkPen('r')
        h.update()
        self.imview.getView().addItem(self.circ_roi)
        self.circ_roi.removeHandle(0)
        self.circ_roi_plotline = pg.PlotCurveItem([0], pen=(0,9))
        self.imview.getView().addItem(self.circ_roi_plotline) 
        self.circ_roi.sigRegionChanged[object].connect(self.on_update_circ_roi)
        
        self.hyperspec_data = None
        self.display_image = None
        self.spec_x_array = None
        
        self.scan_specific_setup()
Ejemplo n.º 16
0
    def __init__(self):
        """Core functions for display
        """
        self.app = QtGui.QApplication([])
        self.app_icon = QtGui.QIcon()
        self.app_icon.addFile(SCRIPT_DIR + '\\bolt-icon.png',
                              QtCore.QSize(128, 128))
        self.app.setWindowIcon(self.app_icon)

        self.window = QtGui.QMainWindow()
        self.area = qtdk.DockArea()

        self.window.setCentralWidget(self.area)
        self.window.resize(1000, 500)
        self.window.setWindowTitle('FLASH - LEGO 3D Printer Software')

        self.docks = []
        self.widgets = []
        self.premade_widgets = {}

        self.extruders = []
Ejemplo n.º 17
0
    def __init__(self, scene_proxy, parent=None):
        QtGui.QDialog.__init__(self, parent)

        cov_ui = path.join(path.dirname(path.realpath(__file__)),
                           'ui/noise_dialog.ui')
        loadUi(cov_ui, baseinstance=self)
        self.closeButton.setIcon(self.style().standardPixmap(
                                 QtGui.QStyle.SP_DialogCloseButton))
        self.setWindowFlags(QtCore.Qt.Window)

        self.noise_patch = self.NoisePlot(scene_proxy)
        self.noise_synthetic = self.NoiseSyntheticPlot(scene_proxy)

        colormap = QKiteToolColormap(self.noise_patch)
        self.noise_synthetic.setGradientEditor(colormap)

        self.dockarea = dockarea.DockArea(self)
        self.dockarea.addDock(
            dockarea.Dock('Covariance.noise_data',
                          widget=self.noise_patch,
                          size=(6, 6),
                          autoOrientation=False,),
            position='top')
        self.dockarea.addDock(
            dockarea.Dock('Covariance.syntheticNoise',
                          widget=self.noise_synthetic,
                          size=(6, 6),
                          autoOrientation=False,),
            position='bottom')
        self.dockarea.addDock(
            dockarea.Dock('Colormap',
                          widget=colormap,
                          size=(1, 1),
                          autoOrientation=False,),
            position='right')
        self.horizontalLayoutPlot.addWidget(self.dockarea)

        self.resetSizeButton.released.connect(self.noise_synthetic.resetSize)
        self.anisotropicCB.toggled.connect(
            lambda b: self.noise_synthetic.enableAnisotropic(b))
Ejemplo n.º 18
0
    def setup_gui(self):
        """Creates a DockArea and fills it with the Slm.options given

        For each option, it extracts the correct ui from gui by name, loads it into a widget and adds it to the DockArea

        :return:
        """
        uic.loadUi(os.path.join(os.path.dirname(__file__), 'ui_base.ui'), self)
        self.dockarea = dockarea.DockArea()
        self.splitter.insertWidget(0, self.dockarea)
        self.dockarea.show()  # Absolutely no idea why this is needed

        self.all_widgets = dict()
        self.all_docks = []
        for option in self.SLM.options:
            widget = getattr(gui, '%sUi' % option)(self)
            dock = dockarea.Dock(option)
            dock.addWidget(widget)
            self.dockarea.addDock(dock, 'bottom')
            self.all_widgets[option] = widget
            self.all_docks += [dock]
        self.make_pushButton.pressed.connect(self.make)
Ejemplo n.º 19
0
    def InitUI(self):
        """
        UI initialisation
        """

        QtGui.QApplication.setStyle(
            QtGui.QStyleFactory.create('plastique'))  #looks pretty!

        self.dockArea = da.DockArea()
        self.setCentralWidget(self.dockArea)

        self.logViewDock = LogViewDock(globalSession=self.globalSession,
                                       name='Log Book',
                                       size=(1, 1))
        self.logViewer = self.logViewDock.viewer
        self.logViewer.openLogbook()
        self.dockArea.addDock(self.logViewDock)

        self.analysisDock = AnalysisDock(name='Analysis',
                                         size=(1, 1),
                                         globalSession=self.globalSession)
        self.dockArea.addDock(self.analysisDock, 'right')
Ejemplo n.º 20
0
    def setup_ui(self):
        """
        """

        self.setLayout(QtGui.QVBoxLayout())

        self.area = dockarea.DockArea()
        self.layout().addWidget(self.area)

        self.dock_traj = dockarea.Dock("Trajectories Plot", size=(3, 12))
        self.dock_info = dockarea.Dock("Info Panel", size=(1, 12))
        self.dock_buttons = dockarea.Dock("Buttons",
                                          size=(3, 1),
                                          hideTitle=True)
        self.dock_status = dockarea.Dock("Status",
                                         size=(3, 0.5),
                                         hideTitle=True)
        self.area.addDock(self.dock_traj, 'left')
        self.area.addDock(self.dock_info, 'right', self.dock_traj)
        self.area.addDock(self.dock_buttons, 'bottom')
        self.area.addDock(self.dock_status, 'bottom')

        # Trajectory Plot Dock

        self.vb = DataSelectorViewBox()
        self.pw = pg.PlotWidget(viewBox=self.vb)
        self.vb.traj_widget = self
        self.dock_traj.addWidget(self.pw)
        self.dock_traj.layout.setContentsMargins(5, 5, 5, 5)

        self.dock_status.layout.setContentsMargins(5, 5, 5, 5)
        self.status = QtGui.QLabel(self)
        self.dock_status.addWidget(self.status)

        self.pw.scene().sigMouseMoved.connect(self.update_mouse_infos)

        self.setup_buttons()
        self.setup_menus()
Ejemplo n.º 21
0
    def __init__(self, model, parent=None):
        QtWidgets.QDialog.__init__(self, parent)
        self.model = model

        loadUi(get_resource("weight_matrix.ui"), baseinstance=self)
        self.closeButton.setIcon(self.style().standardIcon(
            QtWidgets.QStyle.SP_DialogCloseButton))

        self.weight_matrix = self.MatrixPlot(model, self)
        self.dockarea = dockarea.DockArea(self)

        self.dockarea.addDock(
            dockarea.Dock(
                "Covariance.weight_matrix_focal",
                widget=self.weight_matrix,
                size=(4, 4),
                autoOrientation=False,
            ),
            position="left",
        )

        self.horizontalLayoutPlot.addWidget(self.dockarea)
        self.model.sigCovarianceChanged.connect(self.updateMatrixButtons)
        self.model.sigCovarianceConfigChanged.connect(self.updateMatrixButtons)
Ejemplo n.º 22
0
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.setWindowTitle('Turbulence visualization GUI')
        self.resize(800, 600)

        dockArea = da.DockArea()
        self.setCentralWidget(dockArea)

        ## Create controlling dock
        controlDock = da.Dock('Parameters', size=(200, 600))
        dockArea.addDock(controlDock, 'left')
        # Although controlDock functions like a LayoutWidget already,
        # the margins don't behave nicely. Hence we use an extra middle hand
        #layout = pg.LayoutWidget()
        layout = QtGui.QBoxLayout(QtGui.QBoxLayout.TopToBottom)
        dummyWidget = QtGui.QWidget()
        dummyWidget.setLayout(layout)
        controlDock.addWidget(dummyWidget)
        layout.setAlignment(QtCore.Qt.AlignTop)

        # Add size controller
        layout.addWidget(SizeWidget())

        # Add generator controller
        layout.addWidget(GeneratorChoiceWidget())

        ## Create plotting dock
        volDock = da.Dock('Volumetric plot', size=(600, 800))
        dockArea.addDock(volDock, 'right')

        global volumetricPlot
        volumetricPlot = VolumetricPlot()
        self.volumetricPlot = volumetricPlot  # Store reference
        volDock.addWidget(volumetricPlot, 0, 0)

        # Set up transparency slider
        Tslider = QtGui.QSlider()
        Tslider.setMinimum(0)
        Tslider.setMaximum(255)
        Tslider.setValue(127)
        Tslider.valueChanged.connect(volumetricPlot.transparencyChanged)
        Tslider.sliderReleased.connect(volumetricPlot.updateVolumeData)
        volDock.addWidget(Tslider, 0, 1)

        Sslider = QtGui.QSlider()
        Sslider.setMinimum(0)
        Sslider.setMaximum(volumetricPlot.Nz)
        Sslider.setValue(volumetricPlot.sliceHeight)
        Sslider.valueChanged.connect(volumetricPlot.sliceHeightChanged)
        Sslider.sliderReleased.connect(volumetricPlot.sliceVolumeData)
        volDock.addWidget(Sslider, 0, 2)

        Pslider = QtGui.QSlider()
        Pslider.setMinimum(10)
        Pslider.setMaximum(150)
        Pslider.setValue(100)
        Pslider.valueChanged.connect(volumetricPlot.powerParamChanged)
        Pslider.sliderReleased.connect(volumetricPlot.updateVolumeData)
        volDock.addWidget(Pslider, 0, 3)

        self.show()
Ejemplo n.º 23
0
def respfunc_viewer(path):
    app = QtGui.QApplication([])
    pyqtgraph.setConfigOption("background", "w")
    pyqtgraph.setConfigOption("foreground", "k")

    win = QtGui.QMainWindow()
    win.setWindowTitle("MT response function data viewer")

    darea = dockarea.DockArea()
    w = QtGui.QWidget()
    win.setCentralWidget(darea)

    taglist = QtGui.QListWidget(win)
    taglist.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
    taglist_dock = dockarea.Dock("Tags")
    taglist_dock.addWidget(taglist)
    darea.addDock(taglist_dock)

    sitelist = QtGui.QListWidget()
    sitelist.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
    sitelist_dock = dockarea.Dock("Tree...")
    sitelist_dock.addWidget(sitelist)
    darea.addDock(sitelist_dock, "left", taglist_dock)

    resplot = pyqtgraph.PlotWidget()
    resplot_dock = dockarea.Dock("APPARENT RESISTIVITY")
    resplot_dock.addWidget(resplot)
    darea.addDock(resplot_dock, "left", sitelist_dock)

    phaseplot = pyqtgraph.PlotWidget()
    phaseplot_dock = dockarea.Dock("PHASE")
    phaseplot_dock.addWidget(phaseplot)
    darea.addDock(phaseplot_dock, "bottom", resplot_dock)

    default_pen = [[(255, 255, 255, 90)], dict(width=1)]
    select_pen = [["r"], dict(width=1.5)]
    skipflag_pen = [[(255, 255, 255, 30)], dict(width=0.5)]

    resplotitem = resplot.getPlotItem()
    phaseplotitem = phaseplot.getPlotItem()
    resplotitem.invertX(True)
    phaseplotitem.invertX(True)
    resplotitem.setLogMode(x=True, y=True)
    phaseplotitem.setLogMode(x=True, y=False)
    phaseplotitem.vb.setXLink(resplotitem.vb)
    resplotitem.setYRange(np.log10(0.1), np.log10(1000))
    phaseplotitem.setYRange(0, 90)

    resvb = resplotitem.vb
    phasevb = phaseplotitem.vb

    data = utils.AttrDict()

    tagfns = glob.glob(op.join(path, "*-cal.json"))
    tag2fn = {}
    fn2tag = {}
    sites = set()
    tagfns.sort()

    data = utils.AttrDict()
    with open(op.join(path, "maskedfreqs.json"), mode="r") as f:
        maskedfreqs = utils.read_json(f)
    maskedlines = utils.AttrDict()
    datasymbols = utils.AttrDict()

    psymbols = utils.AttrDict({
        "xy": dict(pen=None, symbol="o", symbolBrush="b"),
        "yx": dict(pen=None, symbol="s", symbolBrush="r")
    })
    plines = utils.AttrDict({"xy": dict(pen="b"), "yx": dict(pen="r")})

    plotpens = utils.AttrDict({
        "xy": "b",
        "yx": "r",
    })
    plotsymbols = utils.AttrDict({"xy": "o", "yx": "s"})

    def plot(tag):

        if not hasattr(datasymbols[tag], "res_xy"):
            datasymbols[tag].res_xy = pyqtgraph.PlotDataItem(
                data[tag].freqs, data[tag].res_xy, **psymbols.xy)
            datasymbols[tag].res_yx = pyqtgraph.PlotDataItem(
                data[tag].freqs, data[tag].res_yx, **psymbols.yx)
            datasymbols[tag].phase_xy = pyqtgraph.PlotDataItem(
                data[tag].freqs, data[tag].phase_xy, **psymbols.xy)
            datasymbols[tag].phase_yx = pyqtgraph.PlotDataItem(
                data[tag].freqs, data[tag].phase_yx, **psymbols.yx)

            maskedlines[tag].res_xy = pyqtgraph.PlotDataItem(
                data[tag].freqs, data[tag].res_xy, **plines.xy)
            maskedlines[tag].res_yx = pyqtgraph.PlotDataItem(
                data[tag].freqs, data[tag].res_yx, **plines.yx)
            maskedlines[tag].phase_xy = pyqtgraph.PlotDataItem(
                data[tag].freqs, data[tag].phase_xy, **plines.xy)
            maskedlines[tag].phase_yx = pyqtgraph.PlotDataItem(
                data[tag].freqs, data[tag].phase_yx, **plines.yx)

            resplotitem.addItem(datasymbols[tag].res_xy)
            resplotitem.addItem(datasymbols[tag].res_yx)
            resplotitem.addItem(maskedlines[tag].res_xy)
            resplotitem.addItem(maskedlines[tag].res_yx)

            phaseplotitem.addItem(datasymbols[tag].phase_xy)
            phaseplotitem.addItem(datasymbols[tag].phase_yx)
            phaseplotitem.addItem(maskedlines[tag].phase_xy)
            phaseplotitem.addItem(maskedlines[tag].phase_yx)

        for i, freq in enumerate(data[tag].freqs):
            if maskedfreqs[tag]["masks"][i] == 0:
                data[tag].freqs[i] = float(maskedfreqs[tag]["freqs"][i])
            else:
                data[tag].freqs[i] = np.nan

        maskedlines[tag].res_xy.setData(data[tag].freqs, data[tag].res_xy)
        maskedlines[tag].res_yx.setData(data[tag].freqs, data[tag].res_yx)
        maskedlines[tag].phase_xy.setData(data[tag].freqs, data[tag].phase_xy)
        maskedlines[tag].phase_yx.setData(data[tag].freqs, data[tag].phase_yx)

    progress = QtGui.QProgressDialog("Loading data...", "Abort", 0,
                                     len(tagfns), win)
    progress.setWindowModality(QtCore.Qt.WindowModal)

    for i, tagfn in enumerate(tagfns):
        progress.setValue(i)
        tag = op.basename(tagfn).replace("-cal.json", "")
        tag2fn[tag] = tagfn
        fn2tag[tagfn] = tag
        site = tag.split("-")[0]
        sites.add(site)
        data[tag] = utils.read_json(tagfn)
        if not tag in maskedfreqs:
            maskedfreqs[tag] = utils.AttrDict({
                "freqs":
                data[tag].freqs.copy(),
                "masks":
                np.empty_like(data[tag].freqs) * 0
            })

        if not tag in maskedlines:
            maskedlines[tag] = utils.AttrDict()
            datasymbols[tag] = utils.AttrDict()

        plot(tag)

        if progress.wasCanceled():
            break

    progress.setValue(len(tagfns))

    resfreqselect = pyqtgraph.LinearRegionItem([0, -1])
    phasefreqselect = pyqtgraph.LinearRegionItem([0, -1])
    resplotitem.addItem(resfreqselect)
    phaseplotitem.addItem(phasefreqselect)

    def res_region_moved():
        phasefreqselect.setRegion(resfreqselect.getRegion())

    def phase_region_moved():
        resfreqselect.setRegion(phasefreqselect.getRegion())

    resfreqselect.sigRegionChanged.connect(res_region_moved)
    phasefreqselect.sigRegionChanged.connect(phase_region_moved)

    def populate_tag_list(filter_sites=None):
        if filter_sites:
            tags = [
                t for t in tag2fn.keys() if t.split("-")[0] in filter_sites
            ]
        else:
            tags = sorted(tag2fn.keys())
        tags.sort()
        taglist.clear()
        for tag in tags:
            # print tag
            tagitem = QtGui.QListWidgetItem(taglist)
            tagitem.setText(tag)
        plot_per_tag_list()
        print

    def plot_per_tag_list():
        tags = [t.text() for t in taglist.selectedItems()]
        if not tags:
            tags = [
                t.text()
                for t in [taglist.item(i) for i in xrange(taglist.count())]
            ]

        for plotitemtag, tagitems in datasymbols.items():
            if plotitemtag in tags:
                for item_name, item in tagitems.items():
                    item.setSymbol(plotsymbols[item_name[-2:]])
                    # item.setPen(None)#plotpens[item_name[-2:]])
            else:
                for item in tagitems.values():
                    item.setSymbol(None)
                    # item.setPen(None)

        for plotitemtag, tagitems in maskedlines.items():
            if plotitemtag in tags:
                for item_name, item in tagitems.items():
                    item.setPen(plotpens[item_name[-2:]])
            else:
                for item in tagitems.values():
                    item.setPen(None)

    def selected_site_names():
        return [s.text() for s in sitelist.selectedItems()]

    def pick_site():
        newsites = selected_site_names()
        populate_tag_list(newsites)
        # plot_per_tag_list()

    def toggle_selected_mask(value):
        tags = [str(t.text()) for t in taglist.selectedItems()]
        log_mask_range = resfreqselect.getRegion()
        fmin = 10**log_mask_range[0]
        fmax = 10**log_mask_range[1]
        for tag in tags:
            for i, freq in enumerate(maskedfreqs[tag]["freqs"]):
                if freq >= fmin and freq <= fmax:
                    maskedfreqs[tag]["masks"][i] = value
            plot(tag)
        print log_mask_range, tags, "\n"

    disable = QtGui.QPushButton("&Delete selected frequencies")
    enable = QtGui.QPushButton("&Enable selected frequencies")
    sitelist_dock.addWidget(disable)
    sitelist_dock.addWidget(enable)
    disable.clicked.connect(lambda: toggle_selected_mask(1))
    enable.clicked.connect(lambda: toggle_selected_mask(0))

    # def generate_key_press_event_handler(self, vb, event):
    #     vb.keyPressEvent(self, event)
    #     if event.key() is Qt.Key_X:
    #         toggle_selected_mask(mode="xy")
    #     elif event.key() is Qt.Key_Y:
    #         toggle_selected_mask(mode="yx")

    # resplotitem.vb.keyPressEvent = lambda

    populate_tag_list()

    sites = sorted(list(sites))
    for site in sites:
        siteitem = QtGui.QListWidgetItem(sitelist)
        siteitem.setText(site)

    sitelist.itemSelectionChanged.connect(pick_site)
    taglist.itemSelectionChanged.connect(plot_per_tag_list)

    def cleanup():
        with open(op.join(path, "maskedfreqs.json"), mode="w") as f:
            utils.write_json(maskedfreqs, f)

    win.showMaximized()
    app.aboutToQuit.connect(cleanup)
    app.exec_()
Ejemplo n.º 24
0
    def setup(self):

        self.settings.New('drift_correct_type',
                          dtype=str,
                          initial='Pairwise',
                          choices=('Pairwise', 'Pairwise + Running Avg'))

        self.settings.New('drift_correct_adc_chan', dtype=int)

        self.settings.New('drift_correct', dtype=bool)
        self.settings.New('overwrite_alignment', dtype=bool)
        # if drift corrected datasets already exist, overwrite?

        self.settings.New('run_preprocess', dtype=bool)
        self.settings.get_lq('run_preprocess').add_listener(self.preprocess)

        self.settings.New('use_preprocess', dtype=bool, initial=True)
        self.settings.get_lq('use_preprocess').add_listener(self.load_new_data)

        self.settings.New('update_auger_map', dtype=bool, initial=False)
        self.settings.get_lq('update_auger_map').add_listener(
            self.update_current_auger_map)

        self.settings.New('equalize_detectors', dtype=bool)
        self.settings.New('normalize_by_pass_energy', dtype=bool)
        self.settings.New('spatial_smooth_sigma', dtype=float, vmin=0.0)
        self.settings.New('spectral_smooth_type',
                          dtype=str,
                          choices=['None', 'Gaussian', 'Savitzky-Golay'],
                          initial='None')
        self.settings.New('spectral_smooth_gauss_sigma', dtype=float, vmin=0.0)
        self.settings.New('spectral_smooth_savgol_width', dtype=int, vmin=0)
        self.settings.New('spectral_smooth_savgol_order',
                          dtype=int,
                          vmin=0,
                          initial=2)

        # Assume same tougaard parameters everywhere
        self.settings.New('subtract_tougaard', dtype=bool)
        self.settings.New('R_loss', dtype=float)
        self.settings.New('E_loss', dtype=float)

        auger_lqs = [
            'equalize_detectors', 'normalize_by_pass_energy',
            'spatial_smooth_sigma', 'spectral_smooth_type',
            'spectral_smooth_gauss_sigma', 'spectral_smooth_savgol_width',
            'spectral_smooth_savgol_order', 'subtract_tougaard', 'R_loss',
            'E_loss'
        ]

        # Link all the auger spectrum lqs to the update current auger map listener
        for alq in auger_lqs:
            self.settings.get_lq(alq).add_listener(
                self.update_current_auger_map)

        self.settings.New('ke0_start', dtype=float)
        self.settings.New('ke0_stop', dtype=float)
        self.settings.New('ke1_start', dtype=float)
        self.settings.New('ke1_stop', dtype=float)

        for lqname in ['ke0_start', 'ke0_stop', 'ke1_start', 'ke1_stop']:
            self.settings.get_lq(lqname).add_listener(
                self.on_change_ke_settings)

        # Subtract the B section (ke1_start through ke1_stop) by a power law fit
        self.settings.New('subtract_ke1',
                          dtype=str,
                          choices=['None', 'Linear', 'Power Law'],
                          initial='None')
        self.settings.get_lq('subtract_ke1').add_listener(
            self.update_current_auger_map)

        #Math mode now updates automatically on change
        self.settings.New('math_mode', dtype=str, initial='A')
        self.settings.get_lq('math_mode').add_listener(
            self.on_change_math_mode)

        self.settings.New('AB_mode',
                          dtype=str,
                          choices=['Mean', 'Integral'],
                          initial='Mean')
        self.settings.get_lq('AB_mode').add_listener(
            self.on_change_ke_settings)

        self.settings.New('spectrum_over_ROI', dtype=bool)
        self.settings.get_lq('spectrum_over_ROI').add_listener(
            self.on_change_spectrum_over_ROI)

        self.settings.New('analysis_over_spectrum', dtype=bool)
        self.settings.get_lq('analysis_over_spectrum').add_listener(
            self.update_current_auger_map)

        self.settings.New('mean_spectrum_only', dtype=bool, initial=False)
        self.settings.get_lq('mean_spectrum_only').add_listener(
            self.on_change_mean_spectrum_only)

        # Make plots on white background
        #pg.setConfigOption('background', 'w')
        #pg.setConfigOption('foreground', 'k')

        self.ui = self.dockarea = dockarea.DockArea()

        # List of settings to include in preprocessing tab
        names_prep = [
            'drift_correct_type', 'drift_correct_adc_chan', 'drift_correct',
            'overwrite_alignment', 'run_preprocess'
        ]

        self.setdock = self.dockarea.addDock(
            name='Settings',
            position='left',
            widget=self.settings.New_UI(exclude=names_prep))
        self.prepdock = self.dockarea.addDock(
            name='Preprocess',
            position='left',
            widget=self.settings.New_UI(include=names_prep))
        self.dockarea.moveDock(self.setdock, 'above', self.prepdock)

        # Images
        self.imview_sem0_stack = pg.ImageView()
        self.imview_sem0_stack.getView().invertY(False)  # lower left origin
        self.imdockA_stack = self.dockarea.addDock(
            name='SE2 Image Stack', widget=self.imview_sem0_stack)

        self.imview_sem1_stack = pg.ImageView()
        self.imview_sem1_stack.getView().invertY(False)  # lower left origin
        self.imdockB_stack = self.dockarea.addDock(
            name='InLens Image Stack',
            position='right',
            widget=self.imview_sem1_stack)

        self.imview_sem0 = pg.ImageView()
        self.imview_sem0.getView().invertY(False)  # lower left origin
        self.imdockA = self.dockarea.addDock(name='SE2 Mean Image',
                                             widget=self.imview_sem0)

        self.imview_sem1 = pg.ImageView()
        self.imview_sem1.getView().invertY(False)  # lower left origin
        self.imdockB = self.dockarea.addDock(name='InLens Mean Image',
                                             widget=self.imview_sem1)

        self.imview_auger = pg.ImageView()
        self.imview_auger.getView().invertY(False)  # lower left origin
        self.imdockAuger = self.dockarea.addDock(name='Auger Map',
                                                 widget=self.imview_auger)
        self.im_auger = self.imview_auger.getImageItem()

        # tab image and auger map docks
        self.dockarea.moveDock(self.imdockA_stack, 'above', self.imdockB_stack)
        self.dockarea.moveDock(self.imdockB, 'above', self.imdockA_stack)
        self.dockarea.moveDock(self.imdockA, 'above', self.imdockB)
        self.dockarea.moveDock(self.imdockAuger, 'above', self.imdockA)

        # Polygon ROI
        self.poly_roi = pg.PolyLineROI([[20, 0], [20, 20], [0, 20]],
                                       pen=pg.mkPen((255, 0, 0),
                                                    dash=[5, 5],
                                                    width=1.5),
                                       closed=True)
        #self.poly_roi = pg.RectROI([20, 20], [20, 20], pen=(0,9))
        #self.poly_roi = pg.CircleROI((0,0), (10,10) , movable=True, pen=(0,9))
        #self.poly_roi.addTranslateHandle((0.5,0.5))
        self.imview_auger.getView().addItem(self.poly_roi)
        self.poly_roi.sigRegionChanged[object].connect(self.on_change_roi)

        # Scalebar ROI
        self.scalebar = pg.LineROI([5, 5], [25, 5],
                                   width=0,
                                   pen=pg.mkPen(color=(255, 255, 0),
                                                width=4.5))
        self.imview_auger.getView().addItem(self.scalebar)

        # Create initial scalebar w/ text
        self.scale_text = pg.TextItem(color=(255, 255, 0), anchor=(0.5, 1))
        self.imview_auger.getView().addItem(self.scale_text)
        self.scale_text.setFont(pg.QtGui.QFont('Arial', pointSize=11))
        self.scalebar.sigRegionChanged[object].connect(self.on_change_scalebar)

        # Change handle colors so they don't appear by default, but do when hovered over
        scale_handles = self.scalebar.getHandles()
        scale_handles[0].currentPen.setColor(pg.mkColor(255, 255, 255, 0))
        scale_handles[1].currentPen.setColor(pg.mkColor(255, 255, 255, 0))
        # This disables the middle handle that allows line width change
        scale_handles[2].setOpacity(0.0)

        # Spectrum plot
        self.graph_layout = pg.GraphicsLayoutWidget()
        self.spec_plot = self.graph_layout.addPlot()
        self.legend = self.spec_plot.addLegend()
        self.spec_plot.setLabel('bottom', 'Electron Kinetic Energy')
        self.spec_plot.setLabel('left', 'Intensity (Hz)')
        #self.rect_plotdata = self.spec_plot.plot()
        #self.point_plotdata = self.spec_plot.plot(pen=(0,9))

        self.dockarea.addDock(name='Spec Plot',
                              position='bottom',
                              widget=self.graph_layout)

        self.lr0 = pg.LinearRegionItem(values=[0, 1],
                                       brush=QtGui.QBrush(
                                           QtGui.QColor(0, 0, 255, 50)))
        self.lr1 = pg.LinearRegionItem(values=[2, 3],
                                       brush=QtGui.QBrush(
                                           QtGui.QColor(255, 0, 0, 50)))

        for lr in (self.lr0, self.lr1):
            lr.setZValue(10)
            self.spec_plot.addItem(lr, ignoreBounds=True)
            lr.sigRegionChangeFinished.connect(self.on_change_regions)

        self.chan_plotlines = []
        # define plotline color scheme going from orange -> yellow -> green
        R = np.linspace(220, 0, 4)
        G = np.linspace(220, 100, 4)

        plot_colors = [(R[0], G[0], 0), (R[1], G[0], 0), (R[0], G[1], 0),
                       (R[2], G[0], 0), (R[0], G[2], 0), (R[3], G[0], 100),
                       (R[0], G[3], 0)]
        for ii in range(7):
            self.chan_plotlines.append(
                self.spec_plot.plot([0],
                                    pen=pg.mkPen(color=plot_colors[ii],
                                                 width=2),
                                    name='chan ' + str(ii),
                                    width=20))
        self.total_plotline = self.spec_plot.plot(pen=pg.mkPen(color=(0, 0, 0),
                                                               width=3),
                                                  name='mean')
def test_dockarea():
    a = da.DockArea()
    d1 = da.Dock("dock 1")
    a.addDock(d1, 'left')

    assert a.topContainer is d1.container()
    assert d1.container().container() is a
    assert d1.area is a
    assert a.topContainer.widget(0) is d1

    d2 = da.Dock("dock 2")
    a.addDock(d2, 'right')

    assert a.topContainer is d1.container()
    assert a.topContainer is d2.container()
    assert d1.container().container() is a
    assert d2.container().container() is a
    assert d2.area is a
    assert a.topContainer.widget(0) is d1
    assert a.topContainer.widget(1) is d2

    d3 = da.Dock("dock 3")
    a.addDock(d3, 'bottom')

    assert a.topContainer is d3.container()
    assert d2.container().container() is d3.container()
    assert d1.container().container() is d3.container()
    assert d1.container().container().container() is a
    assert d2.container().container().container() is a
    assert d3.container().container() is a
    assert d3.area is a
    assert d2.area is a
    assert a.topContainer.widget(0) is d1.container()
    assert a.topContainer.widget(1) is d3

    d4 = da.Dock("dock 4")
    a.addDock(d4, 'below', d3)

    assert d4.container().type() == 'tab'
    assert d4.container() is d3.container()
    assert d3.container().container() is d2.container().container()
    assert d4.area is a
    a.printState()

    # layout now looks like:
    #    vcontainer
    #        hcontainer
    #            dock 1
    #            dock 2
    #        tcontainer
    #            dock 3
    #            dock 4

    # test save/restore state
    state = a.saveState()
    a2 = da.DockArea()
    # default behavior is to raise exception if docks are missing
    with pytest.raises(Exception):
        a2.restoreState(state)

    # test restore with ignore missing
    a2.restoreState(state, missing='ignore')
    assert a2.topContainer is None

    # test restore with auto-create
    a2.restoreState(state, missing='create')
    assert a2.saveState() == state
    a2.printState()

    # double-check that state actually matches the output of saveState()
    c1 = a2.topContainer
    assert c1.type() == 'vertical'
    c2 = c1.widget(0)
    c3 = c1.widget(1)
    assert c2.type() == 'horizontal'
    assert c2.widget(0).name() == 'dock 1'
    assert c2.widget(1).name() == 'dock 2'
    assert c3.type() == 'tab'
    assert c3.widget(0).name() == 'dock 3'
    assert c3.widget(1).name() == 'dock 4'

    # test restore with docks already present
    a3 = da.DockArea()
    a3docks = []
    for i in range(1, 5):
        dock = da.Dock('dock %d' % i)
        a3docks.append(dock)
        a3.addDock(dock, 'right')
    a3.restoreState(state)
    assert a3.saveState() == state

    # test restore with extra docks present    
    a3 = da.DockArea()
    a3docks = []
    for i in [1, 2, 5, 4, 3]:
        dock = da.Dock('dock %d' % i)
        a3docks.append(dock)
        a3.addDock(dock, 'left')
    a3.restoreState(state)
    a3.printState()


    # test a more complex restore
    a4 = da.DockArea()
    state1 = {'float': [], 'main': 
        ('horizontal', [
            ('vertical', [
                ('horizontal', [
                    ('tab', [
                        ('dock', 'dock1', {}), 
                        ('dock', 'dock2', {}), 
                        ('dock', 'dock3', {}), 
                        ('dock', 'dock4', {})
                        ], {'index': 1}), 
                    ('vertical', [
                        ('dock', 'dock5', {}), 
                        ('horizontal', [
                            ('dock', 'dock6', {}), 
                            ('dock', 'dock7', {})
                            ], {'sizes': [184, 363]})
                        ], {'sizes': [355, 120]})
                    ], {'sizes': [9, 552]})
                ], {'sizes': [480]}), 
            ('dock', 'dock8', {})
            ], {'sizes': [566, 69]})
        }

    state2 = {'float': [], 'main': 
        ('horizontal', [
            ('vertical', [
                ('horizontal', [
                    ('dock', 'dock2', {}), 
                    ('vertical', [
                        ('dock', 'dock5', {}), 
                        ('horizontal', [
                            ('dock', 'dock6', {}), 
                            ('dock', 'dock7', {})
                            ], {'sizes': [492, 485]})
                        ], {'sizes': [936, 0]})
                    ], {'sizes': [172, 982]})
                ], {'sizes': [941]}), 
            ('vertical', [
                ('dock', 'dock8', {}), 
                ('dock', 'dock4', {}), 
                ('dock', 'dock1', {})
                ], {'sizes': [681, 225, 25]})
            ], {'sizes': [1159, 116]})}

    a4.restoreState(state1, missing='create')
    # dock3 not mentioned in restored state; stays in dockarea by default
    c, d = a4.findAll()
    assert d['dock3'].area is a4
    
    a4.restoreState(state2, missing='ignore', extra='float')
    a4.printState()

    c, d = a4.findAll()
    # dock3 not mentioned in restored state; goes to float due to `extra` argument
    assert d['dock3'].area is not a4
    assert d['dock1'].container() is d['dock4'].container() is d['dock8'].container()
    assert d['dock6'].container() is d['dock7'].container()
    assert a4 is d['dock2'].area is d['dock2'].container().container().container()
    assert a4 is d['dock5'].area is d['dock5'].container().container().container().container()

    # States should be the same with two exceptions:
    #   dock3 is in a float because it does not appear in state2
    #   a superfluous vertical splitter in state2 has been removed
    state4 = a4.saveState()
    state4['main'][1][0] = state4['main'][1][0][1][0]
    assert clean_state(state4['main']) == clean_state(state2['main'])
    def initializePlot(self):
        self.first_run = True
        self.paused = False
        self.win = qtgqt.QtGui.QMainWindow()
        area = darea.DockArea()
        white = (200, 200, 200)
        red = (200, 66, 66)
        redB = pg.mkBrush(200, 66, 66, 200)
        blue = (6, 106, 166)
        blueB = pg.mkBrush(6, 106, 166, 200)
        green = (16, 200, 166)
        greenB = pg.mkBrush(16, 200, 166, 200)
        yellow = (244, 244, 160)
        yellowB = pg.mkBrush(244, 244, 160, 200)
        darkyellow = (224, 166, 58)
        darkyellowB = pg.mkBrush(224, 166, 58, 200)
        self.win.setWindowTitle("Leaf dashboard 2")
        self.win.resize(700, 600)
        self.win.setCentralWidget(area)
        dock1 = darea.Dock("Pose",
                           size=(1, 1))  # give this dock minimum possible size
        dock2 = darea.Dock("Lidar",
                           size=(1, 1))  # give this dock minimum possible size
        dock3 = darea.Dock("Camera",
                           size=(1, 1))  # give this dock minimum possible size
        dock4 = darea.Dock("dock N",
                           size=(500, 400))  # size is only a suggestion
        area.addDock(dock1, "left")
        area.addDock(dock2, "bottom", dock1)
        area.addDock(dock3, "bottom", dock2)
        area.addDock(dock4, "bottom", dock3)
        widg1 = pg.LayoutWidget()
        dhLabel = qtgqt.QtGui.QLabel("Duro:")
        dhLabel.setStyleSheet("background-color: rgb(4, 4, 4);")
        dhLabel.setAlignment(pg.QtCore.Qt.AlignRight)
        dhLabel.setFixedSize(50, 25)
        dsLabel = qtgqt.QtGui.QLabel("Duro:")
        dsLabel.setStyleSheet("background-color: rgb(4, 4, 4);")
        dsLabel.setAlignment(pg.QtCore.Qt.AlignRight)
        dsLabel.setFixedSize(50, 25)
        nhLabel = qtgqt.QtGui.QLabel("Nova:")
        nhLabel.setStyleSheet("background-color: rgb(4, 4, 4);")
        nhLabel.setAlignment(pg.QtCore.Qt.AlignRight)
        nsLabel = qtgqt.QtGui.QLabel("Nova:")
        nsLabel.setStyleSheet("background-color: rgb(4, 4, 4);")
        nsLabel.setAlignment(pg.QtCore.Qt.AlignRight)
        self.duroHzLabel = qtgqt.QtGui.QLabel(" **.* Hz")
        self.duroRtkLabel = qtgqt.QtGui.QLabel("+++")
        self.novaHzLabel = qtgqt.QtGui.QLabel("  **.* Hz")
        self.novaRtkLabel = qtgqt.QtGui.QLabel("+++")
        self.pausePoseBtn = qtgqt.QtGui.QPushButton("Pause")
        self.savePoseBtn = qtgqt.QtGui.QPushButton("Save")
        self.speedLabel = qtgqt.QtGui.QLabel(" **.* Km/h")
        self.angleLabel = qtgqt.QtGui.QLabel(" **.* rad")
        widg1.addWidget(dhLabel, row=1, col=0)
        widg1.addWidget(dsLabel, row=1, col=2)
        widg1.addWidget(nhLabel, row=2, col=0)
        widg1.addWidget(nsLabel, row=2, col=2)
        widg1.addWidget(self.duroHzLabel, row=1, col=1)
        widg1.addWidget(self.duroRtkLabel, row=1, col=3)
        widg1.addWidget(self.novaHzLabel, row=2, col=1)
        widg1.addWidget(self.novaRtkLabel, row=2, col=3)
        widg1.addWidget(self.speedLabel, row=3, col=1)
        widg1.addWidget(self.angleLabel, row=3, col=3)
        widg1.addWidget(self.savePoseBtn, row=4, col=1)
        widg1.addWidget(self.pausePoseBtn, row=4, col=3)
        widg1.setStyleSheet(
            "background-color: rgb(40, 44, 52); color: rgb(171, 178, 191);")
        dock1.setStyleSheet("background-color: rgb(18, 20, 23);")
        self.novaHzLabel.setStyleSheet(
            "font-family: Monospace; font: 20pt; color: rgb(6, 106, 166)")
        self.novaRtkLabel.setStyleSheet(
            "font-family: Monospace; font: 20pt; color: rgb(6, 106, 166)")
        self.duroHzLabel.setStyleSheet(
            "font-family: Monospace; font: 20pt; color: rgb(224, 166, 58)")
        self.duroRtkLabel.setStyleSheet(
            "font-family: Monospace; font: 20pt; color: rgb(244, 166, 58)")
        self.angleLabel.setStyleSheet(
            "font-family: Monospace; font: 20pt; color: rgb(200, 200, 200)")
        self.speedLabel.setStyleSheet(
            "font-family: Monospace; font: 20pt; color: rgb(200, 200, 200)")
        self.pauseLidarBtn = qtgqt.QtGui.QPushButton("Pause")
        dock1.addWidget(widg1)
        self.state = None
        self.widg2 = pg.PlotWidget(title="Gps difference")
        self.widg2.setAspectLocked(True)
        self.pltGpsOdom = pg.ScatterPlotItem(size=10,
                                             pen=pg.mkPen(None),
                                             brush=blueB)
        self.pltLeafOdom = pg.ScatterPlotItem(size=10,
                                              pen=pg.mkPen(None),
                                              brush=redB)
        self.widg2.showGrid(x=True, y=True)
        self.widg2.addItem(self.pltGpsOdom)
        self.widg2.addItem(self.pltLeafOdom)
        dock4.addWidget(self.widg2)
        self.pauseCamBtn = qtgqt.QtGui.QPushButton("Pause")
        self.pausePoseBtn.clicked.connect(self.pausePose)
        self.pauseLidarBtn.clicked.connect(self.pauseLidar)
        self.pauseCamBtn.clicked.connect(self.pauseCamera)
        self.savePoseBtn.clicked.connect(self.saveToCsv)
        self.tGps = pg.TextItem(text="Gps", color=blue)
        self.tLeaf = pg.TextItem(text="Leaf odom", color=red)
        self.tstart = pg.TextItem(text="Start", color=white)
        widg2 = pg.LayoutWidget()
        widg3 = pg.LayoutWidget()

        shLabel = qtgqt.QtGui.QLabel("Sick:")
        shLabel.setStyleSheet("background-color: rgb(4, 4, 4);")
        shLabel.setAlignment(pg.QtCore.Qt.AlignRight)
        shLabel.setFixedSize(50, 25)
        olhLabel = qtgqt.QtGui.QLabel("OusterLeft:")
        olhLabel.setStyleSheet("background-color: rgb(4, 4, 4);")
        olhLabel.setAlignment(pg.QtCore.Qt.AlignRight)
        olhLabel.setFixedSize(80, 25)
        orhLabel = qtgqt.QtGui.QLabel("OusterRight:")
        orhLabel.setStyleSheet("background-color: rgb(4, 4, 4);")
        orhLabel.setAlignment(pg.QtCore.Qt.AlignRight)
        orhLabel.setFixedSize(95, 25)
        vlhLabel = qtgqt.QtGui.QLabel("VeloLeft:")
        vlhLabel.setStyleSheet("background-color: rgb(4, 4, 4);")
        vlhLabel.setAlignment(pg.QtCore.Qt.AlignRight)
        vrhLabel = qtgqt.QtGui.QLabel("VeloRight:")
        vrhLabel.setStyleSheet("background-color: rgb(4, 4, 4);")
        vrhLabel.setAlignment(pg.QtCore.Qt.AlignRight)
        self.sickHzLabel = qtgqt.QtGui.QLabel(" **.* Hz")
        self.sickHzLabel.setStyleSheet(
            "font-family: Monospace; font: 20pt; color: rgb(224, 166, 58)")
        self.ousterLefHzLabel = qtgqt.QtGui.QLabel(" **.* Hz")
        self.ousterLefHzLabel.setStyleSheet(
            "font-family: Monospace; font: 20pt; color: rgb(16, 200, 166)")
        self.ousterRigHzLabel = qtgqt.QtGui.QLabel(" **.* Hz")
        self.ousterRigHzLabel.setStyleSheet(
            "font-family: Monospace; font: 20pt; color: rgb(16, 200, 166)")
        self.veloLefHz = qtgqt.QtGui.QLabel(" **.* Hz")
        self.veloLefHz.setStyleSheet(
            "font-family: Monospace; font: 20pt; color: rgb(200, 66, 66)")
        self.veloRigHz = qtgqt.QtGui.QLabel(" **.* Hz")
        self.veloRigHz.setStyleSheet(
            "font-family: Monospace; font: 20pt; color: rgb(200, 66, 66)")
        widg2.addWidget(shLabel, row=1, col=0)
        widg2.addWidget(olhLabel, row=1, col=2)
        widg2.addWidget(orhLabel, row=1, col=4)
        widg2.addWidget(vlhLabel, row=2, col=2)
        widg2.addWidget(vrhLabel, row=2, col=4)
        widg2.addWidget(self.sickHzLabel, row=1, col=1)
        widg2.addWidget(self.ousterLefHzLabel, row=1, col=3)
        widg2.addWidget(self.ousterRigHzLabel, row=1, col=5)
        widg2.addWidget(self.veloLefHz, row=2, col=3)
        widg2.addWidget(self.veloRigHz, row=2, col=5)
        widg2.addWidget(self.pauseLidarBtn, row=3, col=5)

        dock2.setStyleSheet("background-color: rgb(18, 20, 23);")
        dock3.setStyleSheet("background-color: rgb(18, 20, 23);")
        widg2.setStyleSheet(
            "background-color: rgb(40, 44, 52); color: rgb(171, 178, 191);")
        widg3.setStyleSheet(
            "background-color: rgb(40, 44, 52); color: rgb(171, 178, 191);")
        zhLabel = qtgqt.QtGui.QLabel("Zed:")
        zhLabel.setStyleSheet("background-color: rgb(4, 4, 4);")
        zhLabel.setAlignment(pg.QtCore.Qt.AlignRight)
        zhLabel.setFixedSize(50, 25)
        zrLabel = qtgqt.QtGui.QLabel("Resolution:")
        zrLabel.setStyleSheet("background-color: rgb(4, 4, 4);")
        zrLabel.setAlignment(pg.QtCore.Qt.AlignRight)
        zrLabel.setFixedSize(80, 25)
        self.zedHzLabel = qtgqt.QtGui.QLabel(" **.* Hz")
        self.zedHzLabel.setStyleSheet(
            "font-family: Monospace; font: 20pt; color: rgb(123, 64, 133)")
        self.zedRzLabel = qtgqt.QtGui.QLabel("100x100 px")
        self.zedRzLabel.setStyleSheet(
            "font-family: Monospace; font: 20pt; color: rgb(123, 64, 133)")
        widg3.addWidget(zhLabel, row=1, col=0)
        widg3.addWidget(zrLabel, row=1, col=2)
        widg3.addWidget(self.zedHzLabel, row=1, col=1)
        widg3.addWidget(self.zedRzLabel, row=1, col=3)
        widg3.addWidget(self.pauseCamBtn, row=2, col=3)
        dock2.addWidget(widg2)
        dock3.addWidget(widg3)
        self.drawCircle(self.widg2)
        self.win.show()
Ejemplo n.º 27
0
def main():
    args = get_argparser().parse_args()
    init_logger(args)

    app = QtGui.QApplication([])
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)
    atexit.register(lambda: loop.close())

    smgr = StateManager(args.db_file)

    schedule_ctl = AsyncioClient()
    loop.run_until_complete(
        schedule_ctl.connect_rpc(args.server, args.port_control,
                                 "master_schedule"))
    atexit.register(lambda: schedule_ctl.close_rpc())

    win = MainWindow(app, args.server)
    area = dockarea.DockArea()
    smgr.register(area)
    smgr.register(win)
    win.setCentralWidget(area)
    status_bar = QtGui.QStatusBar()
    status_bar.showMessage("Connected to {}".format(args.server))
    win.setStatusBar(status_bar)

    d_explorer = ExplorerDock(win, status_bar, schedule_ctl)
    smgr.register(d_explorer)
    loop.run_until_complete(
        d_explorer.sub_connect(args.server, args.port_notify))
    atexit.register(lambda: loop.run_until_complete(d_explorer.sub_close()))

    d_datasets = DatasetsDock(win, area)
    smgr.register(d_datasets)
    loop.run_until_complete(
        d_datasets.sub_connect(args.server, args.port_notify))
    atexit.register(lambda: loop.run_until_complete(d_datasets.sub_close()))

    if os.name != "nt":
        d_ttl_dds = MonInj()
        loop.run_until_complete(d_ttl_dds.start(args.server, args.port_notify))
        atexit.register(lambda: loop.run_until_complete(d_ttl_dds.stop()))

    if os.name != "nt":
        area.addDock(d_ttl_dds.dds_dock, "top")
        area.addDock(d_ttl_dds.ttl_dock, "above", d_ttl_dds.dds_dock)
        area.addDock(d_datasets, "above", d_ttl_dds.ttl_dock)
    else:
        area.addDock(d_datasets, "top")
    area.addDock(d_explorer, "above", d_datasets)

    d_schedule = ScheduleDock(status_bar, schedule_ctl)
    loop.run_until_complete(
        d_schedule.sub_connect(args.server, args.port_notify))
    atexit.register(lambda: loop.run_until_complete(d_schedule.sub_close()))

    d_log = LogDock()
    smgr.register(d_log)
    loop.run_until_complete(d_log.sub_connect(args.server, args.port_notify))
    atexit.register(lambda: loop.run_until_complete(d_log.sub_close()))

    dataset_db = AsyncioClient()
    loop.run_until_complete(
        dataset_db.connect_rpc(args.server, args.port_control,
                               "master_dataset_db"))
    atexit.register(lambda: dataset_db.close_rpc())

    def _set_dataset(k, v):
        asyncio.ensure_future(dataset_db.set(k, v))

    def _del_dataset(k):
        asyncio.ensure_future(dataset_db.delete(k))

    d_console = ConsoleDock(d_datasets.get_dataset, _set_dataset, _del_dataset)

    area.addDock(d_console, "bottom")
    area.addDock(d_log, "above", d_console)
    area.addDock(d_schedule, "above", d_log)

    smgr.load()
    smgr.start()
    atexit.register(lambda: loop.run_until_complete(smgr.stop()))
    win.show()
    loop.run_until_complete(win.exit_request.wait())
    def initializePlot(self):
        self.first_run = True
        self.win = qtgqt.QtGui.QMainWindow()
        area = darea.DockArea()
        white = (200, 200, 200)
        red = (200, 66, 66)
        redB = pg.mkBrush(200, 66, 66, 200)
        blue = (6, 106, 166)
        blueB = pg.mkBrush(6, 106, 166, 200)
        green = (16, 200, 166)
        greenB = pg.mkBrush(16, 200, 166, 200)
        yellow = (244, 244, 160)
        yellowB = pg.mkBrush(244, 244, 160, 200)
        darkyellow = (224, 166, 58)
        darkyellowB = pg.mkBrush(224, 166, 58, 200)
        self.win.setWindowTitle("Leaf control 1")
        self.win.setWindowIcon(
            qtgqt.QtGui.QIcon(
                self.rospack.get_path("ros_guis") + "/img/icon01.png"))
        self.win.resize(700, 600)
        self.win.setCentralWidget(area)
        dock1def = darea.Dock("Default",
                              size=(1,
                                    1))  # give this dock minimum possible size
        dock2oth = darea.Dock("Others",
                              size=(1,
                                    1))  # give this dock minimum possible size
        dock3ctr = darea.Dock("Control",
                              size=(1,
                                    1))  # give this dock minimum possible size
        dock4gps = darea.Dock("2 Gps visualization",
                              size=(500, 400))  # size is only a suggestion
        area.addDock(dock1def, "left")
        area.addDock(dock2oth, "bottom", dock1def)
        area.addDock(dock3ctr, "above", dock2oth)
        area.addDock(dock4gps, "bottom", dock3ctr)
        dhLabel = qtgqt.QtGui.QLabel("Duro:")
        dhLabel.setStyleSheet("background-color: rgb(4, 4, 4);")
        dhLabel.setAlignment(pg.QtCore.Qt.AlignRight)
        dhLabel.setFixedSize(50, 25)
        dsLabel = qtgqt.QtGui.QLabel("Duro:")
        dsLabel.setStyleSheet("background-color: rgb(4, 4, 4);")
        dsLabel.setAlignment(pg.QtCore.Qt.AlignRight)
        dsLabel.setFixedSize(50, 25)
        nhLabel = qtgqt.QtGui.QLabel("Nova:")
        nhLabel.setStyleSheet("background-color: rgb(4, 4, 4);")
        nhLabel.setAlignment(pg.QtCore.Qt.AlignRight)
        nsLabel = qtgqt.QtGui.QLabel("Nova:")
        nsLabel.setStyleSheet("background-color: rgb(4, 4, 4);")
        nsLabel.setAlignment(pg.QtCore.Qt.AlignRight)
        self.duroRtkLabel = qtgqt.QtGui.QLabel("+++")
        self.novaRtkLabel = qtgqt.QtGui.QLabel("+++")
        self.pauseSensorReadClickedBtn = qtgqt.QtGui.QPushButton("Pause")
        self.savePoseBtn = qtgqt.QtGui.QPushButton("Save")
        self.allSensorLaunchBtn = qtgqt.QtGui.QPushButton("Start AllSensor")
        self.tfSensorLaunchBtn = qtgqt.QtGui.QPushButton("Start TF")
        self.tfDuroLaunchBtn = qtgqt.QtGui.QPushButton("Start TF Duro")
        self.tfNovaLaunchBtn = qtgqt.QtGui.QPushButton("Start TF Nova")
        self.duroSensorLaunchBtn = qtgqt.QtGui.QPushButton("Start Duro GPS")
        self.novaSensorLaunchBtn = qtgqt.QtGui.QPushButton("Start Nova GPS")
        self.zedSensorLaunchBtn = qtgqt.QtGui.QPushButton("Start ZED camera")
        self.sickSensorLaunchBtn = qtgqt.QtGui.QPushButton("Start SICK")
        self.ousterLeftSensorLaunchBtn = qtgqt.QtGui.QPushButton(
            "Start left Ouster")
        self.ousterRightSensorLaunchBtn = qtgqt.QtGui.QPushButton(
            "Start right Ouster")
        self.veloLeftSensorLaunchBtn = qtgqt.QtGui.QPushButton(
            "Start left Velodyne")
        self.veloRightSensorLaunchBtn = qtgqt.QtGui.QPushButton(
            "Start right Velodyne")
        self.canSensorLaunchBtn = qtgqt.QtGui.QPushButton("Start CAN")
        self.radarSensorLaunchBtn = qtgqt.QtGui.QPushButton("Start Radar")
        self.mpcOnOffBtn = qtgqt.QtGui.QPushButton("Disable MPC")
        self.temporaryLaunchBtn = qtgqt.QtGui.QPushButton("Start temporary")
        self.loadWaypointBtn = qtgqt.QtGui.QPushButton("Load waypoints")
        self.saveWaypointBtn = qtgqt.QtGui.QPushButton("Save waypoints")
        self.carParamsBtn = qtgqt.QtGui.QPushButton("Publish car parameters")
        self.imuLaunchBtn = qtgqt.QtGui.QPushButton("Start IMU")
        self.odomLaunchBtn = qtgqt.QtGui.QPushButton("Start Odom")
        self.selectFileBtn = qtgqt.QtGui.QPushButton("...")
        self.selectFileBtn.setMaximumWidth(22)
        self.speedLabel = qtgqt.QtGui.QLabel(" **.* Km/h")
        self.isAutonomLabel = qtgqt.QtGui.QLabel("-")
        self.angleLabel = qtgqt.QtGui.QLabel(" **.* rad")
        self.csvLabel = qtgqt.QtGui.QLabel("none")
        self.csvLabel.setAlignment(pg.QtCore.Qt.AlignRight)
        self.csvTextbox = qtgqt.QtGui.QLineEdit()
        self.allSensorLaunched = False
        self.waypointLoaded = False
        self.waypointSaving = False
        self.tfLaunched = False
        self.tfSensorLaunched = False
        self.tfDuroLaunched = False
        self.tfNovaLaunched = False
        self.duroSensorLaunched = False
        self.novaSensorLaunched = False
        self.zedSensorLaunched = False
        self.sickSensorLaunched = False
        self.ousterLeftSensorLaunched = False
        self.ousterRightSensorLaunched = False
        self.veloLeftSensorLaunched = False
        self.veloRightSensorLaunched = False
        self.canSensorLaunched = False
        self.radarSensorLaunched = False
        self.temporaryLaunched = False
        self.imuLaunched = False
        self.carParamsLaunched = False
        self.odomLaunched = False
        self.mpcFollow = True
        widg1def = pg.LayoutWidget()
        widg1def.setStyleSheet(
            "background-color: rgb(40, 44, 52); color: rgb(171, 178, 191);")
        dock1def.setStyleSheet("background-color: rgb(18, 20, 23);")
        dock1def.addWidget(widg1def)
        self.novaRtkLabel.setStyleSheet(
            "font-family: Monospace; font: 20pt; color: rgb(6, 106, 166)")
        self.duroRtkLabel.setStyleSheet(
            "font-family: Monospace; font: 20pt; color: rgb(244, 166, 58)")
        self.angleLabel.setStyleSheet(
            "font-family: Monospace; font: 20pt; color: rgb(200, 200, 200)")
        self.speedLabel.setStyleSheet(
            "font-family: Monospace; font: 20pt; color: rgb(200, 200, 200)")
        self.isAutonomLabel.setStyleSheet(
            "font-family: Monospace; font: 20pt; color: rgb(200, 200, 200)")
        self.csvLabel.setStyleSheet("font: 10pt; color: rgb(244, 166, 58)")
        sickLabel = qtgqt.QtGui.QLabel("Sick:")
        sickLabel.setStyleSheet("background-color: rgb(4, 4, 4);")
        sickLabel.setAlignment(pg.QtCore.Qt.AlignRight)
        sickLabel.setFixedSize(50, 25)
        olhLabel = qtgqt.QtGui.QLabel("OusterLeft:")
        olhLabel.setStyleSheet("background-color: rgb(4, 4, 4);")
        olhLabel.setAlignment(pg.QtCore.Qt.AlignRight)
        olhLabel.setFixedSize(80, 25)
        orhLabel = qtgqt.QtGui.QLabel("OusterRight:")
        orhLabel.setStyleSheet("background-color: rgb(4, 4, 4);")
        orhLabel.setAlignment(pg.QtCore.Qt.AlignRight)
        orhLabel.setFixedSize(95, 25)
        vlhLabel = qtgqt.QtGui.QLabel("VeloLeft:")
        vlhLabel.setStyleSheet("background-color: rgb(4, 4, 4);")
        vlhLabel.setAlignment(pg.QtCore.Qt.AlignRight)
        vrhLabel = qtgqt.QtGui.QLabel("VeloRight:")
        vrhLabel.setStyleSheet("background-color: rgb(4, 4, 4);")
        vrhLabel.setAlignment(pg.QtCore.Qt.AlignRight)
        self.sickOkLabel = qtgqt.QtGui.QLabel("**")
        self.sickOkLabel.setStyleSheet(
            "font-family: Monospace; font: 20pt; color: rgb(224, 166, 58)")
        self.ousterLefLabel = qtgqt.QtGui.QLabel(" **")
        self.ousterLefLabel.setStyleSheet(
            "font-family: Monospace; font: 20pt; color: rgb(16, 200, 166)")
        self.ousterRigLabel = qtgqt.QtGui.QLabel(" **")
        self.ousterRigLabel.setStyleSheet(
            "font-family: Monospace; font: 20pt; color: rgb(16, 200, 166)")
        self.veloLef = qtgqt.QtGui.QLabel(" **")
        self.veloLef.setStyleSheet(
            "font-family: Monospace; font: 20pt; color: rgb(200, 66, 66)")
        self.veloRig = qtgqt.QtGui.QLabel(" **")
        self.veloRig.setStyleSheet(
            "font-family: Monospace; font: 20pt; color: rgb(200, 66, 66)")
        # default
        widg1def.addWidget(dsLabel, row=1, col=6)
        widg1def.addWidget(nsLabel, row=2, col=6)
        widg1def.addWidget(self.duroRtkLabel, row=1, col=7)
        widg1def.addWidget(self.novaRtkLabel, row=2, col=7)
        widg1def.addWidget(self.speedLabel, row=3, col=2)
        widg1def.addWidget(self.angleLabel, row=3, col=4)
        widg1def.addWidget(self.isAutonomLabel, row=4, col=4)
        widg1def.addWidget(self.pauseSensorReadClickedBtn, row=4, col=7)
        widg1def.addWidget(olhLabel, row=1, col=1)
        widg1def.addWidget(orhLabel, row=1, col=3)
        widg1def.addWidget(vlhLabel, row=2, col=1)
        widg1def.addWidget(vrhLabel, row=2, col=3)
        widg1def.addWidget(sickLabel, row=4, col=1)
        widg1def.addWidget(self.sickOkLabel, row=4, col=2)
        widg1def.addWidget(self.ousterLefLabel, row=1, col=2)
        widg1def.addWidget(self.ousterRigLabel, row=1, col=4)
        widg1def.addWidget(self.veloLef, row=2, col=2)
        widg1def.addWidget(self.veloRig, row=2, col=4)
        self.zedOkLabel = qtgqt.QtGui.QLabel("**")
        self.zedOkLabel.setStyleSheet(
            "font-family: Monospace; font: 20pt; color: rgb(123, 64, 133)")
        zhLabel = qtgqt.QtGui.QLabel("Zed:")
        zhLabel.setStyleSheet("background-color: rgb(4, 4, 4);")
        zhLabel.setAlignment(pg.QtCore.Qt.AlignRight)
        zhLabel.setFixedSize(50, 25)
        widg1def.addWidget(zhLabel, row=3, col=6)
        widg1def.addWidget(self.zedOkLabel, row=3, col=7)

        self.state = None
        self.widgGps = pg.PlotWidget(title="Gps difference")
        self.widgGps.setAspectLocked(True)
        self.pltGpsOdom = pg.ScatterPlotItem(size=10,
                                             pen=pg.mkPen(None),
                                             brush=blueB)
        self.pltDuroOrientation = pg.PlotCurveItem(
            pen=pg.mkPen(qtgqt.QtGui.QColor(244, 166, 58), width=6))
        self.pltNovaOrientation = pg.PlotCurveItem(
            pen=pg.mkPen(qtgqt.QtGui.QColor(200, 66, 66), width=8))
        self.pltLeafOdom = pg.ScatterPlotItem(size=10,
                                              pen=pg.mkPen(None),
                                              brush=redB)
        self.widgGps.showGrid(x=True, y=True)
        self.widgGps.addItem(self.pltGpsOdom)
        self.widgGps.addItem(self.pltNovaOrientation)
        self.widgGps.addItem(self.pltDuroOrientation)
        self.widgGps.addItem(self.pltLeafOdom)
        dock4gps.addWidget(self.widgGps)
        self.pauseSensorReadClickedBtn.clicked.connect(
            self.pauseSensorReadClicked)
        self.savePoseBtn.clicked.connect(self.saveToCsvClicked)
        self.allSensorLaunchBtn.clicked.connect(self.startAllSensorClicked)
        self.tfSensorLaunchBtn.clicked.connect(self.startTFClicked)
        self.tfDuroLaunchBtn.clicked.connect(self.tfDuroClicked)
        self.tfNovaLaunchBtn.clicked.connect(self.tfNovaClicked)
        self.zedSensorLaunchBtn.clicked.connect(self.zedSensorClicked)
        self.duroSensorLaunchBtn.clicked.connect(self.duroSensorClicked)
        self.novaSensorLaunchBtn.clicked.connect(self.novaSensorClicked)
        self.sickSensorLaunchBtn.clicked.connect(self.sickSensorClicked)
        self.ousterLeftSensorLaunchBtn.clicked.connect(
            self.ousterLeftSensorClicked)
        self.ousterRightSensorLaunchBtn.clicked.connect(
            self.ousterRightSensorClicked)
        self.veloLeftSensorLaunchBtn.clicked.connect(
            self.veloLeftSensorClicked)
        self.veloRightSensorLaunchBtn.clicked.connect(
            self.veloRightSensorClicked)
        self.canSensorLaunchBtn.clicked.connect(self.canSensorClicked)
        self.radarSensorLaunchBtn.clicked.connect(self.radarSensorClicked)
        self.mpcOnOffBtn.clicked.connect(self.mpcOnOffBtnClicked)
        self.temporaryLaunchBtn.clicked.connect(self.temporaryClicked)
        self.loadWaypointBtn.clicked.connect(self.loadCsvClicked)
        self.saveWaypointBtn.clicked.connect(self.saveCsvClicked)
        self.selectFileBtn.clicked.connect(self.selectCsvClicked)
        self.carParamsBtn.clicked.connect(self.carParamsClicked)
        self.imuLaunchBtn.clicked.connect(self.startImuClicked)
        self.odomLaunchBtn.clicked.connect(self.startOdomClicked)

        self.tGps = pg.TextItem(text="Gps", color=blue)
        self.tLeaf = pg.TextItem(text="Leaf odom", color=red)
        self.tstart = pg.TextItem(text="Start", color=white)

        dock2oth.setStyleSheet("background-color: rgb(18, 20, 23);")
        self.drawCircle(self.widgGps)
        # other controls
        widg2oth = pg.LayoutWidget()
        dock2oth.setStyleSheet("background-color: rgb(18, 20, 23);")
        widg2oth.setStyleSheet(
            "background-color: rgb(40, 44, 52); color: rgb(171, 178, 191);")
        widg2oth.addWidget(self.tfSensorLaunchBtn, row=1, col=1)
        widg2oth.addWidget(self.tfDuroLaunchBtn, row=1, col=2)
        widg2oth.addWidget(self.tfNovaLaunchBtn, row=1, col=3)
        widg2oth.addWidget(self.zedSensorLaunchBtn, row=2, col=1)
        widg2oth.addWidget(self.duroSensorLaunchBtn, row=2, col=2)
        widg2oth.addWidget(self.novaSensorLaunchBtn, row=2, col=3)
        widg2oth.addWidget(self.sickSensorLaunchBtn, row=3, col=1)
        widg2oth.addWidget(self.ousterLeftSensorLaunchBtn, row=3, col=2)
        widg2oth.addWidget(self.ousterRightSensorLaunchBtn, row=3, col=3)
        widg2oth.addWidget(self.canSensorLaunchBtn, row=4, col=1)
        widg2oth.addWidget(self.radarSensorLaunchBtn, row=5, col=1)
        widg2oth.addWidget(self.mpcOnOffBtn, row=5, col=3)
        widg2oth.addWidget(self.veloLeftSensorLaunchBtn, row=4, col=2)
        widg2oth.addWidget(self.veloRightSensorLaunchBtn, row=4, col=3)
        widg2oth.addWidget(self.temporaryLaunchBtn, row=5, col=2)
        widg2oth.addWidget(self.carParamsBtn, row=6, col=1)
        widg2oth.addWidget(self.imuLaunchBtn, row=6, col=2)
        widg2oth.addWidget(self.odomLaunchBtn, row=6, col=3)

        dock2oth.addWidget(widg2oth)

        # control
        widg3ctr = pg.LayoutWidget()
        dock3ctr.setStyleSheet("background-color: rgb(18, 20, 23);")
        widg3ctr.setStyleSheet(
            "background-color: rgb(40, 44, 52); color: rgb(171, 178, 191);")
        widg3ctr.addWidget(self.allSensorLaunchBtn, row=1, col=1)
        widg3ctr.addWidget(self.loadWaypointBtn, row=2, col=1)
        widg3ctr.addWidget(self.saveWaypointBtn, row=3, col=1)
        widg3ctr.addWidget(self.csvLabel, row=2, col=2)
        widg3ctr.addWidget(self.selectFileBtn, row=2, col=3)
        widg3ctr.addWidget(self.csvTextbox, row=3, col=2)
        dock3ctr.addWidget(widg3ctr)
        widg3ctr.addWidget(self.allSensorLaunchBtn, row=1, col=1)
        try:
            current_file = rospy.get_param("waypoint_file_name")
            self.csvLabel.setText(os.path.basename(str(current_file)))
        except:
            self.csvLabel.setText("No waypoint_file_name param")
        self.pauseSensorReadClicked(
        )  # start paused - the same effect as pushed the pause button
        self.win.show()
Ejemplo n.º 29
0
    def initUI(self):
        """"Assembles the basic Gui layout, status bar, menubar
        toolbar etc."""
        # status bar
        self.statusBar().showMessage('Ready')

        # actions
        soundAction = QtGui.QAction(
            QtGui.QIcon.fromTheme('media-playback-start'), 'Play Sound', self)
        soundAction.setShortcut('Ctrl+S')
        soundAction.setStatusTip('Play data as sound')
        soundAction.triggered.connect(self.playSound)
        exitAction = QtGui.\
            QAction(QtGui.QIcon.fromTheme('window-close'),
                    'Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(QtGui.qApp.quit)
        openAction = QtGui.\
            QAction(QtGui.QIcon.fromTheme('document-open'), 'Open', self)
        openAction.setShortcut('Ctrl+O')
        openAction.setStatusTip('Open an arf file')
        openAction.triggered.connect(self.showDialog)

        newAction = QtGui.QAction('New', self)
        newAction.setStatusTip('Create new file')
        newAction.triggered.connect(self.new)

        exportAction = QtGui.QAction(QtGui.QIcon.fromTheme('document-save-as'),
                                     'Export Checked Data', self)
        exportAction.setShortcut('Ctrl+e')
        exportAction.setStatusTip('Export dataset as wav')
        exportAction.triggered.connect(self.export)

        exportSelectionAction = QtGui.QAction('Export Selection', self)
        exportSelectionAction.setVisible(False)
        exportSelectionAction.setStatusTip('')
        exportSelectionAction.triggered.connect(self.export_selection)
        self.exportSelectionAction = exportSelectionAction
        self.spec_selected = None

        exportPlotAction = QtGui.QAction('Export Plot', self)
        exportPlotAction.setStatusTip('Export Plot')
        exportPlotAction.triggered.connect(self.exportPlot)

        plotcheckedAction = QtGui.QAction(QtGui.QIcon.fromTheme('face-smile'),
                                          'Plot Checked', self)
        plotcheckedAction.setShortcut('Ctrl+k')
        plotcheckedAction.setStatusTip('plot checked')
        plotcheckedAction.triggered.connect(self.toggleplotchecked)
        self.plotcheckedAction = plotcheckedAction

        refreshAction = QtGui.QAction(QtGui.QIcon.fromTheme('view-refresh'),
                                      'Refresh Data View', self)
        refreshAction.setShortcut('Ctrl+r')
        refreshAction.setStatusTip('Refresh Data View')
        refreshAction.triggered.connect(self.refresh_data_view)

        labelAction = QtGui.QAction(QtGui.QIcon.fromTheme('insert-object'),
                                    'Add Labels', self)
        labelAction.setVisible(False)
        labelAction.setShortcut('Ctrl+l')
        labelAction.setStatusTip('Add label entry to current group')
        labelAction.triggered.connect(self.add_label)
        self.labelAction = labelAction

        deleteLabelAction = QtGui.QAction('Delete Label', self)
        deleteLabelAction.setVisible(False)
        deleteLabelAction.setShortcut('Ctrl+d')
        deleteLabelAction.setStatusTip('Add label entry to current group')
        self.deleteLabelAction = deleteLabelAction

        # addPlotAction = QtGui.QAction('Add Plot', self)
        # addPlotAction.setVisible(False)
        # addPlotAction.setStatusTip('Add checked datasets to current plot')
        # addPlotAction.triggered.connect(self.add_plot)
        # self.addPlotAction = addPlotAction

        # menubar
        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(exitAction)
        fileMenu.addAction(openAction)
        fileMenu.addAction(exportAction)
        fileMenu.addAction(plotcheckedAction)
        fileMenu.addAction(refreshAction)

        # toolbar
        self.toolbar = self.addToolBar('Toolbar')
        self.toolbar.addAction(exitAction)
        self.toolbar.addAction(openAction)
        self.toolbar.addAction(newAction)
        self.toolbar.addAction(soundAction)
        self.toolbar.addAction(exportAction)
        self.toolbar.addAction(exportPlotAction)
        self.toolbar.addAction(exportSelectionAction)
        self.toolbar.addAction(plotcheckedAction)
        self.toolbar.addAction(refreshAction)
        self.toolbar.addAction(labelAction)
        self.toolbar.addAction(deleteLabelAction)
        #self.toolbar.addAction(addPlotAction)

        # tree model
        self.tree_model = TreeModel(self.file_names)

        # tree view
        self.tree_view = ArfTreeView()
        self.tree_view.setModel(self.tree_model)
        self.tree_view.pressed.connect(self.selectEntry)
        if self.current_file:
            self.populateTree()

        # tree_toolbar
        self.tree_toolbar = treeToolBar(self.tree_model)

        #attribute table
        self.attr_table = QtGui.QTableWidget(10, 2)
        self.attr_table.setHorizontalHeaderLabels(('key', 'value'))

        #plot region
        self.plot_scroll_area = plotScrollArea(parent=self)
        self.data_layout = pg.GraphicsLayoutWidget()
        self.plot_scroll_area.setWidget(self.data_layout)
        self.plot_scroll_area.setWidgetResizable(True)
        self.subplots = []

        #settings panel
        self.settings_panel = settingsPanel()

        #error message
        self.error_message = QtGui.QErrorMessage(parent=self)
        self.error_message.setFixedSize(500, 200)
        # final steps
        self.area = pgd.DockArea()
        tree_dock = pgd.Dock("Tree", size=(250, 100))
        data_dock = pgd.Dock("Data", size=(400, 100))
        attr_table_dock = pgd.Dock("Attributes", size=(200, 50))
        settings_dock = pgd.Dock('Settings', size=(150, 1))
        self.area.addDock(tree_dock, 'left')
        self.area.addDock(data_dock, 'right')
        self.area.addDock(attr_table_dock, 'bottom', tree_dock)
        self.area.addDock(settings_dock, 'bottom', attr_table_dock)
        tree_dock.addWidget(self.tree_view)
        header = self.tree_view.header()
        header.resizeSection(0, 150)
        header.resizeSection(1, 100)
        header.resizeSection(2, 150)
        tree_dock.addWidget(self.tree_toolbar)
        tree_dock.addAction(exitAction)
        data_dock.addWidget(self.plot_scroll_area)
        #data_dock.addWidget(self.data_layout)
        attr_table_dock.addWidget(self.attr_table)
        settings_dock.addWidget(self.settings_panel)
        self.settings_panel.show()

        self.setCentralWidget(self.area)
        self.setWindowTitle('arfview')
        self.resize(1300, 700)
        self.show()
Ejemplo n.º 30
0
    def __init__(self, ppath, name, config_file, parent=None):
        super(MainWindow, self).__init__(parent)        
        QtGui.QMainWindow.__init__(self)
        # sizing of Main Window
        self.setGeometry(QtCore.QRect(100, 0, 1500, 800))
    
        # Variables related to EEG representation
        # maximum length of shown EEG
    
        self.twin_eeg = 5
        self.twin_view = self.twin_eeg
        # number of time point in EEG; set in self.load_session()
        self.len_eeg = 0
    
        # variables for cell activity
        self.ephys = True
        # list of firing rates or DFF
        self.act_list = []
    
        # Variables related to behavior annotation
        self.tstep = 1.0
        # time series of annotated time points
        # list is set in load_video_timing and/or load_config
        self.tscale_ann = []
        # index of currently shown video frame
        self.image_idx = 0
        # index of currently annotated time point
        # Note that image_idx and tscale_index might not be identical
        # due to the delay at which the camera starts recording
        self.tscale_index = 10
        # the current time point shown in [s]
        self.curr_time = 0
        # the currently shown image frame
        self.image_frame = 0
        # show video or not
        self.show_video = True

        # in annotation mode each time series point in self.tscale_ann can be assigned a behavior
        self.pann_mode = False
        # only if configuration file is provided pconfig can be True; only if pconfig == True,
        # pann_mode can be True, i.e. annotation only works, 
        # if a configuration file was provided
        self.pconfig = False

        # annotate whole time range at once, activated by "space"
        self.pcollect_index = False
        # list of indices within range
        self.index_list = []

        # ndarray of currently displayed video frame
        #self.curr_image = np.array([])
        # dummy image
        self.curr_image = np.zeros((1,1))

        # setup names for recording folder / mouse     
        self.name = name
        self.ppath = ppath        
        if self.name == '':
            self.openFileNameDialog()
        self.mouse = re.split('_', self.name)[0]
        self.load_video_timing()
        self.curr_time = self.tscale_ann[self.tscale_index]

        # test if it's ephys or fiber photometry
        files = [f for f in os.listdir(os.path.join(self.ppath, self.name)) if re.match('^ch_', f)]
        if len(files) > 0:
            self.ephys = True
        else:
            self.ephys = False
        #if os.path.isfile(os.path.join(self.ppath, self.name, 'DFF.mat')) or os.path.isfile(os.path.join(self.ppath, self.name, 'tone.mat')):
        #    self.ephys = False

        # check for amplifier:
        amplifier = get_infoparam(os.path.join(self.ppath, self.name, 'info.txt'), 'amplifier')[0]
        self.img_offset = 1
        if amplifier == 'TDT':
            self.img_offset = 2


        # load configuration file
        self.config_file = config_file
        # graph for annotation, have to declare already here,
        # otherwise there's a problem with load_config()
        self.graph_annotation = pg.PlotWidget()
        # similar need to generate graph to show current time point and behavior annotation
        self.graph_treck      = pg.PlotWidget()
        # load behavior configuration and annotation
        self.load_config()
        

        # make sure Stack folder with unzipped images exists
        if not(os.path.isdir(os.path.join(self.ppath, self.name, 'Stack'))):
            if os.path.isfile(os.path.join(self.ppath, self.name, 'stack.zip')):
                vypro.unpack_zipstack(self.ppath, self.name)
            else:
                print("no video stack available for recording %s" % self.name)
                self.show_video = False

        # now that the configuration is loaded, set image index
        self.set_image_idx()

        # whole area is a docking area, where single docks can be added to
        self.area = dock.DockArea()      
        self.setCentralWidget(self.area)
        
        # Dock with video frame
        self.dock_video = dock.Dock("Video %s" % self.name, size=(50, 30))
        self.area.addDock(self.dock_video, 'left')
        
        # add layout for video player
        self.layout_video = pg.LayoutWidget()

        # graph to show current video frame
        self.graph_frame = pg.PlotWidget()
        self.layout_video.addWidget(self.graph_frame)

        # and finally add layout_video to dock_video
        self.dock_video.addWidget(self.layout_video)

        # Dock with graphs to display if unit is driven
        self.dock_annotation = dock.Dock("Annotation", size=(30, 30))
        self.area.addDock(self.dock_annotation, 'bottom')
        self.layout_annotation = pg.LayoutWidget()
        self.layout_annotation.addWidget(self.graph_annotation,         row=0, col=0, colspan=4, rowspan=1)

        # Row 1
        self.layout_annotation.addWidget(QtGui.QLabel("Symbols"), row=1, col=0)
        self.label_symbols = QtGui.QLineEdit(', '.join(k+'-'+self.symbols[k] for k in self.symbols))        
        self.layout_annotation.addWidget(self.label_symbols,            row=1, col=1, colspan=2)        
        self.button_create = QtGui.QPushButton('Create')
        self.layout_annotation.addWidget(self.button_create,            row=1, col=3)
        self.button_create.clicked.connect(self.create_annotation)         

        # Row 2
        # Activity - Grp, Unit, Plot
        self.layout_annotation.addWidget(QtGui.QLabel("Activity"),  row=2, col=0)
        self.edit_group  = QtGui.QLineEdit('')
        self.layout_annotation.addWidget(self.edit_group,           row=2, col=1, colspan=1)
        self.edit_unit   = QtGui.QLineEdit('')
        self.layout_annotation.addWidget(self.edit_unit,            row=2, col=2, colspan=1)
        self.button_plot = QtGui.QPushButton('Plot')
        self.layout_annotation.addWidget(self.button_plot,          row=2, col=3, colspan=1)
        self.button_plot.clicked.connect(self.plot_activity)

        # Row 3
        self.layout_annotation.addWidget(QtGui.QLabel("t step[s]"), row=3, col=0)
        self.edit_tstep = QtGui.QLineEdit('1')
        self.layout_annotation.addWidget(self.edit_tstep,           row=3, col=1)
        self.button_tstep = QtGui.QPushButton('Set')
        self.layout_annotation.addWidget(self.button_tstep,         row=3, col=2)
        self.button_tstep.clicked.connect(self.set_tstep)
        self.label_mode = QtGui.QLabel("Annotate")
        self.layout_annotation.addWidget(self.label_mode,           row=3, col=3)


        # finally add layout_annotation to dock_annotation
        self.dock_annotation.addWidget(self.layout_annotation)

        # dock for data
        self.dock_session = dock.Dock("Whole Session", size=(100, 600))
        self.dock_eeg = dock.Dock("EEG/EMG", size=(100, 800))
                
        self.area.addDock(self.dock_session, 'left')
        self.area.addDock(self.dock_eeg, 'bottom', self.dock_session)
        
        # show the whole GUIp
        self.show()
                
        self.display_mode()
        self.set_image()
        self.load_session()
        self.plot_treck()
        self.plot_eeg()