Esempio n. 1
0
 def __init__(self, xtitle, ytitle,*args):
     super(QBPlot, self).__init__(*args)
     self.setupUi(self)
     self.x_axis_title = xtitle
     self.y_axis_title = ytitle
     pg.setConfigOption('background', (226, 226, 226))
     pg.setConfigOption('foreground', 'k')
Esempio n. 2
0
	def __init__(self, versionNo):
		print("PyVNA __init__()")
		self.version = versionNo

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

		self.vna_idx = 1
		super(PyVNA, self).__init__()

		icopath = "./Akela Logo.ico"

		# Icon isn't on current path, and we're running in a frozen context,
		# so therefore look for the icon at the frozen location.
		if not os.path.exists(icopath) and getattr(sys, 'frozen', False):
			icopath = os.path.join(sys._MEIPASS, icopath)


		icon = QIcon(icopath)
		self.setWindowIcon(icon)

		self.vnas = []
		self.initUI()

		self.setWindowTitle("OpenVNA Python Example Program")
Esempio n. 3
0
    def __init__(self):
        
        QtGui.QMainWindow.__init__(self)            # These three commands
        Ui_MainWindow.__init__(self)                # are needed to

        pg.setConfigOption('background', 'w')       # sets graph background to white                                                 
        pg.setConfigOption('foreground', 'k')       # sets axis color to black 

        self.setupUi(self)                          # to setup the ui
        # La logica di programmare una interfaccia mi sembra la seguente:
        # per prima cosa inizializzo l'interfaccia grafica
        # dopo aver inizializzato l'interfaccia 
        # (che modifico e organizzo tramite Qt Creator)
        # associo ad ogni azione che eseguo sulla interfaccia 
        # un metodo della classe che definisco a seguito

        self.btnStart.clicked.connect(self.Start)
        
        self.timer = QtCore.QTimer(self)                # qui richiamo l'oggetto  timer delle libreria QT 
        self.timer.timeout.connect(self.UpdateView)     # e gli dico che quando il timer va in timeout devo fare l'update dells visuale 
        
        # le istruzioni seguenti servono a disabilitare il mouse su tutti
        # i possobili plot dell'interfaccia
        self.pltMonitor.setMouseEnabled(x=False,y=False)  
        self.pltAlign.setMouseEnabled(x=False,y=False)  
        self.pltDelay.setMouseEnabled(x=False,y=False)  
        self.NumCh = 8

        self.inAcq = False      # flag di acquisizione in corso o meno

        self.getParameters()
    def __init__(self, args):    
    	self.args = args

        #QtGui.QApplication.setGraphicsSystem('raster')
        app = QtGui.QApplication([])
        #mw = QtGui.QMainWindow()
        #mw.resize(800,800)

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

        win = pg.GraphicsWindow(title="Basic plotting examples")
        win.resize(1000,600)
        win.setWindowTitle('plot')

        # Enable antialiasing for prettier plots
        pg.setConfigOptions(antialias=True)
    
        self.order_book_plot = OrderBookPlot(self.args, win)

        if self.args.enable_sample_mode:
            timer = QtCore.QTimer()
            timer.timeout.connect(self.update_sample)
            timer.start(500)
        else:
            thread = RabbitMQThread(self.args)
            thread.newData.connect(self.order_book_plot.update)
            thread.start()
    
        import sys
        ## Start Qt event loop unless running in interactive mode or using pyside.
        if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
            QtGui.QApplication.instance().exec_()
Esempio n. 5
0
 def __init__(self, name="Demo", icon="cwicon"):
     super(MainChip, self).__init__()
     
     self.manageTraces = TraceManagerDialog(self)
     # self.manageTraces.tracesChanged.
     self.name = name        
     self.filename = None
     self.dirty = True
     self.projEditWidget = ProjectTextEditor(self)
     self.projectChanged.connect(self.projEditWidget.setProject)
     pg.setConfigOption('background', 'w')
     pg.setConfigOption('foreground', 'k')
     self.lastMenuActionSection = None        
     self.initUI(icon)
     self.paramTrees = []
     self.originalStdout = None
     
     #Fake widget for dock
     #TODO: Would be nice if this auto-resized to keep small, but not amount of playing
     #with size policy or min/max sizes has worked.
     fake = QWidget()
     self.setCentralWidget(fake)
     
     self.paramScripting = self.addConsole("Script Commands", visible=False)
     self.addPythonConsole()
Esempio n. 6
0
    def __init__(self, stream, buf_size, col="w", chnames=False, invert=False):
        """ Initializes the grapher.

        Args:
            stream: <pylsl.StreamInfo instance> pointer to a stream
            buf_size: <integer> visualization buffer length in samples
            col: <char> color of the line plot (b,r,g,c,m,y,k and w)
        """

        self.stream = stream
        self.inlet = pylsl.StreamInlet(stream)

        self.buf_size = buf_size
        self.channel_count = self.inlet.channel_count
        self.gbuffer = np.zeros(self.buf_size * self.channel_count)
        self.gtimes = np.zeros(self.buf_size) + pylsl.local_clock()
        self.col = col
        if chnames:
            if self.channel_count == len(chnames):
                self.chnames = chnames
            else:
                print("Channel names vs channel count mismatch, skipping")
        else:
            self.chnames = False

        if invert:
            pg.setConfigOption("background", "w")
            pg.setConfigOption("foreground", "k")
        self.fill_buffer()
        self.start_graph()
Esempio n. 7
0
    def __init__(self, plot_params):
        pg.setConfigOption('background', 'w')
        self.pw = pg.PlotWidget(pen=pg.mkPen('b', width=4))
        self.pw.setYRange(-0.4,0.4)
        self.pw.disableAutoRange(ViewBox.ViewBox.YAxis)
        self.pw.hideButtons()
        self.bar_color = (100,100,255)
        self.data = {}# All of the data points ever received
        self.plot_data = {}# The datapoints that are shown on the screen
        self.plots = {}
        self.lines = set()
        self.listeners = []
        plot_params.setdefault("type", "bar")
        if plot_params['type'] == "bar":
            self.bar = True
            self.bar_buffer = {} # A buffer that holds datapoints until they are averaged into bars
            self.dp_counter = {} # The number of datapoints in the buffer so far
            if 'bar_width' in plot_params:
                self.bar_width = int(plot_params['bar_width'])
            else:
                self.bar_width = 15
        else:
            self.bar = False

        print "'", plot_params['signals'], "'"
        for sig in plot_params['signals'].split(","):
            signal_name = self.read_signal(sig)
            self.lines = self.lines.union(signal_name)
Esempio n. 8
0
File: jfet.py Progetto: devttys0/EE
    def plot(self, Rs=None, Vg=0):
        pg.setConfigOption('background', 'w')
        pg.setConfigOption('foreground', 'k')

        # Generate plot
        plt = pg.plot(title=self.__class__.__name__, clear=True)
        plt.setYRange(0, self.IDSS_MAX)
        plt.setXRange(self.VP_MAX, 0)
        plt.showGrid(True, True, 1.0)
        plt.setLabel('left', "Id (mA)")
        plt.setLabel('bottom', "Vgs (V)")

        (x, y) = self.id_max_points()
        plt.plot(x, y, pen=pg.mkPen('g', width=3))

        (x, y) = self.id_min_points()
        plt.plot(x, y, pen=pg.mkPen('b', width=3))

        if Rs is not None:
            (x, y) = self.vg_intercept(Rs, Vg)
            plt.plot(x, y, pen=pg.mkPen('r', width=3))

        # Display plot
        QtGui.QApplication.instance().exec_()
        pg.exit()
Esempio n. 9
0
def figure(title = None, background='w'):
    if background == 'w':
        pg.setConfigOption('background', 'w')  # set background to white
        pg.setConfigOption('foreground', 'k')
    pg.mkQApp()
    win = pg.GraphicsWindow(title=title)
    return win
Esempio n. 10
0
    def __init__(self):
        
        QtGui.QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)

        pg.setConfigOption('background', 'w')      # sets background to white                                                 
        pg.setConfigOption('foreground', 'k')      # sets axis color to black 

        self.setupUi(self)
        self.btnStart.clicked.connect(self.Start)
        self.tabWidget.currentChanged.connect(self.SetupView)
        
        self.timer = QtCore.QTimer(self)
        self.timer.timeout.connect(self.UpdateView)
        
        self.curTab = self.tabWidget.currentIndex()
        self.SetupView(self.curTab)

        self.pltMonitor.setMouseEnabled(x=False,y=False)  
        self.pltAlign.setMouseEnabled(x=False,y=False)  
        self.pltDelay.setMouseEnabled(x=False,y=False)  
        self.pltSingle.setMouseEnabled(x=False,y=False)  
        self.pltCoinc.setMouseEnabled(x=False,y=False)  
        self.pltSingleVis.setMouseEnabled(x=False,y=False)  
        self.pltCoincVis.setMouseEnabled(x=False,y=False)  

        self.inAcq = False

        self.getParameters()
Esempio n. 11
0
def set_pg_colors(form):
    '''Set default BG and FG color for pyqtgraph plots.'''
    bgColorRGBA = form.palette().color(QtGui.QPalette.ColorRole.Window)
    fgColorRGBA = form.palette().color(QtGui.QPalette.ColorRole.WindowText)
    pg.setConfigOption('background', bgColorRGBA)
    pg.setConfigOption('foreground', fgColorRGBA)
    pg.setConfigOptions(antialias=True)  ## this will be expensive for the local plot
Esempio n. 12
0
    def __init__(self):
        QtGui.QWidget.__init__(self)
        subpanel.__init__(self)

        #pg.setConfigOption('background', (255,255,255))
        pg.setConfigOption('foreground', (128,128,128))
        
        self.ui = Ui_plotWindow()
        self.ui.setupUi(self)
        self.ui.graphicsView.hideAxis('bottom')
        self.ui.graphicsView.getAxis('top').setHeight(10)
        self.ui.graphicsView.getAxis('bottom').setHeight(10)
        self.ui.graphicsView.getAxis('left').setWidth(50)
        self.ui.graphicsView.setBackground((255,255,255))
        #brush = QtGui.QBrush()
        #self.ui.graphicsView.setForegroundBrush(brush.color(QtGui.QColor('grey')))
        self.plotCount = 0
        self.legend = None
        
        self.colors = [QtGui.QColor('blue'),
                       QtGui.QColor('red'),
                       QtGui.QColor('lime'),
                       QtGui.QColor('cornflowerblue'),
                       QtGui.QColor('greenyellow'),
                       QtGui.QColor('violet'),
                       QtGui.QColor('orange'),
                       QtGui.QColor('deepskyblue'),
                       QtGui.QColor('firebrick'),
                       QtGui.QColor('aqua')]
Esempio n. 13
0
 def __init__(self,filename,env,parent=None):
   super(correlateAttributes,self).__init__(parent)
   pg.setConfigOption('background', 'w')
   pg.setConfigOption('foreground', 'k')
   self.fileName=filename
   self.setWindowTitle("Correlate attributes")
   self.resize(1000,1000)
   self.env=env
   self.attr1=QtGui.QLineEdit()
   self.attr2=QtGui.QLineEdit()
   formbox=QtGui.QFormLayout()
   formbox.addRow('Name of attribute 1 : ',self.attr1)
   formbox.addRow('Name of attribute 2 : ',self.attr2)
   form=QtGui.QFrame()
   form.setLayout(formbox)
   self.p1=pg.PlotWidget()
   button1=QtGui.QPushButton('Calculate correlation')
   button1.clicked.connect(self.calculate)
   vbox1=QtGui.QVBoxLayout()
   vbox1.addStretch(1)
   vbox1.addWidget(form)
   vbox1.addWidget(button1)
   vbox1.addWidget(self.p1)
   self.setLayout(vbox1)
   self.show()
    def __init__(self, parent = None):
        QtGui.QWidget.__init__(self, parent)
        
        pg.setConfigOption('background', 'w')
        pg.setConfigOption('foreground', 'k')
        pg.setConfigOptions(antialias=False)
        self.scopeWidget = pg.PlotWidget()
        self.scopeWidget.setTitle('Scope trace', size='12')

        self.vbl = QtGui.QVBoxLayout()
        self.vbl.addWidget(self.scopeWidget)
        self.setLayout(self.vbl)
        self.scopeWidget.setLabel('left', 'Signal', units='V')
        self.scopeWidget.setLabel('bottom', 'Time', units='s')
        self.scopeWidget.showGrid(x=False, y=True)
        self.scopeWidget.clear()

        self.lr1 = pg.LinearRegionItem([0,0], brush=pg.mkBrush(0,0,160,80))
        self.lr2 = pg.LinearRegionItem([0,0], brush=pg.mkBrush(52,124,23,80))
        self.lr1.setZValue(10)
        self.lr2.setZValue(10)
        self.scopeWidget.addItem(self.lr2)
        self.scopeWidget.addItem(self.lr1)
        self.lr1.setMovable(False)
        self.lr2.setMovable(False)
Esempio n. 15
0
    def setupGUI(self):
        self.setWindowTitle("Calculator plot")
        self.setGeometry(80, 50, 800, 600)
        self.setWindowIcon(QtGui.QIcon('../images/Logo.png'))
        pg.setConfigOption('background', (255,255,255))
        pg.setConfigOption('foreground',(0,0,0))
        self.layout = QtGui.QVBoxLayout()
        self.layout.setContentsMargins(0,0,0,0)
        self.layout.setSpacing(0)
        self.setLayout(self.layout)
        # split window into two halfs
        self.splitter = QtGui.QSplitter()
        self.splitter.setOrientation(QtCore.Qt.Horizontal)
        self.layout.addWidget(self.splitter)

        self.tree = pg.TreeWidget()
        self.sublayout = pg.GraphicsLayoutWidget()
        self.splitter.addWidget(self.tree)
        self.splitter.addWidget(self.sublayout)
        self.plt = self.sublayout.addPlot()
        setup_plot(self.plt)
        pg.setConfigOptions(antialias=True)

        self.tree.setHeaderHidden(True)
        self.tree.setDragEnabled(False)
        self.tree.setIndentation(10)
        self.tree.setColumnCount(3)
        self.tree.setColumnWidth(0, 110)
        self.tree.setColumnWidth(1, 90)
        self.tree.setColumnWidth(2, 5)

        optItem = pg.TreeWidgetItem(['Options'])
        xNameItem = pg.TreeWidgetItem(['x title'])
        yNameItem = pg.TreeWidgetItem(['y title'])
        optItem.addChild(xNameItem)
        optItem.addChild(yNameItem)

        addPlotItem = pg.TreeWidgetItem()
        self.addPlotButton = QtGui.QPushButton('Add')
        self.enterAction = QtGui.QAction('',self,shortcut='Return')
        self.addAction(self.enterAction)
        self.applyButton = QtGui.QPushButton('Apply')
        self.applyButton.setDisabled(True)

        addPlotItem.setWidget(0,self.applyButton)
        addPlotItem.setWidget(1,self.addPlotButton)
        self.items = pg.TreeWidgetItem(['Items'])
        self.tree.addTopLevelItem(optItem)
        self.tree.addTopLevelItem(self.items)
        self.tree.addTopLevelItem(pg.TreeWidgetItem())
        self.tree.addTopLevelItem(addPlotItem)
        optItem.setExpanded(True)

        self.xNameEdit = QtGui.QLineEdit('X')
        self.yNameEdit = QtGui.QLineEdit('Y')
        xNameItem.setWidget(1,self.xNameEdit)
        yNameItem.setWidget(1,self.yNameEdit)
        self.plt.setLabel('bottom', 'X',**LabelStyle)
        self.plt.setLabel('left', 'Y',**LabelStyle)
 def __init__(self, parent=None, scale_min=0, scale_max=1, steps=0.1, title='None'):
     setConfigOption('background', 'w')
     PlotWidget.__init__(self,  parent, enableMenu=False, border=False, title=title)
     self.range_ = arange(scale_min, scale_max, steps)
     self.curve = self.plot(self.range_, zeros([len(self.range_)]), clear=False, pen='b')
     # self.curve2 = self.plot(self.range_, zeros([len(self.range_)]) + 0.5, clear=False, pen='r')
     self.disableAutoRange()
     self.setRange(xRange=(scale_min, scale_max))
Esempio n. 17
0
 def __init__(self,filename,env,parent=None):
      super(correlateData,self).__init__(parent)
      pg.setConfigOption('background', 'w')
      pg.setConfigOption('foreground', 'k')
      self.fileName=filename
      self.setWindowTitle("Correlate data")
      self.resize(1000,1000)
      self.env=env
      self.correlation={}
      self.signalChoice1=QtGui.QComboBox()
      self.signalChoice2=QtGui.QComboBox()
      self.signals=readHdf5.getSignals(self.fileName[0],self.env)
      self.signalChoice1.addItems(self.signals)
      self.signalChoice2.addItems(self.signals) 
             
      self.p1=pg.PlotWidget()
      self.p2=pg.PlotWidget()
      self.p3=pg.PlotWidget()
      
      self.listShots=QtGui.QListWidget()
      self.listShots.addItems(self.fileName)
      self.listShots.itemClicked.connect(self.display)
      button1=QtGui.QPushButton('Calculate correlation')
      button1.clicked.connect(self.calculate)
      button2= QtGui.QPushButton('Remove correlation')
      button2.clicked.connect(self.delCorr)
      self.corrName=QtGui.QLineEdit()
      button3= QtGui.QPushButton('Save correlation')
      button3.clicked.connect(self.saveCorr)
      
      vbox1=QtGui.QVBoxLayout()         
      vbox1.addStretch(1)
      
      vbox2=QtGui.QVBoxLayout()         
      vbox2.addStretch(1)
      hbox1=QtGui.QHBoxLayout()
      hbox1.addStretch(1)
      #dataWin=QtGui.QFrame()
      #dataWin.setLayout(hbox1)
      vbox1.addWidget(self.signalChoice1)
      vbox1.addWidget(self.signalChoice2)
      vbox1.addWidget(self.p1)
      vbox1.addWidget(self.p2)
      vbox2.addWidget(self.listShots)
      vbox2.addWidget(button1)
      vbox2.addWidget(self.p3)
      vbox2.addWidget(self.corrName)
      vbox2.addWidget(button2)
      win2=QtGui.QFrame()
      win2.setLayout(vbox1)
      win3=QtGui.QFrame()
      win3.setLayout(vbox2)
      
      hbox1.addWidget(win2)
      hbox1.addWidget(win3)
      #self.setCentralWidget(dataWin)
      self.setLayout(hbox1)
      self.show()
Esempio n. 18
0
    def __init__(self):
        
        QtGui.QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)

        pg.setConfigOption('background', 'w')      # sets background to white                                                 
        pg.setConfigOption('foreground', 'k')      # sets axis color to black 

        self.setupUi(self)
        self.btnStart.clicked.connect(self.Start)

        self.apparatus = apparatus.Apparatus()

        self.btnConfig.clicked.connect(self.showConfigUI)
        self.btnConnect.clicked.connect(self.connectApparatus)
        self.config = config.Config()
        self.configUI = config.ConfigUI(self.config,self.apparatus)
        self.btnMainDir.clicked.connect(self.SetMainDir)
        self.btnAutoMeasure.clicked.connect(self.autoStart)
        
        self.connected = False

        self.savetimer = QtCore.QTimer(self)
        self.savetimer.timeout.connect(self.SaveData)

        self.updatetimer = QtCore.QTimer(self)
        
        self.NumCh = 4

        self.pltMonitor.setMouseEnabled(x=False,y=False)  
        self.pltAlign.setMouseEnabled(x=False,y=False)  
        self.pltDelay.setMouseEnabled(x=False,y=False)  
        self.pltSingleVis.setMouseEnabled(x=False,y=False)  
        self.pltCoincVis.setMouseEnabled(x=False,y=False)  

        self.inAcq = False
        
        self.clock = QtCore.QTime()
        self.clock.start()
        self.saving = False
        self.maindir = ''
        self.saveStartIndex = 0
        self.saveCurIndex = 0
        self.saveInterval = 30
        self.savedSize = 0

        self.autoIndex = 0
        iters = [
                    [0,1], # outcome Bob1
                    [0,1], # Bob1
                    [0,1], # Bob2
                    [2,3]  # Alice
                ]
        self.autoBases = list(itertools.product(*iters))
        self.autoAcq = False
        self.measNumber = 1

        self.getParameters()
Esempio n. 19
0
def main():
    gsac, opts = getDataOpts()
    pg.setConfigOption('background', 'w')
    pg.setConfigOption('foreground', 'k')
    gui = mainGUI(gsac, opts)
    ### Start Qt event loop unless running in interactive mode or using pyside.
    if sys.flags.interactive != 1 or not hasattr(QtCore, 'PYQT_VERSION'):
        #pg.QtGui.QApplication.exec_()
        gui.app.exec_()
Esempio n. 20
0
def main():
    parser = argparse.ArgumentParser("plot values from msgpack stream")
    parser.add_argument("--hist", help="length of the plot-history", type=int, default=1000)
    parser.add_argument("var", help="variable to plot", nargs='+')

    args = parser.parse_args()

    app = QtGui.QApplication([])

    pg.setConfigOption('background', '#EEEEEE')
    pg.setConfigOptions(antialias=True)
    win = pg.GraphicsWindow(title="graph")

    plot = Plot(win, histlen=args.hist)
    for color_idx, var in enumerate(args.var):
        plot.addLine(plot_colors[color_idx % len(plot_colors)], var)

    timer = QtCore.QTimer()
    timer.timeout.connect(plot.update)
    timer.start(50)

    class DatagramRcv(QtCore.QThread):
        def __init__(self, remote, variables):
            self.remote = remote
            self.variables = variables
            super(DatagramRcv, self).__init__()

        def run(self):
            context = zmq.Context()
            socket = context.socket(zmq.SUB)
            socket.connect(self.remote)

            for entry in self.variables:
                topic, var = entry.split(':')
                socket.setsockopt(zmq.SUBSCRIBE, msgpack.packb(topic))

            while True:
                buf = socket.recv()
                unpacker = msgpack.Unpacker(encoding='ascii')
                unpacker.feed(buf)
                topic, data = tuple(unpacker)
                for idx, var in enumerate(self.variables):
                    var_topic, var_path = var.split(':')
                    if topic == var_topic:
                        val = variable_path_extract_value(var_path, data)
                        if val is not None:
                            plot.lines[idx].updateData(val)

    rcv_thread = DatagramRcv("tcp://localhost:5556", args.var)
    rcv_thread.start()

    signal.signal(signal.SIGINT, signal.SIG_DFL)  # to kill on ctl-C

    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()
    rcv_thread.terminate()
Esempio n. 21
0
 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)
Esempio n. 22
0
 def __init__(self, parent=None):
     pyqtgraph.setConfigOption('background', 'w') #before loading widget
     super(ExampleApp, self).__init__(parent)
     self.setupUi(self)
     self.grFFT.plotItem.showGrid(True, True, 0.7)
     self.grPCM.plotItem.showGrid(True, True, 0.7)
     self.maxFFT=0
     self.maxPCM=0
     self.ear = SWHear.SWHear()
     self.ear.stream_start()
Esempio n. 23
0
 def __init__(self, ProgramStartTime = time.strftime("%Y%m%dT%H%M%S")):
     pg.setConfigOption('background', 'w')
     pg.setConfigOption('foreground', 'k')
     self.xData = collections.deque(maxlen=8640) 
     self.yData = collections.deque(maxlen=8640) 
     self.Program_Start_Time = ProgramStartTime  
     self.app = QtGui.QApplication([])
     self.p = pg.plot()
     self.curve = self.p.plot(pen=pg.mkPen('r', width=3))      
     self.initializeGraph() 
def main():
    # Set PyQtGraph colors
    pg.setConfigOption('background', 'w')
    pg.setConfigOption('foreground', 'k')

    # Enable antialiasing for prettier plots
    pg.setConfigOptions(antialias=True)

    app = MyApplication(sys.argv)
    sys.exit(app.exec_())
Esempio n. 25
0
    def __init__(self, parent=None, recorder=None):
        super().__init__(parent)

        # Use given recorder, to load just-collected gazeData, if available
        self.recorder = recorder

        self.gazeData = pandas.DataFrame()
        self.path = None

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

        analysisWidget = pyqtgraph.GraphicsLayoutWidget(self)

        # Prepare plots
        self.gazePlot = analysisWidget.addPlot(row=1, col=1)
        self.speedPlot = analysisWidget.addPlot(row=2, col=1, colspan=2)
        self.gazePlot.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        self.gazePlot.invertY()
        self.xPlot = analysisWidget.addPlot(row=1, col=2)

        self.speedPlot.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Maximum)
        self.gazePlot.setLabels(left='px', bottom='px')
        self.xPlot.setLabels(left='px', bottom='Time (s)')
        self.speedPlot.setLabels(left='Speed (px/s)', bottom='Time (s)')

        # A region on the bottom (speed) plot is used to select the
        # time interval to show on the top (gaze) plot
        self.timeRegion = pyqtgraph.LinearRegionItem()
        self.gazePlot.setAspectLocked(ratio=1)
        self.gazePlot.disableAutoRange()

        self.regionBeingDragged = False
        self.timeRegion.sigRegionChanged.connect(self.handleRegionChanged)
        self.timeRegion.sigRegionChangeFinished.connect(self.handleRegionChangeFinished)


        self.setCentralWidget(analysisWidget)

        # Actions
        if self.recorder:
            loadRecAction = QtGui.QAction(self.style().standardIcon(QtGui.QStyle.SP_BrowserReload), 'Load rec.', self)
            self.toolbar.addAction(loadRecAction)
            loadRecAction.triggered.connect(self.loadFromRecorder)

        loadFileAction = QtGui.QAction(self.style().standardIcon(QtGui.QStyle.SP_DirHomeIcon), 'Load file', self)
        self.toolbar.addAction(loadFileAction)
        loadFileAction.triggered.connect(self.loadFile)

        # Set up plot items and add checkboxes to the toolbar
        self.plotElements = {}
        self.toolbar.addSeparator()
        self.initPlotItems()
        
        self.initPlayAnimation()
	def __init__(self, parent=None):
		pg.GraphicsWindow.__init__(self, title="Amplitude Spectrum")
		pg.setConfigOption('background', '')
		pg.setConfigOptions(antialias=True)
		self.plot_item_a = self.addPlot(title='Amplitude Spectrum', labels={'left': 'Amplitude', 'bottom': 'Freq (f)'})
		self.plot_item_p = self.addPlot(title='Phase Spectrum', labels={'left': 'Phase', 'bottom': 'Freq (f)'})
		
		self.plot_item_a.disableAutoRange()
		self.plot_item_p.disableAutoRange()
		self.plot_item_a.showGrid(x=True, y=True)
		self.plot_item_p.showGrid(x=True, y=True)
Esempio n. 27
0
 def __init__(self, parent=None):
     super(COcalcMain, self).__init__(parent)
     pqg.setConfigOption('background', '#f0f0f0')
     pqg.setConfigOption('foreground', '#2d3142')
     pqg.mkPen(color=(0, 97, 255))
     self.setupUi(self)
     self.timeInterval.setPlainText("2") #want to allow user the option to change this value
     self.HUtoIodineConversion.setPlainText("24")
     self.apply.clicked.connect(self.ApplyChecker)
     self.reset.clicked.connect(self.Reset)
     self.patient = PatientData.Patient() #object that holds the data and does the calculations
Esempio n. 28
0
	def initPlotArea(self):
		pg.setConfigOption('background', 'w')
		pg.setConfigOption('foreground', 'k')
		self.view = pg.GraphicsLayoutWidget()         
		scrollBarH = QScrollBar()
		scrollBarV = QScrollBar()
		self.view.setHorizontalScrollBar(scrollBarH)
		self.view.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)
		self.view.setVerticalScrollBar(scrollBarV)
		self.view.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
		self.setCentralWidget(self.view)
Esempio n. 29
0
 def __init__(self):
     super(VTPlot, self).__init__()
     
     self._vtgui = plugin_utils.getVTGui()
     self._mdiarea = self._vtgui.workspace
     self._settings = qtcore.QSettings()
     self._logger = plugin_utils.getLogger(defaults.MODULE_NAME)
     self._add_submenu()
     # pyqtgraph options
     qtgraph.setConfigOption('background', 'w')
     qtgraph.setConfigOption('foreground', 'k')
 def init_plot(self):
     pg.setConfigOption('background', 'w')
     pg.setConfigOption('foreground', 'k')
     self.ui.plot_widget=pg.PlotWidget(name="plot1")
     self.ui.plot_layout.addWidget(self.ui.plot_widget)
     self.ui.plot_widget.setLabel('left', 'Value')
     self.ui.plot_widget.setLabel('bottom', 'Time', units='s')
     self.plot=self.ui.plot_widget.plot()
     self.update_plot_thread=Thread(target=self.update_plot)
     self.update_plot_thread.daemon=True
     self.update_plot_thread.start()
     self.can_update=True
Esempio n. 31
0
    def setupUi(self, Dialog):
        Dialog.setObjectName(_fromUtf8("Dialog"))
        Dialog.resize(1355, 696)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(Dialog.sizePolicy().hasHeightForWidth())
        Dialog.setSizePolicy(sizePolicy)
        Dialog.setFocusPolicy(QtCore.Qt.StrongFocus)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(_fromUtf8(":/icon/Project/HeadlineMining Gitlab/images/icon.ico")),
                       QtGui.QIcon.Normal, QtGui.QIcon.Off)
        Dialog.setWindowIcon(icon)
        Dialog.setAutoFillBackground(False)
        Dialog.setStyleSheet(_fromUtf8("background-image: url(:/bavkground/images/woodback.jpg);"))

        # Graph
        pg.setConfigOption('background', 'w')
        pg.setConfigOption('foreground', 'k')
        pg.setConfigOption('leftButtonPan', False)
        self.Graph = PlotWidget(Dialog)
        self.Graph.setGeometry(QtCore.QRect(670, 30, 651, 321))
        self.Graph.setObjectName(_fromUtf8("Graph"))
        makeGraph(self.Graph)

        # Graph Label
        self.GraphLabel = QtGui.QLabel(Dialog)
        self.GraphLabel.setGeometry(QtCore.QRect(670, 1, 651, 28))
        self.GraphLabel.setAutoFillBackground(False)
        self.GraphLabel.setStyleSheet(_fromUtf8("background:transparent;"))
        self.GraphLabel.setFrameShadow(QtGui.QFrame.Plain)
        self.GraphLabel.setText(_fromUtf8(
            "<html><head/><body><p align=\"center\"><span style=\" font-size:12pt; font-weight:600; color:#fff2af;\"><u>Opinion Graph Of Headlines</u></span></p></body></html>"))
        self.GraphLabel.setTextFormat(QtCore.Qt.RichText)
        self.GraphLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.GraphLabel.setWordWrap(True)
        self.GraphLabel.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
        self.GraphLabel.setObjectName(_fromUtf8("GraphLabel"))

        # wordCloud
        self.wordCloud = pic = QtGui.QLabel(Dialog)
        self.wordCloud.setGeometry(QtCore.QRect(40, 30, 560, 321))
        self.wordCloud.setObjectName(_fromUtf8("wordCloud"))
        drawWordCloud()
        self.wordCloud.setPixmap(QtGui.QPixmap("./data/wc.png"))
        # self.wordCloud.setPixmap(QtGui.QPixmap("../data/wc.png")) #testing

        # WordCloud Label
        self.WordCloudLabel = QtGui.QLabel(Dialog)
        self.WordCloudLabel.setGeometry(QtCore.QRect(40, 1, 560, 28))
        self.WordCloudLabel.setAutoFillBackground(False)
        self.WordCloudLabel.setStyleSheet(_fromUtf8("background:transparent;"))
        self.WordCloudLabel.setFrameShadow(QtGui.QFrame.Plain)
        self.WordCloudLabel.setText(_fromUtf8(
            "<html><head/><body><p align=\"center\"><span style=\" font-size:12pt; font-weight:600; color:#fff2af;\">\
            <u>Hot Topics Based On Usage Frequency In Headlines</u></span></p></body></html>"))
        self.WordCloudLabel.setTextFormat(QtCore.Qt.RichText)
        self.WordCloudLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.WordCloudLabel.setWordWrap(True)
        self.WordCloudLabel.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
        self.WordCloudLabel.setObjectName(_fromUtf8("WordCloudLabel"))

        # Calender
        self.calendarWidget = QtGui.QCalendarWidget(Dialog)
        self.calendarWidget.setGeometry(QtCore.QRect(830, 430, 361, 251))
        self.calendarWidget.setMinimumDate(QtCore.QDate(2017, 1, 2))
        self.calendarWidget.setMaximumDate(QtCore.QDate(2017, 12, 31))
        self.calendarWidget.setObjectName(_fromUtf8("calendarWidget"))
        self.calendarWidget.clicked.connect(self.dateSelected)

        # Calender Label
        self.CalenderLabel = QtGui.QLabel(Dialog)
        self.CalenderLabel.setGeometry(QtCore.QRect(760, 370, 491, 51))
        self.CalenderLabel.setAutoFillBackground(False)
        self.CalenderLabel.setStyleSheet(_fromUtf8("background:transparent;"))
        self.CalenderLabel.setFrameShadow(QtGui.QFrame.Plain)
        self.CalenderLabel.setText(_fromUtf8(
            "<html><head/><body><p align=\"center\"><span style=\" font-size:12pt; font-weight:600; color:#fff2af;\"><u>Select a date from calender below to change day</u></span></p></body></html>"))
        self.CalenderLabel.setTextFormat(QtCore.Qt.RichText)
        self.CalenderLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.CalenderLabel.setWordWrap(True)
        self.CalenderLabel.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
        self.CalenderLabel.setObjectName(_fromUtf8("CalenderLabel"))

        # Nextbutton
        self.pushButton = QtGui.QPushButton(Dialog)
        self.pushButton.setGeometry(QtCore.QRect(670, 490, 81, 81))
        self.pushButton.setStyleSheet(_fromUtf8("background-image: url(:/labelBackground/images/nextButton.png);\n"
                                                "border:none;"))
        self.pushButton.setAutoDefault(True)
        self.pushButton.isCheckable()
        self.pushButton.setDefault(False)
        self.pushButton.setFlat(False)
        self.pushButton.setObjectName(_fromUtf8("pushButton"))
        self.pushButton.clicked.connect(self.nextFourHeadlines)

        # WeeklyButton
        self.weekButton = QtGui.QPushButton(Dialog)
        self.weekButton.setGeometry(QtCore.QRect(1210, 490, 130, 81))
        self.weekButton.setStyleSheet(_fromUtf8("color:white; font-size:14pt; font-weight:600; background:grey; \
                                                 font-family:'Lucida Calligraphy';border-style: outset;\
                                                 border-width: 2px;border-radius: 15px;border-color: black;\
                                                padding: 4px;"))
        self.weekButton.setAutoDefault(True)
        self.weekButton.isCheckable()
        self.weekButton.setText("One Week \nAnalysis")
        self.weekButton.setObjectName(_fromUtf8("weekButton"))
        self.weekButton.clicked.connect(self.oneWeekAnalysis)

        # Calculate accuracy button
        self.accuracyButton = QtGui.QPushButton(Dialog)
        self.accuracyButton.setGeometry(QtCore.QRect(1210, 591, 130, 81))
        self.accuracyButton.setStyleSheet(_fromUtf8("color:white; font-size:14pt; font-weight:600; background:grey; \
                                                         font-family:'Lucida Calligraphy';border-style: outset;\
                                                         border-width: 2px;border-radius: 15px;border-color: black;\
                                                        padding: 4px;"))
        self.accuracyButton.setAutoDefault(True)
        self.accuracyButton.isCheckable()
        self.accuracyButton.setText("Calculate \n Accuracy ")
        self.accuracyButton.setObjectName(_fromUtf8("accuracyButton"))
        self.accuracyButton.clicked.connect(self.calcuateAccuracy)

        # Accuracy instruction label
        self.accuracyLabel = QtGui.QLabel(Dialog)
        self.accuracyLabel.setGeometry(QtCore.QRect(30, 370, 521, 28))
        self.accuracyLabel.setAutoFillBackground(False)
        self.accuracyLabel.setStyleSheet(_fromUtf8("background:transparent;"))
        self.accuracyLabel.setFrameShadow(QtGui.QFrame.Plain)
        self.accuracyLabel.setText(_fromUtf8(
            "<html><head/><body><p align=\"center\"><span style=\" font-size:12pt; font-weight:600; color: #20ee94;\">\
            <u>Cycle through all headlines and select incorrect scores</u></span></p></body></html>"))
        self.accuracyLabel.setTextFormat(QtCore.Qt.RichText)
        self.accuracyLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.accuracyLabel.setWordWrap(True)
        self.accuracyLabel.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
        self.accuracyLabel.setObjectName(_fromUtf8("accuracyLabel"))
        self.accuracyLabel.hide()

        # AccuracyResult Label
        self.accuracyResultLabel = QtGui.QLabel(Dialog)
        self.accuracyResultLabel.setGeometry(QtCore.QRect(645, 591, 150, 100))  # 670, 490, 81, 81
        self.accuracyResultLabel.setAutoFillBackground(False)
        self.accuracyResultLabel.setStyleSheet(_fromUtf8("background:transparent;"))
        self.accuracyResultLabel.setFrameShadow(QtGui.QFrame.Plain)
        self.accuracyResultLabel.setTextFormat(QtCore.Qt.RichText)
        self.accuracyResultLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.accuracyResultLabel.setWordWrap(True)
        self.accuracyResultLabel.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
        self.accuracyResultLabel.setObjectName(_fromUtf8("accuracyResultLabel"))
        self.accuracyResultLabel.hide()

        # checkboxes
        self.checkBox1 = QtGui.QCheckBox(Dialog)
        self.checkBox1.setGeometry(QtCore.QRect(15, 408, 16, 17))
        self.checkBox1.setText(_fromUtf8(""))
        self.checkBox1.setObjectName(_fromUtf8("checkBox1"))
        self.checkBox1.hide()

        self.checkBox2 = QtGui.QCheckBox(Dialog)
        self.checkBox2.setGeometry(QtCore.QRect(15, 488, 16, 17))
        self.checkBox2.setText(_fromUtf8(""))
        self.checkBox2.setObjectName(_fromUtf8("checkBox2"))
        self.checkBox2.hide()

        self.checkBox3 = QtGui.QCheckBox(Dialog)
        self.checkBox3.setGeometry(QtCore.QRect(15, 568, 16, 17))
        self.checkBox3.setText(_fromUtf8(""))
        self.checkBox3.setObjectName(_fromUtf8("checkBox3"))
        self.checkBox3.hide()

        self.checkBox4 = QtGui.QCheckBox(Dialog)
        self.checkBox4.setGeometry(QtCore.QRect(15, 648, 16, 17))
        self.checkBox4.setText(_fromUtf8(""))
        self.checkBox4.setObjectName(_fromUtf8("checkBox4"))
        self.checkBox4.hide()

        # Headline labels
        self.Headline1 = QtGui.QLabel(Dialog)
        self.Headline1.setGeometry(QtCore.QRect(40, 392, 521, 51))
        self.Headline1.setStyleSheet(_fromUtf8("background:transparent;"))
        self.Headline1.setTextFormat(QtCore.Qt.RichText)
        self.Headline1.setAlignment(QtCore.Qt.AlignLeading | QtCore.Qt.AlignCenter | QtCore.Qt.AlignHCenter)
        self.Headline1.setWordWrap(True)
        self.Headline1.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
        self.Headline1.setObjectName(_fromUtf8("Headline1"))

        self.Headline2 = QtGui.QLabel(Dialog)
        self.Headline2.setGeometry(QtCore.QRect(40, 472, 521, 51))
        self.Headline2.setStyleSheet(_fromUtf8("background:transparent;"))
        self.Headline2.setTextFormat(QtCore.Qt.RichText)
        self.Headline2.setAlignment(QtCore.Qt.AlignLeading | QtCore.Qt.AlignCenter | QtCore.Qt.AlignHCenter)
        self.Headline2.setWordWrap(True)
        self.Headline2.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
        self.Headline2.setObjectName(_fromUtf8("Headline2"))

        self.Headline3 = QtGui.QLabel(Dialog)
        self.Headline3.setGeometry(QtCore.QRect(40, 552, 521, 51))
        self.Headline3.setStyleSheet(_fromUtf8("background:transparent;"))
        self.Headline3.setTextFormat(QtCore.Qt.RichText)
        self.Headline3.setAlignment(QtCore.Qt.AlignLeading | QtCore.Qt.AlignCenter | QtCore.Qt.AlignHCenter)
        self.Headline3.setWordWrap(True)
        self.Headline3.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
        self.Headline3.setObjectName(_fromUtf8("Headline3"))

        self.Headline4 = QtGui.QLabel(Dialog)
        self.Headline4.setGeometry(QtCore.QRect(40, 632, 521, 51))
        self.Headline4.setStyleSheet(_fromUtf8("background:transparent;"))
        self.Headline4.setTextFormat(QtCore.Qt.RichText)
        self.Headline4.setAlignment(QtCore.Qt.AlignLeading | QtCore.Qt.AlignCenter | QtCore.Qt.AlignHCenter)
        self.Headline4.setWordWrap(True)
        self.Headline4.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
        self.Headline4.setObjectName(_fromUtf8("Headline4"))

        # Score Labels
        self.Value4 = QtGui.QLabel(Dialog)
        self.Value4.setGeometry(QtCore.QRect(580, 632, 71, 51))
        self.Value4.setStyleSheet(_fromUtf8("background:transparent;"))
        self.Value4.setTextFormat(QtCore.Qt.RichText)
        self.Value4.setAlignment(QtCore.Qt.AlignCenter | QtCore.Qt.AlignLeft)
        self.Value4.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
        self.Value4.setObjectName(_fromUtf8("Value4"))

        self.Value3 = QtGui.QLabel(Dialog)
        self.Value3.setGeometry(QtCore.QRect(580, 552, 71, 51))
        self.Value3.setStyleSheet(_fromUtf8("background:transparent;"))
        self.Value3.setTextFormat(QtCore.Qt.RichText)
        self.Value3.setAlignment(QtCore.Qt.AlignCenter | QtCore.Qt.AlignLeft)
        self.Value3.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
        self.Value3.setObjectName(_fromUtf8("Value3"))

        self.Value2 = QtGui.QLabel(Dialog)
        self.Value2.setGeometry(QtCore.QRect(580, 472, 71, 51))
        self.Value2.setStyleSheet(_fromUtf8("background:transparent;"))
        self.Value2.setTextFormat(QtCore.Qt.RichText)
        self.Value2.setAlignment(QtCore.Qt.AlignCenter | QtCore.Qt.AlignLeft)
        self.Value2.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
        self.Value2.setObjectName(_fromUtf8("Value2"))

        self.Value1 = QtGui.QLabel(Dialog)
        self.Value1.setGeometry(QtCore.QRect(580, 392, 71, 51))
        self.Value1.setStyleSheet(_fromUtf8("background:transparent;"))
        self.Value1.setTextFormat(QtCore.Qt.RichText)
        self.Value1.setAlignment(QtCore.Qt.AlignCenter | QtCore.Qt.AlignLeft)
        self.Value1.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
        self.Value1.setObjectName(_fromUtf8("Value1"))

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)
Esempio n. 32
0
colorSet = [[255, 255, 0, 255], [0, 255, 0, 255], [0, 100, 255, 255],
            [248, 89, 253, 255], [89, 253, 242, 255], [89, 253, 253, 255],
            [253, 89, 226, 255], [253, 229, 204, 255], [51, 255, 255, 255],
            [229, 204, 255, 255], [89, 253, 100, 255], [127, 255, 212, 255],
            [253, 165, 89, 255], [255, 140, 0, 255], [255, 215, 0, 255],
            [0, 0, 255, 255]]

##################### Parameter ###################################
QUEUE_LEN = 15
locBuf = []
objBuf = pd.DataFrame([], columns=['fn', 'x', 'y'])

win = pg.GraphicsWindow()
win.resize(1200, 800)

pg.setConfigOption('foreground', 'y')

win.setWindowTitle('Roadway Traffic Monitoring Detection Radar')

#**************************************
brush_list = [pg.mkColor(c) for c in "rgbcmykwrg"]

# 2) for detected object Doppler scatterPlot
w1 = win.addPlot()
w1.setRange(xRange=[-50, 50], yRange=[0, 100])
w1.setLabel('bottom', 'Object Doppler', 'm/s')
w1.setLabel('left', 'Object Range', 'm')
spots1 = []
curveS1 = pg.ScatterPlotItem(size=20, pen=pg.mkPen('g'), pxMode=True)
w1.addItem(curveS1)
Esempio n. 33
0
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)

        f = open('/dev/null', 'w')
        sys.stdout = f

        self.tabWidget.setCurrentIndex(0)

        # Set pyqtgraph to use white background, black foreground
        pg.setConfigOption('background', 'w')
        pg.setConfigOption('foreground', 'k')
        pg.setConfigOption('imageAxisOrder', 'row-major')
        #pg.setConfigOption('useOpenGL', True)
        #pg.setConfigOption('useWeave', True)

        # Spectrum display

        self.win_spectrum = pg.GraphicsWindow(title="Quad Channel Spectrum")

        self.export_spectrum = pg.exporters.ImageExporter(
            self.win_spectrum.scene())

        self.plotWidget_spectrum_ch1 = self.win_spectrum.addPlot(
            title="Channel 1")
        self.plotWidget_spectrum_ch2 = self.win_spectrum.addPlot(
            title="Channel 2")
        self.win_spectrum.nextRow()
        self.plotWidget_spectrum_ch3 = self.win_spectrum.addPlot(
            title="Channel 3")
        self.plotWidget_spectrum_ch4 = self.win_spectrum.addPlot(
            title="Channel 4")

        self.gridLayout_spectrum.addWidget(self.win_spectrum, 1, 1, 1, 1)

        x = np.arange(1000)
        y = np.random.normal(size=(4, 1000))

        self.spectrum_ch1_curve = self.plotWidget_spectrum_ch1.plot(x,
                                                                    y[0],
                                                                    clear=True,
                                                                    pen='b')
        self.spectrum_ch2_curve = self.plotWidget_spectrum_ch2.plot(x,
                                                                    y[1],
                                                                    clear=True,
                                                                    pen='r')
        self.spectrum_ch3_curve = self.plotWidget_spectrum_ch3.plot(x,
                                                                    y[2],
                                                                    clear=True,
                                                                    pen='g')
        self.spectrum_ch4_curve = self.plotWidget_spectrum_ch4.plot(x,
                                                                    y[3],
                                                                    clear=True,
                                                                    pen='c')

        self.plotWidget_spectrum_ch1.setLabel("bottom", "Frequency [MHz]")
        self.plotWidget_spectrum_ch1.setLabel("left", "Amplitude [dBm]")
        self.plotWidget_spectrum_ch2.setLabel("bottom", "Frequency [MHz]")
        self.plotWidget_spectrum_ch2.setLabel("left", "Amplitude [dBm]")
        self.plotWidget_spectrum_ch3.setLabel("bottom", "Frequency [MHz]")
        self.plotWidget_spectrum_ch3.setLabel("left", "Amplitude [dBm]")
        self.plotWidget_spectrum_ch4.setLabel("bottom", "Frequency [MHz]")
        self.plotWidget_spectrum_ch4.setLabel("left", "Amplitude [dBm]")

        #---> Sync display <---
        # --> Delay

        self.win_sync = pg.GraphicsWindow(title="Receiver Sync")

        self.export_sync = pg.exporters.ImageExporter(self.win_sync.scene())

        self.plotWidget_sync_absx = self.win_sync.addPlot(title="ABS X Corr")
        #self.plotWidget_sync_absx.setDownsampling(ds=4, mode='subsample')
        #self.plotWidget_sync_normph = self.win_sync.addPlot(title="Normalized Phasors")
        self.win_sync.nextRow()
        self.plotWidget_sync_sampd = self.win_sync.addPlot(
            title="Sample Delay History")
        self.plotWidget_sync_phasediff = self.win_sync.addPlot(
            title="Phase Diff History")

        self.gridLayout_sync.addWidget(self.win_sync, 1, 1, 1, 1)

        x = np.arange(1000)
        y = np.random.normal(size=(4, 1000))

        #---> DOA results display <---

        self.win_DOA = pg.GraphicsWindow(title="DOA Plot")
        #Set up image exporter for web display
        self.export_DOA = pg.exporters.ImageExporter(self.win_DOA.scene())

        self.plotWidget_DOA = self.win_DOA.addPlot(
            title="Direction of Arrival Estimation")
        self.plotWidget_DOA.setLabel("bottom", "Incident Angle [deg]")
        self.plotWidget_DOA.setLabel("left", "Amplitude [dB]")
        self.plotWidget_DOA.showGrid(x=True, alpha=0.25)
        self.gridLayout_DOA.addWidget(self.win_DOA, 1, 1, 1, 1)

        self.DOA_res_fd = open("/ram/DOA_value.html",
                               "w")  # DOA estimation result file descriptor

        # Junk data to just init plot legends
        x = np.arange(1000)
        y = np.random.normal(size=(4, 1000))

        self.plotWidget_DOA.addLegend()

        self.plotWidget_DOA.plot(x,
                                 y[0],
                                 pen=pg.mkPen('b', width=2),
                                 name="Bartlett")
        self.plotWidget_DOA.plot(x,
                                 y[1],
                                 pen=pg.mkPen('g', width=2),
                                 name="Capon")
        self.plotWidget_DOA.plot(x,
                                 y[2],
                                 pen=pg.mkPen('r', width=2),
                                 name="MEM")
        self.plotWidget_DOA.plot(x,
                                 y[3],
                                 pen=pg.mkPen('c', width=2),
                                 name="MUSIC")

        #---> Passive radar results display <---

        self.win_PR = pg.GraphicsWindow(title="Passive Radar")

        self.export_PR = pg.exporters.ImageExporter(self.win_PR.scene())

        self.plt_PR = self.win_PR.addPlot(Title="Range-Doppler Matrix")
        self.plt_PR.setLabel("bottom", "Range")
        self.plt_PR.setLabel("left", "Doppler (Speed)")

        self.PR_interp_factor = 4

        self.plt_PR.getAxis("bottom").setScale(1.0 / self.PR_interp_factor)
        self.plt_PR.getAxis("left").setScale(1.0 / self.PR_interp_factor)

        rand_mat = np.random.rand(50, 50)
        self.img_PR = pg.ImageView()

        self.plt_PR.addItem(self.img_PR.imageItem)

        self.img_PR.setImage(rand_mat)
        self.img_PR.autoLevels()
        self.img_PR.autoRange()

        # Take the color map from matplotlib because it's nicer than pyqtgraph's
        colormap = cm.get_cmap("jet")
        colormap._init()
        lut = (colormap._lut * 255).view(np.ndarray)
        self.img_PR.imageItem.setLookupTable(lut)

        #self.img_PR.setPredefinedGradient('spectrum')

        self.gridLayout_RD.addWidget(self.win_PR, 1, 1, 1, 1)

        # Connect pushbutton signals
        self.pushButton_close.clicked.connect(self.pb_close_clicked)
        self.pushButton_proc_control.clicked.connect(
            self.pb_proc_control_clicked)
        self.pushButton_sync.clicked.connect(self.pb_sync_clicked)
        self.pushButton_iq_calib.clicked.connect(self.pb_calibrate_iq_clicked)
        self.pushButton_del_sync_history.clicked.connect(
            self.pb_del_sync_history_clicked)
        self.pushButton_DOA_cal_90.clicked.connect(
            self.pb_calibrate_DOA_90_clicked)
        self.pushButton_set_receiver_config.clicked.connect(
            self.pb_rec_reconfig_clicked)
        self.stream_state = False

        # Status and configuration tab control
        self.tabWidget.currentChanged.connect(self.tab_changed)

        # Connect checkbox signals
        self.checkBox_en_sync_display.stateChanged.connect(
            self.set_sync_params)
        self.checkBox_en_spectrum.stateChanged.connect(
            self.set_spectrum_params)
        self.checkBox_en_DOA.stateChanged.connect(self.set_DOA_params)
        self.checkBox_en_DOA_Bartlett.stateChanged.connect(self.set_DOA_params)
        self.checkBox_en_DOA_Capon.stateChanged.connect(self.set_DOA_params)
        self.checkBox_en_DOA_MEM.stateChanged.connect(self.set_DOA_params)
        self.checkBox_en_DOA_MUSIC.stateChanged.connect(self.set_DOA_params)
        self.checkBox_en_DOA_FB_avg.stateChanged.connect(self.set_DOA_params)
        self.checkBox_en_dc_compensation.stateChanged.connect(
            self.set_iq_preprocessing_params)
        self.checkBox_en_passive_radar.stateChanged.connect(self.set_PR_params)
        self.checkBox_en_td_filter.stateChanged.connect(self.set_PR_params)
        self.checkBox_en_autodet.stateChanged.connect(self.set_PR_params)
        self.checkBox_en_noise_source.stateChanged.connect(
            self.switch_noise_source)

        # Connect spinbox signals
        self.doubleSpinBox_filterbw.valueChanged.connect(
            self.set_iq_preprocessing_params)
        self.spinBox_fir_tap_size.valueChanged.connect(
            self.set_iq_preprocessing_params)
        self.spinBox_decimation.valueChanged.connect(
            self.set_iq_preprocessing_params)

        self.doubleSpinBox_DOA_d.valueChanged.connect(self.set_DOA_params)
        self.spinBox_DOA_sample_size.valueChanged.connect(self.set_DOA_params)

        self.spinBox_td_filter_dimension.valueChanged.connect(
            self.set_PR_params)
        self.doubleSpinBox_cc_det_max_range.valueChanged.connect(
            self.set_PR_params)
        self.doubleSpinBox_cc_det_max_Doppler.valueChanged.connect(
            self.set_PR_params)
        self.spinBox_ref_ch_select.valueChanged.connect(self.set_PR_params)
        self.spinBox_surv_ch_select.valueChanged.connect(self.set_PR_params)
        self.spinBox_cfar_est_win.valueChanged.connect(self.set_PR_params)
        self.spinBox_cfar_guard_win.valueChanged.connect(self.set_PR_params)
        self.doubleSpinBox_cfar_threshold.valueChanged.connect(
            self.set_PR_params)

        self.spinBox_resync_time.valueChanged.connect(self.set_resync_time)

        # Connect combobox signals
        self.comboBox_antenna_alignment.currentIndexChanged.connect(
            self.set_DOA_params)
        self.comboBox_cc_det_windowing.currentIndexChanged.connect(
            self.set_windowing_mode)

        # Instantiate and configura Hydra modules
        self.module_receiver = ReceiverRTLSDR()

        self.module_receiver.block_size = int(sys.argv[1]) * 1024

        self.module_signal_processor = SignalProcessor(
            module_receiver=self.module_receiver)
        self.module_signal_processor.signal_overdrive.connect(
            self.power_level_update)
        self.module_signal_processor.signal_period.connect(
            self.period_time_update)
        self.module_signal_processor.signal_spectrum_ready.connect(
            self.spectrum_plot)
        self.module_signal_processor.signal_sync_ready.connect(self.delay_plot)
        self.module_signal_processor.signal_DOA_ready.connect(self.DOA_plot)
        self.module_signal_processor.signal_PR_ready.connect(self.RD_plot)
        # -> Set default confiration for the signal processing module
        self.set_spectrum_params()
        self.set_sync_params()
        self.set_DOA_params()
        self.set_windowing_mode()

        self.DOA_time = time.time()
        self.PR_time = time.time()
        self.sync_time = time.time()
        self.spectrum_time = time.time()

        #self.spectrum_plot()
        #self.delay_plot()
        #self.DOA_plot()
        #self.RD_plot()

        # Set default confiuration for the GUI components
        self.set_default_configuration()

        self.ip_addr = sys.argv[2]
        threading.Thread(target=run,
                         kwargs=dict(host=self.ip_addr,
                                     port=8080,
                                     quiet=True,
                                     debug=False,
                                     server='paste')).start()
Esempio n. 34
0
    def initUI(self):
        self.setWindowTitle('Graph')
        self.setFixedSize(1000, 800)

        self.list_channel = QListWidget(self)
        self.stack_window = QStackedWidget(self)
        self.channel_monitor = QWidget()
        self.graph_control = QWidget()

        layout_main = QHBoxLayout(spacing=0)
        layout_main.setContentsMargins(0, 0, 0, 0)

        layout_main.addWidget(self.list_channel)
        layout_main.addWidget(self.stack_window)
        layout_main.addWidget(self.channel_monitor)
        layout_main.addWidget(self.graph_control)

        self.setLayout(layout_main)

        """# List Channel"""
        self.list_channel.setFrameShape(QListWidget.NoFrame)
        self.list_channel.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.list_channel.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.list_channel.currentRowChanged.connect(self.stack_window.setCurrentIndex)

        self.list_channel.setStyleSheet("""
                                       QListWidget{
                                       min-width: 150px;
                                       max-width: 150px;
                                       color: white;
                                       background: grey;
                                       }
                                       """)

        font = QFont()
        font.setFamily('MonoxLight')
        font.setPointSize(20)

        for i in range(6):
            item = QListWidgetItem()
            item.setFont(font)
            item.setText('%03d - %03d' % (32*i + 1, 32*(i + 1)))
            item.setSizeHint(QSize(0, 60))
            item.setTextAlignment(Qt.AlignCenter)
            self.list_channel.addItem(item)
        item = QListWidgetItem()
        item.setFont(font)
        item.setText('Custom')
        item.setSizeHint(QSize(0, 60))
        item.setTextAlignment(Qt.AlignCenter)
        self.list_channel.addItem(item)

        """# Stack Window"""
        self.list_page_widget = []
        self.list_graph_show = []
        self.list_layout_page = []
        self.list_tabwidget = []

        pg.setConfigOption('background', 'w')
        pg.setConfigOption('foreground', 'k')
        list_stringaxis = []

        for i in range(7):
            list_stringaxis.append(CustomAxis({1:'a', 2: 'b'}, orientation='left'))
            self.list_page_widget.append(QWidget())
            self.list_graph_show.append(PlotWidgetCol(axisItems={'left':list_stringaxis[i]}))
            self.list_layout_page.append(QHBoxLayout())
            self.list_layout_page[i].setContentsMargins(0, 0, 0, 0)
            self.list_tabwidget.append(QTabWidget())

        for i in range(7):
            self.list_page_widget[i].setLayout(self.list_layout_page[i])
            self.list_layout_page[i].addWidget(self.list_tabwidget[i])
            self.stack_window.addWidget(self.list_page_widget[i])
            tab_graph = QWidget()
            tab_monitor = QWidget()
            self.list_tabwidget[i].addTab(tab_graph, 'Graph')
            self.list_tabwidget[i].addTab(tab_monitor, 'Monitor')
            layout_page = QHBoxLayout()
            layout_graph = QHBoxLayout()
            layout_graph.addWidget(self.list_graph_show[i])
            tab_graph.setLayout(layout_graph)
            layout_monitor = QGridLayout()
            tab_monitor.setLayout(layout_monitor)

        tab_custom_option = QWidget()
        layout_tab_custom_option = QVBoxLayout()
        tab_custom_option.setLayout(layout_tab_custom_option)
        self.list_tabwidget[6].addTab(tab_custom_option, 'Select')

        """# Page Custom Tab Select"""
        layout_tab_custom_option_up = QHBoxLayout()
        layout_tab_custom_option_mid = QHBoxLayout()
        layout_tab_custom_option_down = QHBoxLayout()
        layout_tab_custom_option.addLayout(layout_tab_custom_option_up)
        layout_tab_custom_option.addLayout(layout_tab_custom_option_mid)
        layout_tab_custom_option.addLayout(layout_tab_custom_option_down)

        font = QFont()
        font.setFamily('MonoxLight')
        font.setPointSize(12)

        label_custom_select_num = QLabel('Profile ID        ')
        label_custom_select_num.setFont(font)

        self.label_custom_select_num = QLabel('00 / 32')
        self.label_custom_select_num.setFont(font)
        self.lineedit_custom_select_num = QLineEdit(16*'0' + '-' + 16*'0' + '-' + 16*'0')
        self.lineedit_custom_select_num.setFont(font)
        self.data_lineedit_custom_select_num = self.lineedit_custom_select_num.text()

        self.pushbutton_custom_select_num = QPushButton('&Ok')

        layout_tab_custom_option_up.addWidget(label_custom_select_num)
        layout_tab_custom_option_up.addWidget(self.lineedit_custom_select_num)
        layout_tab_custom_option_up.addWidget(self.pushbutton_custom_select_num)
        layout_tab_custom_option_down.addStretch(1)
        layout_tab_custom_option_down.setAlignment(Qt.AlignBottom)
        layout_tab_custom_option_down.addWidget(self.label_custom_select_num)

        groupbox_custom_option_channel_a = QGroupBox('A')
        groupbox_custom_option_channel_a.setAlignment(Qt.AlignCenter)
        groupbox_custom_option_channel_a.setStyleSheet("""
                                                     QGroupBox{
                                                     font-family: MonoxRegular;
                                                     font-size: 20px;
                                                     }
                                                     """)
        groupbox_custom_option_channel_b = QGroupBox('B')
        groupbox_custom_option_channel_b.setAlignment(Qt.AlignCenter)
        groupbox_custom_option_channel_b.setStyleSheet("""
                                                     QGroupBox{
                                                     font-family: MonoxRegular;
                                                     font-size: 20px;
                                                     }
                                                     """)
        groupbox_custom_option_channel_c = QGroupBox('C')
        groupbox_custom_option_channel_c.setAlignment(Qt.AlignCenter)
        groupbox_custom_option_channel_c.setStyleSheet("""
                                                     QGroupBox{
                                                     font-family: MonoxRegular;
                                                     font-size: 20px;
                                                     }
                                                     """)
        self.list_checkbox_channel = []
        for i in range(192):
            checkbox_select = QCheckBox('%03i' % (i + 1))
            checkbox_select.setStyleSheet("""
                                          QCheckBox{
                                          font-family: MonoxRegular;
                                          font-size: 15px;
                                          }
                                          """)
            self.list_checkbox_channel.append(checkbox_select)

        layout_tab_custom_option_mid.addWidget(groupbox_custom_option_channel_a)
        layout_tab_custom_option_mid.addWidget(groupbox_custom_option_channel_b)
        layout_tab_custom_option_mid.addWidget(groupbox_custom_option_channel_c)

        list_layout_custom_option_channel_global = []
        for i in range(3):
            list_layout_custom_option_channel_global.append(QHBoxLayout())

        groupbox_custom_option_channel_a.setLayout(list_layout_custom_option_channel_global[0])
        groupbox_custom_option_channel_b.setLayout(list_layout_custom_option_channel_global[1])
        groupbox_custom_option_channel_c.setLayout(list_layout_custom_option_channel_global[2])

        list_layout_custom_option_channel = []

        num = 12
        for i in range(num):
            list_layout_custom_option_channel.append(QVBoxLayout())
            list_layout_custom_option_channel[i].setAlignment(Qt.AlignCenter)

        for i in range(3):
            for j in range(num // 3):
                list_layout_custom_option_channel_global[i].addLayout(list_layout_custom_option_channel[(num // 3)*i + j])

        for i in range(num):
            for j in range(192 // num):
                list_layout_custom_option_channel[i].addWidget(self.list_checkbox_channel[(192 // num)*i + j])

        layout_graph_control = QVBoxLayout()
        layout_graph_control.setAlignment(Qt.AlignBottom)
        #layout_graph_control.setSpacing()
        self.graph_control.setLayout(layout_graph_control)

        self.lcdnumber_countdown = QLCDNumber()
        self.lcdnumber_countdown.setDigitCount(4)
        self.lcdnumber_countdown.setMode(QLCDNumber.Dec)
        self.lcdnumber_countdown.setSegmentStyle(QLCDNumber.Flat)
        self.lcdnumber_countdown.setStyleSheet("""
                                               QLCDNumber{
                                               min-width: 150px;
                                               max-width: 150px;
                                               min-height: 80px;
                                               max-height: 80px;
                                               }
                                               """)
        layout_graph_control.addWidget(self.lcdnumber_countdown)

        self.lcdnumber_countdown_num = QLCDNumber()
        self.lcdnumber_countdown_num.setDigitCount(4)
        self.lcdnumber_countdown_num.setMode(QLCDNumber.Dec)
        self.lcdnumber_countdown_num.setSegmentStyle(QLCDNumber.Flat)
        self.lcdnumber_countdown_num.setStyleSheet("""
                                               QLCDNumber{
                                               min-width: 150px;
                                               max-width: 150px;
                                               min-height: 80px;
                                               max-height: 80px;
                                               }
                                               """)
        layout_graph_control.addWidget(self.lcdnumber_countdown_num)

        self.pushbutton_graph_save = QPushButton('Save')
        self.pushbutton_graph_save.setStyleSheet("""
                                                 QPushButton{
                                                 min-width: 150px;
                                                 min-height: 60px;
                                                 }
                                                 """)
        widget_control_button = QWidget()
        widget_control_button.setStyleSheet("""
                                            QWidget{
                                            min-height: 300px;
                                            }
                                            """)
        layout_graph_control_button = QVBoxLayout()
        widget_control_button.setLayout(layout_graph_control_button)
        layout_graph_control_button.setAlignment(Qt.AlignBottom)
        layout_graph_control_button.addWidget(self.pushbutton_graph_save)
        layout_graph_control.addWidget(widget_control_button)
Esempio n. 35
0
from collections import deque

import pyqtgraph as pg
from PyQt5.QtCore import QTimer, pyqtSlot
from PyQt5.QtWidgets import QWidget

from gui.bookOverview import BookOverview
from .templates.productWidget import Ui_Form

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


class ProductWidget(QWidget, Ui_Form):

    def __init__(self, account, product, parent=None):
        self.account = account
        self.product = product
        QWidget.__init__(self)
        self.speed_histogram_data = (deque([0], maxlen=120), deque([0], maxlen=120))
        self.amount_histogram_data = (deque([0], maxlen=120), deque([0], maxlen=120))
        self.price_histogram_data = (deque([0], maxlen=120), deque([0], maxlen=120))
        self.update_timer = QTimer(self)
        self.update_timer.timeout.connect(self.update_speed_plots)
        self.update_timer.start(1000)
        self.setupUi(self)

    def setupUi(self, Form):
        super().setupUi(Form)
        self._init_speed_histogram()
        self._init_marker_overview()
Esempio n. 36
0
dpi_scaling = 1.0
dpi_100percent = 96


def set_dpi_scaling():
    app = QtWidgets.QApplication.instance()
    screen = app.screens()[0]  # type QtGui.QScreen
    dpi = screen.logicalDotsPerInch()
    global dpi_scaling
    dpi_scaling = dpi / dpi_100percent


preferred_styles = ['plastique', 'Fusion', 'cleanlooks', 'motif', 'cde']
preferred_style = 'Fusion'

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

resource_manager = None

user_path = os.path.expanduser("~")
executable_dir = os.path.dirname(sys.executable)

qt_dir = os.path.dirname(os.path.abspath(__file__))
radie_dir = os.path.join(qt_dir, "..")
resources_dir = os.path.join(qt_dir, "resources")
icon_path = os.path.join(resources_dir, "icons")

radie_icon = os.path.join(icon_path, "radie.svg")
Esempio n. 37
0
def save_fit_psp_test_set():
    """NOTE THIS CODE DOES NOT WORK BUT IS HERE FOR DOCUMENTATION PURPOSES SO 
    THAT WE CAN TRACE BACK HOW THE TEST DATA WAS CREATED IF NEEDED.
    Create a test set of data for testing the fit_psp function.  Uses Steph's 
    original first_puls_feature.py code to filter out error causing data.
    
    Example run statement
    python save save_fit_psp_test_set.py --organism mouse --connection ee
    
    Comment in the code that does the saving at the bottom
    """
    
    
    import pyqtgraph as pg
    import numpy as np
    import csv
    import sys
    import argparse
    from multipatch_analysis.experiment_list import cached_experiments
    from manuscript_figures import get_response, get_amplitude, response_filter, feature_anova, write_cache, trace_plot, \
        colors_human, colors_mouse, fail_rate, pulse_qc, feature_kw
    from synapse_comparison import load_cache, summary_plot_pulse
    from neuroanalysis.data import TraceList, Trace
    from neuroanalysis.ui.plot_grid import PlotGrid
    from multipatch_analysis.connection_detection import fit_psp
    from rep_connections import ee_connections, human_connections, no_include, all_connections, ie_connections, ii_connections, ei_connections
    from multipatch_analysis.synaptic_dynamics import DynamicsAnalyzer
    from scipy import stats
    import time
    import pandas as pd
    import json
    import os
    
    app = pg.mkQApp()
    pg.dbg()
    pg.setConfigOption('background', 'w')
    pg.setConfigOption('foreground', 'k')
    
    parser = argparse.ArgumentParser(description='Enter organism and type of connection you"d like to analyze ex: mouse ee (all mouse excitatory-'
                    'excitatory). Alternatively enter a cre-type connection ex: sim1-sim1')
    parser.add_argument('--organism', dest='organism', help='Select mouse or human')
    parser.add_argument('--connection', dest='connection', help='Specify connections to analyze')
    args = vars(parser.parse_args(sys.argv[1:]))
    
    all_expts = cached_experiments()
    manifest = {'Type': [], 'Connection': [], 'amp': [], 'latency': [],'rise':[], 'rise2080': [], 'rise1090': [], 'rise1080': [],
                'decay': [], 'nrmse': [], 'CV': []}
    fit_qc = {'nrmse': 8, 'decay': 499e-3}
    
    if args['organism'] == 'mouse':
        color_palette = colors_mouse
        calcium = 'high'
        age = '40-60'
        sweep_threshold = 3
        threshold = 0.03e-3
        connection = args['connection']
        if connection == 'ee':
            connection_types = ee_connections.keys()
        elif connection == 'ii':
            connection_types = ii_connections.keys()
        elif connection == 'ei':
            connection_types = ei_connections.keys()
        elif connection == 'ie':
            connection_types == ie_connections.keys()
        elif connection == 'all':
            connection_types = all_connections.keys()
        elif len(connection.split('-')) == 2:
            c_type = connection.split('-')
            if c_type[0] == '2/3':
                pre_type = ('2/3', 'unknown')
            else:
                pre_type = (None, c_type[0])
            if c_type[1] == '2/3':
                post_type = ('2/3', 'unknown')
            else:
                post_type = (None, c_type[0])
            connection_types = [(pre_type, post_type)]
    elif args['organism'] == 'human':
        color_palette = colors_human
        calcium = None
        age = None
        sweep_threshold = 5
        threshold = None
        connection = args['connection']
        if connection == 'ee':
            connection_types = human_connections.keys()
        else:
            c_type = connection.split('-')
            connection_types = [((c_type[0], 'unknown'), (c_type[1], 'unknown'))]
    
    plt = pg.plot()
    
    scale_offset = (-20, -20)
    scale_anchor = (0.4, 1)
    holding = [-65, -75]
    qc_plot = pg.plot()
    grand_response = {}
    expt_ids = {}
    feature_plot = None
    feature2_plot = PlotGrid()
    feature2_plot.set_shape(5,1)
    feature2_plot.show()
    feature3_plot = PlotGrid()
    feature3_plot.set_shape(1, 3)
    feature3_plot.show()
    amp_plot = pg.plot()
    synapse_plot = PlotGrid()
    synapse_plot.set_shape(len(connection_types), 1)
    synapse_plot.show()
    for c in range(len(connection_types)):
        cre_type = (connection_types[c][0][1], connection_types[c][1][1])
        target_layer = (connection_types[c][0][0], connection_types[c][1][0])
        conn_type = connection_types[c]
        expt_list = all_expts.select(cre_type=cre_type, target_layer=target_layer, calcium=calcium, age=age)
        color = color_palette[c]
        grand_response[conn_type[0]] = {'trace': [], 'amp': [], 'latency': [], 'rise': [], 'dist': [], 'decay':[], 'CV': [], 'amp_measured': []}
        expt_ids[conn_type[0]] = []
        synapse_plot[c, 0].addLegend()
        for expt in expt_list:
            for pre, post in expt.connections:
                if [expt.uid, pre, post] in no_include:
                    continue
                cre_check = expt.cells[pre].cre_type == cre_type[0] and expt.cells[post].cre_type == cre_type[1]
                layer_check = expt.cells[pre].target_layer == target_layer[0] and expt.cells[post].target_layer == target_layer[1]
                if cre_check is True and layer_check is True:
                    pulse_response, artifact = get_response(expt, pre, post, analysis_type='pulse')
                    if threshold is not None and artifact > threshold:
                        continue
                    response_subset, hold = response_filter(pulse_response, freq_range=[0, 50], holding_range=holding, pulse=True)
                    if len(response_subset) >= sweep_threshold:
                        qc_plot.clear()
                        qc_list = pulse_qc(response_subset, baseline=1.5, pulse=None, plot=qc_plot)
                        if len(qc_list) >= sweep_threshold:
                            avg_trace, avg_amp, amp_sign, peak_t = get_amplitude(qc_list)
    #                        if amp_sign is '-':
    #                            continue
    #                        #print ('%s, %0.0f' %((expt.uid, pre, post), hold, ))
    #                        all_amps = fail_rate(response_subset, '+', peak_t)
    #                        cv = np.std(all_amps)/np.mean(all_amps)
    #                        
    #                        # weight parts of the trace during fitting
                            dt = avg_trace.dt
                            weight = np.ones(len(avg_trace.data))*10.  #set everything to ten initially
                            weight[int(10e-3/dt):int(12e-3/dt)] = 0.   #area around stim artifact
                            weight[int(12e-3/dt):int(19e-3/dt)] = 30.  #area around steep PSP rise 
                            
                            # check if the test data dir is there and if not create it
                            test_data_dir='test_psp_fit'
                            if not os.path.isdir(test_data_dir):
                                os.mkdir(test_data_dir)
                                
                            save_dict={}
                            save_dict['input']={'data': avg_trace.data.tolist(),
                                                'dtype': str(avg_trace.data.dtype),
                                                'dt': float(avg_trace.dt),
                                                'amp_sign': amp_sign,
                                                'yoffset': 0, 
                                                'xoffset': 14e-3, 
                                                'avg_amp': float(avg_amp),
                                                'method': 'leastsq', 
                                                'stacked': False, 
                                                'rise_time_mult_factor': 10., 
                                                'weight': weight.tolist()} 
                            
                            # need to remake trace because different output is created
                            avg_trace_simple=Trace(data=np.array(save_dict['input']['data']), dt=save_dict['input']['dt']) # create Trace object
                            
                            psp_fits_original = fit_psp(avg_trace, 
                                               sign=save_dict['input']['amp_sign'], 
                                               yoffset=save_dict['input']['yoffset'], 
                                               xoffset=save_dict['input']['xoffset'], 
                                               amp=save_dict['input']['avg_amp'],
                                               method=save_dict['input']['method'], 
                                               stacked=save_dict['input']['stacked'], 
                                               rise_time_mult_factor=save_dict['input']['rise_time_mult_factor'], 
                                               fit_kws={'weights': save_dict['input']['weight']})  
    
                            psp_fits_simple = fit_psp(avg_trace_simple, 
                                               sign=save_dict['input']['amp_sign'], 
                                               yoffset=save_dict['input']['yoffset'], 
                                               xoffset=save_dict['input']['xoffset'], 
                                               amp=save_dict['input']['avg_amp'],
                                               method=save_dict['input']['method'], 
                                               stacked=save_dict['input']['stacked'], 
                                               rise_time_mult_factor=save_dict['input']['rise_time_mult_factor'], 
                                               fit_kws={'weights': save_dict['input']['weight']})  
                            print expt.uid, pre, post    
                            if psp_fits_original.nrmse()!=psp_fits_simple.nrmse():     
                                print '  the nrmse values dont match'
                                print '\toriginal', psp_fits_original.nrmse()
                                print '\tsimple', psp_fits_simple.nrmse()
def main():
    global plotItem, viewBox, pw

    (xMin, xMax, xDelta) = (-5, 5, 0.1)
    x = np.arange(xMin, xMax, xDelta)
    mu = 0.
    sigma = 1.
    y = 1 / (sigma * np.sqrt(2 * np.pi)) * np.exp(-(x - mu)**2 /
                                                  (2 * sigma**2))

    mu = 1.0
    sigma = 0.7
    y2 = 1 / (sigma * np.sqrt(2 * np.pi)) * np.exp(-(x - mu)**2 /
                                                   (2 * sigma**2))

    pg.setConfigOption('background', 'w')
    pg.setConfigOption('foreground', 'k')
    app = pg.mkQApp()

    win = pg.GraphicsWindow(title="Overlay 2 plots")
    win.clear()

    win.addLabel("Second plot has log scale", row=1, col=1, colspan=10)
    win.addLabel("A comment", row=2, col=1, colspan=10)

    plotItem = win.addPlot(row=3, col=1)
    plotItem.setLabels(left='axis 1')
    plotItem.showAxis('top')
    plotItem.showAxis('right')
    plotItem.getAxis('right').style['showValues'] = False
    plotItem.getAxis('right').setLabel('axis2', color='#00ffff')
    plotItem.setLogMode(x=False, y=False)

    plotDataItem = plotItem.plot()
    plotDataItem.setData(x, y)

    ## create a new ViewBox, link the right axis to its coordinate system
    viewBox = pg.ViewBox()
    plotItem.scene().addItem(viewBox)
    #
    # Link this axis to a ViewBox, causing its displayed range to
    # match the visible range of the view.
    #
    plotItem.getAxis('right').linkToView(viewBox)
    #
    # link the views x-axis to another view
    #
    viewBox.setXLink(plotItem)

    vbDataItem = pg.PlotDataItem(x, y2, pen='#00ffff')
    vbDataItem.setLogMode(False, True)
    viewBox.addItem(vbDataItem)

    viewBox.enableAutoRange(x=True, y=True)
    #viewBox.setXRange( -5, 5)
    #viewBox.setYRange( -10, 1)

    updateViews()
    plotItem.vb.sigResized.connect(updateViews)

    app.processEvents()
    time.sleep(0.1)
    app.processEvents()

    print "Prtc ",
    sys.stdin.readline()
Esempio n. 39
0
class LatentSpaceWidget(pg.GraphicsWindow):
    pg.setConfigOption('background', 'w')
    pg.setConfigOption('foreground', 'k')
    ptr1 = 0

    def __init__(self, parent=None, config_ergo='rula', **kargs):
        pg.GraphicsWindow.__init__(self, **kargs)
        self.setParent(parent)
        timer = pg.QtCore.QTimer(self)
        timer.timeout.connect(self.update)
        timer.start(10)  # number of seconds (every 1000) for next update

        self.view = pg.PlotWidget(self)
        self.view.resize(350, 350)
        self.view.setWindowTitle('Ergonomic score in latent space')
        self.view.setAspectLocked(True)
        self.view.show()

        self.port = yarp.BufferedPortBottle()
        self.port.open('/plot_latentspace/' + config_ergo)
        yarp.Network.connect('/AE/latent:o', self.port.getName())

        metric = 'jointAngle'

        path_src = "/home/amalaise/Documents/These/code/ergo_prediction/ergonomic_assessment/src/"

        self.config_ergo = config_ergo

        if self.config_ergo == 'rula':
            ergo_name = ['RULA_SCORE']
            ergo_assessment = ErgoAssessment(path_src +
                                             'config/rula_config.json')
        else:
            ergo_name = ['TABLE_REBA_C']
            ergo_assessment = ErgoAssessment(path_src +
                                             'config/reba_config.json')

        size_latent = 2
        dx = 0.02

        loss = [[]]
        autoencoder = []

        all_score = []
        all_size = []
        type_data = []

        path = path_src + "save/AE/" + metric + "/" + str(size_latent) + '/'
        list_files = [
            f for f in os.listdir(path)
            if os.path.isfile(os.path.join(path, f))
        ]
        list_files.sort()
        file = list_files[0]

        with open(path + file, 'rb') as input:
            autoencoder = pickle.load(input)

        input_data = autoencoder.get_data_test()
        data_output, encoded_data, score = autoencoder.test_model(input_data)
        score = autoencoder.evaluate_model(input_data, data_output, metric)

        Max = np.max(encoded_data, axis=0)
        Min = np.min(encoded_data, axis=0)
        Mean = np.mean(encoded_data, axis=0)

        # Compute ergo score

        list_ergo_score = ergo_assessment.get_list_score_name()
        list_ergo_score.sort()

        reduce_posture = HumanPosture(path_src + 'config/mapping_joints.json')
        posture = Skeleton('dhm66_ISB_Xsens.urdf')

        self.X = np.arange(0.0, 1.0 + dx, dx)

        pd_ergo_grid = pd.read_csv(self.config_ergo + '_grid.csv',
                                   index_col=False)
        self.ergo_grid = np.asarray(pd_ergo_grid)

        ergo_color_grid = np.zeros(
            (len(self.ergo_grid), len(self.ergo_grid), 3))

        print(np.shape(ergo_color_grid))

        for i in range(len(self.ergo_grid)):
            for j in range(len(self.ergo_grid)):
                if config_ergo == 'reba':
                    if self.ergo_grid[i, j] == 1:
                        ergo_color_grid[i, j] = [0, 1, 0]
                    elif self.ergo_grid[i, j] == 2:
                        ergo_color_grid[i, j] = [0.3, 0.7, 0]
                    elif self.ergo_grid[i, j] == 3:
                        ergo_color_grid[i, j] = [0.5, 0.5, 0]
                    elif self.ergo_grid[i, j] == 4:
                        ergo_color_grid[i, j] = [0.7, 0.3, 0]
                else:
                    if self.ergo_grid[i, j] == 2:
                        ergo_color_grid[i, j] = [0, 1, 0]
                    elif self.ergo_grid[i, j] == 3:
                        ergo_color_grid[i, j] = [0.3, 0.7, 0]
                    elif self.ergo_grid[i, j] == 4:
                        ergo_color_grid[i, j] = [0.5, 0.5, 0]
                    elif self.ergo_grid[i, j] == 5:
                        ergo_color_grid[i, j] = [0.7, 0.3, 0]

        self.ergo_grid = ergo_color_grid

        # self.ergo_grid = np.zeros((len(self.X), len(self.X)))

        # for i, data_x in enumerate(self.X):
        #     for j, data_y in enumerate(self.X):

        #         x = np.zeros((1,size_latent))
        #         x[0, 0] = data_x
        #         x[0, 1] = data_y

        #         decoded_data = autoencoder.decode_data(x)
        #         if metric == 'posture':
        #             whole_body = reduce_posture.reduce2complete(decoded_data[0])
        #             posture.update_posture(whole_body)
        #         else:
        #             posture.update_posture(decoded_data[0])

        #         ergo_score = tools.compute_sequence_ergo(ergo_assessment, decoded_data[0], 0, ergo_name, path_src)[0]

        #         if self.config_ergo == 'reba':
        #             if ergo_score == 1:
        #                 ergo_score = 1
        #             elif 1 < ergo_score < 5:
        #                 ergo_score = 2
        #             elif 4 < ergo_score < 6:
        #                 ergo_score = 3
        #             else:
        #                 ergo_score = 4

        #         self.ergo_grid[j,i] = ergo_score

        self.flag = 0

        self.plot_latent_space()

    def plot_latent_space(self, x=0, y=0):
        if self.flag:
            self.view.removeItem(self.scatter)
            self.view.removeItem(self.plot_traj)
        else:
            self.list_traj = [[], []]

        self.scatter = pg.ScatterPlotItem(pen=pg.mkPen(width=10, color='b'),
                                          symbol='s',
                                          size=3)

        img_np = np.rot90(np.rot90(np.rot90(self.ergo_grid)))

        img = pg.ImageItem(img_np)

        self.scatter.setData(x=[x], y=[y])

        self.list_traj[0].append(x)
        self.list_traj[1].append(y)

        if len(self.list_traj[0]) > 10:
            del self.list_traj[0][0]
            del self.list_traj[1][0]

        self.plot_traj = pg.PlotCurveItem(x=self.list_traj[0],
                                          y=self.list_traj[1],
                                          pen=pg.mkPen(width=2, color='b'))

        img.setZValue(-100)
        self.view.addItem(img)
        self.view.addItem(self.scatter)
        self.view.addItem(self.plot_traj)
        self.view.getPlotItem().hideAxis('bottom')
        self.view.getPlotItem().hideAxis('left')

        if self.flag == 0:
            del self.list_traj[0][0]
            del self.list_traj[1][0]
            self.flag = 1

    def update(self):
        b_in = self.port.read()
        data = b_in.toString().split(' ')

        del data[0]

        data = list(map(float, data))
        data = np.asarray(data)

        self.plot_latent_space(x=data[0] * len(self.X),
                               y=len(self.X) - data[1] * len(self.X))
Esempio n. 40
0
from . import compute
from . import dcor
from . import export
from . import pipeline_plot
from . import preferences
from . import quick_view
from . import update
from . import widgets

from .. import pipeline
from .. import session

from .._version import version as __version__

# global plotting configuration parameters
pg.setConfigOption("background", "w")
pg.setConfigOption("foreground", "k")
pg.setConfigOption("antialias", True)
pg.setConfigOption("imageAxisOrder", "row-major")

# set Qt icon theme search path
QtGui.QIcon.setThemeSearchPaths([
    os.path.join(pkg_resources.resource_filename("shapeout2", "img"),
                 "icon-theme")
])
QtGui.QIcon.setThemeName(".")


class ShapeOut2(QtWidgets.QMainWindow):
    plots_changed = QtCore.pyqtSignal()
Esempio n. 41
0
    def __init__(self):
        super(Window, self).__init__()
        self.setGeometry(100, 100, 1050,
                         700)  # coords start from top left x, y, width, height
        self.setWindowTitle('hjDivePlan')

        # set toolbar
        toolbar = QtGui.QToolBar(self)
        run_plan = QtGui.QAction(QtGui.QIcon('images/play.png'), 'run', self)
        QtGui.QAction.connect(run_plan, QtCore.SIGNAL('triggered()'),
                              self.run_calculation)
        run_plan.setShortcut('Ctrl+R')
        toolbar.addAction(run_plan)
        tables = QtGui.QAction(QtGui.QIcon('images/tables.png'), 'tables',
                               self)
        QtGui.QAction.connect(tables, QtCore.SIGNAL('triggered()'),
                              self.display_tables)
        tables.setShortcut('Ctrl+T')
        toolbar.addAction(tables)
        save = QtGui.QAction(QtGui.QIcon('images/save.png'), 'save', self)
        QtGui.QAction.connect(save, QtCore.SIGNAL('triggered()'),
                              self.save_plan)
        tables.setShortcut('Ctrl+S')
        toolbar.addAction(save)
        info = QtGui.QAction(QtGui.QIcon('images/info2.png'), 'info', self)
        QtGui.QAction.connect(info, QtCore.SIGNAL('triggered()'),
                              self.display_info)
        info.setShortcut('Ctrl+I')
        toolbar.addAction(info)
        exit_planner = QtGui.QAction(QtGui.QIcon('images/exit.png'), 'exit',
                                     self)
        exit_planner.setShortcut('Ctrl+Q')
        QtGui.QAction.connect(exit_planner, QtCore.SIGNAL('triggered()'),
                              self.quit_app)
        toolbar.addAction(exit_planner)
        self.addToolBar(QtCore.Qt.LeftToolBarArea, toolbar)

        # fonts
        self.header_font = QtGui.QFont('SansSerif', 16)
        self.header_font.setBold(True)
        self.main_font = QtGui.QFont('SansSerif', 16)
        self.options_font = QtGui.QFont('Arial', 14)
        self.param_palette = QtGui.QPalette()
        self.param_palette.setColor(QtGui.QPalette.Foreground, QtCore.Qt.blue)

        # start main layout
        whole_layout = QtGui.QVBoxLayout()
        whole_layout.addSpacerItem(QtGui.QSpacerItem(120, 10))

        # dive params
        self.dive_dict = {1: {'d': 0, 't': 0}, 2: {'d': 0, 't': 0}}
        self.g_mix_val = 21
        self.po2_value = 1.4
        self.cylinder_size_val = 12
        self.sac_rate_val = 25
        self.reserve_val = 'thirds'
        self.refill = False

        # settings row
        settings_boxes = QtGui.QHBoxLayout()
        settings_boxes.addWidget(self.dive_set_box())
        settings_boxes.addWidget(self.gas_box())
        whole_layout.addLayout(settings_boxes)
        whole_layout.addSpacerItem(QtGui.QSpacerItem(120, 10))

        # plot box
        # invert default background foreground
        pg.setConfigOption('background', 'w')
        pg.setConfigOption('foreground', 'k')

        plot_box = QtGui.QGroupBox('Dive profile')
        plot_box.setFont(self.header_font)
        plot_layout = QtGui.QHBoxLayout()
        self.plot_widget = pg.PlotWidget()
        self.plot_widget.setLabel('left', 'Depth', 'm')
        self.plot_widget.setLabel('bottom', 'Time', 'mins')
        self.plot_widget.setFont(self.main_font)
        plot_layout.addWidget(self.plot_widget)
        plot_box.setLayout(plot_layout)
        whole_layout.addWidget(plot_box)

        # param box
        whole_layout.addWidget(self.param_box())

        main_widget = QtGui.QWidget()
        main_widget.setLayout(whole_layout)
        self.setCentralWidget(main_widget)
        self.show()
Esempio n. 42
0
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
import numpy as np
from communication import Communication
import math
from dataBase import data_base
from PyQt5.QtWidgets import QPushButton

pg.setConfigOption('background', (33, 33, 33))
pg.setConfigOption('foreground', (197, 198, 199))
# Interface variables
app = QtGui.QApplication([])
view = pg.GraphicsView()
Layout = pg.GraphicsLayout()
view.setCentralItem(Layout)
view.show()
view.setWindowTitle('Flight monitoring')
view.resize(1200, 700)

# declare object for serial Communication
ser = Communication()
# declare object for storage in CSV
data_base = data_base()
# Fonts for text items
font = QtGui.QFont()
font.setPixelSize(90)


# Title at top
text = """
Flight monitoring interface for cansats and OBC's <br>
Esempio n. 43
0
'''
feature_plot
'''

import sys
import numpy as np
import PyQt4.QtGui as QG
import PyQt4.QtCore as QC
import pyqtgraph as pg
pg.setConfigOption('antialias', True)
import pickle

feat_name = [
    'zcr', 'energy', 'energy_entropy', 'spectral_centroid', 'spectral_spread',
    'spectral_entropy', 'spectral_flux', 'spectral_rolloff', 'mfcc_1',
    'mfcc_2', 'mfcc_3', 'mfcc_4', 'mfcc_5', 'mfcc_6', 'mfcc_7', 'mfcc_8',
    'mfcc_9', 'mfcc_10', 'mfcc_11', 'mfcc_12', 'mfcc_13', 'chroma_1',
    'chroma_2', 'chroma_3', 'chroma_4', 'chroma_5', 'chroma_6', 'chroma_7',
    'chroma_8', 'chroma_9', 'chroma_10', 'chroma_11', 'chroma_12', 'chroma_std'
]


class feature_plot_mod(QG.QWidget):
    def __init__(self, parent=None):
        self.tabV = []
        self.tab_id = -1

        super(feature_plot_mod,
              self).__init__(parent)  # superclassのコンストラクタを使用。
        self.setWindowTitle("feature plot")
Esempio n. 44
0
import PyQt5.QtGui as qtg
import PyQt5.QtWidgets as qtw
import pyqtgraph as pygraph
import pyqtgraph.exporters as exporters

import mate.net.nao_data as nao_data
import mate.net.utils as net_utils
import mate.ui.utils as ui_utils
from mate.net.nao import Nao
from mate.ui.panels._panel import _Panel
from . import util
from mate.debug.colorlog import ColorLog

logger = ColorLog()

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


class Main(_Panel):
    name = "Plot"
    shortcut = qtg.QKeySequence("Ctrl+P")
    data_received_signal = qtc.pyqtSignal(nao_data.DebugValue, str)

    def __init__(self, main_window, nao: Nao, model=None):
        super(Main, self).__init__(main_window, self.name, nao)
        ui_utils.loadUi(__file__, self)
        self.model = ui_utils.load_model(
            os.path.dirname(__file__) + "/model.json", model)
        """
        self.data contains the data of curves.
Esempio n. 45
0
# Form implementation generated from reading ui file 'iFAMS_V5_New.ui'
#
# Created by: PyQt5 UI code generator 5.10.1
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets
import os
from numpy import arange, sin, pi
import GuiTestFun
import numpy as np
from operator import itemgetter
import pyqtgraph as pg

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


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(1148, 839)
        MainWindow.setStyleSheet(
            "background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(198, 198, 198, 255), stop:1 rgba(255, 255, 255, 255));R"
        )
        MainWindow.setWindowState(QtCore.Qt.WindowMaximized)
        QtGui.QApplication.setStyle(QtGui.QStyleFactory.create("Plastique"))
        MainWindow.setWindowIcon(QtGui.QIcon('CapI.png'))
        self.centralwidget = QtWidgets.QWidget(MainWindow)
Esempio n. 46
0
Created on Tue Apr 16 13:52:18 2019

@author: Jonas Mathiassen
A PyQt spectrum analyzer gui for the PicoScope 4262. 
Requires the picoscope library found at https://github.com/colinoflynn/pico-python.
This in turn requires the Picoscope SDK found at https://www.picotech.com/downloads.
"""

from PyQt5 import QtWidgets, QtCore

import pyqtgraph as pg
import numpy as np
from picoscope import ps4000
import sys

pg.setConfigOption('background', [247, 247, 247])
pg.setConfigOption('foreground', 'k')


def setupScope(nSamples=1 << 12):
    ps = ps4000.PS4000()

    # Example of simple capture
    res = ps.setSamplingFrequency(10E6, nSamples)
    sampleRate = res[0]
    print("Sampling @ %f MHz, %d samples" % (res[0] / 1E6, res[1]),
          f"RBW:{res[0]/(res[1]):.5f}")
    ps.setChannel("A", "DC", VRange=1e-3)
    return [ps, sampleRate]

    def __init__(self, MainWindow):
        self.temp_window = MainWindow
        MainWindow.setObjectName("MainWindow")

        from utils.window_utils import get_resolution_ratio
        self.width_ratio, self.height_ratio = get_resolution_ratio(600, 450)
        MainWindow.setMinimumHeight(self.height_ratio * 450)
        MainWindow.setMinimumWidth(self.width_ratio * 600)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")

        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(
            QtCore.QRect(self.width_ratio * 50, self.height_ratio * 20,
                         self.width_ratio * 71, self.height_ratio * 17))
        self.label.setObjectName("label")

        self.txt_search = QtWidgets.QLineEdit(self.centralwidget)
        self.txt_search.setPlaceholderText("  Search")
        self.txt_search.setGeometry(
            QtCore.QRect(self.width_ratio * 50, self.height_ratio * 60,
                         self.width_ratio * 329, self.height_ratio * 25))
        self.txt_search.setObjectName("txt_search")

        self.groupBox = QtWidgets.QGroupBox(self.centralwidget)
        self.groupBox.setGeometry(
            QtCore.QRect(self.width_ratio * 380, self.height_ratio * 45,
                         self.width_ratio * 131, self.height_ratio * 150))
        self.groupBox.setObjectName("groupBox")

        self.btn_reset = QtWidgets.QPushButton(self.groupBox)
        self.btn_reset.setGeometry(
            QtCore.QRect(self.width_ratio * 20, self.height_ratio * 80,
                         self.width_ratio * 91, self.height_ratio * 25))
        self.btn_reset.setObjectName("btn_reset")

        self.btn_evaluate = QtWidgets.QPushButton(self.groupBox)
        self.btn_evaluate.setGeometry(
            QtCore.QRect(self.width_ratio * 20, self.height_ratio * 40,
                         self.width_ratio * 89, self.height_ratio * 25))
        self.btn_evaluate.setObjectName("btn_evaluate")

        self.btn_return = QtWidgets.QPushButton(self.groupBox)
        self.btn_return.setGeometry(
            QtCore.QRect(self.width_ratio * 20, self.height_ratio * 120,
                         self.width_ratio * 91, self.height_ratio * 25))
        self.btn_return.setObjectName("btn_return")

        self.scrollArea = QtWidgets.QScrollArea(self.centralwidget)
        self.scrollArea.setGeometry(
            QtCore.QRect(self.width_ratio * 50, self.height_ratio * 90,
                         self.width_ratio * 329, self.height_ratio * 105))
        self.scrollArea.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
        self.scrollArea.setHorizontalScrollBarPolicy(
            QtCore.Qt.ScrollBarAsNeeded)
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setObjectName("scrollArea")
        self.scrollAreaWidgetContents_3 = QtWidgets.QWidget()
        self.scrollAreaWidgetContents_3.setGeometry(
            QtCore.QRect(0, 0, self.width_ratio * 309,
                         self.height_ratio * 105))
        self.scrollAreaWidgetContents_3.setObjectName(
            "scrollAreaWidgetContents_3")
        self.scrollArea.setWidget(self.scrollAreaWidgetContents_3)

        import pyqtgraph as pg

        pg.setConfigOption('background', 'w')
        pg.setConfigOption('foreground', 'k')
        self.win = pg.PlotWidget()
        self.win.setXRange(0.5, 9.5)
        self.win.setYRange(0, 100)

        self.bg = pg.BarGraphItem(x=[],
                                  height=[],
                                  width=0.5,
                                  brushes=BAR_COLORS)
        self.win.addItem(self.bg)

        # set the layout
        self.graph_layout = QtWidgets.QVBoxLayout()
        self.graph_layout.setGeometry(
            QtCore.QRect(self.width_ratio * 40, self.height_ratio * 220,
                         self.width_ratio * 481, self.height_ratio * 250))

        self.lbl_evaluation_status = QtWidgets.QLabel()
        self.lbl_evaluation_status.setGeometry(
            QtCore.QRect(self.width_ratio * 10, self.height_ratio * 30,
                         self.width_ratio * 500, self.height_ratio * 17))
        self.lbl_evaluation_status.setObjectName("lbl_evaluation_status")

        self.graph_layout.addWidget(self.lbl_evaluation_status)

        self.groupBox_overview = QtWidgets.QGroupBox(self.centralwidget)
        self.groupBox_overview.setGeometry(
            QtCore.QRect(self.width_ratio * 40, self.height_ratio * 220,
                         self.width_ratio * 481, self.height_ratio * 180))
        self.groupBox_overview.setObjectName("groupBox_overview")
        self.groupBox_overview.setLayout(self.graph_layout)

        self.lbl_evaluation_none = QtWidgets.QLabel()
        self.lbl_evaluation_none.setGeometry(
            QtCore.QRect(0, 0, self.width_ratio * 500, self.height_ratio * 17))
        self.lbl_evaluation_none.setObjectName("lbl_evaluation_none")
        self.lbl_evaluation_none.setText("Not Evaluated")
        self.lbl_evaluation_none.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_evaluation_none.setStyleSheet(
            "color:red;background-color:white;")

        self.none_layout = QtWidgets.QVBoxLayout()
        self.none_layout.setGeometry(
            QtCore.QRect(self.width_ratio * 40, self.height_ratio * 220,
                         self.width_ratio * 481, self.height_ratio * 250))
        self.none_layout.addWidget(self.lbl_evaluation_none)

        self.graph_layout2 = QtWidgets.QVBoxLayout()
        self.graph_layout2.setGeometry(
            QtCore.QRect(self.width_ratio * 40, self.height_ratio * 378,
                         self.width_ratio * 481, self.height_ratio * 55))

        self.groupBox_3 = QtWidgets.QGroupBox(self.centralwidget)
        self.groupBox_3.setGeometry(
            QtCore.QRect(self.width_ratio * 40, self.height_ratio * 378,
                         self.width_ratio * 481, self.height_ratio * 55))
        self.groupBox_3.setLayout(self.graph_layout2)

        create_graph_indicator(self.graph_layout2)
        self.graph_layout.addLayout(self.graph_layout2)
        self.groupBox_3.hide()

        self.groupBox_overview_none = QtWidgets.QGroupBox(self.centralwidget)
        self.groupBox_overview_none.setGeometry(
            QtCore.QRect(self.width_ratio * 40, self.height_ratio * 220,
                         self.width_ratio * 481, self.height_ratio * 180))
        self.groupBox_overview_none.setObjectName("groupBox_overview_none")
        self.groupBox_overview_none.setLayout(self.none_layout)

        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(
            QtCore.QRect(0, 0, self.width_ratio * 615, self.height_ratio * 22))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusBar = QtWidgets.QStatusBar(MainWindow)
        self.statusBar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusBar)

        self.load_products_list()
        self.selected_product = None

        self.listWidget.itemClicked.connect(self.list_item_event)
        self.btn_evaluate.clicked.connect(self.btn_evaluate_clicked)
        self.btn_reset.clicked.connect(self.btn_reset_clicked)
        self.btn_return.clicked.connect(self.btn_return_clicked)
        self.txt_search.textChanged.connect(self.search_product)

        self.btn_reset.setDisabled(True)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
Esempio n. 48
0
    def __init__(self):
        pg.setConfigOption("foreground", "k")
        super().__init__()
        self.setupUi(self)
        self.init_gui()

        self.esp_32_0_receiver = DataReceiver("30:AE:A4:73:D6:BA")
        self.esp_32_1_receiver = DataReceiver("30:AE:A4:74:39:42")
        self.esp_32_2_receiver = DataReceiver("30:AE:A4:74:A5:BE")

        self.esp_32_0_receiver.consoleOutText.connect(self.update_console)
        self.esp_32_1_receiver.consoleOutText.connect(self.update_console)
        self.esp_32_2_receiver.consoleOutText.connect(self.update_console)

        self.esp_32_0_receiver.receivedData.connect(self.update_top_plot)
        self.esp_32_1_receiver.receivedData.connect(self.update_bottom_plot)
        self.esp_32_1_receiver.receivedData.connect(self.update_top_plot)
        self.esp_32_2_receiver.receivedData.connect(self.update_top_plot)

        self.dallas_temp_curve = self.top_plot.plot(
            name="dallas_temp",
            pen=self.set_pen(QColor(255, 116, 0))
            # pen=self.set_pen(QColor(255,0,0))
        )
        self.sound_curve = self.top_plot.plot(
            name="sound",
            pen=self.set_pen(QColor(245, 0, 29))
            # pen=self.set_pen(QColor(255, 0, 0))
        )
        self.photoresistor_curve = self.top_plot.plot(
            name='photoresistor',
            pen=self.set_pen(QColor(0, 255, 0))
            # pen=self.set_pen(QColor(255, 0, 0))
        )
        self.dht_temp_curve = self.bottom_plot.plot(
            name="dht_temp",
            pen=self.set_pen(QColor(173, 0, 159))
            # pen=self.set_pen(QColor(255, 0, 0))
        )
        self.humidity_curve = self.bottom_plot.plot(
            name="humidity",
            pen=self.set_pen(QColor(233, 251, 0))
            # pen=self.set_pen(QColor(255, 0, 0))
        )

        self.startButton.clicked.connect(self.start_receiving)
        self.stopButton.clicked.connect(self.stop_receiving)

        self.startButton.setStyleSheet(f"""
            #startButton {{
                background-color: rgb(51,67,107);
                border-radius: 5px;
                color: rgb(231,233,220);
             }}
             #startButton:pressed {{
                 background-color: {colorsDict["lavender"]};
             }}
             """)

        self.stopButton.setStyleSheet(f"""
            #stopButton {{
                background-color: grey;
                border-radius: 5px;
                color: rgb(231,233,220);
             }}
             #stopButton:pressed {{
                 background-color: {colorsDict["lavender"]};
             }}
             """)
Esempio n. 49
0
    def plot(self):
        pg.setConfigOption('background', 'w')
        pg.setConfigOption('foreground', 'k')

        pw_iv50 = pg.PlotWidget(title='50-IV')
        self.plt_iv50_1 = pw_iv50.plot(symbol="o",
                                       pen=pg.mkPen("r", width=1),
                                       symbolSize=12,
                                       symbolBrush=(0, 255, 0))
        self.plt_iv50_2 = pw_iv50.plot(symbol="o",
                                       pen=pg.mkPen("g", width=1),
                                       symbolSize=12,
                                       symbolBrush=(0, 255, 0))
        self.plt_iv50_3 = pw_iv50.plot(symbol="o",
                                       pen=pg.mkPen("r", width=1),
                                       symbolSize=10,
                                       symbolBrush=(0, 170, 0))
        self.plt_iv50_4 = pw_iv50.plot(symbol="o",
                                       pen=pg.mkPen("g", width=1),
                                       symbolSize=10,
                                       symbolBrush=(0, 170, 0))
        self.plt_iv50_5 = pw_iv50.plot(symbol="o",
                                       pen=pg.mkPen("r", width=1),
                                       symbolSize=8,
                                       symbolBrush=(0, 85, 0))
        self.plt_iv50_6 = pw_iv50.plot(symbol="o",
                                       pen=pg.mkPen("g", width=1),
                                       symbolSize=8,
                                       symbolBrush=(0, 85, 0))
        self.plt_iv50_7 = pw_iv50.plot(symbol="o",
                                       pen=pg.mkPen("r", width=1),
                                       symbolSize=6,
                                       symbolBrush=(0, 0, 0))
        self.plt_iv50_8 = pw_iv50.plot(symbol="o",
                                       pen=pg.mkPen("g", width=1),
                                       symbolSize=6,
                                       symbolBrush=(0, 0, 0))
        self.gridLayout.addWidget(pw_iv50, 0, 0)

        plt300 = pg.PlotWidget(title='300-IV')
        self.plt_iv300_1 = plt300.plot(symbol="o",
                                       pen=pg.mkPen("r", width=1),
                                       symbolSize=12,
                                       symbolBrush=(0, 255, 0))
        self.plt_iv300_2 = plt300.plot(symbol="o",
                                       pen=pg.mkPen("g", width=1),
                                       symbolSize=12,
                                       symbolBrush=(0, 255, 0))
        self.plt_iv300_3 = plt300.plot(symbol="o",
                                       pen=pg.mkPen("r", width=1),
                                       symbolSize=10,
                                       symbolBrush=(0, 170, 0))
        self.plt_iv300_4 = plt300.plot(symbol="o",
                                       pen=pg.mkPen("g", width=1),
                                       symbolSize=10,
                                       symbolBrush=(0, 170, 0))
        self.plt_iv300_5 = plt300.plot(symbol="o",
                                       pen=pg.mkPen("r", width=1),
                                       symbolSize=8,
                                       symbolBrush=(0, 85, 0))
        self.plt_iv300_6 = plt300.plot(symbol="o",
                                       pen=pg.mkPen("g", width=1),
                                       symbolSize=8,
                                       symbolBrush=(0, 85, 0))
        self.plt_iv300_7 = plt300.plot(symbol="o",
                                       pen=pg.mkPen("r", width=1),
                                       symbolSize=6,
                                       symbolBrush=(0, 0, 0))
        self.plt_iv300_8 = plt300.plot(symbol="o",
                                       pen=pg.mkPen("g", width=1),
                                       symbolSize=6,
                                       symbolBrush=(0, 0, 0))
        self.gridLayout.addWidget(plt300, 0, 1)

        pw_month = pg.PlotWidget(title='MONTH-50-300-MONTH')
        pw_month.showGrid(x=False, y=True)
        pw_month.addLegend(offset=(30, 100))
        self.plt_month50 = pw_month.plot(name="50")
        self.plt_month300 = pw_month.plot(name="300")
        self.gridLayout.addWidget(pw_month, 0, 2)

        pw_qvix = pg.PlotWidget(title='QVIX')
        pw_qvix.showGrid(x=True, y=True)
        pw_qvix.addLegend()
        self.plt_qvix = pw_qvix.plot(pen=pg.mkPen("d", width=4), name="iv")
        self.gridLayout.addWidget(pw_qvix, 1, 0)

        pw_north = pg.PlotWidget(title='NORTH')
        pw_north.showGrid(x=False, y=True)
        pw_north.addLegend()
        self.plt_north_hgt = pw_north.plot(pen=pg.mkPen("b", width=2),
                                           name="hgt")
        self.plt_north_sgt = pw_north.plot(pen=pg.mkPen("g", width=1),
                                           name="sgt")
        self.plt_north_all = pw_north.plot(pen=pg.mkPen("d", width=1),
                                           name="all")
        self.gridLayout.addWidget(pw_north, 1, 1)

        pw_volume = pg.PlotWidget(title='VOLUME')
        pw_volume.showGrid(x=False, y=True)
        self.plt_volume = pw_volume.plot(name="volume")
        self.stock_50 = pw_volume.plot(name="stock_50")
        self.gridLayout.addWidget(pw_volume, 1, 2)
Esempio n. 50
0
def main():
    args = example_utils.ExampleArgumentParser(num_sens=1).parse_args()
    example_utils.config_logging(args)

    if args.socket_addr:
        client = SocketClient(args.socket_addr)
    elif args.spi:
        client = SPIClient()
    else:
        port = args.serial_port or example_utils.autodetect_serial_port()
        client = UARTClient(port)

    config = configs.EnvelopeServiceConfig()
    config.sensor = args.sensors
    config.range_interval = [0.2, 0.6]
    config.sweep_rate = 60
    config.gain = 0.65

    info = client.setup_session(config)
    num_points = info["data_length"]
    xs = np.linspace(*config.range_interval, num_points)
    num_hist = 2*config.sweep_rate

    hist_data = np.zeros([num_hist, num_points])
    hist_max = np.zeros(num_hist)
    smooth_max = example_utils.SmoothMax(config.sweep_rate)

    app = QtWidgets.QApplication([])
    pg.setConfigOption("background", "w")
    pg.setConfigOption("foreground", "k")
    pg.setConfigOptions(antialias=True)
    win = pg.GraphicsLayoutWidget()
    win.closeEvent = lambda _: interrupt_handler.force_signal_interrupt()
    win.setWindowTitle("Acconeer PyQtGraph example")

    env_plot = win.addPlot(title="Envelope")
    env_plot.showGrid(x=True, y=True)
    env_plot.setLabel("bottom", "Depth (m)")
    env_plot.setLabel("left", "Amplitude")
    env_curve = env_plot.plot(pen=pg.mkPen("k", width=2))

    win.nextRow()
    hist_plot = win.addPlot()
    hist_plot.setLabel("bottom", "Time (s)")
    hist_plot.setLabel("left", "Depth (m)")
    hist_image_item = pg.ImageItem()
    hist_image_item.translate(-2, config.range_start)
    hist_image_item.scale(2/num_hist, config.range_length/num_points)
    hist_plot.addItem(hist_image_item)

    # try to get a colormap from matplotlib
    try:
        hist_image_item.setLookupTable(example_utils.pg_mpl_cmap("viridis"))
    except ImportError:
        pass

    win.show()

    interrupt_handler = example_utils.ExampleInterruptHandler()
    print("Press Ctrl-C to end session")

    client.start_streaming()

    while not interrupt_handler.got_signal:
        info, sweep = client.get_next()

        hist_data = np.roll(hist_data, -1, axis=0)
        hist_data[-1] = sweep
        hist_max = np.roll(hist_max, -1)
        hist_max[-1] = np.max(sweep)
        y_max = smooth_max.update(np.amax(hist_max))
        env_curve.setData(xs, sweep)
        env_plot.setYRange(0, y_max)
        hist_image_item.updateImage(hist_data, levels=(0, y_max))

        app.processEvents()

    print("Disconnecting...")
    app.closeAllWindows()
    client.disconnect()
    def __init__(self, data, bins, sample, log=False, *args, **kwargs):
        plt.close(
            plt.gca().get_figure()
        )  # Mega hack to save the day (close annoying mpl figure....... not a fan). MDT = magic don't touch
        pg.setConfigOption('background', 'w')
        pg.setConfigOption('foreground', 'k')
        super().__init__(*args, **kwargs)
        self.l = QtGui.QGridLayout()
        self.setLayout(self.l)

        # Add plotItem to allow for axes

        self.imv1 = CustomImageView(view=pg.PlotItem())
        self.imv2 = pg.ImageView(view=pg.PlotItem())

        #Insert widgets into layout
        self.l.addWidget(self.imv1, 0, 0)
        self.l.addWidget(self.imv2, 1, 0)

        # Create the region-of-interest line segment
        self.roi = pg.ROI([1, 0], [1, 1], pen='r', resizable=True)
        self.roi.setSize([1, 0.1])
        self.roi.addScaleHandle(
            [0.5, 1],
            [0.5, 0.5],
        )
        self.roi.addScaleHandle([0, 0.5], [0.5, 0.5])
        self.roi.addRotateHandle([1.0, 1.0], [0.5, 0.5])

        # Change color of roi markers
        handleColor = QtGui.QColor(255, 102, 0)
        for handle in self.roi.getHandles():
            handle.pen.setColor(handleColor)

        self.imv1.addItem(self.roi)

        self.Data, self.bins = data, bins

        if len(data) == 4:
            with warnings.catch_warnings():
                warnings.simplefilter("ignore")
                self.data = np.divide(self.Data[0] * self.Data[-1],
                                      self.Data[1] * self.Data[2])
                self.data[self.Data[-1] == 0] = -np.nanmin(
                    self.data[self.data != 0])
        else:
            self.data = self.Data

        # set unmeasured areas to negative value
        if log:
            self.data = np.log10(self.data + 1e-20)

        # transpose data to comply with viewer requirements
        self.data = self.data.transpose((2, 0, 1))

        # Extract the sample
        self.sample = sample
        # Calculate the projection directions
        self.axes = np.array(
            [self.sample.calculateQxQyToHKL(*X) for X in self.sample.RotMat])

        ## Display the data
        self.imv1.setImage(self.data,
                           xvals=self.bins[2][0, 0, :],
                           levels=(-1e-7, 1e-5),
                           autoLevels=False)

        self.imv1.setHistogramRange(-8.5e-8, 1e-5)
        # unlock aspect ratio
        self.imv1.view.setAspectLocked(False)

        # Generate and add correct labels to axes
        self.xaxis = self.imv1.view.axes['bottom']['item']
        self.yaxis = self.imv1.view.axes['left']['item']

        self.xlabel = _tools.generateLabel(_tools.LengthOrder(self.axes[0]))
        self.ylabel = _tools.generateLabel(_tools.LengthOrder(self.axes[1]))

        self.xaxis.setLabel(text=self.xlabel, units='RLU')
        self.yaxis.setLabel(text=self.ylabel, units='RLU')

        # Setup color map for main window
        self.setupColorscale(self.imv1)

        # Calcualte scaling and offsets between image view and RLU axes
        self.qxRange = np.diff(self.bins[0][[0, -1], 0, 0])
        self.qyRange = np.diff(self.bins[1][0, [0, -1], 0])
        self.ERange = np.diff(self.bins[2][0, 0, [0, -1]])

        self.qxScale = self.qxRange * np.linalg.norm(
            self.axes[0]) / self.bins[0].shape[0]
        self.qyScale = self.qyRange * np.linalg.norm(
            self.axes[1]) / self.bins[0].shape[1]
        self.EScale = self.ERange / self.bins[0].shape[2]

        self.qxCenter = self.bins[0][0, 0, 0] * np.linalg.norm(self.axes[0])
        self.qyCenter = self.bins[1][0, 0, 0] * np.linalg.norm(self.axes[1])
        self.ECenter = self.bins[2][0, 0, 0]

        # Apply scaling and translation
        img1Item = self.imv1.getImageItem()
        img1Item.scale(self.qxScale, self.qyScale)
        img1Item.translate(self.qxCenter / self.qxScale,
                           self.qyCenter / self.qyScale)
        # Un-invert yaxis
        self.imv1.view.getViewBox().invertY(False)
        self.imv1.view.autoRange(True)
        self.imv1.view.setAutoVisible(x=True, y=True)

        # Add labels colormap for cut window
        self.imv2.view.setLabel("left", "Energy", units='meV')
        self.imv2.view.setLabel("bottom", "HKL", units='RLU')
        self.setupColorscale(self.imv2)

        # Hide all unneeded menus and uninvert yaxes
        self.imv2.ui.roiBtn.hide()
        self.imv2.ui.menuBtn.hide()
        self.imv2.view.getViewBox().invertY(False)

        # Extract projection matrix used for position calculation along cut
        self.projectionMatrix = self.axes
        self.projectionMatrix[0] *= 1 / np.linalg.norm(
            self.projectionMatrix[0])
        self.projectionMatrix[1] *= 1 / np.linalg.norm(
            self.projectionMatrix[1])
        self.xaxis2 = self.imv2.view.axes['bottom']['item']
        self.yaxis2 = self.imv2.view.axes['left']['item']

        self.xaxis2.tickStrings = lambda values, scale, spacing: self.XtickStrings(
            self.roi, values, scale, spacing)
        self.yaxis2.tickStrings = lambda values, scale, spacing: self.YtickStrings(
            values, scale, spacing)

        # Create function to be called when cut changes

        # Connect update-function to correct slot
        self.roi.sigRegionChanged.connect(self.update)

        # Call update for initial position
        self.update()
Esempio n. 52
0
A GUI displays the data as it's acquired, and collects statistics
from multiple traces.
More information on the DAQ is available at:
https://documentation.help/NI-DAQmx-Key-Concepts/documentation.pdf
We use the python module: https://nidaqmx-python.readthedocs.io
"""
import os

os.system("color")  # allows error/warning/info messages to print in colour
import re
import sys
import time
import numpy as np
import pyqtgraph as pg

pg.setConfigOption('background', 'w')  # set graph background default white
pg.setConfigOption('foreground', 'k')  # set graph foreground default black
from collections import OrderedDict
# some python packages use PyQt4, some use PyQt5...
try:
    from PyQt4.QtCore import pyqtSignal, QRegExp, QItemSelectionModel, QThread
    from PyQt4.QtGui import (QApplication, QPushButton, QWidget, QLabel,
                             QAction, QGridLayout, QMainWindow, QMessageBox,
                             QLineEdit, QIcon, QFileDialog, QMenu,
                             QActionGroup, QFont, QTableWidget,
                             QTableWidgetItem, QTabWidget, QVBoxLayout,
                             QDoubleValidator, QIntValidator, QRegExpValidator,
                             QComboBox, QListWidget)
except ImportError:
    from PyQt5.QtCore import pyqtSignal, QRegExp, QItemSelectionModel, QThread
    from PyQt5.QtGui import (QIcon, QDoubleValidator, QIntValidator, QFont,
Esempio n. 53
0
    def __init__(self, camera=None):
        super().__init__()
        # Main Window Widget
        pg.setConfigOption('background', 'w')
        self.central_widget = QWidget()
        self.aimwig = QWidget()
        QApplication.setStyle(QStyleFactory.create('Fusion'))
        # self.changePalette()
        
        # parameters
        self.framerate = 50
        self.roi = [195, 148, 224, 216]
        self.datalen = 150
        self.movingpt = 50
        self.exp = 50
        self.gain = 50
        self.level = None
        self.lock = True
        self.avgval = 44
        self.roi_flag = False

        # Camera
        self.camera = camera

        # First Horizon row Widgets
        self.button_start = QPushButton("Start/Stop")
        self.button_start.setStyleSheet("background-color:rgb(252,42,71)")
        self.button_start.setCheckable(True)
        self.button_reset= QPushButton('Reset/Update')
        self.button_save= QPushButton('SaveData')
        # Second Horizontal row Widgets
        self.button_locklevel= QPushButton("LockLevel")
        self.button_locklevel.setCheckable(True)

        self.value_locklevel= QLineEdit(str(self.level))
        self.value_locklevel.textChanged.connect(self.update_parameters)

        self.label_framerate = QLabel("FRate(millisec)")
        self.value_framerate = QLineEdit(str(self.framerate))
        self.value_framerate.textChanged.connect(self.update_parameters)

        self.label_movingpt = QLabel("MovingPoints")
        self.value_movingpt = QLineEdit(str(self.movingpt))
        self.value_movingpt.textChanged.connect(self.update_parameters)

        self.label_roi = QLabel("ROI")
        self.value_roi = QLineEdit(str(self.roi)[1:-1])
        self.value_roi.setFixedWidth(200)
        self.value_roi.textChanged.connect(self.change_reset_col)

        self.label_datalen = QLabel("Length")
        self.value_datalen = QLineEdit(str(self.datalen))
        self.value_datalen.textChanged.connect(self.update_parameters)

        self.cbox_raw= QCheckBox("RawCurve")
        self.cbox_raw.setChecked(True)

        self.label_avgval = QLabel("AvgVal: " + str(format(int(self.avgval),"010d")))
        self.label_avgval.setStyleSheet("border: 1px solid black");

        # Bottom slider Widgets
        self.label_eslider= QLabel("Exposure: " + str(self.exp))
        self.slider_eslider = QSlider(Qt.Horizontal)
        self.slider_eslider.setRange(0, 100)
        self.camera.set_exposure(self.exp)
        self.slider_eslider.setValue(self.exp)
        self.label_gslider= QLabel("Gain" + str(self.gain) )
        self.slider_gslider = QSlider(Qt.Horizontal)
        self.slider_gslider.setRange(0, 100)
        self.slider_gslider.setValue(self.gain)


        # Image View Widgets
        self.image_view = ImageView(self.aimwig)
        self.roi_view = ImageView()
        # self.roi = pg.CircleROI([80, 50], [20, 20], pen=(4,9))
        # self.image_view.addItem(self.roi)
        # Intensity Graph Widget
        self.gwin = pg.GraphicsWindow()
        self.rplt = self.gwin.addPlot()

        self.pen1 = pg.mkPen('r', width=2)
        self.pen2 = pg.mkPen(color=(255, 15, 15),width=2)
        self.pen3 = pg.mkPen(color=(000, 155, 115), style=QtCore.Qt.DotLine)
        self.curve = self.rplt.plot(pen=self.pen3)
        self.curve2 = self.rplt.plot(pen=self.pen2)
        self.rplt.showGrid(x=True, y=True)
        self.data = []
        self.avg_data = []
        self.count = 0

        # Layouts
        self.mainlayout = QVBoxLayout(self.central_widget)
        self.btn1layout = QHBoxLayout()
        self.btn2layout = QHBoxLayout()
        self.img1layout = QHBoxLayout()
        self.sld1layout = QHBoxLayout()


        self.btn1layout.addWidget(self.button_start)
        self.btn1layout.addWidget(self.button_reset)
        self.btn1layout.addWidget(self.button_save)
        self.btn2layout.addWidget(self.button_locklevel)
        self.btn2layout.addWidget(self.value_locklevel)
        self.btn2layout.addWidget(self.label_framerate)
        self.btn2layout.addWidget(self.value_framerate)
        self.btn2layout.addWidget(self.label_datalen)
        self.btn2layout.addWidget(self.value_datalen)
        self.btn2layout.addWidget(self.label_movingpt)
        self.btn2layout.addWidget(self.value_movingpt)
        self.btn2layout.addWidget(self.label_roi)
        self.btn2layout.addWidget(self.value_roi)
        self.btn2layout.addWidget(self.cbox_raw)
        self.btn2layout.addWidget(self.label_avgval)

        self.img1layout.addWidget(self.image_view)
        self.img1layout.addWidget(self.roi_view)

        self.sld1layout.addWidget(self.label_eslider)
        self.sld1layout.addWidget(self.slider_eslider)
        self.sld1layout.addWidget(self.label_gslider)
        self.sld1layout.addWidget(self.slider_gslider)

        self.mainlayout.addLayout(self.btn1layout)
        self.mainlayout.addLayout(self.btn2layout)
        self.mainlayout.addLayout(self.img1layout)
        self.mainlayout.addLayout(self.sld1layout)

        self.mainlayout.addWidget(self.gwin)
        self.setCentralWidget(self.central_widget)

        # Functionality
        self.button_start.clicked.connect(self.update_image)
        self.button_start.clicked.connect(self.change_start_col)
        self.button_reset.clicked.connect(self.reset_run)
        self.button_locklevel.clicked.connect(self.locklevel)
        self.button_save.clicked.connect(self.save_parameters)
        self.slider_eslider.valueChanged.connect(self.update_exposure)
        self.slider_gslider.valueChanged.connect(self.update_gain)

        self.update_timer = QTimer()
        self.update_timer.timeout.connect(self.update_image)
        self.update_timer.timeout.connect(self.update_plot)

        ## SETTING UP FIRST IMAGE
        self.first_frame = self.camera.get_frame()
        self.update_image()
        self.first_roi = self.getroiimage()
Esempio n. 54
0
    def setupUi(self, MainWindow):
        self.showFullScreen()
        self.setHidden(True)

        MainWindow.setObjectName("Segurança Veicular")
        MainWindow.setEnabled(True)
        MainWindow.resize(self.size())
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")

        self.verticalLayoutWidgetLog = QtWidgets.QGroupBox(self.centralwidget)
        self.verticalLayoutWidgetLog.setTitle("Tela de Log")
        self.verticalLayoutWidgetLog.setGeometry(
            QtCore.QRect(920, 10, 435, 289))
        self.verticalLayoutWidgetLog.setObjectName("verticalLayoutLog")
        self.verticalLayoutWidgetLog.setWindowTitle("LOG")

        self.verticalLayoutLog = QtWidgets.QVBoxLayout(
            self.verticalLayoutWidgetLog)
        self.verticalLayoutLog.setContentsMargins(2, 2, 2, 2)
        self.verticalLayoutLog.setObjectName("verticalLayoutLog")

        self.txtLog = QtWidgets.QPlainTextEdit(self.verticalLayoutWidgetLog)
        self.txtLog.setWindowTitle("Log")
        self.txtLog.setReadOnly(True)
        self.verticalLayoutLog.addWidget(self.txtLog)

        self.verticalLayoutWidgetCamera = QtWidgets.QGroupBox(
            self.centralwidget)
        self.verticalLayoutWidgetCamera.setTitle("Câmera")
        self.verticalLayoutWidgetCamera.setGeometry(
            QtCore.QRect(550, 10, 361, 289))
        self.verticalLayoutWidgetCamera.setObjectName(
            "verticalLayoutWidgetCamera")

        self.verticalLayout = QtWidgets.QVBoxLayout(
            self.verticalLayoutWidgetCamera)
        self.verticalLayout.setContentsMargins(2, 2, 2, 2)
        self.verticalLayout.setObjectName("verticalLayout")

        self.label = QtWidgets.QLabel(self.verticalLayoutWidgetCamera)
        self.label.setObjectName("label")
        self.verticalLayout.addWidget(self.label)

        self.horizontalLayoutWidget = QtWidgets.QGroupBox(self.centralwidget)
        self.horizontalLayoutWidget.setGeometry(
            QtCore.QRect(10, 304, 1345, 241))
        self.horizontalLayoutWidget.setObjectName("horizontalLayoutWidget")

        self.horizontalLayout = QtWidgets.QHBoxLayout(
            self.horizontalLayoutWidget)
        self.horizontalLayout.setContentsMargins(2, 2, 2, 2)
        self.horizontalLayout.setObjectName("horizontalLayout")

        self.horizontalLayoutWidget.setLayout(self.horizontalLayout)

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

        self.graficoMicro = pg.PlotWidget(
            self.horizontalLayoutWidget,
            title="GRÁFICO EM REAL TIME - PERCLOS ANÁLISE")
        self.graficoMicro.setXRange(0, 1000, padding=0)
        self.graficoMicro.setYRange(0, 100, padding=0)
        self.graficoMicro.getPlotItem().showGrid(True, True, 0.2)
        self.horizontalLayout.addWidget(self.graficoMicro)

        self.horizontalLayoutWidget_2 = QtWidgets.QGroupBox(self.centralwidget)
        self.horizontalLayoutWidget_2.setGeometry(
            QtCore.QRect(10, 550, 1345, 150))
        self.horizontalLayoutWidget_2.setObjectName("horizontalLayoutWidget_2")

        self.horizontalLayout_2 = QtWidgets.QHBoxLayout(
            self.horizontalLayoutWidget_2)
        self.horizontalLayout_2.setContentsMargins(2, 2, 2, 2)
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")

        self.graficoMacro = pg.PlotWidget(
            self.horizontalLayoutWidget,
            title="GRÁFICO AQUISIÇÃO DE DADOS INICIAL PARA CALIBRAGEM")
        self.graficoMacro.setLabels(left="PERCLOS", bottom="Frames")
        self.graficoMacro.setXRange(0, 20, padding=0)
        self.graficoMacro.setYRange(0, 1, padding=0)
        self.graficoMacro.getPlotItem().showGrid(True, True, 0.2)
        self.horizontalLayout_2.addWidget(self.graficoMacro)

        self.horizontalLayoutWidget_3 = QtWidgets.QGroupBox(self.centralwidget)
        self.horizontalLayoutWidget_3.setGeometry(QtCore.QRect(
            10, 10, 531, 41))
        self.horizontalLayoutWidget_3.setTitle("Estado do Sistema")
        self.horizontalLayoutWidget_3.setObjectName("horizontalLayoutWidget_3")

        self.layoutParteSuperior = QtWidgets.QHBoxLayout(
            self.horizontalLayoutWidget_3)
        self.layoutParteSuperior.setContentsMargins(2, 2, 2, 2)
        self.layoutParteSuperior.setObjectName("layoutParteSuperior")

        ##----------FPS----------##
        self.lbFPS = QtWidgets.QLabel(self.horizontalLayoutWidget_3)
        #self.lbFPS.setObjectName("lbFPS")
        self.lbFPS.setText("FPS")

        self.lcdFPS = QtWidgets.QLCDNumber(self.horizontalLayoutWidget_3)
        self.lcdFPS.setObjectName("lcdFPS")

        ##----------Marcador de Tempo----------##
        self.lbTempo = QtWidgets.QLabel(self.horizontalLayoutWidget_3)
        self.lbTempo.setText("Tempo")

        self.timeEdit = QtWidgets.QLineEdit(self.horizontalLayoutWidget_3)
        self.timeEdit.setObjectName("timeEdit")

        hora = QTime()
        self.timeEdit.setText(hora.currentTime().toString())

        ##----------Marcador da Ultima Parada----------##
        self.lbProcessoCPU = QtWidgets.QLabel(self.horizontalLayoutWidget_3)
        #self.lbProcessoCPU.setObjectName("lbProcessoCPU")
        self.lbProcessoCPU.setText("CPU: ")

        self.txtProcessoCPU = QtWidgets.QLineEdit(
            self.horizontalLayoutWidget_3)
        self.txtProcessoCPU.setObjectName("txtProcessoCPU")

        ##---------- Botões de Execução ----------##
        self.btCalibrar = QtWidgets.QPushButton(self.horizontalLayoutWidget_3)
        self.btCalibrar.setObjectName("btCalibrar")
        self.btCalibrar.setText("Calibrar")
        self.btExecutar = QtWidgets.QPushButton(self.horizontalLayoutWidget_3)
        self.btExecutar.setObjectName("btExecutar")
        self.btExecutar.setText("Executar")

        #Layout da parte superior
        self.layoutParteSuperior.addWidget(self.lbFPS)
        self.layoutParteSuperior.addWidget(self.lcdFPS)
        self.layoutParteSuperior.addWidget(self.lbTempo)
        self.layoutParteSuperior.addWidget(self.timeEdit)
        self.layoutParteSuperior.addWidget(self.lbProcessoCPU)
        self.layoutParteSuperior.addWidget(self.txtProcessoCPU)
        self.layoutParteSuperior.addWidget(self.btCalibrar)
        self.layoutParteSuperior.addWidget(self.btExecutar)

        #---------- Layout de Análise PERCLOS ----------
        self.layoutPERCLOS = QtWidgets.QGroupBox(self.centralwidget)
        self.layoutPERCLOS.setGeometry(QtCore.QRect(375, 55, 166, 93))
        self.layoutPERCLOS.setObjectName("layoutPERCLOS")
        self.layoutPERCLOS.setTitle("Resumo de Calib. PERCLOS (RA)")

        self.formLayout = QtWidgets.QFormLayout(self.layoutPERCLOS)
        self.formLayout.setContentsMargins(2, 2, 2, 2)
        self.formLayout.setObjectName("formLayout")

        self.lbValorMaxPERCLOS = QtWidgets.QLabel(self.layoutPERCLOS)
        self.lbValorMaxPERCLOS.setObjectName("lbValorMaxPERCLOS")
        self.formLayout.setWidget(0, QtWidgets.QFormLayout.LabelRole,
                                  self.lbValorMaxPERCLOS)

        self.lbValorMinPERCLOS = QtWidgets.QLabel(self.layoutPERCLOS)
        self.lbValorMinPERCLOS.setObjectName("lbValorMinPERCLOS")
        self.formLayout.setWidget(1, QtWidgets.QFormLayout.LabelRole,
                                  self.lbValorMinPERCLOS)

        self.lbP70 = QtWidgets.QLabel(self.layoutPERCLOS)
        self.lbP70.setObjectName("lbP70")
        self.formLayout.setWidget(2, QtWidgets.QFormLayout.LabelRole,
                                  self.lbP70)

        self.txtValorMaxPERCLOS = QtWidgets.QLineEdit(self.layoutPERCLOS)
        self.txtValorMaxPERCLOS.setObjectName("txtValorMaxPERCLOS")
        self.formLayout.setWidget(0, QtWidgets.QFormLayout.FieldRole,
                                  self.txtValorMaxPERCLOS)

        self.txtValorMinPERCLOS = QtWidgets.QLineEdit(self.layoutPERCLOS)
        self.txtValorMinPERCLOS.setObjectName("txtValorMinPERCLOS")
        self.formLayout.setWidget(1, QtWidgets.QFormLayout.FieldRole,
                                  self.txtValorMinPERCLOS)

        self.txtP80 = QtWidgets.QLineEdit(self.layoutPERCLOS)
        self.txtP80.setObjectName("txtP80")
        self.formLayout.setWidget(2, QtWidgets.QFormLayout.FieldRole,
                                  self.txtP80)

        #---------- Layout de Análise Piscadas ----------
        self.layoutPiscada = QtWidgets.QGroupBox(self.centralwidget)
        self.layoutPiscada.setGeometry(QtCore.QRect(10, 55, 351, 120))
        #self.layoutPiscada.setFrameShape(QtWidgets.QFrame.StyledPanel)
        #self.layoutPiscada.setFrameShadow(QtWidgets.QFrame.Raised)
        self.layoutPiscada.setObjectName("layoutPiscada")
        self.layoutPiscada.setTitle("Análise Piscadas")

        self.gridLayoutPiscada = QtWidgets.QGridLayout(self.layoutPiscada)
        self.gridLayoutPiscada.setObjectName("gridLayoutPiscada")
        self.gridLayoutPiscada.setContentsMargins(2, 2, 2, 2)

        self.lbMinutosAntesPiscada = QtWidgets.QLabel(self.layoutPiscada)
        self.lbMinutosAntesPiscada.setObjectName("lbMinutosAntesPiscada")
        self.gridLayoutPiscada.addWidget(self.lbMinutosAntesPiscada, 0, 3, 1,
                                         1, QtCore.Qt.AlignHCenter)

        self.txtMaximaPiscada = QtWidgets.QLineEdit(self.layoutPiscada)
        self.txtMaximaPiscada.setObjectName("txtMaximaPiscada")
        self.gridLayoutPiscada.addWidget(self.txtMaximaPiscada, 1, 1, 1, 1)

        self.lbMaximaPiscada = QtWidgets.QLabel(self.layoutPiscada)
        self.lbMaximaPiscada.setObjectName("lbMaximaPiscada")
        self.gridLayoutPiscada.addWidget(self.lbMaximaPiscada, 1, 0, 1, 1)

        self.lbMinimaPiscada = QtWidgets.QLabel(self.layoutPiscada)
        self.lbMinimaPiscada.setObjectName("lbMinimaPiscada")
        self.gridLayoutPiscada.addWidget(self.lbMinimaPiscada, 2, 0, 1, 1)

        self.txtMinimaPiscada = QtWidgets.QLineEdit(self.layoutPiscada)
        self.txtMinimaPiscada.setObjectName("txtMinimaPiscada")
        self.gridLayoutPiscada.addWidget(self.txtMinimaPiscada, 2, 1, 1, 1)

        self.lbReferenciaTempoPiscadaMax = QtWidgets.QLabel(self.layoutPiscada)
        self.lbReferenciaTempoPiscadaMax.setObjectName(
            "lbReferenciaTempoPiscadaMax")
        self.gridLayoutPiscada.addWidget(self.lbReferenciaTempoPiscadaMax, 1,
                                         2, 1, 1)

        self.txtReferenciaTempoPiscadaMax = QtWidgets.QLineEdit(
            self.layoutPiscada)
        self.txtReferenciaTempoPiscadaMax.setObjectName(
            "txtReferenciaTempoPiscadaMax")
        self.gridLayoutPiscada.addWidget(self.txtReferenciaTempoPiscadaMax, 2,
                                         3, 1, 1)

        self.txtReferenciaTempoPiscada_2 = QtWidgets.QLineEdit(
            self.layoutPiscada)
        self.txtReferenciaTempoPiscada_2.setObjectName(
            "txtReferenciaTempoPiscada_2")
        self.gridLayoutPiscada.addWidget(self.txtReferenciaTempoPiscada_2, 1,
                                         3, 1, 1)

        self.lbPiscada = QtWidgets.QLabel(self.layoutPiscada)
        self.lbPiscada.setObjectName("lbPiscada")
        self.gridLayoutPiscada.addWidget(self.lbPiscada, 0, 0, 1, 1)

        self.lbPorMinutoPiscada = QtWidgets.QLabel(self.layoutPiscada)
        self.lbPorMinutoPiscada.setObjectName("lbPorMinutoPiscada")
        self.gridLayoutPiscada.addWidget(self.lbPorMinutoPiscada, 0, 1, 1, 1,
                                         QtCore.Qt.AlignHCenter)

        self.lbReferenciaTempoPiscadaMin = QtWidgets.QLabel(self.layoutPiscada)
        self.lbReferenciaTempoPiscadaMin.setObjectName(
            "lbReferenciaTempoPiscadaMin")
        self.gridLayoutPiscada.addWidget(self.lbReferenciaTempoPiscadaMin, 2,
                                         2, 1, 1)

        self.lbMediana = QtWidgets.QLabel(self.layoutPiscada)
        self.lbMediana.setObjectName("lbMediana")
        self.gridLayoutPiscada.addWidget(self.lbMediana, 3, 0, 1, 1)

        self.txtMediana = QtWidgets.QLineEdit(self.layoutPiscada)
        self.txtMediana.setObjectName("txtMediana")
        self.gridLayoutPiscada.addWidget(self.txtMediana, 3, 1, 1, 1)

        #---------- Layout de Análise Bocejo ----------
        self.layoutBocejo = QtWidgets.QGroupBox(self.centralwidget)
        self.layoutBocejo.setGeometry(QtCore.QRect(10, 179, 351, 120))
        self.layoutBocejo.setObjectName("layoutBocejo")
        self.layoutBocejo.setTitle("Análise Bocejo")

        self.gridLayoutBocejo = QtWidgets.QGridLayout(self.layoutBocejo)
        self.gridLayoutBocejo.setObjectName("gridLayoutBocejo")

        self.lbMinAntesBocejo = QtWidgets.QLabel(self.layoutBocejo)
        self.lbMinAntesBocejo.setObjectName("lbMinAntesBocejo")
        self.gridLayoutBocejo.addWidget(self.lbMinAntesBocejo, 0, 3, 1, 1,
                                        QtCore.Qt.AlignHCenter)

        self.txtMaximaBocejo = QtWidgets.QLineEdit(self.layoutBocejo)
        self.txtMaximaBocejo.setObjectName("txtMaximaBocejo")
        self.gridLayoutBocejo.addWidget(self.txtMaximaBocejo, 1, 1, 1, 1)

        self.lbMaximaBocejo = QtWidgets.QLabel(self.layoutBocejo)
        self.lbMaximaBocejo.setObjectName("lbMaximaBocejo")
        self.gridLayoutBocejo.addWidget(self.lbMaximaBocejo, 1, 0, 1, 1)

        self.lbMinimaBocejo = QtWidgets.QLabel(self.layoutBocejo)
        self.lbMinimaBocejo.setObjectName("lbMinimaBocejo")
        self.gridLayoutBocejo.addWidget(self.lbMinimaBocejo, 2, 0, 1, 1)

        self.txtMinimoBocejo = QtWidgets.QLineEdit(self.layoutBocejo)
        self.txtMinimoBocejo.setObjectName("txtMinimoBocejo")
        self.gridLayoutBocejo.addWidget(self.txtMinimoBocejo, 2, 1, 1, 1)

        self.lbReferenciaTempoBocejoMax = QtWidgets.QLabel(self.layoutBocejo)
        self.lbReferenciaTempoBocejoMax.setObjectName(
            "lbReferenciaTempoBocejoMax")
        self.gridLayoutBocejo.addWidget(self.lbReferenciaTempoBocejoMax, 1, 2,
                                        1, 1)

        self.txtReferenciaTempoBocejoMin = QtWidgets.QLineEdit(
            self.layoutBocejo)
        self.txtReferenciaTempoBocejoMin.setObjectName(
            "txtReferenciaTempoBocejoMin")
        self.gridLayoutBocejo.addWidget(self.txtReferenciaTempoBocejoMin, 2, 3,
                                        1, 1)

        self.txtReferenciaTempoBocejoMax = QtWidgets.QLineEdit(
            self.layoutBocejo)
        self.txtReferenciaTempoBocejoMax.setObjectName(
            "txtReferenciaTempoBocejoMax")
        self.gridLayoutBocejo.addWidget(self.txtReferenciaTempoBocejoMax, 1, 3,
                                        1, 1)

        self.lbBocejo = QtWidgets.QLabel(self.layoutBocejo)
        self.lbBocejo.setObjectName("lbBocejo")
        self.gridLayoutBocejo.addWidget(self.lbBocejo, 0, 0, 1, 1)

        self.lbPorMinutoBocejo = QtWidgets.QLabel(self.layoutBocejo)
        self.lbPorMinutoBocejo.setObjectName("lbPorMinutoBocejo")
        self.gridLayoutBocejo.addWidget(self.lbPorMinutoBocejo, 0, 1, 1, 1,
                                        QtCore.Qt.AlignHCenter)

        self.lbReferenciaTempoBocejoMin = QtWidgets.QLabel(self.layoutBocejo)
        self.lbReferenciaTempoBocejoMin.setObjectName(
            "lbReferenciaTempoBocejoMin")
        self.gridLayoutBocejo.addWidget(self.lbReferenciaTempoBocejoMin, 2, 2,
                                        1, 1)

        self.lbMedianaBocejo = QtWidgets.QLabel(self.layoutBocejo)
        self.lbMedianaBocejo.setObjectName("lbMedianaBocejo")
        self.gridLayoutBocejo.addWidget(self.lbMedianaBocejo, 3, 0, 1, 1)

        self.txtMedianaBocejo = QtWidgets.QLineEdit(self.layoutBocejo)
        self.txtMedianaBocejo.setObjectName("txtMedianaBocejo")
        self.gridLayoutBocejo.addWidget(self.txtMedianaBocejo, 3, 1, 1, 1)

        #---------- Layout de Análise Estatisticas do PERCLOS ----------
        self.layoutEstatisticaPERCLOS = QtWidgets.QGroupBox(self.centralwidget)
        self.layoutEstatisticaPERCLOS.setGeometry(
            QtCore.QRect(375, 152, 166, 147))
        self.layoutEstatisticaPERCLOS.setObjectName("layoutEstatisticaPERCLOS")
        self.layoutEstatisticaPERCLOS.setTitle("Estatistica PERCLOS")

        self.gridLayoutPiscada_3 = QtWidgets.QGridLayout(
            self.layoutEstatisticaPERCLOS)
        self.gridLayoutPiscada_3.setContentsMargins(2, 2, 2, 2)
        self.gridLayoutPiscada_3.setObjectName("gridLayoutPiscada_3")

        self.lbBaixoPerclosMedia = QtWidgets.QLabel(
            self.layoutEstatisticaPERCLOS)
        self.lbBaixoPerclosMedia.setObjectName("lbBaixoPerclosMedia")
        self.gridLayoutPiscada_3.addWidget(self.lbBaixoPerclosMedia, 2, 0, 1,
                                           1)

        self.txtBaixoPerclosMedia = QtWidgets.QLineEdit(
            self.layoutEstatisticaPERCLOS)
        self.txtBaixoPerclosMedia.setObjectName("txtBaixoPerclosMedia")
        self.gridLayoutPiscada_3.addWidget(self.txtBaixoPerclosMedia, 2, 1, 1,
                                           1)

        self.txtAltoPerclos = QtWidgets.QLineEdit(
            self.layoutEstatisticaPERCLOS)
        self.txtAltoPerclos.setObjectName("txtAltoPerclos")
        self.gridLayoutPiscada_3.addWidget(self.txtAltoPerclos, 3, 1, 1, 1)

        self.txtBaixoPerclos = QtWidgets.QLineEdit(
            self.layoutEstatisticaPERCLOS)
        self.txtBaixoPerclos.setObjectName("txtBaixoPerclos")
        self.gridLayoutPiscada_3.addWidget(self.txtBaixoPerclos, 1, 1, 1, 1)

        self.lbAltoPerclos = QtWidgets.QLabel(self.layoutEstatisticaPERCLOS)
        self.lbAltoPerclos.setObjectName("lbAltoPerclos")
        self.gridLayoutPiscada_3.addWidget(self.lbAltoPerclos, 3, 0, 1, 1)

        self.lbPorMinutoResumoPerclos = QtWidgets.QLabel(
            self.layoutEstatisticaPERCLOS)
        self.lbPorMinutoResumoPerclos.setObjectName("lbPorMinutoResumoPerclos")
        self.gridLayoutPiscada_3.addWidget(self.lbPorMinutoResumoPerclos, 0, 1,
                                           1, 1, QtCore.Qt.AlignHCenter)

        self.lbBaixoPerclos = QtWidgets.QLabel(self.layoutEstatisticaPERCLOS)
        self.lbBaixoPerclos.setObjectName("lbBaixoPerclos")
        self.gridLayoutPiscada_3.addWidget(self.lbBaixoPerclos, 1, 0, 1, 1)

        self.lbAltoPerclosMedia = QtWidgets.QLabel(
            self.layoutEstatisticaPERCLOS)
        self.lbAltoPerclosMedia.setObjectName("lbAltoPerclosMedia")
        self.gridLayoutPiscada_3.addWidget(self.lbAltoPerclosMedia, 4, 0, 1, 1)

        self.txtAltoPerclosMedia = QtWidgets.QLineEdit(
            self.layoutEstatisticaPERCLOS)
        self.txtAltoPerclosMedia.setObjectName("txtAltoPerclosMedia")
        self.gridLayoutPiscada_3.addWidget(self.txtAltoPerclosMedia, 4, 1, 1,
                                           1)

        thCPU = DesempenhoProcessador(self)
        thCPU.desempenhoCPU.connect(self.txtProcessoCPU.setText)
        thCPU.start()

        thHora = Horario(self)
        thHora.horarioEmTempoReal.connect(self.timeEdit.setText)
        thHora.startTelaDeLog.connect(self.txtLog.setPlainText)
        thHora.start()

        self.btCalibrar.clicked.connect(self.executarCalibracao)
        self.btExecutar.clicked.connect(self.executarExecucao)

        MainWindow.setCentralWidget(self.centralwidget)
        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
Esempio n. 55
0
    def __init__(self, parent=None):

        QMainWindow.__init__(self)
        self.setupUi(self)

        print(pg.__version__)

        self.sb = SerialDAQ()  #'/dev/pts/6')

        while not self.sb.connected:

            msg = QMessageBox.critical(None, "Advertencia",
                                       u"La interfaz no está conectada",
                                       QMessageBox.Retry | QMessageBox.Abort)

            if msg == QMessageBox.Retry:
                self.sb.open()
            else:
                sys.exit(1)

        self.updateTimer = QTimer()
        self.updateTimer.timeout.connect(self.update)

        # Asigna valores iniciales por defecto a los parámetros de cada canal
        for i in range(NUM_CANALES):

            str_pendiente = 'pendiente_' + str(i + 1)
            pendiente = getattr(self, str_pendiente)

            str_ordenada = 'ordenada_' + str(i + 1)
            ordenada = getattr(self, str_ordenada)

            str_nombre = 'nombre_' + str(i + 1)
            nombre = getattr(self, str_nombre)

            str_unidad = 'unidad_' + str(i + 1)
            unidad = getattr(self, str_unidad)

            pendiente.setText(str(PENDIENTE_DEF))
            ordenada.setText(str(0.0))

            nombre.setText('Canal ' + str(i + 1))
            unidad.setText('Volt')

            self.sb.config_analog(i + 1,
                                  name=nombre.text(),
                                  activate=False,
                                  calib=(float(ordenada.text()),
                                         float(pendiente.text())))
        self.sb.activate_analog(1)
        self.midiendo = False
        self.guardado = True

        self.vent_grafico = []
        self.grafico = []

        self.actionMedir.triggered.connect(self.medir)
        self.actionGuardar.triggered.connect(self.guardar)
        self.actionSalir.triggered.connect(self.close)

        pg.setConfigOption('background', 'w')
        pg.setConfigOption('foreground', 'k')
Esempio n. 56
0
    def setupUi(self, TabWidget):
        TabWidget.setObjectName("TabWidget")
        TabWidget.setEnabled(True)
        TabWidget.resize(1278, 587)
        font = QtGui.QFont()
        font.setFamily("Arial")
        TabWidget.setFont(font)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("asabranca.png"), QtGui.QIcon.Normal,
                       QtGui.QIcon.Off)
        TabWidget.setWindowIcon(icon)
        TabWidget.setUsesScrollButtons(False)
        TabWidget.setTabBarAutoHide(True)
        pg.setConfigOption('background', 'w')
        pg.setConfigOption('foreground', 'k')

        self.ac_signal.connect(self.Ac_signal)
        self.rot_signal.connect(self.Rot_signal)
        self.vel_signal.connect(self.Vel_signal)
        self.tt_signal.connect(self.TT_signal)
        self.pos_signal.connect(self.Pos_signal)
        self.temp_signal.connect(self.Temp_signal)

        #Aba Principal
        self.tab = QtWidgets.QWidget()
        self.tab.setObjectName("tab")

        self.gridLayout = QtWidgets.QGridLayout(self.tab)
        self.gridLayout.setObjectName("gridLayout")

        self.graphicsView_pac = pg.PlotWidget(self.tab)
        self.graphicsView_pac.setObjectName("graphicsView_pac")
        self.gridLayout.addWidget(self.graphicsView_pac, 0, 0, 1, 1)

        self.graphicsView_prot = pg.PlotWidget(self.tab)
        self.graphicsView_prot.setObjectName("graphicsView_prot")
        self.gridLayout.addWidget(self.graphicsView_prot, 0, 1, 1, 1)

        self.graphicsView_ptt = pg.PlotWidget(self.tab)
        self.graphicsView_ptt.setObjectName("graphicsView_ptt")
        self.gridLayout.addWidget(self.graphicsView_ptt, 1, 0, 1, 1)

        self.graphicsView_pvel = pg.PlotWidget(self.tab)
        self.graphicsView_pvel.setObjectName("graphicsView_pvel")
        self.gridLayout.addWidget(self.graphicsView_pvel, 1, 1, 1, 1)

        self.line = QtWidgets.QFrame(self.tab)
        self.line.setMinimumSize(QtCore.QSize(0, 16))
        self.line.setFrameShape(QtWidgets.QFrame.HLine)
        self.line.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line.setObjectName("line")
        self.gridLayout.addWidget(self.line, 2, 0, 1, 2)

        self.label_ppos = QtWidgets.QLabel(self.tab)
        self.label_ppos.setObjectName("label_ppos")
        self.gridLayout.addWidget(self.label_ppos, 3, 0, 1, 1)
        self.label_ptemp = QtWidgets.QLabel(self.tab)
        self.label_ptemp.setObjectName("label_ptemp")
        self.gridLayout.addWidget(self.label_ptemp, 3, 1, 1, 1)
        self.label_prot = QtWidgets.QLabel(self.tab)
        self.label_prot.setObjectName("label_prot")
        self.gridLayout.addWidget(self.label_prot, 4, 0, 1, 1)
        self.label_pac = QtWidgets.QLabel(self.tab)
        self.label_pac.setObjectName("label_pac")
        self.gridLayout.addWidget(self.label_pac, 4, 1, 1, 1)
        self.label_ptt = QtWidgets.QLabel(self.tab)
        self.label_ptt.setObjectName("label_ptt")
        self.gridLayout.addWidget(self.label_ptt, 5, 0, 1, 1)
        self.label_pvel = QtWidgets.QLabel(self.tab)
        self.label_pvel.setObjectName("label_pvel")
        self.gridLayout.addWidget(self.label_pvel, 5, 1, 1, 1)

        self.line_2 = QtWidgets.QFrame(self.tab)
        self.line_2.setFrameShape(QtWidgets.QFrame.HLine)
        self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line_2.setObjectName("line_2")
        self.gridLayout.addWidget(self.line_2, 6, 0, 1, 2)
        TabWidget.addTab(self.tab, "")

        #Aba Temperatura
        self.tab1 = QtWidgets.QWidget()
        self.tab1.setObjectName("tab1")

        self.gridLayout_2 = QtWidgets.QGridLayout(self.tab1)
        self.gridLayout_2.setObjectName("gridLayout_2")

        self.graphicsView_temp = pg.PlotWidget(self.tab1)
        self.graphicsView_temp.setObjectName("graphicsView_temp")
        self.gridLayout_2.addWidget(self.graphicsView_temp, 0, 0, 1, 1)

        self.line_3 = QtWidgets.QFrame(self.tab1)
        self.line_3.setMinimumSize(QtCore.QSize(0, 16))
        self.line_3.setFrameShape(QtWidgets.QFrame.HLine)
        self.line_3.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line_3.setObjectName("line_3")
        self.gridLayout_2.addWidget(self.line_3, 1, 0, 1, 1)

        self.label_temp = QtWidgets.QLabel(self.tab1)
        self.label_temp.setObjectName("label_temp")
        self.gridLayout_2.addWidget(self.label_temp, 2, 0, 1, 1)
        TabWidget.addTab(self.tab1, "")

        #Aba Aceleração
        self.tab_2 = QtWidgets.QWidget()
        self.tab_2.setObjectName("tab_2")

        self.gridLayout_3 = QtWidgets.QGridLayout(self.tab_2)
        self.gridLayout_3.setObjectName("gridLayout_3")

        self.graphicsView_ac = pg.PlotWidget(self.tab_2)
        self.graphicsView_ac.setObjectName("graphicsView_ac")
        self.gridLayout_3.addWidget(self.graphicsView_ac, 0, 0, 1, 1)

        self.line_4 = QtWidgets.QFrame(self.tab_2)
        self.line_4.setMinimumSize(QtCore.QSize(0, 16))
        self.line_4.setFrameShape(QtWidgets.QFrame.HLine)
        self.line_4.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line_4.setObjectName("line_4")
        self.gridLayout_3.addWidget(self.line_4, 1, 0, 1, 1)

        self.label_ac = QtWidgets.QLabel(self.tab_2)
        self.label_ac.setObjectName("label_ac")
        self.gridLayout_3.addWidget(self.label_ac, 2, 0, 1, 1)
        TabWidget.addTab(self.tab_2, "")

        #Aba Velocidade
        self.tab_3 = QtWidgets.QWidget()
        self.tab_3.setObjectName("tab_3")

        self.gridLayout_4 = QtWidgets.QGridLayout(self.tab_3)
        self.gridLayout_4.setObjectName("gridLayout_4")

        self.graphicsView_vel = pg.PlotWidget(self.tab_3)
        self.graphicsView_vel.setObjectName("graphicsView_vel")
        self.gridLayout_4.addWidget(self.graphicsView_vel, 0, 0, 1, 1)

        self.line_5 = QtWidgets.QFrame(self.tab_3)
        self.line_5.setMinimumSize(QtCore.QSize(0, 16))
        self.line_5.setFrameShape(QtWidgets.QFrame.HLine)
        self.line_5.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line_5.setObjectName("line_5")
        self.gridLayout_4.addWidget(self.line_5, 1, 0, 1, 1)

        self.label_vel = QtWidgets.QLabel(self.tab_3)
        self.label_vel.setObjectName("label_vel")
        self.gridLayout_4.addWidget(self.label_vel, 2, 0, 1, 1)
        TabWidget.addTab(self.tab_3, "")

        #Aba Rotação
        self.tab_4 = QtWidgets.QWidget()
        self.tab_4.setObjectName("tab_4")

        self.gridLayout_5 = QtWidgets.QGridLayout(self.tab_4)
        self.gridLayout_5.setObjectName("gridLayout_5")

        self.graphicsView_rot = pg.PlotWidget(self.tab_4)
        self.graphicsView_rot.setObjectName("graphicsView_rot")
        self.gridLayout_5.addWidget(self.graphicsView_rot, 0, 0, 1, 1)

        self.line_6 = QtWidgets.QFrame(self.tab_4)
        self.line_6.setMinimumSize(QtCore.QSize(0, 16))
        self.line_6.setFrameShape(QtWidgets.QFrame.HLine)
        self.line_6.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line_6.setObjectName("line_6")
        self.gridLayout_5.addWidget(self.line_6, 1, 0, 1, 1)

        self.label_rot = QtWidgets.QLabel(self.tab_4)
        self.label_rot.setObjectName("label_rot")
        self.gridLayout_5.addWidget(self.label_rot, 2, 0, 1, 1)
        TabWidget.addTab(self.tab_4, "")

        #Aba Posição
        self.tab_5 = QtWidgets.QWidget()
        self.tab_5.setObjectName("tab_5")

        self.gridLayout_6 = QtWidgets.QGridLayout(self.tab_5)
        self.gridLayout_6.setObjectName("gridLayout_6")

        self.graphicsView_pos = pg.PlotWidget(self.tab_5)
        self.graphicsView_pos.setObjectName("graphicsView_pos")
        self.gridLayout_6.addWidget(self.graphicsView_pos, 0, 0, 1, 1)

        self.line_7 = QtWidgets.QFrame(self.tab_5)
        self.line_7.setMinimumSize(QtCore.QSize(0, 16))
        self.line_7.setFrameShape(QtWidgets.QFrame.HLine)
        self.line_7.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line_7.setObjectName("line_7")
        self.gridLayout_6.addWidget(self.line_7, 1, 0, 1, 1)

        self.label_pos = QtWidgets.QLabel(self.tab_5)
        self.label_pos.setObjectName("label_pos")
        self.gridLayout_6.addWidget(self.label_pos, 2, 0, 1, 1)
        TabWidget.addTab(self.tab_5, "")

        #Aba Taxa de Transmissão
        self.tab_6 = QtWidgets.QWidget()
        self.tab_6.setObjectName("tab_6")

        self.gridLayout_7 = QtWidgets.QGridLayout(self.tab_6)
        self.gridLayout_7.setObjectName("gridLayout_7")

        self.graphicsView_tt = pg.PlotWidget(self.tab_6)
        self.graphicsView_tt.setObjectName("graphicsView_tt")
        self.gridLayout_7.addWidget(self.graphicsView_tt, 0, 0, 1, 1)

        self.line_8 = QtWidgets.QFrame(self.tab_6)
        self.line_8.setMinimumSize(QtCore.QSize(0, 16))
        self.line_8.setFrameShape(QtWidgets.QFrame.HLine)
        self.line_8.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line_8.setObjectName("line_8")
        self.gridLayout_7.addWidget(self.line_8, 1, 0, 1, 1)

        self.label_tt = QtWidgets.QLabel(self.tab_6)
        self.label_tt.setObjectName("label_tt")
        self.gridLayout_7.addWidget(self.label_tt, 2, 0, 1, 1)
        TabWidget.addTab(self.tab_6, "")

        #Aba Mapa
        self.tab_7 = QtWidgets.QWidget()
        self.tab_7.setObjectName("tab_7")

        self.gridLayout_8 = QtWidgets.QGridLayout(self.tab_7)
        self.gridLayout_8.setObjectName("gridLayout_8")

        self.line_9 = QtWidgets.QFrame(self.tab_7)
        self.line_9.setMinimumSize(QtCore.QSize(0, 16))
        self.line_9.setFrameShape(QtWidgets.QFrame.HLine)
        self.line_9.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line_9.setObjectName("line_9")
        self.gridLayout_8.addWidget(self.line_9, 1, 0, 1, 2)

        self.label_lat = QtWidgets.QLabel(self.tab_7)
        self.label_lat.setObjectName("label_lat")
        self.gridLayout_8.addWidget(self.label_lat, 2, 0, 1, 1)

        self.graphicsView_11 = QtWidgets.QGraphicsView(self.tab_7)
        self.graphicsView_11.setObjectName("graphicsView_11")
        self.gridLayout_8.addWidget(self.graphicsView_11, 0, 0, 1, 1)

        self.label_long = QtWidgets.QLabel(self.tab_7)
        self.label_long.setObjectName("label_long")
        self.gridLayout_8.addWidget(self.label_long, 3, 0, 1, 1)
        TabWidget.addTab(self.tab_7, "")

        self.retranslateUi(TabWidget)
        TabWidget.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(TabWidget)
Esempio n. 57
0
    device1.gyroscope.set_settings(data_range=500)

    deviceFlag = False  # Define a flag to check if second device is selected
    query_device = input('Add another device (y/n)? ')
    if query_device == 'y':
        deviceFlag = True
        address2 = select_device()
        device2 = MetaWearClient(str(address2), debug=True)
        device2.accelerometer.set_settings(data_rate=12.5)
        device2.accelerometer.set_settings(data_range=4.0)
        device2.gyroscope.set_settings(data_rate=25)
        device2.gyroscope.set_settings(data_range=500)
    else:
        deviceFlag = False
        print('Only one device selected\n')

    # Create a QApplication (the if/then is needed in spyder)
    if not QtWidgets.QApplication.instance():
        app = QtWidgets.QApplication(sys.argv)
    else:
        app = QtWidgets.QApplication.instance()

    # Set back- and foreground colors
    pg.setConfigOption('background', 'k')
    pg.setConfigOption('foreground', 'w')

    GUI = MainWindow()
    GUI.show()

    sys.exit(app.exec_())
Esempio n. 58
0
    def __init__(self):
        super(PlotControl, self).__init__()
        pg.setConfigOption('background', 'w')
        pg.setConfigOption('foreground', 'k')
        path = os.getcwd()
        conf = re.sub('bpm_plot', 'config', path)
        direc = re.sub('bpm_plot', 'uis', path)
        uic.loadUi(direc + "/bpm's.ui", self)
        self.setWindowTitle('Orbit Plot')
        self.show()

        soft_conf = load_config_orbit(conf + '/orbitd_conf.txt', path)
        chans_conf = soft_conf['chans_conf']
        self.bpms = soft_conf['bpm_conf']
        self.bpm_coor = soft_conf['bpm_coor']

        for chan in ['act_bpm', 'cmd', 'res', 'orbit', 'control_orbit', 'modet']:
            if chan not in chans_conf:
                print(chan + ' is absent in orbitd_conf')
                sys.exit(app.exec_())

        self.orbit_plots: dict = {
            'x_orbit': OrbitPlot('x', conf + '/x_aper.txt', self.bpms, self.bpm_coor, parent=self),
            'z_orbit': OrbitPlot('z', conf + '/z_aper.txt', self.bpms, self.bpm_coor, parent=self)}

        # variables for under control objects init
        self.ic_mode: str
        self.cur_orbit: nparray = np.zeros(2 * len(self.bpms))
        self.cur_bpms: list = self.bpms.copy()

        # migrate to special bpm tuning window
        self.bpm_btns: list = [self.btn_bpm01, self.btn_bpm02, self.btn_bpm03, self.btn_bpm04, self.btn_bpm05, self.btn_bpm07,
                               self.btn_bpm08, self.btn_bpm09, self.btn_bpm10, self.btn_bpm11, self.btn_bpm12, self.btn_bpm13,
                               self.btn_bpm14, self.btn_bpm15, self.btn_bpm16, self.btn_bpm17]
        self.bpm_lbls:  list = [self.lbl_bpm01, self.lbl_bpm02, self.lbl_bpm03, self.lbl_bpm04, self.lbl_bpm05, self.lbl_bpm07,
                                self.lbl_bpm08, self.lbl_bpm09, self.lbl_bpm10, self.lbl_bpm11, self.lbl_bpm12, self.lbl_bpm13,
                                self.lbl_bpm14, self.lbl_bpm15, self.lbl_bpm16, self.lbl_bpm17]
        self.worked_bpms: dict = {bpm: 1 for bpm in self.bpms}
        self.dict_btns: dict = {self.bpms[i]: self.bpm_btns[i] for i in range(len(self.bpms))}
        self.dict_lbls: dict = {self.bpms[i]: self.bpm_lbls[i] for i in range(len(self.bpms))}
        for btn in self.bpm_btns:
            btn.clicked.connect(self.bpm_btn_clicked)

        p = QVBoxLayout()
        self.plot_coor.setLayout(p)
        for o_type, plot in self.orbit_plots.items():
            p.addWidget(plot)

        self.btn_dict: dict = {'e2v4': self.btn_sel_e2v4, 'p2v4': self.btn_sel_p2v4, 'e2v2': self.btn_sel_e2v2,
                               'p2v2': self.btn_sel_p2v2}
        for key, btn in self.btn_dict.items():
            btn.clicked.connect(self.load_file_)

        self.colors: dict = {'e2v4': 'background-color:#55ffff;', 'p2v4': 'background-color:#ff86ff;',
                             'e2v2': 'background-color:#75ff91;', 'p2v2': 'background-color:#ff6b6b;'}
        self.inj_mode_matr: dict = {'p': False, 'e': False}

        # self.btn_bot_on.clicked.connect(self.bot_ctrl)
        # self.btn_bot_off.clicked.connect(self.bot_ctrl)

        # action btn ctrl
        self.btn_bckgr_discard.clicked.connect(self.bckrg_discard)
        self.btn_save.clicked.connect(self.save_file_)
        self.btn_bckgr.clicked.connect(self.bckgr)
        self.btn_inj_m.clicked.connect(self.load_inj_matrix)
        self.btn_step_up.clicked.connect(self.step_up)
        self.btn_step_dn.clicked.connect(self.step_down)
        self.btn_load_rrm.clicked.connect(self.load_resp_mat)
        self.btn_reknob.clicked.connect(self.knob_recalc)

        # other ordinary channels
        self.chan_act_bpm = cda.StrChan(**chans_conf['act_bpm'])
        self.chan_act_bpm.valueMeasured.connect(self.act_bpm)
        self.chan_mode = cda.StrChan(**chans_conf['modet'])
        self.chan_mode.valueMeasured.connect(self.mode_changed)
        self.chan_cmd = cda.StrChan(**chans_conf['cmd'])
        self.chan_res = cda.StrChan(**chans_conf['res'])
        self.chan_res.valueMeasured.connect(self.cmd_res)

        # data chans
        self.chan_orbit = cda.VChan(**chans_conf['orbit'])
        self.chan_orbit.valueMeasured.connect(self.new_orbit)
        self.chan_ctrl_orbit = cda.VChan(**chans_conf['control_orbit'])
        self.chan_ctrl_orbit.valueMeasured.connect(self.new_ctrl_orbit)
Esempio n. 59
0
}

numlabelsize = 22
txtlabelsize = 20

# STYLING
numfont = QtGui.QFont("Avenir Next")  # requires macos
numfont.setPixelSize(numlabelsize)

txtfont = QtGui.QFont("Avenir Next")  # requires macos
txtfont.setPixelSize(txtlabelsize)

brushes = {k: pg.mkBrush(c) for k, c in colors.items()}

pg.setConfigOptions(antialias=True)
pg.setConfigOption('background', colors['dark'])
pg.setConfigOption('foreground', colors['light'])

QPushButton_style = f"""
QPushButton{{
	color: {colors['light']};
	background-color: transparent;
	border: 1px solid #4589b2;
	padding: 5px;

}}

QPushButton::hover{{
	background-color: rgba(255,255,255,.2);
}}
Esempio n. 60
0
    def initUI(self):

        # The major plot function, this tells you how the interface structure.

        pg.setConfigOption('background', 'w')
        pg.setConfigOption('foreground', 'k')
        app = pg.mkQApp()

        # Enable antialiasing
        pg.setConfigOptions(antialias=True)

        # set windows
        self.window = pg.GraphicsWindow(title='TEST Data SNR Interface')
        self.window.resize(1150, 1000)

        #Load paradise data, variables
        self.paradise_data()

        # set first image
        self.p1 = self.window.addPlot(title='IMAGE 1')

        self.image1 = pg.ImageItem()
        self.image1.setImage(image=self.stackflux())
        self.p1.addItem(self.image1, row=0, col=0)
        self.p1.setMenuEnabled(enableMenu=False)

        # set first image control bar
        hist1 = pg.HistogramLUTItem(fillHistogram=False)
        hist1.setImageItem(self.image1)
        hist1.setLevels(-1, 10)
        hist1.setHistogramRange(-1, 10)
        self.window.addItem(hist1, row=0, col=1)

        # set second image

        self.p2 = self.window.addPlot(title='IMAGE 2')
        self.image2 = pg.ImageItem()

        if self.number == 1:

            self.image2.setImage(image=self.SNR_data())

        else:
            self.SNR_data_red()
            self.stackflux_red()
            self.SNR_data()
            self.image2.setImage(image=self.stackflux_red())

        self.p2.addItem(self.image2, row=0, col=2)
        self.p2.setMenuEnabled(enableMenu=False)

        # set second control bar

        hist2 = pg.HistogramLUTItem(fillHistogram=False)
        hist2.setImageItem(self.image2)
        hist2.setLevels(-1, 10)
        hist2.setHistogramRange(-1, 10)
        self.window.addItem(hist2, row=0, col=3)

        # set third plot

        self.p3 = self.window.addPlot(title='Input', row=1, col=0, colspan=3)
        self.p3.plot(self.cube._wave,
                     self.cube._data[:, self.y_mid, self.x_mid],
                     pen=(0, 0, 0),
                     name='Input')
        if self.number == str(2):
            self.p3.plot(self.cube2._wave,
                         self.cube2._data[:, self.y_mid, self.x_mid],
                         pen=(0, 153, 153))
        self.p3.setXRange(min(self.cube._wave), max(self.cube._wave))
        self.p3.setYRange(np.amin(self.cube._data[:, self.y_mid, self.x_mid]),
                          np.amax(self.cube._data[:, self.y_mid, self.x_mid]))
        self.textposx = 0
        self.textposy = 0

        #cross hair and text
        self.text = pg.TextItem(anchor=(0, 1), color=(255, 153, 51))
        self.p1.addItem(self.text)
        self.vLine = pg.InfiniteLine(angle=90,
                                     movable=False,
                                     pen=(255, 153, 51))
        self.hLine = pg.InfiniteLine(angle=0,
                                     movable=False,
                                     pen=(255, 153, 51))
        self.p1.addItem(self.vLine, ignoreBounds=True)
        self.p1.addItem(self.hLine, ignoreBounds=True)
        self.vb = self.p1.vb

        self.text2 = pg.TextItem(anchor=(0, 1), color=(255, 153, 51))
        self.p2.addItem(self.text2)
        self.vLine2 = pg.InfiniteLine(angle=90,
                                      movable=False,
                                      pen=(255, 153, 51))
        self.hLine2 = pg.InfiniteLine(angle=0,
                                      movable=False,
                                      pen=(255, 153, 51))
        self.p2.addItem(self.vLine2, ignoreBounds=True)
        self.p2.addItem(self.hLine2, ignoreBounds=True)
        self.vb2 = self.p2.vb

        # executions
        self.proxy = pg.SignalProxy(self.p1.scene().sigMouseMoved,
                                    rateLimit=120,
                                    slot=self.mouseMoved)
        self.image1.mouseClickEvent = self.mouseClickImg

        self.proxy2 = pg.SignalProxy(self.p2.scene().sigMouseMoved,
                                     rateLimit=120,
                                     slot=self.mouseMoved)
        self.image2.mouseClickEvent = self.mouseClickImg