Exemple #1
0
 def __init__(self):
     # *******************Setup interactive plotting*********************************
     self.app = QtGui.QApplication([])
     self.staticLayout = QtGui.QGridLayout()
     self.win = pg.GraphicsWindow(title="Basic plotting examples")
     self.win.setLayout(self.staticLayout)
     self.win.resize(1000, 600)
     self.win.setWindowTitle('Smith_Charts')
     pg.setConfigOptions(antialias=True)  # Enable anti-aliasing for prettier plots
     # ******************  Variable Definitions ***********************************
     self.df = pd.DataFrame  # where main bulk of data is stored
     self.windowCount = 1
     # ********************** Dynamic widgets decelerations ****************************************
     self.plotTypeGroup = {}
     self.plotCanvas = QtGui.QGraphicsWidget()
     self.plotCanvasLayout = QtGui.QGraphicsGridLayout(self.plotCanvas)
     self.filesLabel = QtGui.QLabel()
     # Dictionaries to keep track of user settings
     self.settings={}
     self.currentSelectedWindow = 0
     # Dictionaries to keep track of dynamic widgets
     self.files = {}
     self.filesP = {}
     self.markerFreq={}
     self.markerFreqP={}
     self.freqSlice = {}
     self.freqSlice = {}
     self.colors = {}
     self.canvas = {}
     self.titles={}
     self.titlesP={}
     self.smithBoxes={}
     self.smithBoxesP ={}
     self.logMagBoxes={}
     self.logMagBoxesP={}
     self.plots = {}
     self.trace = {}
     self.ports = {}
     self.portsP = {}
     # ******************** Static widgets *****************************************************
     self.staticWidgets = QtGui.QGraphicsWidget()
     self.staticLayout = QtGui.QGraphicsGridLayout(self.staticWidgets)
     # Data selection button
     self.dataButton = QtGui.QPushButton('Grab Data')
     self.dataButtonP = QtGui.QGraphicsProxyWidget()
     self.dataButtonP.setWidget(self.dataButton)
     self.dataButton.clicked.connect(self.GrabData)
     self.staticLayout.addItem(self.dataButtonP, 0, 0)
     # Number of windows
     self.numberOfWindows = QtGui.QLineEdit()
     self.doubleValidator = QtGui.QIntValidator()
     self.numberOfWindows.setValidator(self.doubleValidator)
     self.numberOfWindows.textChanged.connect(self.ValidateWindowCount)
     self.numberOfWindows.setStyleSheet('background-color:black;border-style: outset;color: rgb(255,255,255)')
     self.numberOfWindows.setPlaceholderText("How Many Data Windows")
     self.numberOfWindowsP = QtGui.QGraphicsProxyWidget()
     self.numberOfWindowsP.setWidget(self.numberOfWindows)
     self.staticLayout.addItem(self.numberOfWindowsP, 0, 1)
     self.staticWidgets.setLayout(self.staticLayout)
     self.win.addItem(self.staticWidgets, 0, 0, 1, 1)
    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)
Exemple #3
0
    def __init__(self):
        """
        Constructor
        """
        self.win.resize(1400, 800)
        self.win.setWindowTitle("Attitude plots")
        pg.setConfigOptions(antialias=True)

        # self.win2.resize(1000,600)
        # self.win2.setWindowTitle('Following control')

        self.buildQuaternion()
        self.buildTheta()
        self.buildX()
        self.buildXDot()
        self.win.nextRow()
        self.buildThetaDot()
        self.buildTorque()
        self.buildA()
        self.buildMotor()
        # self.buildMoveX()
        # self.buildMoveY()
        # self.buildMoveZ()
        timer = QtCore.QTimer()
        timer.timeout.connect(self.update)
        timer.start(50)
    def initUi(self):
        """初始化界面"""
        portfolio = self.portfolio
        
        self.setWindowTitle(u'波动率图表')

        pg.setConfigOptions(antialias=True)         #启用抗锯齿
        
        # 创建绘图区以及线
        for chain in portfolio.chainDict.values():
            symbol = chain.symbol + CALL_SUFFIX

            chart = self.addPlot(title=symbol)
            chart.showGrid(x=True, y=True) 
            chart.setLabel('left', u'波动率')          #设置左边标签
            chart.setLabel('bottom', u'行权价')        #设置底部标签                

            self.bidCurveDict[symbol] = chart.plot(pen='r', symbol='t', symbolSize=8, symbolBrush='r')
            self.askCurveDict[symbol] = chart.plot(pen='g', symbolSize=8, symbolBrush='g')
            self.pricingCurveDict[symbol] = chart.plot(pen='w', symbol = 's', symbolSize=8, symbolBrush='w')
        
        self.nextRow()
        
        for chain in portfolio.chainDict.values():
            symbol = chain.symbol + PUT_SUFFIX

            chart = self.addPlot(title=symbol)
            chart.showGrid(x=True, y=True) 
            chart.setLabel('left', u'波动率') 
            chart.setLabel('bottom', u'行权价')

            self.bidCurveDict[symbol] = chart.plot(pen='r', symbol='t', symbolSize=8, symbolBrush='r')
            self.askCurveDict[symbol] = chart.plot(pen='g', symbolSize=8, symbolBrush='g')
            self.pricingCurveDict[symbol] = chart.plot(pen='w', symbol = 's', symbolSize=8, symbolBrush='w')
Exemple #5
0
    def initUI(self):
        win = pg.GraphicsLayoutWidget()
        win.resize(1000, 600)
        win.setWindowTitle(u"Node: "+unicode(self.parent().name()))

        # Enable anti-aliasing for prettier plots
        pg.setConfigOptions(antialias=True)
        # Add Label where coords of current mouse position will be printed
        self.coordLabel = pg.LabelItem(justify='right')
        win.addItem(self.coordLabel)
        
        #add custom datetime axis
        x_axis1 = DateAxisItem(orientation='bottom')
        x_axis2 = DateAxisItem(orientation='bottom')
        self.y_axis1  = pg.AxisItem(orientation='left')  # keep reference to itm since we want to modify its label
        self.y_axis2  = pg.AxisItem(orientation='left')  # keep reference to itm since we want to modify its label

        self.p1 = win.addPlot(row=1, col=0, axisItems={'bottom': x_axis1, 'left': self.y_axis1})
        #self.p1.setClipToView(True)
        self.p2 = win.addPlot(row=2, col=0, axisItems={'bottom': x_axis2, 'left': self.y_axis2}, enableMenu=False, title=' ')
        #self.p1.setClipToView(True)
        self.vb = self.p1.vb  # ViewBox
        
        self.zoomRegion = pg.LinearRegionItem()
        self.zoomRegion.setZValue(-10)
        self.zoomRegion.setRegion([1000, 2000])
        self.p2.addItem(self.zoomRegion, ignoreBounds=True)
        
        self.p1.setAutoVisible(y=True)
        self.legend = self.p1.addLegend()

        self.initCrosshair()
        self.win = win
def main():

    app = QtGui.QApplication.instance()
    pg.setConfigOptions(background='k')
    pg.setConfigOptions(foreground='d')
    if app == None:
        app = QtGui.QApplication([])
    app.quitOnLastWindowClosed()

    # Icon to show in task bar for Windows
    if platform.system() == 'Windows':
        myappid = 'koheron.ldk'
        ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid)

    window = KWindow(app)

    prev_time = 0
    i = 0
    # Start the update loop:
    while window.session_opened:
        i = i+1  
        window.update()
        time_ = time.time() 
        window.frame_rate = 0.95 * window.frame_rate + 0.05/(0.001+time_-prev_time)
        QtGui.QApplication.processEvents()
        prev_time = time_
def plotting():
    from pyqtgraph.Qt import QtGui, QtCore
    import pyqtgraph as pg

    ts = listing[0]
    gids = listing[1]

    #QtGui.QApplication.setGraphicsSystem('raster')
    app = QtGui.QApplication([])
    #mw = QtGui.QMainWindow()
    #mw.resize(800,800)
    # Enable antialiasing for prettier plots
    pg.setConfigOptions(antialias=True)

    win = pg.GraphicsWindow(title="Basic plotting examples")
    win.resize(1000,600)
    win.setWindowTitle('pyqtgraph example: Plotting')

    p4 = win.addPlot(title="Parametric, grid enabled")
    p4.plot(ts, gids)
    p4.showGrid(x=True, y=True)

    ## Start Qt event loop unless running in interactive mode or using pyside.
    if __name__ == '__main__':
        import sys
        if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
            QtGui.QApplication.instance().exec_()
Exemple #8
0
    def __init__(self):
        '''
        Constructor
        '''
        self.win = pg.GraphicsWindow(title="Drone parameters")
        
        self.win.resize(1400,800)
        self.win.setWindowTitle('Attitude plots')
        pg.setConfigOptions(antialias=True)
        
        self.pOmega = None
        self.pOmegaCurves = [None,None]
        self.pOmegaData = [[],[]]

        self.pAlpha = None
        self.pAlphaCurves = [None,None]
        self.pAlphaData = [[],[]]

        self.pDelta = None
        self.pDeltaCurves = [None]
        self.pDeltaData = [[]]

        self.pTimes = []
        
        self.buildOmega()
        self.buildAlpha()
        self.buildDelta()
Exemple #9
0
def setup_graphics(app):

    print("setup graphics")

    global curve1, curve2, win, timer

    win = pg.GraphicsWindow(title="Basic plotting examples")
    win.resize(1000,600)
    win.setWindowTitle('pyqtgraph example: Plotting')

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

    # add the main plot
    p = win.addPlot(title="ADC1")
    p.showGrid(x=True, y=True)
    p.setRange(xRange=[0, 45000], yRange=[0, 256])
    curve1 = p.plot(pen='y')
    curve2 = p.plot(pen='r')
    #data = np.random.normal(size=(10,1000))
    #ptr = 0

    timer = QtCore.QTimer()
    timer.timeout.connect(update_plot)
    timer.start(50)

    print("timer set")
def main():
    print "Starting main"
    
    win = QtGui.QMainWindow()    
    
    cw = QtGui.QWidget()
    
    #component = DoubleBusRing()
    component = SingleBusCROW()
    lbda_step = 0.00001
    lbdas = np.arange(1.5455,1.5485+lbda_step,lbda_step)
    manip = Manipulate(component, lbdas)
    
    cw.setLayout(manip.layout)
    win.setCentralWidget(cw)
    win.show()    
    
    win.setCentralWidget(cw)
   
    pg.setConfigOptions(antialias=True)
    win.setGeometry(100,100,1200,600)
    win.setWindowTitle('Analysor')   
         
    import sys
    pg.setConfigOptions(useWeave=False)
    print "Hello"
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        print "Running"
        QtGui.QApplication.instance().exec_()
        print "Done"
Exemple #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
    def create_main_frame(self):
                # Load Qt UI from .ui file
        ui_loader = QtUiTools.QUiLoader()
        ui_file = QtCore.QFile("view_data.ui")
        ui_file.open(QtCore.QFile.ReadOnly); 
        self.ui = ui_loader.load(ui_file)
        ui_file.close()
        
        self.ui.setParent(self)

        
        #set up image
        pg.setConfigOptions(useWeave=False)
        self.imv = pg.ImageView()
#         self.vLine_1, self.hLine_1 = self.cross_hair(self.imv)
        self.square = self.make_dot(self.imv)
        
        self.imv.setMinimumSize(350, 350)
        plot_tools.plot_pyqt(self.imv,self.data , self.dataview)
        self.imv.scene.sigMouseClicked.connect(self.mouseMoved_image)
        self.imv.getView().setMouseEnabled(x=False, y=False)
        

        self.graph = self.setup_graph()
        
        self.ui.image.addWidget(self.imv)
        self.ui.graphs.addWidget(self.graph)
        
        self.set_slider_settings()

        self.connect_events()
        self.connect_shortcuts()
Exemple #13
0
def create_window():
    win = QtGui.QMainWindow()
    win.resize(1000,600)
    win.setWindowTitle('HypnoPy')

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

    plot_widget = create_plot_widget('Spiral')
    sidebar_width = 200
    slider_widget1 = create_slider_widget(label='SPL threshold',
                                          unit='dB',
                                          min_value=-50,
                                          max_value=50,
                                          init_value=0,
                                          step=1,
                                          connect=_update_SPL_THRESHOLD,
                                          max_width=sidebar_width)
    slider_widget2 = create_slider_widget(label='Window size',
                                          unit='',
                                          min_value=256,
                                          max_value=len(get_buffer()),
                                          init_value=len(get_buffer()),
                                          step=2,
                                          connect=_update_WINDOW_SIZE,
                                          max_width=sidebar_width)
    sidebar = create_sidebar(sidebar_width, slider_widget1, slider_widget2) 
    layout = pg.LayoutWidget()
    layout.addWidget(plot_widget)
    layout.addWidget(sidebar)
    layout.show()
    return layout, plot_widget
Exemple #14
0
def setPgConfigOptions(**kwargs):
    """ Sets the PyQtGraph config options and emits a log message
    """
    for key, value in kwargs.items():
        logger.debug("Setting PyQtGraph config option: {} = {}".format(key, value))

    pg.setConfigOptions(**kwargs)
    def __init__(self, widget, func, sampleinterval=0.05 * ureg.s,
                 timewindow=10. * ureg.s):

        # Data stuff
        self._interval = int(sampleinterval.to(ureg.s).magnitude*1000)
        self._bufsize = int((timewindow.to(ureg.s) /
                                        sampleinterval.to(ureg.s)).magnitude)
        self.databuffer = collections.deque([0.0]*self._bufsize, self._bufsize)
        self.x = np.linspace(-timewindow.to(ureg.s).magnitude, 0.0,
                                                                 self._bufsize)
        self.y = np.zeros(self._bufsize, dtype=np.float)

        self.func = func

        self.plt = widget

        pg.setConfigOptions(antialias=True)
#        self.plt = pg.plot(title='Dynamic Plotting with PyQtGraph')
        size = [widget.width(), widget.height()]
        self.plt.resize(*size)
        self.plt.showGrid(x=True, y=True)
        self.plt.setLabel('left', self.func.__name__, self.func().units)
        self.plt.setLabel('bottom', 'time', 's')
        self.curve = self.plt.plot(self.x, self.y, pen='y')
        # QTimer
        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.updateplot)
        self.timer.start(self._interval)
Exemple #16
0
	def draw_spectrum_analyzer(all_frames, thresh_frames):
		time.sleep(1) # Wait just one second
		pw = pg.plot(title="Spectrum Analyzer") # Window title
		pg.setConfigOptions(antialias=True) # Enable antialias for better resolution
		pw.win.resize(800, 300) # Define window size
		pw.win.move(540 * SCREEN_WIDTH / 1920, 500 * SCREEN_HEIGHT / 1080) # Define window position
		while True: # Loop over the frames of the audio / data chunks
			data = ''.join(all_frames[-1:]) # Get only the last frame of all frames
			data = numpy.fromstring(data, 'int16') # Binary string to numpy int16 data format
			pw.setMouseEnabled(y=False) # Disable mouse
			pw.setYRange(0,1000) # Set Y range of graph
			pw.setXRange(-(RATE/16), (RATE/16), padding=0) # Set X range of graph relative to Bit Rate
			pwAxis = pw.getAxis("bottom") # Get bottom axis
			pwAxis.setLabel("Frequency [Hz]") # Set bottom axis label
			f, Pxx = HearingPerception.find_frequency(data) # Call find frequency function
			f = f.tolist() # Numpy array to list
			Pxx = (numpy.absolute(Pxx)).tolist() # Numpy array to list
			try: # Try this block
				if thresh_frames[-1:][0] == EMPTY_CHUNK: # If last thresh frame is equal to EMPTY CHUNK
					pw.plot(x=f,y=Pxx, clear=True, pen=pg.mkPen('w', width=1.0, style=QtCore.Qt.SolidLine)) # Then plot with white pen
				else: # If last thresh frame is not equal to EMPTY CHUNK
					pw.plot(x=f,y=Pxx, clear=True, pen=pg.mkPen('y', width=1.0, style=QtCore.Qt.SolidLine)) # Then plot with yellow pen
			except IndexError: # If we are getting an IndexError because of this -> thresh_frames[-1:][0]
				pw.plot(x=f,y=Pxx, clear=True, pen=pg.mkPen('w', width=1.0, style=QtCore.Qt.SolidLine)) # Then plot with white pen
			pg.QtGui.QApplication.processEvents() # ???
			time.sleep(0.05) # Wait a few miliseconds
Exemple #17
0
    def plot_trace_list(self, trace_list):

        app = pg.mkQApp()
        app.processEvents()
        ## Putting this at the beginning or end does not have much effect


        win = pg.GraphicsWindow(title="Basic plottting examples")
        win.resize(1000, 600)

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

        p = win.addPlot(title="x0-x1")

        xy = []
        for trace in trace_list:
            x_array = trace.x_array
            #p.plot(x_array[:, 0:2])
            xy.append(x_array)

        xy_array = np.vstack(xy)
        path = pg.arrayToQPath(xy_array[:, 0], xy_array[:, 1], connect='all')

        item = QtGui.QGraphicsPathItem(path)
        item.setPen(pg.mkPen('w'))
        p.addItem(item)

        #p.show()
        QtGui.QApplication.instance().exec_()
	def __init__(self, parent=None):
		pg.GraphicsWindow.__init__(self, title="Spectrum Analyzer")
		self.resize(400,300)
		self.setWindowTitle('Spectrum Analyzer')
		pg.setConfigOptions(antialias=True)
		self.plot_item = self.addPlot(title='Time Domain - u(t)', labels={'left': 'u(t)', 'bottom': 't'})
		self.plot_samples()
	def __init__(self, conn, ide, sensor, numCanal):
		super(QObject, self).__init__()
		self.conn = conn
		self.sensor = sensor
		self.ide = ide
		self.numCanal = numCanal
		pg.setConfigOptions(antialias=True)
		self.dlg = QDialog()
		self.plotDlg = Ui_PlotDlg()
		self.plotDlg.setupUi(self.dlg)
		self.dlg.setWindowModality(Qt.ApplicationModal)
		self.plot = pg.PlotWidget(parent=None, background='default', labels={'left': ('Temperature', 'ºC')},
		                          axisItems={'bottom': TimeAxisItem(orientation='bottom')})
		self.plot.setObjectName("plot")
		self.plotDlg.verticalLayout.addWidget(self.plot)
		self.dlg.show()
		self.curve = self.plot.plot()
		self.plot.enableAutoRange()
		self.curve.curve.setClickable(True)
		self.plot.showGrid(x=True, y=True, alpha=0.5)

		self.plotDlg.dayButton.clicked.connect(self.dayData)
		self.plotDlg.hourButton.clicked.connect(self.hourData)
		self.plotDlg.weekButton.clicked.connect(self.weekData)
		self.plotDlg.monthButton.clicked.connect(self.monthData)
		self.plotDlg.yearButton.clicked.connect(self.yearData)
		self.plot.sigRangeChanged.connect(self.plotClicked)
		self.plot.scene().sigMouseMoved.connect(self.mouseMoved)
		#self.cpoint = pg.CurvePoint(self.curve)
		#self.plot.addItem(self.cpoint)
		self.label = pg.TextItem(anchor=(0, 0))
		#self.label.setParentItem(self.cpoint)
		self.plot.addItem(self.label)
		self.plotDlg.dayButton.setFocus()
		self.dayData()
Exemple #20
0
 def onZipfPlot(self):
     before = time.time()
     
     pg.setConfigOptions(antialias=True)
     dialog= QtGui.QDialog(self)
     plotWidget = pg.PlotWidget(name='Zipf\'s Law Plot')
     
     logx = self.model.getLogX()
     ab = self.model.getPolyFit()
     s = ScatterPlotItem(logx, self.model.getLogfreqDist(), size=4, pen=None, brush=pg.mkBrush(255, 255, 255))
     s.addPoints(logx, self.model.getLogfreqDist())
     plot = plotWidget.plot(logx, [self.model.getPoly(x) for x in logx],  pen=(0,255,255), size=4)
     
     legend = LegendItem((130,60), offset=(500,30))
     legend.setParentItem(plotWidget.getPlotItem())
     legend.addItem(s, 'Corpus data')
     legend.addItem(plot, str(round(ab[0], 3)) + 'x + ' +str(round(ab[1], 3)))
     
     plotWidget.addItem(s)
     lay = QtGui.QVBoxLayout()
     lay.addWidget(plotWidget)
     
     dialog.setLayout(lay)
     dialog.show()
             
     self.fillTimeData("creating Zipf plot", time.time() - before)
    def start_App(self):
        """Initialize the window """
        self.app = eegviewer.gui.QtGui.QApplication(sys.argv)
        self.MainWindow = eegviewer.gui.QtGui.QMainWindow()
        # Enable antialiasing for prettier plots
        pg.setConfigOptions(antialias=True)
        self.ui = eegviewer.gui.Ui_MainWindow()
        self.ui.setupUi(self.MainWindow)
        self.eegplot = self.ui.graphicsView.addPlot(title="EEG Signal")
        self.epochplot = self.ui.graphicsView_2.addPlot(title="Epoch Signals")
        self.evokedplot = self.ui.graphicsView_3.addPlot(title="Evoked Plot")

        self.ui.actionLoad_File.triggered.connect(self.file_load_sequence)        
        self.ui.eeg_channel_combo_box.currentIndexChanged.connect(self.channel_selected_sequence)
        # Epochs stuff
        self.ui.create_epochs_button.pressed.connect(self.compute_epochs_sequence)
        self.ui.epoch_channel_combo_box.currentIndexChanged.connect(self.epoch_update_plot)
        self.ui.epoch_number_spinbox.valueChanged.connect(self.epoch_update_plot)

        # Evoked stuff
        self.ui.create_evoked_button.pressed.connect(self.compute_evoked_sequence)
        self.ui.evoked_channel_combo_box.currentIndexChanged.connect(self.evoked_update_plot)

        #sys.exit(self.app.exec_())
        self.MainWindow.showMaximized()
        self.app.exec_()
    def init_gui(self):
        # create a window with 14 plots (7 rows x 2 columns)
        ## create a window with 8 plots (4 rows x 2 columns)

        win = pg.GraphicsWindow(title="Trigno display")
        win.resize(1000,600)
        win.setWindowTitle('Trigno display')
        pg.setConfigOptions(antialias=True)

        #cols, rows = 2, 4
        cols = 2
        rows = self.config.nchan / cols
        self.npt = 2000
        self.axes = np.empty((rows, cols), dtype=object)
        for i in xrange(rows):
            for j in xrange(cols):
                ax = win.addPlot(title="EMG%d" % (i * cols + j))
                #ax.disableAutoRange(axis=None)
                self.axes[i,j] = ax.plot(np.random.normal(1,1, size=432*3))
            win.nextRow()
            
        self.old_data = np.zeros((self.config.nchan, self.npt))
        self.new_data = np.zeros((self.config.nchan, self.npt))
        
        timer = QtCore.QTimer(self)
        timer.connect(timer, QtCore.SIGNAL("timeout()"), self.timer_event)
        timer.start(0)
def plotting():
    from pyqtgraph.Qt import QtGui, QtCore
    import pyqtgraph as pg

    app = QtGui.QApplication([])

    pg.setConfigOptions(antialias=True)

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

    a = win.addPlot(title=title[0][6:title[0].find(',')])
    a.plot(listing[0], listing[1])
    a.showGrid(x=True, y=True)

    for i in range(2, len(listing), 2):
        print i
        if i % 3 == 0:
            win.nextRow()
        p1 = win.addPlot(title=title[i/ 2][6:title[i/2].find(',')])
        p1.plot(listing[i], listing[i + 1])
        p1.showGrid(x=True, y=True)
        p1.setXLink(a)
        p1.setYLink(a)

    if __name__ == '__main__':
        import sys
        if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
            QtGui.QApplication.instance().exec_()
    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_()
    def realtime_graph(self):
        strPort = '/dev/ttyACM1'
        ser = serial.Serial(strPort, 9600)


        counter =0
        counter2 = 0

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

        win = pg.GraphicsWindow(title="Basic plotting examples")
        win.resize(1000,600)
        win.setWindowTitle('pyqtgraph example: Plotting')

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



        maxLen =10000
        p6 = win.addPlot(title="Updating plot")
        curve = p6.plot( pen=None, symbol='o', symbolPen=None, symbolSize=5)
        data = []
        data1= []

        ptr = 0



        timer = QtCore.QTimer()
        timer.timeout.connect(update)
        timer.start(1)
Exemple #26
0
	def __init__(self, comport, displayTime = 2):
		global SENSOR_DATA_BUFFER_LENGTH
		#input is the maxDisplayTime in seconds
		self.numSensors = 0

		self.board = seismicpi.SeismicPi(comport)

		SENSOR_DATA_BUFFER_LENGTH = displayTime * 1000
		self.qx = deque(maxlen=SENSOR_DATA_BUFFER_LENGTH)

		self.app = QtGui.QApplication([])
		self.win = pg.GraphicsWindow(title = "Sensor Plots")
		self.win.resize(1000, 800)
		
		self.renderLock = False
		
		self.read_sensors = False
		self.read_accel = False
		
		self.pen_colors = ['r', 'g', 'b', 'y']
		
		self.sensors = []
		
		self.paused = False

		pg.setConfigOptions(antialias = False)
Exemple #27
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)
Exemple #28
0
    def __init__(self):
        self._app = QtGui.QApplication([])
        self._win = pg.GraphicsWindow(title="JackPlay Plotter")
        self._win.setWindowTitle("JackPlay Plotter")
        self._plots = dict()
        self._images = dict()

        pg.setConfigOptions(antialias=True)
Exemple #29
0
def affichage(name, shareddic):
    """ Ploting and Display """
    pg.mkQApp()
    pg.setConfigOptions(antialias=True)  ## this will be expensive for the local plot
    force = pg.SpinBox(value=0, int=True, minStep=1, step=10, bounds=(-128, 128))#QtGui.QLineEdit()
    phase = pg.SpinBox(value=1, minStep=0.1, step=0.1, bounds=(0, 2))#QtGui.QLineEdit()
    freq = pg.SpinBox(value=55, minStep=1, step=1, dec=True, bounds=(0, 900))#QtGui.QLineEdit()
    label = QtGui.QLabel()
    #self.data = data
    #self.fps = fps
    labelf = QtGui.QLabel()
    labelf.setText('Force')
    labelp = QtGui.QLabel()
    labelp.setText('Phase')
    labelfr = QtGui.QLabel()
    labelfr.setText('Frequence')
    lcheck = QtGui.QCheckBox('plot local')
    lcheck.setChecked(True)
    lplt = pg.PlotWidget()
    lplt.setYRange(-45, 45)
    lplt.setTitle('Position')
    fplt = pg.PlotWidget()
    fplt.setYRange(-150, 150)
    fplt.setTitle('Forces')
    fplt.getAxis('bottom').setScale(1.0/RESANG)
    layout = pg.LayoutWidget()
    layout.addWidget(labelf)
    layout.addWidget(labelp)
    layout.addWidget(labelfr)
    layout.addWidget(force, row=2, col=0)
    layout.addWidget(phase, row=2, col=1)
    layout.addWidget(freq, row=2, col=2)
    layout.addWidget(lcheck, row=3, col=0)
    layout.addWidget(label, row=3, col=1)
    layout.addWidget(lplt, row=4, col=0, colspan=3)
    layout.addWidget(fplt, row=5, col=0, colspan=3)
    layout.resize(800, 800)
    layout.setWindowTitle('Timon 12: Demo')
    layout.show()
    def update(shareddic):
        """ Every refresh of the display """
        localdata = [0]*1000
        taille = 0#shareddic['taille']
        localdata = shareddic['data']
        localvitesse = shareddic['vitesse']
        lplt.plot(localdata, clear=True)
        lplt.plot(localvitesse, pen=(0, 0, 255))
        fps = shareddic['fps']
        label.setText("Communication %0.2f Hz Taille buffer: %0.2f" % (fps, taille/3.0))
        force = shareddic['force']
        degre = shareddic['degre']
        forcenow = shareddic['forcenow']
        fplt.plot(range(-ANGLEMAX*RESANG, ANGLEMAX*RESANG), force, clear=True)
        fplt.plot([degre*RESANG], [forcenow], pen=(0, 0, 255), symbolBrush=(255, 0, 0), symbolPen='r')
    timer = QtCore.QTimer()
    timer.timeout.connect(lambda: update(shareddic))
    timer.start(50)
    QtGui.QApplication.instance().exec_()
Exemple #30
0
    def __init__graphs(self):
        
        #clear graphs
        self.graph_rawdata.clear()
        self.graph_enrichrate.clear()
        pg.setConfigOptions(antialias=True)
        
#        
        # general graph config
        labelStyle = {'color': '#888', 'font-size': '9pt'} # propriétés CSS à utiliser pour le label

        # RAWDATA GRAPH
        self.graph_rawdata.setBackgroundBrush(QBrush(QColor(Qt.white))) # la classe PlotWidget est un GraphicsWidget qui est un QGraphics View
        self.graph_rawdata.showGrid(x=True, y=True)  # affiche la grille
        self.graph_rawdata.getAxis('bottom').setPen(pg.mkPen(150,150,150)) # couleur de l'axe + grille
        self.graph_rawdata.getAxis('left').setPen(pg.mkPen(150,150,150)) # couleur de l'axe + grille

        self.graph_rawdata.getAxis('bottom').setLabel('Time', units='sec', **labelStyle) # label de l'axe
        self.graph_rawdata.getAxis('left').setLabel('Concentration', units='micromole/L', **labelStyle) # label de l'axe

        # self.graph_rawdata.getViewBox().setMouseMode(pg.ViewBox.RectMode)  # fonction ViewBox pas accessible depuis PlotWidget : fixe selection par zone
        self.graph_rawdata.setMouseEnabled(x=True, y=True) # désactive interactivité axe X


        #ENRICHRATE GRAPH
        self.graph_enrichrate.setBackgroundBrush(QBrush(QColor(Qt.white))) # la classe PlotWidget est un GraphicsWidget qui est un QGraphics View
        self.graph_enrichrate.showGrid(x=True, y=True)  # affiche la grille
        self.graph_enrichrate.getAxis('bottom').setPen(pg.mkPen(150,150,150)) # couleur de l'axe + grille
        self.graph_enrichrate.getAxis('left').setPen(pg.mkPen(150,100,150)) # couleur de l'axe + grille

        self.graph_enrichrate.getAxis('bottom').setLabel('Time', units='sec', **labelStyle) # label de l'axe
        self.graph_enrichrate.getAxis('left').setLabel('Rate', units='min-1', **labelStyle) # label de l'axe

        # self.graph_enrichrate.getViewBox().setMouseMode(pg.ViewBox.RectMode)  # fonction ViewBox pas accessible depuis PlotWidget : fixe selection par zone
        self.graph_enrichrate.setMouseEnabled(x=True, y=True) # désactive interactivité axe X


        #Create empty curves
        linewidth = 1
        self.Courbe_Mass32 = self.graph_rawdata.plot(pen=pg.mkPen([250,0,0], width=linewidth), name='Mass32')
        self.Courbe_Mass40 = self.graph_rawdata.plot(pen=pg.mkPen([200,150,0], width=linewidth), name='Mass40')
        self.Courbe_Mass44 = self.graph_rawdata.plot(pen=pg.mkPen([0,250,0], width=linewidth), name='Mass44')
        self.Courbe_Mass45 = self.graph_rawdata.plot(pen=pg.mkPen([50,200,250], width=linewidth), name='Mass45')
        self.Courbe_Mass46 = self.graph_rawdata.plot(pen=pg.mkPen([250,150,250], width=linewidth), name='Mass46')
        self.Courbe_Mass47 = self.graph_rawdata.plot(pen=pg.mkPen([0,100,250], width=linewidth), name='Mass47')
        self.Courbe_Mass49 = self.graph_rawdata.plot(pen=pg.mkPen([100,0,250], width=linewidth), name='Mass49')
        self.Courbe_totalCO2 = self.graph_rawdata.plot(pen=pg.mkPen([100,100,100], width=linewidth, style=QtCore.Qt.DashLine), name='TotalCO2')# DashDotline DashLine DashDotDotLine ...
        self.Courbe_logE49 = self.graph_rawdata.plot(pen=pg.mkPen([0,0,0], width=linewidth), name='LogEnrich')

        self.Courbe_d40=self.graph_enrichrate.plot(pen=pg.mkPen([200,150,0], width=linewidth), name='d40dt')
        self.Courbe_d44=self.graph_enrichrate.plot(pen=pg.mkPen([0,250,0], width=linewidth), name='d44dt')
        self.Courbe_d45=self.graph_enrichrate.plot(pen=pg.mkPen([50,200,250], width=linewidth), name='d45dt')
        self.Courbe_d46=self.graph_enrichrate.plot(pen=pg.mkPen([250,150,250], width=linewidth), name='d46dt')
        self.Courbe_d47=self.graph_enrichrate.plot(pen=pg.mkPen([0,100,250], width=linewidth), name='d47dt')
        self.Courbe_d49=self.graph_enrichrate.plot(pen=pg.mkPen([100,0,250], width=linewidth), name='d49dt')
        self.Courbe_enrichrate47=self.graph_enrichrate.plot(pen=pg.mkPen([0,100,250], width=linewidth, style=QtCore.Qt.DashLine), name='ER47')
        self.Courbe_enrichrate49=self.graph_enrichrate.plot(pen=pg.mkPen([100,0,250], width=linewidth, style=QtCore.Qt.DashLine), name='ER49')
        self.Courbe_O2evol=self.graph_enrichrate.plot(pen=pg.mkPen([250,0,0], width=linewidth), name='d32dt')
Exemple #31
0
 def run_app():
     app = QtWidgets.QApplication(sys.argv)
     pg.setConfigOptions(imageAxisOrder='row-major')
     mainwin = MainGUI()
     mainwin.show()
     app.exec_()
import tkinter.filedialog
from PIL import Image
import tomopy
import math
import time
import os
import scipy
from scipy import ndimage
from scipy import stats
from scipy import signal
import qimage2ndarray
import pyqtgraph as pg

pg.setConfigOption('background', 'w')  # Plothintergrund weiß (2D)
pg.setConfigOption('foreground', 'k')  # Plotvordergrund schwarz (2D)
pg.setConfigOptions(antialias=True)  # Enable antialiasing for prettier plots

Ui_CorrectionWindow, QCorrectionWindow = loadUiType(
    'movement_correction_callable.ui')  # GUI vom Hauptfenster


class Movement_corrector(Ui_CorrectionWindow, QCorrectionWindow):
    def __init__(self, sinogram, path_out, namepart, number_of_sequences,
                 sequence_size, cor, max_theta, theta_first_list):
        super(Movement_corrector, self).__init__()
        self.setupUi(self)
        self.setWindowTitle('Movement Correction Callable')
        self.movement_correction_running = 1
        #QtWidgets.QApplication.processEvents()
        sinogram = (sinogram * 0.001) - 9.68
        self.multi_sino = numpy.exp(numpy.negative(sinogram))
Exemple #33
0
            print("Input vector: {0}, attempt: {1}, remains: {2}".format(
                vector, it, remains_counter))
            potential_input = rf.float_to_membrane_potential(vector)
            potential_input = potential_input.flatten()
            temporal_layer.I_ext = potential_input
            net_model.run(simulation_time * ms, report='text')
            net_model.store()
            remains_counter -= 1

    # visual
    app = QtGui.QApplication([])
    win = pg.GraphicsWindow(title="som")
    win.resize(1000, 600)
    win.setWindowTitle('brain')
    # Enable antialiasing for prettier plots
    pg.setConfigOptions(antialias=True)

    p1 = win.addPlot(title="Region Selection")

    p1.plot(u_spike_mon.t / ms,
            u_spike_mon.i[:],
            pen=None,
            symbol='o',
            symbolPen=None,
            symbolSize=5,
            symbolBrush=(255, 255, 255, 255))
    p1.showGrid(x=True, y=True)
    lr = pg.LinearRegionItem([0, simulation_time])
    lr.setZValue(0)
    p1.addItem(lr)
    p2 = win.addPlot(title="Zoom on selected region")
    def __init__(self, config_file=''):
        super(PilotGUI, self).__init__()
        self.setStyleSheet("QMainWindow {background: 'black';}")
        pg.setConfigOptions(imageAxisOrder='row-major')
        self.setGeometry(70, 70, 1100, 900)
        self.setWindowTitle('Visualize data')
        self.cwidget = QtGui.QWidget(self)
        self.setCentralWidget(self.cwidget)
        self.l0 = QtGui.QGridLayout()
        self.cwidget.setLayout(self.l0)

        self.menu_config_load()

        #Register button

        #Mask button
        color_ind = 1
        self.mask_button = PressToSelectButton('Masking tool', 'masking', self,
                                               color_ind)
        #self.mask_button.clicked.connect(lambda:
        #masking(self.config_dict['filepath'],0,
        #self.config_dict['save_folder_mask'],
        #self.config_dict['save_folder_masked']))
        self.l0.addWidget(self.mask_button, 4, 0)

        #Detrending button
        color_ind = 25
        self.detrend_button = PressToSelectButton('Detrend', 'detrending',
                                                  self, color_ind)
        self.l0.addWidget(self.detrend_button, 8, 0)

        color_ind = 100
        self.detrend_verif_button = PressToSelectButton(
            'Verify detrending', 'detrend_verify_plot', self, color_ind)
        self.l0.addWidget(self.detrend_verif_button, 8, 6)

        color_ind = 150
        self.segment_raw_button = PressToSelectButton('Segment raw',
                                                      'segment_raw', self,
                                                      color_ind)
        self.l0.addWidget(self.segment_raw_button, 20, 0)

        color_ind = 200
        self.segment_detrended_button = PressToSelectButton(
            'Segment detrended', 'segment_detrended', self, color_ind)
        self.l0.addWidget(self.segment_detrended_button, 24, 0)

        color_ind = 200
        self.dff_raw_button = PressToSelectButton('Calculate dff raw',
                                                  'dff_raw', self, color_ind)
        self.l0.addWidget(self.dff_raw_button, 28, 0)

        color_ind = 200
        self.dff_detrended_button = PressToSelectButton(
            'Calculate dff detrended', 'dff_detrended', self, color_ind)
        self.l0.addWidget(self.dff_detrended_button, 32, 0)

        color_ind = 100
        self.complete_viz_raw_button = PressToSelectButton(
            'dff viz raw', 'complete_viz_raw', self, color_ind)
        self.l0.addWidget(self.complete_viz_raw_button, 28, 6)
After update() generates a new set of data, it can either plot directly to a local
plot (bottom) or remotely via a RemoteGraphicsView (top), allowing speed comparison
between the two cases. IF you have a multi-core CPU, it should be obvious that the 
remote case is much faster.
"""

import initExample  ## Add path to library (just for examples; you do not need this)
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
import pyqtgraph.widgets.RemoteGraphicsView
import numpy as np

app = pg.mkQApp()

view = pg.widgets.RemoteGraphicsView.RemoteGraphicsView()
pg.setConfigOptions(
    antialias=True)  ## this will be expensive for the local plot
view.pg.setConfigOptions(
    antialias=True)  ## prettier plots at no cost to the main process!
view.setWindowTitle('pyqtgraph example: RemoteSpeedTest')

app.aboutToQuit.connect(view.close)

label = QtGui.QLabel()
rcheck = QtGui.QCheckBox('plot remote')
rcheck.setChecked(True)
lcheck = QtGui.QCheckBox('plot local')
lplt = pg.PlotWidget()
layout = pg.LayoutWidget()
layout.addWidget(rcheck)
layout.addWidget(lcheck)
layout.addWidget(label)
Exemple #36
0
            f(self.hover_time, name)
        return


using_graphics = True

try:
    import pyqtgraph as pg
    from pyqtgraph.Qt import QtWidgets

    #Note: This is absolutely required for windows systems to work currently
    #But presumably it will be fixed at some point in the future
    if sys.platform.startswith('win'):
        pg.ptime.time = lambda: 0

    pg.setConfigOptions(imageAxisOrder='row-major')
    pg.setConfigOptions(background='w')

    class PlotWindow(QtWidgets.QMainWindow):
        def __init__(self):
            super().__init__()

        def init_savepng(self, exporter):
            if exporter is None:
                return
            # Set up the save PNG button/call exportpng function that activates when user presses button
            exportdatapngaction = QtWidgets.QAction("Save PNG", self)
            exportdatapngaction.triggered.connect(
                lambda: self.exportpng(exporter))

            # Set up menu bar to display and call creation of save PNG button
Exemple #37
0
    def __init__(self, queue):
        self.queue = queue
        pg.setConfigOptions(antialias=True)
        self.traces = dict()
        self.app = QtGui.QApplication(sys.argv)
        self.win = pg.GraphicsWindow(title='Attention Monitor')
        self.win.setWindowTitle('Attention Monitor')

        # set size of output window
        self.win.setGeometry(5, 115, 640, 480)

        ratios_xlabels = [(0, '0'), (60, '60'), (120, '120')]
        ratios_xaxis = pg.AxisItem(orientation='bottom')
        ratios_xaxis.setTicks([ratios_xlabels])

        ratios_ylabels = [(0, '0'), (0.25, '0.25'), (0.5, '0.5'),
                          (0.75, '0.75'), (1.0, '1.0')]
        ratios_yaxis = pg.AxisItem(orientation='left')
        ratios_yaxis.setTicks([ratios_ylabels])

        poses_xlabels = [(0, '0'), (60, '60'), (120, '120')]
        poses_xaxis = pg.AxisItem(orientation='bottom')
        poses_xaxis.setTicks([poses_xlabels])

        poses_ylabels = [(-45, '-45'), (0, '0'), (45, '45')]
        poses_yaxis = pg.AxisItem(orientation='left')
        poses_yaxis.setTicks([poses_ylabels])

        self.ratios = self.win.addPlot(
            title='Face Metrics',
            row=1,
            col=1,
            axisItems={
                'bottom': ratios_xaxis,
                'left': ratios_yaxis
            },
        )
        self.poses = self.win.addPlot(
            title='Head Pose Metrics',
            row=2,
            col=1,
            axisItems={
                'bottom': poses_xaxis,
                'left': poses_yaxis
            },
        )

        self.lgd = pg.LegendItem(size=(80, 60), offset=(50, 20))
        self.lgd.setParentItem(self.ratios.graphicsItem())
        self.c1 = self.ratios.plot([], pen='c', name='mar')
        self.c2 = self.ratios.plot([], pen='m', name='ear')
        self.lgd.addItem(self.c1, 'Mouth Aspect Ratio')
        self.lgd.addItem(self.c2, 'Eye Aspect Ratio')

        self.lgd2 = pg.LegendItem((80, 60), offset=(50, 20))
        self.lgd2.setParentItem(self.poses.graphicsItem())
        self.c3 = self.poses.plot([], pen='r', name='yaw')
        self.c4 = self.poses.plot([], pen='g', name='pitch')
        self.c5 = self.poses.plot([], pen='b', name='roll')

        self.lgd2.addItem(self.c3, 'Yaw')
        self.lgd2.addItem(self.c4, 'Pitch')
        self.lgd2.addItem(self.c5, 'Roll')

        self.x = np.arange(0, 2 * 60, 2)
Exemple #38
0
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 27 07:00:22 2020

@author: inox
"""
from pyaudio import paInt16, PyAudio
from struct import unpack
from pyqtgraph import GraphicsWindow, setConfigOptions, LegendItem, QtCore, QtGui
from numpy import fft, arange, split, argmax, floor
from scipy.signal import find_peaks as fpeaks

#Inicialización de ventana gráfica con los cuadros de visualización y el dicionario de trazas a graficar
win = GraphicsWindow(title="Analizador de Espectro")
win.setWindowTitle("Analizador de Espectro")
setConfigOptions(antialias=True, background='k')
scope = win.addPlot(title="Waveform", row=1, col=1)
span = win.addPlot(title="FFT", row=2, col=1)
traces = dict()
legend = LegendItem()


#Actualización (o inicialización) de las trazas de los cuadros de visualización
def set_plotdata(name, data_x, data_y):
    if name in traces:
        traces[name].setData(data_x, data_y)
    else:
        if name == 'waveform':
            traces[name] = scope.plot(pen='w', width=4)
            scope.setYRange(-2**(bits - 1), 2**(bits - 1), padding=0)
            scope.setXRange(t[0], t[-1], padding=0.00)
Exemple #39
0
def _visualize(self):
    import pyqtgraph as pg
    import numpy as np

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

    w = pg.GraphicsWindow()
    w.setWindowTitle('Visualization of the Network')
    v = w.addViewBox()
    v.setAspectLocked()

    g = pg.GraphItem()
    v.addItem(g)

    positions = []
    symbols = []
    symbol_brushes = []
    x = 0
    y = 0

    x += 1
    for neuron in self.sensory_neurons:
        y += 1
        neuron.position = (float(x), float(y))
        positions.append(neuron.position)
        symbols.append('t')
        symbol_brushes.append((250, 194, 5))
        neuron.index = len(positions) - 1

    x += len(self.sensory_neurons)
    y = (len(self.sensory_neurons) - len(self.interneurons)) / 2
    for neuron in self.interneurons:
        y += 1
        neuron.position = (random.uniform(x - len(self.sensory_neurons) / 1.5,
                                          x + len(self.sensory_neurons) / 1.5),
                           float(y))
        positions.append(neuron.position)
        symbols.append('h')
        symbol_brushes.append((195, 46, 212))
        neuron.index = len(positions) - 1

    x += len(self.sensory_neurons)
    y = (len(self.sensory_neurons) - len(self.motor_neurons)) / 2
    for neuron in self.motor_neurons:
        y += 1
        neuron.position = (float(x), float(y))
        positions.append(neuron.position)
        symbols.append('s')
        symbol_brushes.append((19, 234, 201))
        neuron.index = len(positions) - 1

    while True:
        connections = []
        lines = []
        for neuron2 in self.neurons:
            for neuron1, weight in neuron2.subscriptions.items():
                connections.append((neuron1.index, neuron2.index))
                lines.append(
                    (55, 55, 55, ((weight + 1) / 2) * 255, (weight + 1)))

        positions = np.asarray(positions)
        connections = np.asarray(connections)
        lines = np.asarray(lines,
                           dtype=[('red', np.ubyte), ('green', np.ubyte),
                                  ('blue', np.ubyte), ('alpha', np.ubyte),
                                  ('width', float)])
        g.setData(pos=positions,
                  adj=connections,
                  pen=lines,
                  size=0.1,
                  symbolBrush=symbol_brushes,
                  symbol=symbols,
                  pxMode=False)  # Update the graph

        pg.QtGui.QApplication.processEvents()
        if self.thread_kill_signal:
            break
        time.sleep(0.0333)
Exemple #40
0
    def __init__(self, parent=None):
        super().__init__()

        self.parent = parent
        self.cfg = parent.cfg
        self.state = mesoSPIM_StateSingleton()

        pg.setConfigOptions(imageAxisOrder='row-major')
        if (hasattr(self.cfg, 'ui_options') and self.cfg.ui_options['dark_mode']) or\
                (hasattr(self.cfg, 'dark_mode') and self.cfg.dark_mode):
            pg.setConfigOptions(background=pg.mkColor(
                '#19232D'))  # To avoid pitch black bg for the image view
        else:
            pg.setConfigOptions(background="w")
        '''Set up the UI'''
        if __name__ == '__main__':
            loadUi('../gui/mesoSPIM_CameraWindow.ui', self)
        else:
            loadUi('gui/mesoSPIM_CameraWindow.ui', self)
        self.setWindowTitle('mesoSPIM-Control: Camera Window')
        ''' Set histogram Range '''
        self.graphicsView.setLevels(100, 4000)

        self.imageItem = self.graphicsView.getImageItem()

        self.histogram = self.graphicsView.getHistogramWidget()
        self.histogram.setMinimumWidth(250)
        self.histogram.item.vb.setMaximumWidth(250)
        ''' This is flipped to account for image rotation '''
        self.y_image_width = self.cfg.camera_parameters['x_pixels']
        self.x_image_width = self.cfg.camera_parameters['y_pixels']
        ''' Initialize crosshairs '''
        self.crosspen = pg.mkPen({'color': "r", 'width': 1})
        self.vLine = pg.InfiniteLine(pos=self.x_image_width / 2,
                                     angle=90,
                                     movable=False,
                                     pen=self.crosspen)
        self.hLine = pg.InfiniteLine(pos=self.y_image_width / 2,
                                     angle=0,
                                     movable=False,
                                     pen=self.crosspen)
        self.graphicsView.addItem(self.vLine, ignoreBounds=True)
        self.graphicsView.addItem(self.hLine, ignoreBounds=True)

        # Create overlay ROIs
        x, y, w, h = 100, 100, 200, 200
        self.roi_box = pg.RectROI((x, y), (w, h), sideScalers=True)
        font = QtGui.QFont()
        font.setPixelSize(16)
        self.roi_box_w_text, self.roi_box_h_text = pg.TextItem(
            color='r'), pg.TextItem(color='r', angle=90)
        self.roi_box_w_text.setFont(font), self.roi_box_h_text.setFont(font)
        self.roi_box_w_text.setPos(x, y + h), self.roi_box_h_text.setPos(
            x, y + h)
        self.roi_list = [
            self.roi_box, self.roi_box_w_text, self.roi_box_h_text
        ]

        # Set up CameraWindow signals
        self.adjustLevelsButton.clicked.connect(self.adjust_levels)
        self.overlayCombo.currentTextChanged.connect(self.change_overlay)
        self.roi_box.sigRegionChangeFinished.connect(
            self.update_box_roi_labels)

        logger.info('Thread ID at Startup: ' +
                    str(int(QtCore.QThread.currentThreadId())))
        sb.value(), imageData1_imageData2PlotXMinSpinBox.value())


def imageData1_imageData2PlotXMinChanged(sb):
    imageData1_imageData2_pw.setXRange(
        imageData1_imageData2PlotXMaxSpinBox.value(), sb.value())


def sampleNumSpinBoxChanged(sb):
    global plot_sample_num
    plot_sample_num = sb.value()
    imageData1_imageData2RandomPlot()


# Interpret image data as row-major instead of col-major
pg.setConfigOptions(imageAxisOrder='row-major')

# メインウィンドウセット
app = QtGui.QApplication([])

win = QtGui.QMainWindow()
win.setWindowTitle('Combinatorial -image analysys')
cw = QtGui.QWidget()
layout = QtGui.QGridLayout()
cw.setLayout(layout)
win.setCentralWidget(cw)
win.show()
win.resize(1200, 700)

# データ読み込み、画像表示
vb = pg.ViewBox(invertY=True)
Exemple #42
0
def main():
    pyqtgraph.setConfigOptions(antialias=True)
    NdscanApplet().run()
Exemple #43
0
    def __init__(self, flags=QtCore.Qt.Window, parent=None):
        super(MainWindow, self).__init__(parent, flags=flags)

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

        self.setWindowTitle("Echo Data Processing")
        self.resize(1100, 600)

        # Массив с данными
        self.data = pd.DataFrame()
        self.data_filename = None

        self._central_widget = QtWidgets.QWidget(self, flags=QtCore.Qt.Widget)

        self._graph_tabs_widget = QtWidgets.QTabWidget(self)
        self._graph_tabs_widget.currentChanged.connect(self._on_tab_changed)

        self._main_layout = QtWidgets.QHBoxLayout()
        self._pyqtgraph_layout = QtWidgets.QVBoxLayout()

        # GraphLayoutWidget с двумя графиками: гистограмма лазера и эхо
        self._plot_area = pg.GraphicsLayoutWidget()
        self.laser_plot = self._plot_area.addPlot()
        self._plot_area.nextRow()
        self.echo_plot = self._plot_area.addPlot()

        # ComboBox для выбора графика
        self._graph_select = QtWidgets.QComboBox()
        self._graph_select.currentIndexChanged.connect(self._calc_curve_data)

        # ComboBox для выбора модели фита
        self._peak_model_select = QtWidgets.QComboBox()
        self._peak_model_select.addItems(PEAK_MODELS.keys())
        self._peak_model_select.addItem('Echo')

        # Область выделения
        self._select_region = pg.LinearRegionItem()
        self._select_region.setZValue(-10)
        self._select_region.sigRegionChanged.connect(self._calc_curve_data)

        # Область выделения для фита
        self._fit_region = pg.LinearRegionItem()
        self._fit_region.setZValue(-10)
        self._fit_region.sigRegionChanged.connect(self._update_statusbar)

        # Посчитана ли статистика фита
        self._fit_stats = False

        # Результирующие графики

        # График фита
        fitting_tab = QtWidgets.QWidget(self, flags=QtCore.Qt.Widget)
        # a figure instance to plot on
        self._fitting_figure = plt.figure()
        self._fitting_canvas = FigureCanvas(self._fitting_figure)
        self._ax = self._fitting_figure.add_subplot(111)
        # Кривые
        self.data_line, = self._ax.plot([], [], '.b', alpha=0.9)
        self.peak_fit_line, = self._ax.plot([], [], '-g', alpha=0.9)
        self.res_line, = self._ax.plot([], [], '.r', alpha=0.8)
        self.echo_fit_line, = self._ax.plot([], [], '-k', alpha=0.9)
        self.echo_fit_extended_line, = self._ax.plot([], [], '--k', alpha=0.6)

        # toolbar
        fitting_toolbar = NavigationToolbar(self._fitting_canvas, self)
        # fit parameters
        params_layout = QtWidgets.QGridLayout()

        # Echo params
        self.y0 = ParamWidget('y0')
        self.A = ParamWidget('A')
        self.t2 = ParamWidget('t2')
        # Initial guesses
        self.y0.value = 5000
        self.A.value = 500
        self.t2.value = 500

        # Peak params
        self.amp = ParamWidget('peak_amplitude', 'Amp')
        self.center = ParamWidget('peak_center', 'Cent')
        self.sigma = ParamWidget('peak_sigma', 'Sigma')
        self.c = ParamWidget('const_c', 'Const')
        # Initial guesses
        self.amp.value = 10000
        self.center.value = 0
        self.sigma.value = 5
        self.c.value = 5000

        # Fit residuals checkbox
        self._fit_res_checkbox = QtWidgets.QCheckBox("Fit residuals")

        params_layout.addWidget(self.amp, 0, 0)
        params_layout.addWidget(self.center, 1, 0)
        params_layout.addWidget(self.sigma, 2, 0)
        params_layout.addWidget(self.c, 3, 0)

        params_layout.addWidget(self.y0, 0, 1)
        params_layout.addWidget(self.A, 1, 1)
        params_layout.addWidget(self.t2, 2, 1)
        params_layout.addWidget(self._fit_res_checkbox, 3, 1)

        params_layout.setVerticalSpacing(0)

        fit_layout = QtWidgets.QVBoxLayout()
        fit_layout.addWidget(fitting_toolbar, 2)
        fit_layout.addWidget(self._fitting_canvas, 6)
        fit_layout.addLayout(params_layout, 1)
        fitting_tab.setLayout(fit_layout)

        self._graph_tabs_widget.addTab(fitting_tab, 'Фит')

        # График зависимости t2 от точки старта фита
        fitting_stats_tab = QtWidgets.QWidget(self, flags=QtCore.Qt.Widget)
        # a figure instance to plot on
        self._fitting_stats_figure = plt.figure()
        self._fitting_stats_canvas = FigureCanvas(self._fitting_stats_figure)
        fitting_stats_toolbar = NavigationToolbar(self._fitting_stats_canvas,
                                                  self)

        fit_stats_layout = QtWidgets.QVBoxLayout()
        fit_stats_layout.addWidget(fitting_stats_toolbar)
        fit_stats_layout.addWidget(self._fitting_stats_canvas)
        fitting_stats_tab.setLayout(fit_stats_layout)

        self._graph_tabs_widget.addTab(fitting_stats_tab, 'Зависимость фита')

        # Фит репорт
        fit_report_widget = QtWidgets.QWidget()
        report_layout = QtWidgets.QVBoxLayout()
        self.fit_report_text = QtWidgets.QTextEdit()
        save_report_btn = QtWidgets.QPushButton("Сохранить")
        save_report_btn.clicked.connect(self._on_save_report_btn_clicked)
        report_layout.addWidget(self.fit_report_text)
        report_layout.addWidget(save_report_btn)
        fit_report_widget.setLayout(report_layout)
        self._graph_tabs_widget.addTab(fit_report_widget, 'Отчет')

        # Бины для гистограммы лазера
        self._bins_widget = QtWidgets.QDoubleSpinBox()
        self._bins_widget.setMinimum(1)
        self._bins_widget.setMaximum(1000)
        self._bins_widget.setValue(200)
        self._bins_widget.valueChanged.connect(self._on_bins_value_changed)

        # Вертикальная линия для фита
        self._v_line = pg.InfiniteLine(angle=90, movable=True)
        self._v_line.sigPositionChangeFinished.connect(
            self._on_v_line_pos_changed)

        # Кпопка копирования в буфер
        self._copy_data_btn = QtWidgets.QPushButton("Copy")
        self._copy_data_btn.clicked.connect(self._on_copy_data_clicked)

        # Кнопка вычитания
        self._sub_btn = QtWidgets.QPushButton("Subtract")
        self._sub_btn.clicked.connect(self._on_sub_btn_clicked)
        self._sub_btn.setToolTip("Subtract peak function")

        # Кнопка фита
        self._fit_btn = QtWidgets.QPushButton("Fit")
        self._fit_btn.clicked.connect(self._on_fit_btn_clicked)
        self._fit_btn.setToolTip("Shift+Click to calc t2-start fit dependency")

        # Галочка логарифмического масштаба
        self._log_checkbox = QtWidgets.QCheckBox("Лог. масштаб")
        self._log_checkbox.stateChanged.connect(self._on_log_scale_changed)

        # Галочка "нормировать на лазер"
        self._div_laser_checkbox = QtWidgets.QCheckBox("Норм. на лазер")
        self._div_laser_checkbox.stateChanged.connect(self._div_laser_changed)

        # Layout для выбора графиков и бинов
        self._aux_layout = QtWidgets.QHBoxLayout()
        self._aux_layout.addWidget(self._bins_widget)
        self._aux_layout.addWidget(self._graph_select)
        self._aux_layout.addWidget(self._log_checkbox)
        self._aux_layout.addWidget(self._div_laser_checkbox)
        self._aux_layout.addStretch(5)
        self._aux_layout.addWidget(self._peak_model_select)
        self._aux_layout.addWidget(self._sub_btn)
        self._aux_layout.addWidget(self._fit_btn)
        self._aux_layout.addWidget(self._copy_data_btn)

        self._pyqtgraph_layout.addWidget(self._plot_area)
        self._pyqtgraph_layout.addLayout(self._aux_layout)

        # Установка лэйаутов
        self._splitter = QtWidgets.QSplitter(self)
        w = QtWidgets.QWidget()
        w.setLayout(self._pyqtgraph_layout)
        self._splitter.addWidget(w)
        self._splitter.addWidget(self._graph_tabs_widget)
        self.setCentralWidget(self._splitter)

        self._create_actions()
        self._create_menu()
        self._create_status_bar()
            self.data,  #The array to store read data into
            2000,  ## length of the data array
            PyDAQmx.byref(self.read),
            None)  ## total number of data points read per channel
        print(f"Acquired {self.read.value} points")
        self.analog_input.StopTask()
        print(self.data.shape)
        return self.data

    def graph_voltage(self):
        self.x = range(1000)
        self.voltage_plot = win.addPlot(title='Voltage')
        self.recording()
        self.curve0 = self.voltage_plot.plot(self.x, self.data[0])
        self.curve1 = self.voltage_plot.plot(self.x, self.data[1])

    def update_plot(self):
        self.recording()
        #        self.voltage_plot.enableAutoRange('xy', False)
        self.curve0.setData(self.x, self.data[0])
        self.curve1.setData(self.x, self.data[1])


if __name__ == "__main__":
    app = QtGui.QApplication([])
    win = pg.GraphicsWindow(title="Electrophysiology")
    pg.setConfigOptions(antialias=False)
    reading_voltage = ReadingVoltage()
    stimulating_voltage = StimVoltage()
    reading_voltage.graph_voltage()
    pg.QtGui.QApplication.instance().exec_()
Exemple #45
0
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
import sys
import info_processing
import classes_for_tree

if len(sys.argv) > 1:
    tree_file = sys.argv[1]

    title = tree_file
else:
    tree_file = None
    title = 'Tree'

app = QtGui.QApplication([])
pg.setConfigOptions(antialias=True)  # for prettier graphs
win = classes_for_tree.Window(title=title, tree_file=tree_file)

## Start Qt event loop unless running in interactive mode or using pyside.
'''
if __name__ == '__main__':
    import sys
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()

'''
app.exec_()
Exemple #46
0
import numpy as np
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
import pyqtgraph.opengl as gl
import orthos
import h5py

from orthos.widgets import *
from orthos.layers import *
from orthos.data_source import *

pg.setConfigOptions(antialias=False, useOpenGL=True)

app = QtGui.QApplication([])
mw = MainWindow()
mw.setWindowTitle('Orthos')
mw.show()
mw.resize(800, 600)

shape = (1000, 1000, 500)
data = numpy.random.rand(*shape) * 255.0
data = data.astype('uint8')

print "start"
opt = LayerViewerOptions()
opt.spatialDimensions = 3
opt.hasTimeAxis = False

viewerWidget = LayerViewerWidget(spatialShape=shape, options=opt)
mw.setCentralWidget(viewerWidget)
Exemple #47
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()
Exemple #48
0
    def __init__(self):
        super(ApplicationWindow, self).__init__()
        uic.loadUi('ui.ui', self)
        pg.setConfigOptions(antialias=True)

        self.plots = []
        self.datalines = []

        self.samples = [np.array([]), np.array([]), np.array([])]  # origin, test1, test2
        self.time = 0

        self.fft_samples = [0, 0, 0]
        self.freqs_ = 0

        self.gain_values = np.zeros(20).reshape((2, 10))

        self.pens = [pg.mkPen('r'), pg.mkPen('w'), pg.mkPen(
            'y'), pg.mkPen('g'), pg.mkPen('m'), pg.mkPen('w')]

        for i in range(3):
            plot1 = self.gView.addPlot(title="Time Domain")
            plot2 = self.gView.addPlot(title="Frequency Domain")
            self.gView.nextRow()
            self.plots.append(plot1)
            self.plots.append(plot2)

        for i in range(6):
            self.datalines.append(self.plots[i].plot(pen=self.pens[i]))

        self.linear_regions = []
        self.NUM_BANDS = 10
        self.line_position = 0
        # origin , test1, test2
        self.mediaPlayers = [QMediaPlayer(), QMediaPlayer(), QMediaPlayer()]

        self.timer = QtCore.QTimer()  # for regions on graph
        self.timer.setInterval(180)
        self.timer.timeout.connect(self.removeRegion)

        self.timer1 = QtCore.QTimer()  # for control the playing of audio
        self.timer1.setInterval(100)
        self.timer1.timeout.connect(self.update_postion)

        self.comb_box_current_index = [0,0]
        # UI
        self.freq_bands = [
            self.freq1, self.freq2, self.freq3, self.freq4, self.freq5,
            self.freq6, self.freq7, self.freq8, self.freq9, self.freq10
        ]
        self.gains = [
            self.gain1, self.gain2, self.gain3, self.gain4, self.gain5,
            self.gain6, self.gain7, self.gain8, self.gain9, self.gain10
        ]
        self.sliders = [
            self.slider1, self.slider2, self.slider3, self.slider4, self.slider5,
            self.slider6, self.slider7, self.slider8, self.slider9, self.slider10
        ]

        self.tests = [self.test1, self.test2]
        self.test_is_modified = [0, 0]

        self.playline = self.playGraph.plot()
        self.pen = pg.mkPen(color='r', width=3)
        self.playGraph.setYRange(min=-2, max=2)
        self.playGraph.showAxis('bottom', False)
        self.playGraph.plotItem.autoBtn = None
        self.playGraph.showAxis('left', False)

        self.min_gain = -30  # dB
        self.max_gain = 30  # dB
        self.disable_some_uis()

        # connections

        self.add_file_btn.clicked.connect(self.add_file)
        self.play_btn.clicked.connect(self.play_audio)
        self.pause_btn.clicked.connect(self.pause_audio)
        self.orgin_radio.clicked.connect(self.stop_play)
        self.test_radio.clicked.connect(self.stop_play)
        self.show_dif_btn.clicked.connect(self.show_popup)
        self.pushButton.clicked.connect(self.show_popup2)
        self.save_btn.clicked.connect(self.save)
        self.reset_btn.clicked.connect(self.reset_sliders)
        self.actionNew_Window.triggered.connect(lambda: self.new_win())

        for i in range(2):
            self.connect_tests(i)
        for i in range(self.NUM_BANDS):
            self.connect_sliders(i)

        self.is_playing = False
Exemple #49
0
    def __init__(self, moviefile=None, savedir=None):
        super(MainW, self).__init__()
        icon_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                 "mouse.png")
        app_icon = QtGui.QIcon()
        app_icon.addFile(icon_path, QtCore.QSize(16, 16))
        app_icon.addFile(icon_path, QtCore.QSize(24, 24))
        app_icon.addFile(icon_path, QtCore.QSize(32, 32))
        app_icon.addFile(icon_path, QtCore.QSize(48, 48))
        app_icon.addFile(icon_path, QtCore.QSize(96, 96))
        app_icon.addFile(icon_path, QtCore.QSize(256, 256))
        self.setWindowIcon(app_icon)

        pg.setConfigOptions(imageAxisOrder='row-major')
        self.setGeometry(15, 15, 1470, 1000)
        self.setWindowTitle('FaceMap')
        self.setStyleSheet("QMainWindow {background: 'black';}")
        self.styleUnpressed = ("QPushButton {Text-align: left; "
                               "background-color: rgb(50,50,50); "
                               "color:white;}")
        self.stylePressed = ("QPushButton {Text-align: left; "
                             "background-color: rgb(100,50,100); "
                             "color:white;}")
        self.styleInactive = ("QPushButton {Text-align: left; "
                              "background-color: rgb(50,50,50); "
                              "color:gray;}")

        try:
            # try to load user settings
            opsfile = os.path.join(os.path.abspath(os.path.dirname(__file__)),
                                   'ops_user.npy')
            self.ops = np.load(opsfile, allow_pickle=True).item()
        except:
            self.ops = {
                'sbin': 4,
                'pupil_sigma': 2.,
                'fullSVD': False,
                'save_path': '',
                'save_mat': False
            }

        self.save_path = self.ops['save_path']

        self.cwidget = QtGui.QWidget(self)
        self.setCentralWidget(self.cwidget)
        self.l0 = QtGui.QGridLayout()
        #layout = QtGui.QFormLayout()
        self.cwidget.setLayout(self.l0)
        #self.p0 = pg.ViewBox(lockAspect=False,name='plot1',border=[100,100,100],invertY=True)
        self.win = pg.GraphicsLayoutWidget()
        # --- cells image
        self.win = pg.GraphicsLayoutWidget()
        self.win.move(600, 0)
        self.win.resize(1000, 500)
        self.l0.addWidget(self.win, 1, 3, 37, 15)
        layout = self.win.ci.layout

        # A plot area (ViewBox + axes) for displaying the image
        self.p0 = self.win.addViewBox(lockAspect=True,
                                      row=0,
                                      col=0,
                                      invertY=True)
        #self.p0.setMouseEnabled(x=False,y=False)
        self.p0.setMenuEnabled(False)
        self.pimg = pg.ImageItem()
        self.p0.addItem(self.pimg)

        # image ROI
        self.pROI = self.win.addViewBox(lockAspect=True,
                                        row=0,
                                        col=1,
                                        invertY=True)
        #self.p0.setMouseEnabled(x=False,y=False)
        self.pROI.setMenuEnabled(False)
        self.pROIimg = pg.ImageItem()
        self.pROI.addItem(self.pROIimg)
        self.scatter = pg.ScatterPlotItem([0], [0], pen='k', symbol='+')
        self.pROI.addItem(self.scatter)

        # roi initializations
        self.iROI = 0
        self.nROIs = 0
        self.saturation = []
        self.ROIs = []

        # saturation sliders
        self.sl = []
        txt = ["saturation", 'saturation']
        self.sat = [255, 255]
        for j in range(2):
            self.sl.append(Slider(j, self))
            self.l0.addWidget(self.sl[j], 1, 6 + 5 * j, 1, 2)
            qlabel = QtGui.QLabel(txt[j])
            qlabel.setStyleSheet('color: white;')
            self.l0.addWidget(qlabel, 0, 6 + 5 * j, 1, 1)

        self.reflector = QtGui.QPushButton('add corneal reflection')
        self.l0.addWidget(self.reflector, 1, 8 + 5 * j, 1, 2)
        self.reflector.setEnabled(False)
        self.reflector.clicked.connect(self.add_reflectROI)
        self.rROI = []
        self.reflectors = []

        self.p1 = self.win.addPlot(name='plot1',
                                   row=1,
                                   col=0,
                                   colspan=2,
                                   title='p1')
        self.p1.setMouseEnabled(x=True, y=False)
        self.p1.setMenuEnabled(False)
        self.p1.hideAxis('left')
        self.scatter1 = pg.ScatterPlotItem()
        self.p1.addItem(self.scatter1)
        #self.p1.setLabel('bottom', 'plot1')
        #self.p1.autoRange(padding=0.01)
        self.p2 = self.win.addPlot(name='plot2',
                                   row=2,
                                   col=0,
                                   colspan=2,
                                   title='p2')
        self.p2.setMouseEnabled(x=True, y=False)
        self.p2.setMenuEnabled(False)
        self.p2.hideAxis('left')
        self.scatter2 = pg.ScatterPlotItem()
        self.p2.addItem(self.scatter1)
        #self.p2.setLabel('bottom', 'plot2')
        self.p2.setXLink("plot1")
        #self.p2.autoRange(padding=0.01)
        self.win.ci.layout.setRowStretchFactor(0, 5)
        self.movieLabel = QtGui.QLabel("No movie chosen")
        self.movieLabel.setStyleSheet("color: white;")
        self.movieLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.nframes = 0
        self.cframe = 0
        # create ROI chooser
        #qlabel = QtGui.QLabel(self)
        #qlabel.setText("<font color='white'>Selected ROI:</font>")
        #self.l0.addWidget(qlabel,3,0,1,2)
        # create frame slider
        binLabel = QtGui.QLabel("SVD spatial bin:")
        binLabel.setStyleSheet("color: gray;")
        self.binSpinBox = QtGui.QSpinBox()
        self.binSpinBox.setRange(1, 20)
        self.binSpinBox.setValue(self.ops['sbin'])
        self.binSpinBox.setFixedWidth(50)
        self.l0.addWidget(binLabel, 7, 0, 1, 3)
        self.l0.addWidget(self.binSpinBox, 8, 0, 1, 3)
        binLabel = QtGui.QLabel("pupil sigma:")
        binLabel.setStyleSheet("color: gray;")
        self.sigmaBox = QtGui.QLineEdit()
        self.sigmaBox.setText(str(self.ops['pupil_sigma']))
        self.sigmaBox.setFixedWidth(45)
        self.l0.addWidget(binLabel, 9, 0, 1, 3)
        self.l0.addWidget(self.sigmaBox, 10, 0, 1, 3)
        self.pupil_sigma = float(self.sigmaBox.text())
        self.sigmaBox.returnPressed.connect(self.pupil_sigma_change)
        self.frameLabel = QtGui.QLabel("Current frame:")
        self.frameLabel.setStyleSheet("color: white;")
        self.frameNumber = QtGui.QLabel("0")
        self.frameNumber.setStyleSheet("color: white;")
        self.frameSlider = QtGui.QSlider(QtCore.Qt.Horizontal)
        #self.frameSlider.setTickPosition(QtGui.QSlider.TicksBelow)
        self.frameSlider.setTickInterval(5)
        self.frameSlider.setTracking(False)
        self.frameDelta = 10
        istretch = 23
        iplay = istretch + 15
        iconSize = QtCore.QSize(20, 20)
        openButton = QtGui.QToolButton()
        openButton.setIcon(self.style().standardIcon(QtGui.QStyle.SP_FileIcon))
        openButton.setIconSize(iconSize)
        openButton.setToolTip("Open single movie file")
        openButton.clicked.connect(self.open_file)

        openButton2 = QtGui.QToolButton()
        openButton2.setIcon(self.style().standardIcon(
            QtGui.QStyle.SP_DialogOpenButton))
        openButton2.setIconSize(iconSize)
        openButton2.setToolTip("Open movie folder")
        openButton2.clicked.connect(self.open_folder)

        openButton3 = QtGui.QToolButton()
        openButton3.setIcon(self.style().standardIcon(
            QtGui.QStyle.SP_FileDialogStart))
        openButton3.setIconSize(iconSize)
        openButton3.setToolTip("Open processed file")
        openButton3.clicked.connect(self.open_proc)

        self.process = QtGui.QPushButton('process ROIs')
        self.process.setFont(QtGui.QFont("Arial", 8, QtGui.QFont.Bold))
        self.process.clicked.connect(self.process_ROIs)
        self.process.setEnabled(False)

        self.savefolder = QtGui.QPushButton("save folder \u2b07")
        self.savefolder.setFont(QtGui.QFont("Arial", 8, QtGui.QFont.Bold))
        self.savefolder.clicked.connect(self.save_folder)
        self.savefolder.setEnabled(False)
        if len(self.save_path) > 0:
            self.savelabel = QtGui.QLabel(self.save_path)
        else:
            self.savelabel = QtGui.QLabel('same as video')
        self.savelabel.setStyleSheet("color: white;")

        self.saverois = QtGui.QPushButton('save ROIs')
        self.saverois.setFont(QtGui.QFont("Arial", 8, QtGui.QFont.Bold))
        self.saverois.clicked.connect(self.save_ROIs)
        self.saverois.setEnabled(False)

        self.batchlist = []
        self.batchname = []
        for k in range(6):
            self.batchname.append(QtGui.QLabel(''))
            self.batchname[-1].setStyleSheet("color: white;")
            self.l0.addWidget(self.batchname[-1], 18 + k, 0, 1, 4)

        self.processbatch = QtGui.QPushButton(u"process batch \u2b07")
        self.processbatch.setFont(QtGui.QFont("Arial", 8, QtGui.QFont.Bold))
        self.processbatch.clicked.connect(self.process_batch)
        self.processbatch.setEnabled(False)

        iconSize = QtCore.QSize(30, 30)
        self.playButton = QtGui.QToolButton()
        self.playButton.setIcon(self.style().standardIcon(
            QtGui.QStyle.SP_MediaPlay))
        self.playButton.setIconSize(iconSize)
        self.playButton.setToolTip("Play")
        self.playButton.setCheckable(True)
        self.playButton.clicked.connect(self.start)

        self.pauseButton = QtGui.QToolButton()
        self.pauseButton.setCheckable(True)
        self.pauseButton.setIcon(self.style().standardIcon(
            QtGui.QStyle.SP_MediaPause))
        self.pauseButton.setIconSize(iconSize)
        self.pauseButton.setToolTip("Pause")
        self.pauseButton.clicked.connect(self.pause)

        btns = QtGui.QButtonGroup(self)
        btns.addButton(self.playButton, 0)
        btns.addButton(self.pauseButton, 1)
        btns.setExclusive(True)

        quitButton = QtGui.QToolButton()
        quitButton.setIcon(self.style().standardIcon(
            QtGui.QStyle.SP_DialogCloseButton))
        quitButton.setIconSize(iconSize)
        quitButton.setToolTip("Quit")
        quitButton.clicked.connect(self.close)

        self.comboBox = QtGui.QComboBox(self)
        self.comboBox.setFixedWidth(100)
        self.comboBox.addItem("ROI type")
        self.comboBox.addItem("pupil")
        self.comboBox.addItem("motion SVD")
        self.comboBox.addItem("blink")
        self.comboBox.addItem("running")
        self.newROI = 0
        self.comboBox.setCurrentIndex(0)
        #self.comboBox.currentIndexChanged.connect(self.mode_change)

        self.addROI = QtGui.QPushButton("add ROI")
        self.addROI.setFont(QtGui.QFont("Arial", 8, QtGui.QFont.Bold))
        self.addROI.clicked.connect(self.add_ROI)
        self.addROI.setEnabled(False)

        self.checkBox = QtGui.QCheckBox("Compute multivideo SVD")
        self.checkBox.setStyleSheet("color: gray;")
        if self.ops['fullSVD']:
            self.checkBox.toggle()

        self.save_mat = QtGui.QCheckBox("Save *.mat file")
        self.save_mat.setStyleSheet("color: gray;")
        if self.ops['save_mat']:
            self.save_mat.toggle()

        self.l0.addWidget(openButton, 1, 0, 1, 1)
        self.l0.addWidget(openButton2, 1, 1, 1, 1)
        self.l0.addWidget(openButton3, 1, 2, 1, 1)
        self.l0.addWidget(self.comboBox, 2, 0, 1, 3)
        self.l0.addWidget(self.addROI, 3, 0, 1, 3)
        self.l0.addWidget(self.checkBox, 11, 0, 1, 4)
        self.l0.addWidget(self.save_mat, 12, 0, 1, 3)
        self.l0.addWidget(self.savefolder, 13, 0, 1, 3)
        self.l0.addWidget(self.savelabel, 14, 0, 1, 4)
        self.l0.addWidget(self.saverois, 15, 0, 1, 3)
        self.l0.addWidget(self.process, 16, 0, 1, 3)
        self.l0.addWidget(self.processbatch, 17, 0, 1, 3)
        self.l0.addWidget(self.playButton, iplay, 0, 1, 1)
        self.l0.addWidget(self.pauseButton, iplay, 1, 1, 1)
        #self.l0.addWidget(quitButton,0,1,1,1)
        self.playButton.setEnabled(False)
        self.pauseButton.setEnabled(False)
        self.pauseButton.setChecked(True)

        self.l0.addWidget(QtGui.QLabel(''), istretch, 0, 1, 3)
        self.l0.setRowStretch(istretch, 1)
        self.l0.addWidget(self.frameLabel, istretch + 13, 0, 1, 3)
        self.l0.addWidget(self.frameNumber, istretch + 14, 0, 1, 3)
        self.l0.addWidget(self.frameSlider, istretch + 15, 3, 1, 15)

        # plotting boxes
        pl = QtGui.QLabel("after processing")
        pl.setStyleSheet("color: gray;")
        self.l0.addWidget(pl, istretch + 1, 0, 1, 3)
        pl = QtGui.QLabel("p1")
        pl.setStyleSheet("color: gray;")
        self.l0.addWidget(pl, istretch + 2, 0, 1, 1)
        pl = QtGui.QLabel("p2")
        pl.setStyleSheet("color: gray;")
        self.l0.addWidget(pl, istretch + 2, 1, 1, 1)
        pl = QtGui.QLabel("roi")
        pl.setStyleSheet("color: gray;")
        self.l0.addWidget(pl, istretch + 2, 2, 1, 1)
        self.cbs1 = []
        self.cbs2 = []
        self.lbls = []
        for k in range(8):
            self.cbs1.append(QtGui.QCheckBox(''))
            self.l0.addWidget(self.cbs1[-1], istretch + 3 + k, 0, 1, 1)
            self.cbs2.append(QtGui.QCheckBox(''))
            self.l0.addWidget(self.cbs2[-1], istretch + 3 + k, 1, 1, 1)
            self.cbs1[-1].toggled.connect(self.plot_processed)
            self.cbs2[-1].toggled.connect(self.plot_processed)
            self.cbs1[-1].setEnabled(False)
            self.cbs2[-1].setEnabled(False)
            self.lbls.append(QtGui.QLabel(''))
            self.lbls[-1].setStyleSheet("color: white;")
            self.l0.addWidget(self.lbls[-1], istretch + 3 + k, 2, 1, 1)

        #self.l0.addWidget(QtGui.QLabel(''),17,2,1,1)
        #self.l0.setRowStretch(16,2)
        ll = QtGui.QLabel('play/pause [SPACE]')
        ll.setStyleSheet("color: gray;")
        self.l0.addWidget(ll, istretch + 3 + k + 1, 0, 1, 4)
        #ll = QtGui.QLabel('(when paused, left/right arrow keys can move slider)')
        #ll.setStyleSheet("color: white;")
        #self.l0.addWidget(ll,14,0,1,4)
        self.frameSlider.valueChanged.connect(self.go_to_frame)
        self.l0.addWidget(self.movieLabel, 0, 0, 1, 5)
        self.updateFrameSlider()
        #self.updateButtons()
        self.updateTimer = QtCore.QTimer()
        self.updateTimer.timeout.connect(self.next_frame)
        self.cframe = 0
        self.loaded = False
        self.Floaded = False
        self.wraw = False
        self.win.scene().sigMouseClicked.connect(self.plot_clicked)
        self.win.show()
        self.show()
        self.processed = False
        if moviefile is not None:
            self.load_movies([[moviefile]])
        if savedir is not None:
            self.save_path = savedir
            self.savelabel.setText(savedir)
Exemple #50
0
def _start():
    '''Start the module
    This uses the global variables from setup and adds a set of global variables
    '''
    global parser, args, config, r, response, patch, monitor, ft_host, ft_port, ft_input, name
    global timeout, hdr_input, start, channels, window, clipsize, stepsize, historysize, lrate, scale_red, scale_blue, offset_red, offset_blue, winx, winy, winwidth, winheight, prefix, numhistory, freqaxis, history, showred, showblue, filtorder, filter, freqrange, notch, app, win, text_redleft_curr, text_redright_curr, text_blueleft_curr, text_blueright_curr, text_redleft_hist, text_redright_hist, text_blueleft_hist, text_blueright_hist, freqplot_curr, freqplot_hist, spect_curr, spect_hist, redleft_curr, redright_curr, blueleft_curr, blueright_curr, redleft_hist, redright_hist, blueleft_hist, blueright_hist, fft_curr, fft_hist, specmax_curr, specmin_curr, specmax_hist, specmin_hist, plotnr, channr, timer, begsample, endsample, taper

    # this is the timeout for the FieldTrip buffer
    timeout = patch.getfloat('fieldtrip', 'timeout', default=30)

    hdr_input = None
    start = time.time()
    while hdr_input is None:
        monitor.info("Waiting for data to arrive...")
        if (time.time() - start) > timeout:
            raise RuntimeError("timeout while waiting for data")
        time.sleep(0.1)
        hdr_input = ft_input.getHeader()

    monitor.info("Data arrived")
    monitor.debug(hdr_input)
    monitor.debug(hdr_input.labels)

    # read variables from ini/redis
    channels = patch.getint('arguments', 'channels', multiple=True)
    window = patch.getfloat('arguments', 'window', default=5.0)  # in seconds
    clipsize = patch.getfloat('arguments', 'clipsize',
                              default=0.0)  # in seconds
    stepsize = patch.getfloat('arguments', 'stepsize',
                              default=0.1)  # in seconds
    historysize = patch.getfloat('arguments', 'historysize',
                                 default=10)  # in seconds
    lrate = patch.getfloat('arguments', 'learning_rate', default=0.2)
    scale_red = patch.getfloat('scale', 'red')
    scale_blue = patch.getfloat('scale', 'blue')
    offset_red = patch.getfloat('offset', 'red')
    offset_blue = patch.getfloat('offset', 'blue')
    winx = patch.getfloat('display', 'xpos')
    winy = patch.getfloat('display', 'ypos')
    winwidth = patch.getfloat('display', 'width')
    winheight = patch.getfloat('display', 'height')
    prefix = patch.getstring('output', 'prefix')

    window = int(round(window * hdr_input.fSample))  # in samples
    clipsize = int(round(clipsize * hdr_input.fSample))  # in samples
    numhistory = int(historysize /
                     stepsize)  # number of observations in the history
    freqaxis = fftfreq((window - 2 * clipsize), 1. / hdr_input.fSample)
    history = np.zeros((len(channels), freqaxis.shape[0], numhistory))

    # this is used to taper the data prior to Fourier transforming
    taper = np.hanning(window)

    # ideally it should be possible to change these on the fly
    showred = patch.getint('input', 'showred', default=1)
    showblue = patch.getint('input', 'showblue', default=1)

    # lowpass, highpass and bandpass are optional, but mutually exclusive
    filtorder = 9
    if patch.hasitem('arguments', 'bandpass'):
        filter = patch.getfloat('arguments', 'bandpass', multiple=True)
    elif patch.hasitem('arguments', 'lowpass'):
        filter = patch.getfloat('arguments', 'lowpass')
        filter = [np.nan, filter]
    elif patch.hasitem('arguments', 'highpass'):
        filter = patch.getfloat('arguments', 'highpass')
        filter = [filter, np.nan]
    else:
        filter = [np.nan, np.nan]

    # notch filtering is optional
    notch = patch.getfloat('arguments', 'notch', default=np.nan)

    # wait until there is enough data
    begsample = -1
    while begsample < 0:
        time.sleep(0.1)
        hdr_input = ft_input.getHeader()
        if hdr_input != None:
            begsample = hdr_input.nSamples - window
            endsample = hdr_input.nSamples - 1

    # initialize graphical window
    app = QtGui.QApplication(sys.argv)
    win = pg.GraphicsWindow(title="EEGsynth plotspectral")
    win.setWindowTitle('EEGsynth plotspectral')
    win.setGeometry(winx, winy, winwidth, winheight)

    # initialize graphical elements
    text_redleft_curr = pg.TextItem("", anchor=(1, 0), color='r')
    text_redright_curr = pg.TextItem("", anchor=(0, 0), color='r')
    text_blueleft_curr = pg.TextItem("", anchor=(1, -1), color='b')
    text_blueright_curr = pg.TextItem("", anchor=(0, -1), color='b')
    text_redleft_hist = pg.TextItem("", anchor=(1, 0), color='r')
    text_redright_hist = pg.TextItem("", anchor=(0, 0), color='r')
    text_blueleft_hist = pg.TextItem("", anchor=(1, -1), color='b')
    text_blueright_hist = pg.TextItem("", anchor=(0, -1), color='b')

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

    # Initialize variables
    freqplot_curr = []
    freqplot_hist = []
    spect_curr = []
    spect_hist = []
    redleft_curr = []
    redright_curr = []
    blueleft_curr = []
    blueright_curr = []
    redleft_hist = []
    redright_hist = []
    blueleft_hist = []
    blueright_hist = []
    fft_curr = []
    fft_hist = []
    specmax_curr = []
    specmin_curr = []
    specmax_hist = []
    specmin_hist = []

    # Create panels for each channel
    for plotnr, channr in enumerate(channels):

        plot = win.addPlot(title="%s%s" % ('Spectrum channel ', channr))
        # speeds up the initial axis scaling set the range to something different than [0, 0]
        plot.setXRange(0, 1)
        plot.setYRange(0, 1)

        freqplot_curr.append(plot)
        freqplot_curr[plotnr].setLabel('left', text='Power')
        freqplot_curr[plotnr].setLabel('bottom', text='Frequency (Hz)')

        spect_curr.append(freqplot_curr[plotnr].plot(pen='w'))
        redleft_curr.append(freqplot_curr[plotnr].plot(pen='r'))
        redright_curr.append(freqplot_curr[plotnr].plot(pen='r'))
        blueleft_curr.append(freqplot_curr[plotnr].plot(pen='b'))
        blueright_curr.append(freqplot_curr[plotnr].plot(pen='b'))

        plot = win.addPlot(
            title="%s%s%s%s%s" %
            ('Averaged spectrum channel ', channr, ' (', historysize, 's)'))
        # speeds up the initial axis scaling set the range to something different than [0, 0]
        plot.setXRange(0, 1)
        plot.setYRange(0, 1)

        freqplot_hist.append(plot)
        freqplot_hist[plotnr].setLabel('left', text='Power')
        freqplot_hist[plotnr].setLabel('bottom', text='Frequency (Hz)')

        spect_hist.append(freqplot_hist[plotnr].plot(pen='w'))
        redleft_hist.append(freqplot_hist[plotnr].plot(pen='r'))
        redright_hist.append(freqplot_hist[plotnr].plot(pen='r'))
        blueleft_hist.append(freqplot_hist[plotnr].plot(pen='b'))
        blueright_hist.append(freqplot_hist[plotnr].plot(pen='b'))
        win.nextRow()

        # initialize as lists
        specmin_curr.append(None)
        specmax_curr.append(None)
        specmin_hist.append(None)
        specmax_hist.append(None)
        fft_curr.append(None)
        fft_hist.append(None)

    # print frequency at lines
    freqplot_curr[0].addItem(text_redleft_curr)
    freqplot_curr[0].addItem(text_redright_curr)
    freqplot_curr[0].addItem(text_blueleft_curr)
    freqplot_curr[0].addItem(text_blueright_curr)
    freqplot_hist[0].addItem(text_redleft_hist)
    freqplot_hist[0].addItem(text_redright_hist)
    freqplot_hist[0].addItem(text_blueleft_hist)
    freqplot_hist[0].addItem(text_blueright_hist)

    signal.signal(signal.SIGINT, _stop)

    # Set timer for update
    timer = QtCore.QTimer()
    timer.timeout.connect(_loop_once)
    timer.setInterval(10)  # timeout in milliseconds
    timer.start(int(round(stepsize * 1000)))  # in milliseconds
Exemple #51
0
import sys
from PyQt5 import QtCore, QtGui, QtWidgets  # Qt5三大模块 为了方便同学看清楚模块来源 使用完整导入的写法
import pyqtgraph as pg  # 一个基于Qt实现的python第三方绘图库 用于绘制立绘身后的力场
import numpy as np  # 一个经典老牌的python科学计算库
import pyaudio  # python音频库 可以进行录音 播放等功能 用于读取话筒音量
import audioop  # 一个高性能的音频计算库
pg.setConfigOptions(antialias=True,
                    background='#00000000')  # pyqtgraph设置抗锯齿+背景透明


class DetectSound(QtCore.QThread):  # 创建QThread类来实时获取麦克风说话音量
    volume = QtCore.pyqtSignal(list)  # 初始化pyqtSignal类属性 发射类型为list

    def __init__(self):  # 构造函数
        super(DetectSound, self).__init__()  # 继承QThread

    def run(self):  # QThread内建的run函数 所有耗时长的操作都写在这里面 防止卡死界面
        p = pyaudio.PyAudio()  # 初始化PyAudio实例
        stream = p.open(format=pyaudio.paInt16,
                        channels=1,
                        rate=44100,
                        input=True)  # 打开音频流对象 读取话筒输入缓冲区
        volume = []  # 用于存放响度值的列表
        while 1:  # 无限循环读取话筒音频流 必须在run()里面实现 否则UI界面会卡死
            data = stream.read(3)  # 每次读取3个采样点
            volume.append(audioop.rms(data, 2)**0.8 / 4000 +
                          1)  # 使用audioop.rms计算音量响度 然后通过开方和除法缩小数值
            if len(volume) == 180:  # 当列表长度到达180个时
                self.volume.emit(volume)  # 用pyqtSignal将响度列表发射给主窗口线程
                volume = []  # 清空列表 重新采样
Exemple #52
0
    def __init__(self):

        # pyqtgraph stuff
        pg.setConfigOptions(antialias=True)
        self.traces = dict()
        self.app = QtGui.QApplication(sys.argv)
        self.win = pg.GraphicsWindow(title='Spectrum Analyzer')
        self.win.setWindowTitle('Spectrum Analyzer')
        self.win.setGeometry(5, 115, 1910, 1070)

        wf_xlabels = [(0, '0'), (2048, '2048'), (4096, '4096')]
        wf_xaxis = pg.AxisItem(orientation='bottom')
        wf_xaxis.setTicks([wf_xlabels])

        wf_ylabels = [(0, '0'), (127, '128'), (255, '255')]
        wf_yaxis = pg.AxisItem(orientation='left')
        wf_yaxis.setTicks([wf_ylabels])

        sp_xlabels = [(np.log10(10), '10'), (np.log10(100), '100'),
                      (np.log10(1000), '1000'), (np.log10(22050), '22050')]
        sp_xaxis = pg.AxisItem(orientation='bottom')
        sp_xaxis.setTicks([sp_xlabels])

        self.waveform = self.win.addPlot(
            title='WAVEFORM',
            row=1,
            col=1,
            axisItems={
                'bottom': wf_xaxis,
                'left': wf_yaxis
            },
        )
        self.spectrum = self.win.addPlot(
            title='SPECTRUM',
            row=2,
            col=1,
            axisItems={'bottom': sp_xaxis},
        )

        # pyaudio stuff
        #self.FORMAT = pyaudio.paInt16
        #self.CHANNELS = 1
        #self.RATE = 44100
        #self.CHUNK = 1024 * 2
        self.channels = [0]
        self.channel_mask = chan_list_to_mask(self.channels)
        self.sample_size = 1000
        self.rate = 10000
        self.options = OptionFlags.DEFAULT

        self.request = self.sample_size
        self.timeout = 11

        #self.p = pyaudio.PyAudio()
        #self.stream = self.p.open(
        #    format=self.FORMAT,
        #    channels=self.CHANNELS,
        #    rate=self.RATE,
        #    input=True,
        #    output=True,
        #    frames_per_buffer=self.CHUNK,
        #)
        # waveform and spectrum x points
        self.address = select_hat_device(HatIDs.MCC_118)
        self.hat = mcc118(self.address)

        #self.x = np.arange(0, 2 * self.CHUNK, 2)
        #self.f = np.linspace(0, self.RATE / 2, self.CHUNK / 2)
        self.x = np.arange(0, self.sample_size)
        self.f = np.linspace(0, self.rate, self.sample_size)
Exemple #53
0
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        # 在初始化之前设置pg,因为初始化会写死配置,无法在更改
        # pg.setConfigOption('foreground', 'd')
        # 使曲线看起来光滑
        pg.setConfigOptions(antialias=True)
        # 设置文字的字体
        font = QFont()
        font.setFamily("Microsoft Yahei")
        font.setPointSize(11)

        self.setMinimumHeight(750)
        self.setMinimumWidth(1000)
        # self.setFixedSize(1000, 750)

        # 统一设置按钮的字体
        btn_list = []

        # 设置题目和状态栏
        self.setWindowTitle("心电平台检测")

        # 设置状态栏
        self.status = self.statusBar()
        self.status.showMessage("检测~")

        # 整体布局
        pagelayout = QVBoxLayout()

        # 顶层按钮布局
        top = QFrame(self)
        top.setFrameShape(QFrame.StyledPanel)
        btn_layout = QHBoxLayout(top)
        self.data_com = QComboBox()
        delegate = QStyledItemDelegate()
        self.data_com.setItemDelegate(delegate)
        self.data_com.addItem("选择心电数据")
        self.data_com.setFixedSize(200, 40)
        self.data_com.setFont(font)
        set_btn = QPushButton("设置")
        help_btn = QPushButton("帮助")
        save_btn = QPushButton("存储")
        back_btn = QPushButton("回放")
        fig_btn = QPushButton("截图")
        patient_table_btn = QPushButton("病例表")
        self.stop_btn = QPushButton("暂停")
        btn_list.append(set_btn)
        btn_list.append(help_btn)
        btn_list.append(save_btn)
        btn_list.append(back_btn)
        btn_list.append(self.stop_btn)
        btn_list.append(fig_btn)
        btn_list.append(patient_table_btn)
        btn_layout.addWidget(self.data_com)
        btn_layout.addWidget(set_btn)
        btn_layout.addWidget(help_btn)
        btn_layout.addWidget(save_btn)
        btn_layout.addWidget(self.stop_btn)
        btn_layout.addWidget(back_btn)
        btn_layout.addWidget(fig_btn)
        btn_layout.addWidget(patient_table_btn)

        for btn in btn_list:
            btn.setFont(font)
            btn.setFixedSize(100, 40)

        # 以此统计病人数量
        self.patient = 0
        for i in range(0, 10):
            self.patient += 1
            self.data_com.addItem(str(100 + i))

        # 底层布局
        bottom = QFrame(self)
        bottom.setFrameShape(QFrame.StyledPanel)
        self.bottom_layout = QStackedLayout(bottom)

        # 1. 绘图区域
        plot_widget = QWidget(bottom)
        plot_layout = QHBoxLayout()
        win = pg.GraphicsLayoutWidget()
        self.p = win.addPlot()
        self.p.getAxis("bottom").tickFont = font
        self.p.getAxis("left").tickFont = font
        # 背景透明
        win.setBackground(background=None)
        plot_layout.addWidget(win)
        plot_widget.setLayout(plot_layout)
        self.bottom_layout.addWidget(plot_widget)

        # 2. 帮助文档
        help_widget = QWidget(bottom)
        help_layout = QHBoxLayout()
        self.help_text = QTextEdit()
        self.help_text.setReadOnly(True)
        help_layout.addWidget(self.help_text)
        help_widget.setLayout(help_layout)
        self.bottom_layout.addWidget(help_widget)
        help_btn.clicked.connect(self.show_help)

        # 3. 设置
        set_widget = QWidget(bottom)
        set_layout = QVBoxLayout()
        theme_layout = QHBoxLayout()
        self.theme_white_radio = QRadioButton("白色主题")
        self.theme_white_radio.setFixedWidth(120)
        self.theme_black_radio = QRadioButton("黑色主题")
        theme_label = QLabel("主题颜色选择")
        theme_label.setFixedWidth(120)
        theme_layout.addWidget(theme_label)
        theme_layout.addWidget(self.theme_white_radio)
        theme_layout.addWidget(self.theme_black_radio)
        line_width_layout = QHBoxLayout()
        line_width = QLabel("设置线宽(范围1-4)")
        line_width.setFixedWidth(150)
        line_width_layout.addWidget(line_width)
        self.line_width_spin = QSpinBox()
        self.line_width_spin.setMinimum(1)
        self.line_width_spin.setMaximum(4)
        line_width_layout.addWidget(self.line_width_spin)
        set_layout.addLayout(theme_layout)
        set_layout.addLayout(line_width_layout)
        set_widget.setLayout(set_layout)
        self.bottom_layout.addWidget(set_widget)
        self.theme_white_radio.toggled.connect(self.change_status)
        self.theme_black_radio.toggled.connect(self.change_status)
        set_btn.clicked.connect(self.set_)

        # 暂停与启动的切换
        self.stop_btn.clicked.connect(self.stop_)

        # 截图功能
        fig_btn.clicked.connect(self.save_fig)

        # 回放功能
        back_btn.clicked.connect(self.back_show)

        # 保存数据功能
        save_widget = QWidget(bottom)
        save_layout = QHBoxLayout()
        save_label = QLabel("请选择保存数据的区间")
        save_label.setFixedHeight(40)
        self.left_interval = QLineEdit()
        self.left_interval.setFixedHeight(40)
        self.left_interval.setPlaceholderText("起始点,左区间")
        self.right_interval = QLineEdit()
        self.right_interval.setFixedHeight(40)
        self.right_interval.setPlaceholderText("终止点,右区间")
        save_confirm_btn = QPushButton("确认")
        save_confirm_btn.setFixedHeight(40)
        save_layout.addWidget(save_label)
        save_layout.addWidget(self.left_interval)
        save_layout.addWidget(self.right_interval)
        save_layout.addWidget(save_confirm_btn)
        save_widget.setLayout(save_layout)
        save_btn.clicked.connect(self.save_widget_)
        save_confirm_btn.clicked.connect(self.save_data)
        self.bottom_layout.addWidget(save_widget)

        # 病例表的填写
        table_widget = QWidget(bottom)
        table_layout = QHBoxLayout()
        self.patient_table = QTableWidget()
        self.patient_table.setColumnCount(9)
        self.patient_table.setRowCount(self.patient)
        self.patient_table.setHorizontalHeaderLabels([
            '标号', '年龄', '性别', '用药', '房性早博', '室性早博', '心室融合心博', '右束支传导阻塞心博',
            '左束支传导阻塞心博'
        ])
        # self.patient_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.patient_table.resizeColumnsToContents()
        self.patient_table.verticalHeader().setVisible(False)
        table_layout.addWidget(self.patient_table)
        table_widget.setLayout(table_layout)
        self.bottom_layout.addWidget(table_widget)
        patient_table_btn.clicked.connect(self.show_table)

        # 设置最终的窗口布局与控件-------------------------------------
        splitter = QSplitter(Qt.Vertical)
        splitter.addWidget(top)
        splitter.addWidget(bottom)

        widget = QWidget()
        pagelayout.addWidget(splitter)
        widget.setLayout(pagelayout)
        self.setCentralWidget(widget)

        # 计时器 当时间到了就出发绘图函数
        self.timer = QTimer()
        self.timer.timeout.connect(self.update)

        # 记录当前用户
        self.people = ""
        # 当用户改变时出发函数 重新绘图
        self.data_com.currentIndexChanged.connect(self.show_ecg1)
        self.data_com.view().pressed.connect(self.show_ecg)
        # 读取数据的标志
        self.flag = 0
        # 帮助文档的标志
        self.help = 0
        # 暂停的标志
        self.stop = 0
Exemple #54
0
 def __init__(self):
     super().__init__()
     pg.setConfigOptions(antialias=True)
     self.drawPlot(250.0)
Exemple #55
0
class ImageViewDialog(QDialog):
    pg.setConfigOptions(antialias=True)

    def __init__(self, size=(640, 480), unit=(None, None), *args, **kwargs):
        super(ImageViewDialog, self).__init__(*args, **kwargs)
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setWindowFlags(self.windowFlags() | Qt.WindowSystemMenuHint
                            | Qt.WindowMinMaxButtonsHint)
        self.measure = 'value' if unit[0] is None else unit[0]
        self.unit = '' if unit[1] is None else unit[1]
        self.resize(size[0], size[1])
        self.initUI()
        self.sigConnect()
        self.apply_cmap('thermal')

    def initUI(self):
        self.plot_item = pg.PlotItem()
        self.plot_item.setLabel(axis='left')
        self.plot_item.setLabel(axis='bottom')
        self.plot_item.setTitle("")

        self.image_item = pg.ImageItem()
        self.image_item.hoverEvent = self.imageHoverEvent

        self.imv = pg.ImageView(view=self.plot_item, imageItem=self.image_item)
        self.imv.ui.roiBtn.hide()
        self.imv.ui.menuBtn.hide()

        self.cmap_cb = QComboBox()
        self.cmap_cb.addItems([
            "thermal", "flame", "yellowy", "bipolar", "spectrum", "cyclic",
            "greyclip", "grey", "viridis", "inferno", "plasma", "magma"
        ])

        cb_layout = QHBoxLayout()
        cb_layout.addStretch()
        cb_layout.addWidget(QLabel('Color map:'))
        cb_layout.addWidget(self.cmap_cb)

        layout = QVBoxLayout()
        layout.addWidget(self.imv)
        layout.addLayout(cb_layout)
        self.setLayout(layout)

    def sigConnect(self):
        self.cmap_cb.activated[str].connect(self.apply_cmap)

    def imshow(self, img):
        self.image_data = img
        self.imv.setImage(img)
        img_flat = img.flatten()
        self.imv.setLevels(min=np.min(img_flat[np.nonzero(img_flat)]),
                           max=np.max(img_flat))

    def add_roi(self, roi):
        handles = roi.getHandles()
        positions = []
        for h in handles:
            pos = (h.pos().x(), h.pos().y())
            positions.append(pos)
        r = pg.PolyLineROI(positions=positions, closed=True)
        self.plot_item.addItem(r)

    def set_cmap(self, colors):
        cmap = pg.ColorMap(pos=np.linspace(0.0, 1.0, len(colors)),
                           color=colors)
        self.imv.setColorMap(cmap)

    def setTitle(self, title):
        self.setWindowTitle(title)

    def apply_cmap(self, name):
        self.imv.setPredefinedGradient(name)

    def imageHoverEvent(self, event):
        if event.isExit():
            self.plot_item.setTitle("")
            return
        pos = event.pos()
        i, j = pos.x(), pos.y()
        i = int(np.clip(i, 0, self.image_data.shape[0] - 1))
        j = int(np.clip(j, 0, self.image_data.shape[1] - 1))
        val = self.image_data[j, i]
        self.plot_item.setTitle(
            f"location: ({i:#d}, {j:#d})  {self.measure}: {val:#g}{self.unit}")
Exemple #56
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
Exemple #57
0
def main():
    args = utils.ExampleArgumentParser(num_sens=1).parse_args()
    utils.config_logging(args)

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

    config = configs.EnvelopeServiceConfig()
    config.sensor = args.sensors
    config.update_rate = 30

    session_info = client.setup_session(config)

    start = session_info["range_start_m"]
    length = session_info["range_length_m"]
    num_depths = session_info["data_length"]
    step_length = session_info["step_length_m"]
    depths = np.linspace(start, start + length, num_depths)
    num_hist = 2 * int(round(config.update_rate))
    hist_data = np.zeros([num_hist, depths.size])
    smooth_max = utils.SmoothMax(config.update_rate)

    app = QtWidgets.QApplication([])
    pg.setConfigOption("background", "w")
    pg.setConfigOption("foreground", "k")
    pg.setConfigOptions(antialias=True)
    win = pg.GraphicsLayoutWidget()
    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, start)
    hist_image_item.scale(2 / num_hist, step_length)
    hist_plot.addItem(hist_image_item)

    # Get a nice colormap from matplotlib
    hist_image_item.setLookupTable(utils.pg_mpl_cmap("viridis"))

    win.show()

    interrupt_handler = utils.ExampleInterruptHandler()
    win.closeEvent = lambda _: interrupt_handler.force_signal_interrupt()
    print("Press Ctrl-C to end session")

    client.start_session()

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

        hist_data = np.roll(hist_data, -1, axis=0)
        hist_data[-1] = data

        env_curve.setData(depths, data)
        env_plot.setYRange(0, smooth_max.update(data))
        hist_image_item.updateImage(hist_data,
                                    levels=(0, np.max(hist_data) * 1.05))

        app.processEvents()

    print("Disconnecting...")
    app.closeAllWindows()
    client.disconnect()
Exemple #58
0
class Axes(pg.PlotWidget):
    addPolyFinished = pyqtSignal(object)
    pg.setConfigOptions(imageAxisOrder='row-major')
    pg.setConfigOptions(antialias=True)

    def __init__(self, lock_aspect=False, *args, **kwargs):
        super(Axes, self).__init__(*args, **kwargs)
        self.initUI()
        self.setupConnect()
        self.setAspectLocked(lock_aspect)

    def initUI(self):
        self.setTitle("")
        self.image = pg.ImageItem()
        self.linePlot = pg.PlotDataItem()
        self.scatterPlot = pg.PlotDataItem()
        self.data = {}
        self.graphs = {}
        self.n_graphs = 0
        self.imagedata = None
        self.lineLAT = None
        self.lineAP = None
        self.ellipse = None
        self.poly = None
        self.poly_pts_pos = []
        self.addItem(self.image)
        self.addItem(self.linePlot)
        self.addItem(self.scatterPlot)
        self.rois = []
        self.alt_image = None

    def setupConnect(self):
        self.image.hoverEvent = self.imageHoverEvent

    def imshow(self, img):
        if img is None:
            return
        self.imagedata = img
        self.invertY(True)
        self.image.setImage(img)
        self.autoRange()

    def add_alt_view(self, img):
        self.alt_image = img
        self.set_alt_image()

    def set_alt_image(self):
        if self.alt_image is not None:
            self.image.setImage(self.alt_image)

    def set_primary_image(self):
        if self.imagedata is not None:
            self.image.setImage(self.imagedata)

    def scatter(self, *args, **kwargs):
        self.scatterPlot.setData(*args, **kwargs)
        self.autoRange()

    def plot_(self, *args, **kwargs):
        self.linePlot.setData(*args, **kwargs)
        self.autoRange()

    def immarker(self, *args, **kwargs):
        self.scatter(*args, **kwargs)
        self.rois.append('marker')

    def plot(self, *args, **kwargs):
        tag = kwargs['name'] if 'name' in kwargs else f'series{self.n_graphs}'
        savedata = True
        if 'savedata' in kwargs.keys():
            savedata = kwargs['savedata']
            kwargs.pop('savedata')
        if savedata:
            if len(args) == 1:
                data = args[0]
            elif len(args) == 2:
                data = np.vstack(args).T
            else:
                data = None
            self.data[tag] = data
        plot = pg.PlotDataItem()
        plot.setData(*args, **kwargs)
        self.addItem(plot)
        self.graphs[tag] = plot
        self.n_graphs += 1

    def bar(self, *args, **kwargs):
        if 'name' in kwargs:
            tag = kwargs['name']
        else:
            tag = f'series{self.n_graphs}'
        bargraph = pg.BarGraphItem(*args, **kwargs)
        self.addItem(bargraph)
        self.graphs[tag] = bargraph
        self.n_graphs += 1

    def clearImage(self):
        self.imagedata = None
        self.invertY(False)
        self.image.clear()
        self.alt_image = None

    def clear_graph(self, tag):
        self.removeItem(self.graphs[tag])
        self.graphs.pop(tag)
        self.n_graphs -= 1

    def clearGraph(self):
        self.linePlot.clear()
        self.scatterPlot.clear()
        tags = list(self.graphs.keys())
        for tag in tags:
            self.clear_graph(tag)
        try:
            self.rois.remove('marker')
        except:
            pass

    def clearAll(self):
        self.clearImage()
        self.clearGraph()
        self.clearLines()
        self.clearShapes()

    def clearROIs(self):
        self.image.clear()
        self.clearGraph()
        self.clearLines()
        self.clearShapes()
        if self.alt_image is not None:
            self.add_alt_view(self.alt_image)
        else:
            self.imshow(self.imagedata)

    def clearLines(self):
        try:
            self.removeItem(self.lineLAT)
            self.removeItem(self.lineAP)
            self.rois.remove('lineLAT')
            self.rois.remove('lineAP')
            self.lineLAT = None
            self.lineAP = None
        except:
            return

    def clearPoly(self):
        try:
            self.poly_pts_pos = []
            self.removeItem(self.poly)
            self.rois.remove('poly')
        except:
            pass
        self.poly = None

    def clearEllipse(self):
        try:
            self.removeItem(self.ellipse)
            self.rois.remove('ellipse')
        except:
            pass
        self.ellipse = None

    def clearShapes(self):
        self.clearEllipse()
        self.clearPoly()

    def imageHoverEvent(self, event):
        if event.isExit() or len(self.imagedata.shape) != 2:
            self.setTitle("")
            return
        pos = event.pos()
        i, j = pos.x(), pos.y()
        i = int(np.clip(i, 0, self.imagedata.shape[0] - 1))
        j = int(np.clip(j, 0, self.imagedata.shape[1] - 1))
        val = self.imagedata[j, i]
        self.setTitle(f"pixel: ({i:#d}, {j:#d})  value: {val:#g}")

    def addLAT(self, p1, p2):
        if self.lineLAT == None and self.imagedata is not None:
            self.lineLAT = pg.LineSegmentROI([p1, p2], pen={'color': "00FF7F"})
            self.addItem(self.lineLAT)
            self.rois.append('lineLAT')

    def addAP(self, p1, p2):
        if self.lineAP == None and self.imagedata is not None:
            self.lineAP = pg.LineSegmentROI([p1, p2], pen={'color': "00FF7F"})
            self.addItem(self.lineAP)
            self.rois.append('lineAP')

    def addEllipse(self):
        if self.ellipse == None and self.imagedata is not None:
            x, y = self.imagedata.shape
            unit = np.sqrt(x * y) / 4
            self.ellipse = pg.EllipseROI(pos=[(x / 2) - unit,
                                              (y / 2) - unit * 1.5],
                                         size=[unit * 2, unit * 3],
                                         pen={'color': "00FF7F"})
            self.addItem(self.ellipse)
            self.rois.append('ellipse')

    def applyPoly(self, poly):
        if self.poly is None and self.imagedata is not None:
            self.poly = poly
            self.rois.append('poly')
            self.addItem(self.poly)

    def addPoly(self):
        if self.poly is None and self.imagedata is not None:
            self.click_event_bak = self.image.mouseClickEvent
            self.double_click_event_bak = self.image.mouseDoubleClickEvent
            self.image.mouseClickEvent = self.mouse_click_event
            self.image.mouseDoubleClickEvent = self.mouse_double_click_event
            vb = self.image.getViewBox()
            vb.setCursor(Qt.CrossCursor)
            self.poly = pg.PolyLineROI(positions=[(0, 0)])
            self.addItem(self.poly)
            self.poly.clearPoints()
            self.poly_pts_pos = []

    def cancel_addPoly(self):
        if self.poly is not None:
            self.image.mouseClickEvent = self.click_event_bak
            self.image.mouseDoubleClickEvent = self.double_click_event_bak
            self.clearPoly()

    def mouse_double_click_event(self, event):
        if event.button() == 1 and 'poly_pos' in self.graphs.keys():
            self.image.mouseClickEvent = self.click_event_bak
            self.image.mouseDoubleClickEvent = self.double_click_event_bak
            vb = self.image.getViewBox()
            vb.unsetCursor()
            self.poly.setPoints(self.poly_pts_pos, closed=True)
            self.rois.append('poly')
            self.clear_graph('poly_pos')
            self.addPolyFinished.emit(self.poly)

    def mouse_click_event(self, event):
        if event.button() == 1:
            pos = event.pos()
            self.poly_pts_pos.append((pos.x(), pos.y()))
            poly_pts_pos = np.array(self.poly_pts_pos)
            if 'poly_pos' not in self.graphs.keys():
                self.plot(poly_pts_pos[:, 0],
                          poly_pts_pos[:, 1],
                          pen=None,
                          symbol='+',
                          symbolPen=None,
                          symbolSize=10,
                          symbolBrush=(255, 0, 0, 255),
                          name='poly_pos')
            else:
                self.graphs['poly_pos'].setData(poly_pts_pos[:, 0],
                                                poly_pts_pos[:, 1])
Exemple #59
0
# @File    : app.py
# @License : (C) Copyright 2013-2017, 凯瑞投资

from data_fetch.market_data import OHLC, NewOHLC
from data_handle.indicator import Ma, Macd, Std
from data_visualize.OHLC_ui import OHlCWidget
from data_visualize.console import AnalysisConsole
from data_visualize.Login_ui import LoginDialog
from data_fetch.util import MONTH_LETTER_MAPS
from data_fetch.trade_data import TradeData
import datetime as dt
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtWidgets
import sys

pg.setConfigOptions(leftButtonPan=True, crashWarning=True)
# ------------------------------数据获取与整理---------------------------+
# 确定需要展示的K先范围
start_time = dt.datetime.now() - dt.timedelta(minutes=680)
end_time = dt.datetime.now() + dt.timedelta(minutes=10)
symbol = 'HSI' + MONTH_LETTER_MAPS[dt.datetime.now().month] + str(
    dt.datetime.now().year)[-1]  # 根据当前时间生成品种代码
# 初始化主图的历史ohlc,最新ohlc与指标数据的参数配置
ohlc = OHLC(start_time, end_time, 'HSIH8', minbar=580)
tick_datas = NewOHLC('HSIH8')
i_macd = Macd(short=10, long=22, m=9)
i_ma = Ma(ma10=10, ma20=20, ma30=30, ma60=60)
i_std = Std(window=60, min_periods=2)
trade_datas = TradeData(start_time, end_time, 'HSENG$.MAR8')
# 将指标假如到主图数据里
ohlc + i_ma
Exemple #60
0
# Create the data
fs = 10e3
N = 1e5
amp = 2 * np.sqrt(2)
noise_power = 0.01 * fs / 2
time = np.arange(N) / float(fs)
mod = 500 * np.cos(2 * np.pi * 0.25 * time)
carrier = amp * np.sin(2 * np.pi * 3e3 * time + mod)
noise = np.random.normal(scale=np.sqrt(noise_power), size=time.shape)
noise *= np.exp(-time / 5)
x = carrier + noise
f, t, Sxx = signal.spectrogram(x, fs)

# Interpret image data as row-major instead of col-major
pyqtgraph.setConfigOptions(imageAxisOrder='row-major')

pyqtgraph.mkQApp()
win = pyqtgraph.GraphicsLayoutWidget()
# A plot area (ViewBox + axes) for displaying the image
p1 = win.addPlot()

# Item for displaying image data
img = pyqtgraph.ImageItem()
p1.addItem(img)
# Add a histogram with which to control the gradient of the image
hist = pyqtgraph.HistogramLUTItem()
# Link the histogram to the image
hist.setImageItem(img)
# If you don't add the histogram to the window, it stays invisible, but I find it useful.
win.addItem(hist)