def _get_sel_profiles_curve(self): curve = pg.PlotCurveItem(x=None, y=None, pen=self.make_pen(self.color)) Updater.update_lines([curve], **self.graph.parameter_setter.sel_line_settings) return curve
def set_contingency(self, cont, var, cvar): """ Set the contingency to display. """ assert len(cont) > 0 self.plot.clear() leftaxis = self.plot.getAxis("left") bottomaxis = self.plot.getAxis("bottom") bottomaxis.setLabel(var.name) palette = colorpalette.ColorPaletteGenerator(len(cvar.values)) colors = [palette[i] for i in range(len(cvar.values))] if is_continuous(var): if self.cont_est_type == OWDistributions.Hist: leftaxis.setLabel("Frequency") else: leftaxis.setLabel("Density") bottomaxis.setTicks(None) weights = numpy.array([numpy.sum(W) for _, W in cont]) weights /= numpy.sum(weights) curve_est = self._density_estimator() curves = [curve_est(dist) for dist in cont] curves = [(X, Y * w) for (X, Y), w in zip(curves, weights)] cum_curves = [curves[0]] for X, Y in curves[1:]: cum_curves.append(sum_rect_curve(X, Y, *cum_curves[-1])) for (X, Y), color in reversed(list(zip(cum_curves, colors))): item = pg.PlotCurveItem() item.setData(X, Y, antialias=True, stepMode=True, fillLevel=0, brush=QtGui.QBrush(color)) item.setPen(QtGui.QPen(color)) self.plot.addItem(item) # # XXX: sum the individual curves and not the distributions. # # The conditional distributions might be 'smother' then # # the cumulative one # cum_dist = [cont[0]] # for dist in cont[1:]: # cum_dist.append(dist_sum(dist, cum_dist[-1])) # # curves = [rect_kernel_curve(dist) for dist in cum_dist] # colors = [Qt.blue, Qt.red, Qt.magenta] # for (X, Y), color in reversed(list(zip(curves, colors))): # item = pg.PlotCurveItem() # item.setData(X, Y, antialias=True, stepMode=True, # fillLevel=0, brush=QtGui.QBrush(color)) # item.setPen(QtGui.QPen(color)) # self.plot.addItem(item) elif is_discrete(var): leftaxis.setLabel("Frequency") bottomaxis.setTicks([list(enumerate(var.values))]) cont = numpy.array(cont) for i, (value, dist) in enumerate(zip(var.values, cont.T)): dsum = sum(dist) geom = QtCore.QRectF(i - 0.333, 0, 0.666, dsum) item = DistributionBarItem(geom, dist / dsum, colors) self.plot.addItem(item)
def addCurve(self, plot, name, col=(255, 0, 0)): C = pg.PlotCurveItem(name=name, pen=col) plot.addItem(C) return C
layout.setContentsMargins(0, 0, 0, 0) depthLabel = pg.QtGui.QLabel('fractal depth:') layout.addWidget(depthLabel, 0, 0) depthSpin = pg.SpinBox(value=5, step=1, bounds=[1, 10], delay=0, int=True) depthSpin.resize(100, 20) layout.addWidget(depthSpin, 0, 1) w = pg.GraphicsLayoutWidget() layout.addWidget(w, 1, 0, 1, 2) win.show() # Set up graphics v = w.addViewBox() v.setAspectLocked() baseLine = pg.PolyLineROI([[0, 0], [1, 0], [1.5, 1], [2, 0], [3, 0]], pen=(0, 255, 0, 100), movable=False) v.addItem(baseLine) fc = pg.PlotCurveItem(pen=(255, 255, 255, 200), antialias=True) v.addItem(fc) v.autoRange() transformMap = [0, 0, None] def update(): # recalculate and redraw the fractal curve depth = depthSpin.value() pts = baseLine.getState()['points'] nbseg = len(pts) - 1 nseg = nbseg**depth
def __init__(self): super().__init__() self.timer = QTimer(self) self.capture = WebcamVideoStream(src=1).start() self.image = None self.outImage = None self.countImg = 0 self.frameNumber = 0 self.font1 = QFont("Times", 14) self.font2 = QFont("Times", 11) vbox1 = QVBoxLayout() vbox2 = QVBoxLayout() vbox3 = QVBoxLayout() vbox4 = QVBoxLayout() hbox1 = QHBoxLayout() hbox2 = QHBoxLayout() vbox = QVBoxLayout() # ------------------------------------------------------------------------------------------------------------- # Producing Color Elements # ------------------------------------------------------------------------------------------------------------- # Title self.rgbTitle = QLabel('Measured Color') self.rgbTitle.setFont(self.font1) self.rgbTitle.setMinimumWidth(150) self.rgbTitle.setAlignment(Qt.AlignCenter) # RGB Label self.rgbLabel = QLabel() self.rgbLabel.setFixedWidth(150) self.rgbLabel.setFixedHeight(150) self.rgbLabel.setAlignment(Qt.AlignCenter) # RBG Value self.rgbValue = QLabel() self.rgbValue.setFont(self.font2) self.rgbValue.setAlignment(Qt.AlignCenter) # RGB Value Label self.rgbValueLabel = QLabel('RGB Value: ') self.rgbValueLabel.setFont(self.font2) self.rgbValueLabel.setAlignment(Qt.AlignLeft) # LAB Value self.labValue = QLabel() self.labValue.setFont(self.font2) self.labValue.setAlignment(Qt.AlignCenter) # LAB Value Label self.labValueLabel = QLabel('LAB Value: ') self.labValueLabel.setFont(self.font2) self.labValueLabel.setAlignment(Qt.AlignLeft) # Box1 Operations rgb_frame_box = QGroupBox("Producing Color") rgb_frame_box_layout = QGridLayout() rgb_frame_box.setLayout(rgb_frame_box_layout) rgb_frame_box.setMaximumWidth(220) # Box2 Operations color_value_box = QGroupBox("Color Codes") color_value_box_layout = QGridLayout() color_value_box.setLayout(color_value_box_layout) color_value_box.setFixedWidth(220) # Adding Widgets rgb_frame_box_layout.addWidget(self.rgbTitle, 1, 0) rgb_frame_box_layout.addWidget(self.rgbLabel, 2, 0) color_value_box_layout.addWidget(self.rgbValueLabel, 1, 0) color_value_box_layout.addWidget(self.rgbValue, 1, 1) color_value_box_layout.addWidget(self.labValueLabel, 2, 0) color_value_box_layout.addWidget(self.labValue, 2, 1) # ------------------------------------------------------------------------------------------------------------- # Desired Color # ------------------------------------------------------------------------------------------------------------- # Title self.RALTitle = QLabel('RAL Codes') self.RALTitle.setFont(self.font1) self.RALTitle.setMinimumWidth(150) self.RALTitle.setAlignment(Qt.AlignLeft) # RAL Label self.RALLabel = QLabel() self.RALLabel.setFixedWidth(150) self.RALLabel.setFixedHeight(150) self.RALLabel.setAlignment(Qt.AlignCenter) # Combo Box self.RALCombo = QComboBox() self.RALCombo.addItems(RALtoRGB.RAL) self.RALCombo.currentIndexChanged.connect(self.apply) self.RALCombo.setFixedWidth(100) # RAL to RGB Label self.RALtoRGBValue = QLabel('RAL to RGB: ') self.RALtoRGBValue.setFont(self.font2) self.RALtoRGBValue.setAlignment(Qt.AlignLeft) # RAL to RGB Value self.RALtoRGB = QLabel("[...,...,...]") self.RALtoRGB.setFont(self.font2) self.RALtoRGB.setAlignment(Qt.AlignRight) self.RALtoRGB.setFixedWidth(100) # Box Operations desired_color_box = QGroupBox("Desired Color") desired_color_box_layout = QGridLayout() desired_color_box.setLayout(desired_color_box_layout) desired_color_box.setFixedWidth(220) # Adding Widgets desired_color_box_layout.addWidget(self.RALTitle, 1, 0) desired_color_box_layout.addWidget(self.RALLabel, 2, 0) desired_color_box_layout.addWidget(self.RALCombo, 3, 0) desired_color_box_layout.addWidget(self.RALtoRGBValue, 4, 0) desired_color_box_layout.addWidget(self.RALtoRGB, 4, 1) # ------------------------------------------------------------------------------------------------------------- # Camera Elements # ------------------------------------------------------------------------------------------------------------- # Image Label self.imgLabel = QLabel() self.imgLabel.setFixedHeight(480) self.imgLabel.setFixedWidth(640) # Button for capture image self.capPic = QPushButton("Capture") self.capPic.setFixedSize(80, 40) self.capPic.clicked.connect(self.capture_img) # Dialog Button for select folder self.dialogBtn = QToolButton() self.dialogBtn.setText("...") self.dialogBtn.clicked.connect(self.open_file_dialog) # Line for put file path in to it self.dialogLine = QLineEdit() self.dialogLine.setEnabled(False) # CheckBox self.autoCap = QCheckBox("Capture Automatically") # PWM text self.pwmTxt = QLineEdit() self.pwmTxt.setFixedSize(80, 40) # PWM Button self.pwmBtn = QPushButton("Set PWM") self.pwmBtn.setFixedSize(80, 40) self.pwmBtn.clicked.connect(self.set_pwm) # Box1 Operations img_frame_box1 = QGroupBox("Camera") img_frame_box_layout = QGridLayout() img_frame_box1.setLayout(img_frame_box_layout) img_frame_box1.setMinimumWidth(650) img_frame_box_layout.addWidget(self.imgLabel, 1, 0) # Box2 Operations img_frame_box2 = QGroupBox() img_frame_box_layout2 = QGridLayout() img_frame_box2.setLayout(img_frame_box_layout2) img_frame_box_layout2.addWidget(self.capPic, 1, 0) img_frame_box_layout2.addWidget(self.autoCap, 1, 1) img_frame_box_layout2.addWidget(self.dialogBtn, 1, 3) img_frame_box_layout2.addWidget(self.dialogLine, 1, 2) img_frame_box_layout2.addWidget(self.pwmTxt, 2, 1) img_frame_box_layout2.addWidget(self.pwmBtn, 2, 0) # ------------------------------------------------------------------------------------------------------------- # Plot # ------------------------------------------------------------------------------------------------------------- self.plot1 = pg.PlotWidget() self.plot1_curve1 = pg.PlotCurveItem(pen=(1, 1)) self.plot1_curve2 = pg.PlotCurveItem(pen=(1, 2)) self.plot1_curve3 = pg.PlotCurveItem(pen=(1, 3)) self.plot1.addItem(self.plot1_curve1) self.plot1.addItem(self.plot1_curve2) self.plot1.addItem(self.plot1_curve3) self.plot2 = pg.PlotWidget() self.plot2_curve1 = pg.PlotCurveItem(pen=(1, 1)) self.plot2.addItem(self.plot2_curve1) self.plot1.setXRange(0, 255) self.plot1.setYRange(0, 100) img_plot_box2 = QGroupBox() img_plot_box_layout2 = QGridLayout() img_plot_box2.setLayout(img_plot_box_layout2) img_plot_box_layout2.addWidget(self.plot1, 0, 0) img_plot_box_layout2.addWidget(self.plot2, 1, 0) # ------------------------------------------------------------------------------------------------------------- # Box Operations # ------------------------------------------------------------------------------------------------------------- vbox1.addWidget(rgb_frame_box) vbox1.addWidget(color_value_box) vbox1.addStretch(1) vbox2.addWidget(desired_color_box) vbox2.addStretch(1) vbox3.addWidget(img_frame_box1) vbox3.addWidget(img_frame_box2) vbox4.addWidget(img_plot_box2) hbox1.addLayout(vbox1) hbox1.addLayout(vbox2) hbox1.addLayout(vbox3) hbox2.addLayout(vbox4) vbox.addLayout(hbox1) vbox.addLayout(hbox2) self.setLayout(vbox) self.setWindowTitle('PyQt5') self.start_webcam() self.show()
def setupUi(self, MainWindow): super().setupUi(MainWindow) #### self.visualizerGView = pg.GraphicsView(self.visualizerTab) self.visualizerGView.setObjectName(_fromUtf8("visualizerGView")) self.visualizerVLayout.addWidget(self.visualizerGView) self.layout = pg.GraphicsLayout(border=(100, 100, 100)) self.visualizerGView.setCentralItem(self.layout) #### # Mel filterbank plot self.fft_plot = self.layout.addPlot(title='Filterbank Output', colspan=3) self.fft_plot.setRange(yRange=[-0.1, 1.2]) self.fft_plot.disableAutoRange(axis=pg.ViewBox.YAxis) self.x_data = np.array(range(1, config.N_FFT_BINS + 1)) self.mel_curve = pg.PlotCurveItem() self.mel_curve.setData(x=self.x_data, y=self.x_data * 0) self.fft_plot.addItem(self.mel_curve) # Visualization plot self.layout.nextRow() self.led_plot = self.layout.addPlot(title='Visualization Output', colspan=3) self.led_plot.setRange(yRange=[-5, 260]) self.led_plot.disableAutoRange(axis=pg.ViewBox.YAxis) # Pen for each of the color channel curves self.r_pen = pg.mkPen((255, 30, 30, 200), width=4) self.g_pen = pg.mkPen((30, 255, 30, 200), width=4) self.b_pen = pg.mkPen((30, 30, 255, 200), width=4) # Color channel curves self.r_curve = pg.PlotCurveItem(pen=self.r_pen) self.g_curve = pg.PlotCurveItem(pen=self.g_pen) self.b_curve = pg.PlotCurveItem(pen=self.b_pen) # Define x data self.x_data = np.array(range(1, config.N_PIXELS + 1)) self.r_curve.setData(x=self.x_data, y=self.x_data * 0) self.g_curve.setData(x=self.x_data, y=self.x_data * 0) self.b_curve.setData(x=self.x_data, y=self.x_data * 0) # Add curves to plot self.led_plot.addItem(self.r_curve) self.led_plot.addItem(self.g_curve) self.led_plot.addItem(self.b_curve) # Frequency range label self.freq_label = pg.LabelItem('') # Frequency slider self.freq_slider = pg.TickSliderItem(orientation='bottom', allowAdd=False) self.freq_slider.addTick( (config.MIN_FREQUENCY / (config.MIC_RATE / 2.0))**0.5) self.freq_slider.addTick( (config.MAX_FREQUENCY / (config.MIC_RATE / 2.0))**0.5) self.freq_slider.tickMoveFinished = self.freq_slider_change self.freq_label.setText('Frequency range: {} - {} Hz'.format( config.MIN_FREQUENCY, config.MAX_FREQUENCY)) # Create effect "buttons" (labels with click event) self.energy_label = pg.LabelItem('Energy') self.scroll_label = pg.LabelItem('Scroll') self.spectrum_label = pg.LabelItem('Spectrum') self.energy_label.mousePressEvent = self.energy_click self.scroll_label.mousePressEvent = self.scroll_click self.spectrum_label.mousePressEvent = self.spectrum_click self.energy_click(0) # Layout self.layout.nextRow() self.layout.addItem(self.freq_label, colspan=3) self.layout.nextRow() self.layout.addItem(self.freq_slider, colspan=3) self.layout.nextRow() self.layout.addItem(self.energy_label) self.layout.addItem(self.scroll_label) self.layout.addItem(self.spectrum_label) # Fix secondTab self.tabWidget.setTabText(self.tabWidget.indexOf(self.visualizerTab), _translate("MainWindow", "Visualizer", None)) #SIGNALS AND CONNECTORS self.visualizerStartBtn.clicked.connect(self.start_visualizer_click) self.visualizerStopBtn.clicked.connect(self.stop_visualizer_click) self.parent_app.aboutToQuit.connect(self.closeEvent) # AUDIO INPUT DEVICES self.getaudiodevices() self.soundDeviceSelectBox.currentIndexChanged.connect( self.inputDeviceChanged)
def loadFromFile(self,plot,curves,filename,**kwargs): if os.stat(filename).st_size>100000: #File too big. not histogram. return False with open(filename) as f: comments='' delim = ',' while True: header = f.readline() if header[0]=='#': comments+=header[1:] continue data1 = header.strip() if ',' in data1: delim = ',' elif ' ' in data1: delim = ' ' elif '\t' in data1: delim = '\t' else: delim = ' ' break #print (filename,comments) if re.search('[a-df-zA-DF-Z]', header): #Header has letters ar = np.loadtxt(filename,skiprows=1,delimiter=delim) try: #parse headers and set them as axis labels header = header.replace(' ',',') p=header.split(',') if len(p)>=2: plot.getAxis('bottom').setLabel(p[0]) plot.getAxis('left').setLabel(p[1]) except Exception as e: plot.getAxis('bottom').setLabel('channel') plot.getAxis('left').setLabel('count') else: try: ar = np.loadtxt(filename,delimiter=delim) except Exception as e: logging.exception(e) print('error loading:',filename,delim,e) return False #XR = [0,0];YR=[0,0] fit = kwargs.get('fit',False) if fit: plot.addLegend() z=ar for A in range(int(len(ar[0])/2)): #integer division self.x =ar[:,int(A)*2] self.y =ar[:,int(A)*2+1] if kwargs.get('histMode',False): pen=(155, 255, 155,180) if A<len(self.trace_colors): brush = list(self.trace_colors[A][:3])+[120] else: brush=(0, 20, 255,130) if A<len(curves): curves[A].setData(self.x,self.y[:-1], stepMode=True, fillLevel=0, brush=brush,pen = pen) else: if fit: #Exponential decay fitting. self.x = self.x/60 #convert to minutes Amp, K , log_Amp, res = self.fit_exp_linear(self.x,self.y, 0) #No offset expected fit_dY = Amp * np.exp(K * self.x) # + offset fitcurve = pg.PlotCurveItem(name = " <span style='color: green'>N0 = %.2f , Decay Coefficient = %.2e, Half life = %.2f Min </span>"%(Amp,K,0.693/K) , pen = curves[A].opts['pen']) plot.addItem(fitcurve) print ('N0=%.2f ; Residual=%.3f SD of slope (log mode) = '%(Amp, res),np.sqrt( (1./(len(self.x)-2))*sum((log_Amp+K*self.x - np.log(self.y))**2)/sum((self.x - np.average(self.x))**2) )) if kwargs.get('log',False): fitcurve.setData(self.x,log_Amp+K*self.x) legendY = np.log(self.y.max()) legendY -= A*legendY/10 else: #print 'SD of slope :',np.sqrt( (1./(len(self.x)-2))*sum((fit_dY - self.y)**2)/sum((self.x - np.average(self.x))**2) ) fitcurve.setData(self.x,fit_dY) legendY = self.y.max() legendY -= A*legendY/20. #text = pg.TextItem(html=" <span style='color: green'>N0 = %.2f , Decay Coefficient = %.2e, Half life = %.2f Min </span>"%(Amp,K,0.693/K), anchor=(-0.3,0.5), border='r') #plot.addItem(text) #text.setPos(0,legendY ) if kwargs.get('log',False): Y = np.log(self.y) else: Y = self.y if kwargs.get('errorBars',False): if kwargs.get('log',False): errbar = 1./np.sqrt(self.y) else: errbar = np.sqrt(Y)/2. bw = (self.x[1]-self.x[0])/2. err = pg.ErrorBarItem(x=self.x, y=Y, top=errbar, bottom=errbar, beam=bw) plot.addItem(err) if fit: tmpc = plot.plot(self.x,Y,pen=None, symbolBrush=(0,100,200), symbolPen='b', symbol='star', symbolSize=12) else: curves[int(A)].setData(self.x,Y,symbolBrush=(0,0,200), symbolPen='w', symbol='o', symbolSize=14) # curves[A].setData(self.x,self.y, symbolBrush=(0,0,200), symbolPen='w', symbol='o', symbolSize=14) #if( min(self.x) < XR[0] ):XR[0] = min(self.x)-abs(min(self.x))*.1 #if( max(self.x) > XR[1] ):XR[1] = max(self.x)+abs(max(self.x))*.1 #if( min(self.y) < YR[0] ):YR[0] = min(self.y)-abs(min(self.y))*.1 #if( max(self.y) > YR[1] ):YR[1] = max(self.y)+abs(max(self.y))*.1 plot.getAxis('left').setGrid(170) plot.getAxis('bottom').setGrid(170) #self.autoScale(plot,XR[0],XR[1],YR[0],YR[1]); plot.enableAutoRange() return True
def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) # Get the data for the avoided crossing pickle_foldername = os.path.join(os.getcwd(), 'Crossings_Data') pickle_filename = os.path.join(pickle_foldername, 'pickled_data.p') with open(pickle_filename, 'r') as file: pickled_data = pickle.load(file) self.bond_lengths = pickled_data['bond_lengths'] self.Low_A_Curve = pickled_data['Low_A_Curve'] self.High_A_Curve = pickled_data['High_A_Curve'] self.Low_D_Curve = pickled_data['Low_D_Curve'] self.High_D_Curve = pickled_data['High_D_Curve'] self.Low_A_MO = pickled_data['Low_A_MO'] self.High_A_MO = pickled_data['High_A_MO'] self.Low_D_MO = pickled_data['Low_D_MO'] self.High_D_MO = pickled_data['High_D_MO'] self.a_curves = True # Now set up the GUI self.layout = QtGui.QVBoxLayout(self) self.options = QtGui.QHBoxLayout() self.adiabat = QtGui.QRadioButton(self, text='Adiabatic Curves') self.adiabat.setChecked(True) self.options.addWidget(self.adiabat) self.adiabat.clicked.connect(self.changeCurves) self.diabat = QtGui.QRadioButton(self, text='Diabatic Curves') self.options.addWidget(self.diabat) self.diabat.clicked.connect(self.changeCurves) self.i_button = InstructionsButton(self, my_file='Crossing.txt') self.options.addWidget(self.i_button) self.layout.addLayout(self.options) self.plot_object = pg.PlotWidget() self.plot_object.getPlotItem().setMouseEnabled(False, False) self.plot_object.setLabel('bottom', 'Bond Length', units='α') self.plot_object.setLabel('left', 'Energy') self.plot_object.hideAxis('left') # Create and add things to the plot widget self.curve_AH = pg.PlotCurveItem(pen=(30, 100)) self.curve_AH.setData(self.bond_lengths, self.High_A_Curve) self.plot_object.addItem(self.curve_AH) self.curve_AL = pg.PlotCurveItem(pen=(20, 100)) self.curve_AL.setData(self.bond_lengths, self.Low_A_Curve) self.plot_object.addItem(self.curve_AL) self.curve_DH = pg.PlotCurveItem(pen=(90, 100)) self.curve_DH.setData(self.bond_lengths, self.High_D_Curve) self.plot_object.addItem(self.curve_DH) self.curve_DL = pg.PlotCurveItem(pen=(80, 100)) self.curve_DL.setData(self.bond_lengths, self.Low_D_Curve) self.plot_object.addItem(self.curve_DL) self.curser = pg.InfiniteLine(pos=0, angle=90, bounds=[1.5, 5.0], pen=pg.mkPen(width=3, color='g'), movable=True) self.curser.sigPositionChanged.connect(self.curserMoved) self.plot_object.addItem(self.curser) self.layout.addWidget(self.plot_object) self.layout.addItem(VerticalSpacer()) self.animate_button = QtGui.QPushButton(self, text='Start/Stop Animation') self.layout.addWidget(self.animate_button) self.animate_button.clicked.connect(self.animationPressed) self.animating = False self.animation_timer = QtCore.QTimer() self.animation_timer.timeout.connect(self.animateFrame) self.vid_frame = 0
def createGraphSetView(self, graphSetSetting, dataSet): # [6.3-2] PlotWidget pwList = list() self.pIList = list() for i in range(len(graphSetSetting["graphs"])): graphSetting = graphSetSetting["graphs"]["graph" + str(i + 1)] self.pIList.append(list()) sideAxisList = list() invertXTF = bool(graphSetting["range"]["xRange"]["min"] > graphSetting["range"]["xRange"]["max"]) invertYTF = bool(graphSetting["range"]["y1Range"]["min"] > graphSetting["range"]["y1Range"]["max"]) pwList.append( pg.PlotWidget(viewBox=pg.ViewBox(border=pg.mkPen( color='#000000', width=self.imageScale), invertX=invertXTF, invertY=invertYTF))) self.lw.addWidget(pwList[i], graphSetting["position"]["r"], graphSetting["position"]["c"], graphSetting["span"]["r"], graphSetting["span"]["c"]) # [6.3-4] pwList[i].setBackground(graphSetting["backgroundColor"]) if graphSetting["size"]["h"] != 0 and graphSetting["size"][ "w"] != 0: pwList[i].setMinimumSize(graphSetting["size"]["w"], graphSetting["size"]["h"]) pwList[i].setMaximumSize(graphSetting["size"]["w"], graphSetting["size"]["h"]) if graphSetting["yAxisNum"] == 1: # [6.3-5] plotItem p1 = pwList[i].plotItem self.pIList[i].append(p1) sideAxisList.append(p1.getAxis('left')) # [6.3-22] self.initializeAxisItem(p1.getAxis('bottom'), sideAxisList[0]) elif graphSetting["yAxisNum"] == 2: p1 = pwList[i].plotItem p2 = pg.ViewBox(invertX=invertXTF, invertY=invertYTF) self.pIList[i].append(p1) self.pIList[i].append(p2) sideAxisList.append(p1.getAxis('left')) sideAxisList.append(p1.getAxis('right')) # [6.3-22] self.initializeAxisItem(p1.getAxis('bottom'), sideAxisList[0], sideAxisList[1]) self.setMultipleAxisPlot(p1, p2) elif graphSetting["yAxisNum"] == 3: p1 = pwList[i].plotItem p2 = pg.ViewBox(invertX=invertXTF, invertY=invertYTF) p3 = pg.ViewBox(invertX=invertXTF, invertY=invertYTF) ax3 = pg.AxisItem(orientation='right') self.pIList[i].append(p1) self.pIList[i].append(p2) self.pIList[i].append(p3) sideAxisList.append(p1.getAxis('left')) sideAxisList.append(p1.getAxis('right')) sideAxisList.append(ax3) # [6.3-22] self.initializeAxisItem(p1.getAxis('bottom'), sideAxisList[0], sideAxisList[1], sideAxisList[2]) self.setMultipleAxisPlot(p1, p2, p3, ax3) # [6.3-7] # [6.3-9] p1.setRange(xRange=(graphSetting["range"]["xRange"]["min"], graphSetting["range"]["xRange"]["max"]), padding=0) if graphSetting["xAxisTitleColor"] != None: fontCss = self.fontCss fontCss['color'] = graphSetting["xAxisTitleColor"] # [6.3-6] p1.getAxis('bottom').setLabel(graphSetting["xAxisTitle"], **fontCss) tick = {} for m in ["major", "minor"]: if graphSetting["tick"]["xTick"][m] == -1: tick[m] = None else: tick[m] = graphSetting["tick"]["xTick"][m] p1.getAxis('bottom').setTickSpacing(tick["major"], tick["minor"]) sideAxisNum = 1 for ax, p in zip(sideAxisList, self.pIList[i]): if graphSetting["y" + str(sideAxisNum) + "AxisTitleColor"] != None: fontCss = self.fontCss fontCss['color'] = graphSetting["y" + str(sideAxisNum) + "AxisTitleColor"] ax.setLabel( graphSetting["y" + str(sideAxisNum) + "AxisTitle"], **fontCss) tick = {} for m in ["major", "minor"]: if graphSetting["tick"]["y" + str(sideAxisNum) + "Tick"][m] == -1: tick[m] = None else: tick[m] = graphSetting["tick"]["y" + str(sideAxisNum) + "Tick"][m] ax.setTickSpacing(tick["major"], tick["minor"]) p.setRange( yRange=(graphSetting["range"]["y" + str(sideAxisNum) + "Range"]["min"], graphSetting["range"]["y" + str(sideAxisNum) + "Range"]["max"]), padding=0) sideAxisNum += 1 # [6.3-8] for j in range(len(graphSetting["plots"])): plotSetting = graphSetting["plots"]["plot" + str(j + 1)] if plotSetting["dataScopeMin"] == -1: dataScopeMin = None else: dataScopeMin = plotSetting["dataScopeMin"] if plotSetting["dataScopeMax"] == -1: dataScopeMax = None else: dataScopeMax = plotSetting["dataScopeMax"] style = { "Line (Solid)": Qt.SolidLine, "Line (Dash)": Qt.DashLine, "Line (Dot)": Qt.DotLine, "Line (DashDot)": Qt.DashDotLine, "Line (DashDotDot)": Qt.DashDotDotLine, "Point (Circle)": "o", "Point (Square)": "s", "Point (Triangle)": "t", "Point (Diamond)": "d", "Point (Plus)": "+" } if plotSetting["style"] not in style: plotSetting["style"] = "Line (Solid)" if plotSetting["style"].startswith("Line"): self.pIList[i][plotSetting["yAxis"]].addItem( pg.PlotCurveItem( dataSet[self.getDataIndex( plotSetting["x"])][dataScopeMin:dataScopeMax], dataSet[self.getDataIndex( plotSetting["y"])][dataScopeMin:dataScopeMax], pen=pg.mkPen(color=plotSetting["color"], width=self.imageScale, style=style[plotSetting["style"]]), name=plotSetting["title"], antialias=graphSetSetting["antialias"])) if plotSetting["style"].startswith("Point"): self.pIList[i][plotSetting["yAxis"]].addItem( pg.ScatterPlotItem( dataSet[self.getDataIndex( plotSetting["x"])][dataScopeMin:dataScopeMax], dataSet[self.getDataIndex( plotSetting["y"])][dataScopeMin:dataScopeMax], symbol=style[plotSetting["style"]], pen=pg.mkPen(None), brush=pg.mkBrush(plotSetting["color"]), size=5, name=plotSetting["title"], antialias=graphSetSetting["antialias"]))
import numpy as np import pyqtgraph as pg from PyQt5 import QtCore plot = pg.plot() s = pg.PlotCurveItem() plot.addItem(s) x = np.array([1, 2, 3]) y = np.array([1, 2, 3]) app_x = np.array([4]) app_y = np.array([4]) x = np.hstack((x, app_x)) y = np.hstack((y, app_y)) print(x) print(y) s.setData(x=x, y=y) if __name__ == '__main__': import sys if sys.flags.interactive != 1 or not hasattr(QtCore, 'PYQT_VERSION'): pg.QtGui.QApplication.exec_()
def __init__(self, Clusterer, show_bg, point_size=3): super().__init__() self.clustering_view = QWidget() self.layout = QGridLayout() self.clustering_view.setLayout(self.layout) self.RD_plot = pg.PlotWidget() self.RD_hist = pg.PlotWidget() self.point_cloud_view = gl.GLViewWidget() self.RD_plot.sizeHint = pg.QtCore.QSize(800, 600) self.point_cloud_view.sizeHint = lambda: pg.QtCore.QSize(800, 600) self.point_cloud_view.setSizePolicy(self.RD_plot.sizePolicy()) self.layout.addWidget(self.point_cloud_view, 0, 0, 2, 1) self.layout.addWidget(self.RD_plot, 0, 1) self.layout.addWidget(self.RD_hist, 1, 1) self.point_cloud_view.setBackgroundColor('w') self.point_cloud_view.opts['distance'] = 2000 self.point_cloud_view.opts['fov'] = 1 self.thread_show_clustering = QThread() self.ShowClustering = ShowClustering(Clusterer, point_size, show_bg) self.ShowClustering.gl_finished.connect( self.thread_show_clustering.quit) self.ShowClustering.gl_ready.connect(self.point_cloud_ready) self.ShowClustering.moveToThread(self.thread_show_clustering) self.thread_show_clustering.started.connect( self.ShowClustering.show_clustering) self.thread_show_clustering.start() # start plot RD ordered_RD = Clusterer.RD[Clusterer.ordered_lst] self.RD_plot.setBackground('w') self.RD_plot.setDownsampling(auto=True) self.RD_plot.plot(ordered_RD, pen=pg.mkPen('k', width=2)) color_table = ColorTable.gen_color_table(style='int') color_table.pop(0) cycol = cycle(color_table) # num_leaves = len(leaves) leaves = Clusterer.obtain_leaf_nodes() count = 0 for node in leaves: if node.is_cluster: item = node.index_range ave_RD = node.average_RD(ordered_RD) self.RD_plot.plot(item, [ave_RD, ave_RD], pen=pg.mkPen(color=next(cycol), width=2)) count += 1 # start plot RD hist self.RD_hist.setBackground('w') hist, bins = np.histogram(Clusterer.RD, bins=50, density=True) curve = pg.PlotCurveItem(bins, hist, pen=pg.mkPen('b', width=2), stepMode=True) self.RD_hist.addItem(curve) # self.thread_show_RD = QThread() # self.thread_show_RD_hist = QThread() self.clustering_view.show()
def reset(self): was = self.redraw self.redraw = False engine.dataset = [] for p in self.ALLPLOTS: p.clear() p.enableAutoRange(pg.ViewBox.XYAxes, True) #set single curves #FZ self._gc_fz_raw = pg.ScatterPlotItem(clickable=False) self._gc_fz_raw.setPen(pg.mkPen(COL_CIR_OUTER)) self._gc_fz_raw.setBrush(pg.mkBrush(COL_CIR_INNER)) self._gc_fz_raw.setSymbol('o') self.ui.g_fz_single.addItem(self._gc_fz_raw) self._gc_fz = pg.PlotCurveItem(clickable=False) self._gc_fz.setPen(pg.mkPen(COL_LIN, width=4)) self.ui.g_fz_single.addItem(self._gc_fz) #FiZi self._gc_fizi = pg.ScatterPlotItem(clickable=False) self._gc_fizi.setPen(pg.mkPen(COL_CIR_OUTER)) self._gc_fizi.setBrush(pg.mkBrush(COL_CIR_INNER)) self._gc_fizi.setSymbol('o') self.ui.g_fizi_single.addItem(self._gc_fizi) self._gc_fizi_fit = pg.PlotCurveItem(clickable=False) self._gc_fizi_fit.setPen(pg.mkPen(COL_LIN_FIT, width=6)) #style=QtCore.Qt.DashLine self.ui.g_fizi_single.addItem(self._gc_fizi_fit) #EZe self._gc_eze = pg.ScatterPlotItem(clickable=False) self._gc_eze.setPen(pg.mkPen(COL_CIR_OUTER)) self._gc_eze.setBrush(pg.mkBrush(COL_CIR_INNER)) self._gc_eze.setSymbol('o') self.ui.g_eze_single.addItem(self._gc_eze) self._gc_eze_fit = pg.PlotCurveItem(clickable=False) self._gc_eze_fit.setPen(pg.mkPen(COL_LIN_FIT, width=6)) #style=QtCore.Qt.DashLine self.ui.g_eze_single.addItem(self._gc_eze_fit) self.redraw = was #Titles and labels (single and all) def title_style(lab): return '<span style="font-family: Arial; font-weight:bold; font-size: 10pt;">{}</span>'.format( lab) def lab_style(lab): return '<span style="">{}</span>'.format(lab) #FZ single self.ui.g_fz_single.setTitle( title_style('Force-displacement (single)')) self.ui.g_fz_single.setLabel('left', lab_style('F [N]')) self.ui.g_fz_single.setLabel('bottom', lab_style('z [m]')) #FiZi single self.ui.g_fizi_single.setTitle( title_style('Force-indentation (single)')) self.ui.g_fizi_single.setLabel('left', lab_style('F [N]')) self.ui.g_fizi_single.setLabel('bottom', lab_style('<font>δ</font> [m]')) #EZe single self.ui.g_eze_single.setTitle( title_style('Elasticity Spectra (single)')) self.ui.g_eze_single.setLabel('left', lab_style('E [Pa]')) self.ui.g_eze_single.setLabel('bottom', lab_style('<font>δ</font> [m]')) #FZ all self.ui.g_fz_all.setTitle(title_style('Force-displacement (data set)')) self.ui.g_fz_all.setLabel('left', lab_style('F [N]')) self.ui.g_fz_all.setLabel('bottom', lab_style('z [m]')) #FiZi all self.ui.g_fizi_all.setTitle( title_style('Force-indentation (data set)')) self.ui.g_fizi_all.setLabel('left', lab_style('F [N]')) self.ui.g_fizi_all.setLabel('bottom', lab_style('<font>δ</font> [m]')) #EZe self.ui.g_eze_all.setTitle( title_style('Elasticity Spectra (data set)')) self.ui.g_eze_all.setLabel('left', lab_style('E [Pa]')) self.ui.g_eze_all.setLabel('bottom', lab_style('<font>δ</font> [m]'))
curve = p.plot(x=[], y=[], pen=pg.mkPen(color='#c4380d')) p.showAxis('right') p.setLabel('right', 'Dynamic Resistance', units="<font>Ω</font>", color='#025b94', **{'font-size': '20pt'}) p.getAxis('right').setPen(pg.mkPen(color='#025b94', width=3)) p2 = pg.ViewBox() p.scene().addItem(p2) p.getAxis('right').linkToView(p2) p2.setXLink(p) p2.setYRange(-10, 10) curve2 = pg.PlotCurveItem(pen=pg.mkPen(color='#025b94', width=1)) p2.addItem(curve2) def updateViews(): global p2 p2.setGeometry(p.getViewBox().sceneBoundingRect()) p2.linkedViewChanged(p.getViewBox(), p2.XAxis) updateViews() p.getViewBox().sigResized.connect(updateViews) x = np.arange(0, 10.01, 0.01) data = 5 + np.sin(30 * x) data2 = -5 + np.cos(30 * x)
def _get_mean_curve(self): pen = self.make_pen(self.color.darker(LinePlotStyle.MEAN_DARK_FACTOR)) curve = pg.PlotCurveItem(x=self.x_data, y=self.__mean, pen=pen) Updater.update_lines([curve], **self.graph.parameter_setter.mean_settings) return curve
def add_stream(self, accumulator: DataFrameAccumulator, header_items=None): """Adds a data collector stream to the plot: Parameters ---------- accumulator : instance of the DataAccumulator class header_items : specify elements in the DataAccumulator to be plot by their header name. Returns ------- """ try: if header_items is None: if accumulator.plot_columns is not None: header_items = accumulator.plot_columns else: header_items = accumulator.columns[1:] # first column is always t self.colors = self.get_colors(len(self.stream_items) + len(header_items)) self.accumulators.append(accumulator) self.selected_columns.append(header_items) except ValueError: return self.bounds.append(None) i_curve = len(self.stream_items) for header_item in header_items: c = pg.PlotCurveItem( x=np.array([0]), y=np.array([i_curve]), connect="finite" ) curve_label = pg.TextItem(header_item, anchor=(0, 1)) curve_label.setPos(-self.time_past * 0.9, i_curve) value_label = pg.TextItem("", anchor=(0, 0.5)) font_bold = QFont("Sans Serif", 8) font_bold.setBold(True) value_label.setFont(font_bold) value_label.setPos(0, i_curve + 0.5) max_label = pg.TextItem("", anchor=(0, 0)) max_label.setPos(0, i_curve + 1) min_label = pg.TextItem("", anchor=(0, 1)) min_label.setPos(0, i_curve) self.stream_items.append( PlotTuple(c, curve_label, min_label, max_label, value_label) ) i_curve += 1 for sitems, color in zip(self.stream_items, self.colors): for itm in sitems: self.plotContainer.addItem(itm) if isinstance(itm, pg.PlotCurveItem): itm.setPen(color, width=self.penwidth) else: itm.setColor(color) self.plotContainer.setYRange(-0.1, len(self.stream_items) + 0.1)
def initialize(self): if self.data is None: return self.viewBox = MyViewBox() self.viewBox.gain_zoom.connect(self.gain_zoom) #~ self.viewBox.lasso_started.connect(self.on_lasso_started) self.viewBox.lasso_drawing.connect(self.on_lasso_drawing) self.viewBox.lasso_finished.connect(self.on_lasso_finished) self.plot = pg.PlotItem(viewBox=self.viewBox) self.graphicsview.setCentralItem(self.plot) self.plot.hideButtons() self.scatter = pg.ScatterPlotItem(size=3, pxMode=True) self.plot.addItem(self.scatter) self.scatter.sigClicked.connect(self.on_scatter_clicked) brush = QT.QColor('magenta') brush.setAlpha(180) self.scatter_select = pg.ScatterPlotItem(pen=pg.mkPen(None), brush=brush, size=11, pxMode=True) self.plot.addItem(self.scatter_select) self.scatter_select.setZValue(1000) color = self.controller.qcolors.get(labelcodes.LABEL_NOISE) self.scatter_noise = pg.ScatterPlotItem(pen=pg.mkPen(None), brush=color, size=3, pxMode=True) self.plot.addItem(self.scatter_noise) self.lasso = pg.PlotCurveItem(pen='#7FFF00') self.plot.addItem(self.lasso) med, mad = median_mad(self.data) m = 4. * np.max(mad) self.limit = m self.plot.setXRange(-m, m) self.plot.setYRange(-m, m) ndim = self.data.shape[1] self.selected_comp = np.ones((ndim), dtype='bool') self.projection = np.zeros((ndim, 2)) self.projection[0, 0] = 1. self.projection[1, 1] = 1. self.point_visible = np.zeros(self.data.shape[0], dtype=bool) self.by_cluster_random_decimate(refresh=False) self.plot2 = pg.PlotItem(viewBox=MyViewBox(lockAspect=True)) self.graphicsview2.setCentralItem(self.plot2) self.plot2.hideButtons() angles = np.arange(0, 360, .1) self.circle = pg.PlotCurveItem(x=np.cos(angles), y=np.sin(angles), pen=(255, 255, 255)) self.plot2.addItem(self.circle) self.direction_lines = pg.PlotCurveItem(x=[], y=[], pen=(255, 255, 255)) self.direction_data = np.zeros((ndim * 2, 2)) self.plot2.addItem(self.direction_lines) self.plot2.setXRange(-1, 1) self.plot2.setYRange(-1, 1) self.proj_labels = [] for i in range(ndim): text = 'PC{}'.format(i) label = pg.TextItem(text, color=(1, 1, 1), anchor=(0.5, 0.5), border=None, fill=pg.mkColor((128, 128, 128, 180))) self.proj_labels.append(label) self.plot2.addItem(label) self.graphicsview2.setMaximumSize(200, 200) #~ self.hyper_faces = list(itertools.product(range(ndim), range(ndim))) self.hyper_faces = list(itertools.permutations(range(ndim), 2)) self.n_face = -1
def __init__(self, image=None, fillHistogram=True, rgbHistogram=False, levelMode='mono'): pg.GraphicsWidget.__init__(self) self.lut = None self.imageItem = lambda: None # fake a dead weakref self.levelMode = levelMode self.rgbHistogram = rgbHistogram self.layout = QtGui.QGraphicsGridLayout() self.setLayout(self.layout) self.layout.setContentsMargins(1, 1, 1, 1) self.layout.setSpacing(0) self.vb = pg.ViewBox(parent=self) self.vb.setMaximumHeight(20) self.vb.setMinimumHeight(20) self.vb.setMouseEnabled(x=False, y=True) self.gradient = pg.GradientEditorItem() self.gradient.setOrientation('top') self.gradient.loadPreset('viridis') self.gradient.setFlag(self.gradient.ItemStacksBehindParent) self.vb.setFlag(self.gradient.ItemStacksBehindParent) self.layout.addItem(self.gradient, 0, 0) self.layout.addItem(self.vb, 1, 0) self.axis = pg.AxisItem('bottom', linkView=self.vb, maxTickLength=-10, parent=self) self.layout.addItem(self.axis, 2, 0) self.regions = [ pg.LinearRegionItem([0, 1], 'vertical', swapMode='block'), #we dont need those here #pg.LinearRegionItem([0, 1], 'vertical', swapMode='block', pen='r',brush=fn.mkBrush((255, 50, 50, 50)), span=(0., 1/3.)), #pg.LinearRegionItem([0, 1], 'vertical', swapMode='block', pen='g',brush=fn.mkBrush((50, 255, 50, 50)), span=(1/3., 2/3.)), #pg.LinearRegionItem([0, 1], 'vertical', swapMode='block', pen='b',brush=fn.mkBrush((50, 50, 255, 80)), span=(2/3., 1.)), #pg.LinearRegionItem([0, 1], 'vertical', swapMode='block', pen='w',brush=fn.mkBrush((255, 255, 255, 50)), span=(2/3., 1.)) ] for region in self.regions: region.setZValue(1000) self.vb.addItem(region) region.lines[0].addMarker('<|', 0.5) region.lines[1].addMarker('|>', 0.5) region.sigRegionChanged.connect(self.regionChanging) region.sigRegionChangeFinished.connect(self.regionChanged) self.region = self.regions[0] add = QtGui.QPainter.CompositionMode_Plus self.plots = [ pg.PlotCurveItem(pen=(200, 200, 200, 100)), # mono pg.PlotCurveItem(pen=(255, 0, 0, 100), compositionMode=add), # r pg.PlotCurveItem(pen=(0, 255, 0, 100), compositionMode=add), # g pg.PlotCurveItem(pen=(0, 0, 255, 100), compositionMode=add), # b pg.PlotCurveItem(pen=(200, 200, 200, 100), compositionMode=add), # a ] self.plot = self.plots[0] for plot in self.plots: self.vb.addItem(plot) self.fillHistogram(fillHistogram) self.range = None self.gradient.sigGradientChanged.connect(self.gradientChanged) self.vb.sigRangeChanged.connect(self.viewRangeChanged)
def setupUi(self): ipport = QLabel("TCP/IP port", self) self.ipportEdit = QLineEdit(self.guvip, self) tcpport = QLabel("TCP port", self) self.tcpportEdit = QLineEdit(self.guvport, self) guvtype_lbl = QLabel("GUV type", self) self.guvtype_cb = QComboBox(self) mylist = ["GUV-541", "GUV-2511", "GUV-3511"] self.guvtype_cb.addItems(mylist) self.guvtype_cb.setCurrentIndex(mylist.index(self.guvtype_str)) ############################################## self.runstopButton = QPushButton("START", self) self.clearButton = QPushButton("Clear", self) ############################################## schroll_lbl = QLabel("Schroll elapsed time ", self) self.combo0 = QComboBox(self) mylist0 = ["100", "200", "400", "600", "800", "1000", "1500", "2000"] self.combo0.addItems(mylist0) self.combo0.setCurrentIndex(mylist0.index(str(self.schroll_pts))) ############################################## self.cb_logdata = QCheckBox('Log data to file', self) self.cb_logdata.toggle() self.cb_logdata.setChecked(self.log_guv_check) #self.cb_logdata.setLayoutDirection(Qt.RightToLeft) self.file_edit = QLineEdit(self.log_guv_str, self) self.file_edit.setStyleSheet("color: blue") if self.cb_logdata.isChecked(): self.file_edit.setEnabled(True) else: self.file_edit.setEnabled(False) self.lcd = QLCDNumber(self) self.lcd.setStyleSheet("color: red") self.lcd.setFixedWidth(170) self.lcd.setFixedHeight(35) self.lcd.setSegmentStyle(QLCDNumber.Flat) self.lcd.setNumDigits(11) self.time_str = time.strftime("%y%m%d-%H%M") self.lcd.display(self.time_str) ############################################## g0_1 = QGridLayout() g0_1.addWidget(ipport, 0, 0) g0_1.addWidget(self.ipportEdit, 0, 1) g0_1.addWidget(tcpport, 0, 2) g0_1.addWidget(self.tcpportEdit, 0, 3) g0_1.addWidget(guvtype_lbl, 0, 4) g0_1.addWidget(self.guvtype_cb, 0, 5) g0_2 = QGridLayout() g0_2.addWidget(schroll_lbl, 0, 0) g0_2.addWidget(self.combo0, 0, 1) g0_2.addWidget(self.runstopButton, 0, 2) g0_2.addWidget(self.clearButton, 0, 3) g0_2.addWidget(self.cb_logdata, 1, 0) g0_2.addWidget(self.lcd, 1, 1) g0_4 = QVBoxLayout() g0_4.addLayout(g0_1) g0_4.addLayout(g0_2) g0_4.addWidget(self.file_edit) ############################################## # set graph and toolbar to a new vertical group vcan self.pw1 = pg.PlotWidget() self.pw1.setFixedWidth(600) ############################################## # create table self.tableWidget = self.createTable() ############################################## # SET ALL VERTICAL COLUMNS TOGETHER vbox = QVBoxLayout() vbox.addLayout(g0_4) vbox.addWidget(self.pw1) hbox = QVBoxLayout() hbox.addLayout(vbox) hbox.addWidget(self.tableWidget) self.threadpool = QThreadPool() print("Multithreading in the GUV dialog with maximum %d threads" % self.threadpool.maxThreadCount()) self.isRunning = False self.setLayout(hbox) self.setWindowTitle("Test GUV") # PLOT 2 settings # create plot and add it to the figure canvas self.p1 = self.pw1.plotItem self.curves = [] colors = itertools.cycle(["r", "b", "g", "y", "m", "c", "w"]) for i in range(20): mycol = next(colors) self.curves.append( self.p1.plot(pen=pg.mkPen(color=mycol), symbol='s', symbolPen=mycol, symbolBrush=mycol, symbolSize=4)) # create plot and add it to the figure self.p0_1 = pg.ViewBox() self.curve2 = pg.PlotCurveItem(pen='r') self.p0_1.addItem(self.curve2) # connect respective axes to the plot #self.p1.showAxis('left') self.p1.getAxis('left').setLabel("Power density", units="", color='yellow') self.p1.showAxis('right') self.p1.getAxis('right').setLabel("Arb unit", units="", color='red') self.p1.scene().addItem(self.p0_1) self.p1.getAxis('right').linkToView(self.p0_1) self.p0_1.setXLink(self.p1) self.p1.getAxis('bottom').setLabel("Time passed", units="s", color='yellow') # Use automatic downsampling and clipping to reduce the drawing load self.pw1.setDownsampling(mode='peak') self.pw1.setClipToView(True) # Initialize and set titles and axis names for both plots self.clear_vars_graphs() self.combo0.activated[str].connect(self.onActivated0) self.guvtype_cb.activated[str].connect(self.onActivated1) self.cb_logdata.toggled.connect(self.logdata) # run or cancel the main script self.runstopButton.clicked.connect(self.runstop) self.clearButton.clicked.connect(self.set_clear) self.clearButton.setEnabled(False)
self.setPos(self.mapToParent(ev.pos()) - self.pressDelta) rect = movableRect(QtCore.QRectF(0, 0, 0.5, 0.5)) rect.setPen(pg.mkPen(100, 200, 100)) vb.addItem(rect) l.addItem(vb, 0, 1) gv.centralWidget.setLayout(l) # # yScale = pg.AxisItem(orientation='left', linkView=vb) # l.addItem(yScale, 0, 0) p2 = pg.ViewBox(border='m') p2.addItem(pg.PlotCurveItem([300, 160, 300, 200, 200, 100], pen='m')) l.addItem(p2, 1, 1) p3 = pg.ViewBox(border='b') p3.addItem(pg.PlotCurveItem([00, 160, 300, 200, 200, 100], pen='c')) l.addItem(p3, 2, 1) p4 = pg.ViewBox(border='b') p4.addItem(pg.PlotCurveItem([00, 160, 300, 200, 200, 100], pen='m')) l.addItem(p4, 3, 1) # # xScale4 = pg.AxisItem(orientation='bottom') # l.addItem(xScale4, 0, 1) # yScale4 = pg.AxisItem(orientation='left') # l.addItem(yScale4, 1, 0)
IGNORE = 0 app = QtGui.QApplication([]) view = pg.GraphicsView() layout = pg.GraphicsLayout(border=(100, 100, 100)) view.setCentralItem(layout) view.show() view.setWindowTitle('Visualization') view.resize(800, 300) left_plot = layout.addPlot(title='Left Channel', colspan=3) left_plot.setRange(yRange=[0, 1000]) left_plot.disableAutoRange(axis=pg.ViewBox.YAxis) left_line_p = pg.mkPen((255, 0, 0), width=2) left_line = pg.PlotCurveItem(pen=left_line_p) left_plot.addItem(left_line) right_line_p = pg.mkPen((0, 0, 255), width=2) right_line = pg.PlotCurveItem(pen=right_line_p) left_plot.addItem(right_line) fft_freq = np.fft.fftfreq(CHUNK, 1. / RATE)[IGNORE:int(CHUNK / 2)] def fft(data): fft_wave = np.fft.fft(data) fft_wave = fft_wave[:int(CHUNK / 2)] / CHUNK # fft_wave = np.round(fft_wave) # rfft = np.fft.rfft(data)
import pyqtgraph as pg from pyqtgraph.Qt import QtGui, QtCore # Create GUI window app = QtGui.QApplication([]) view = pg.GraphicsView() layout = pg.GraphicsLayout(border=(100,100,100)) view.setCentralItem(layout) view.show() view.setWindowTitle('Visualization') view.resize(800,600) # Mel filterbank plot fft_plot = layout.addPlot(title='Filterbank Output', colspan=3) fft_plot.setRange(yRange=[-0.1, 1.2]) fft_plot.disableAutoRange(axis=pg.ViewBox.YAxis) x_data = np.array(range(1, config.N_FFT_BINS + 1)) mel_curve = pg.PlotCurveItem() mel_curve.setData(x=x_data, y=x_data*0) fft_plot.addItem(mel_curve) # Visualization plot layout.nextRow() led_plot = layout.addPlot(title='Visualization Output', colspan=3) led_plot.setRange(yRange=[-5, 260]) led_plot.disableAutoRange(axis=pg.ViewBox.YAxis) # Pen for each of the color channel curves r_pen = pg.mkPen((255, 30, 30, 200), width=4) g_pen = pg.mkPen((30, 255, 30, 200), width=4) b_pen = pg.mkPen((30, 30, 255, 200), width=4) # Color channel curves r_curve = pg.PlotCurveItem(pen=r_pen) g_curve = pg.PlotCurveItem(pen=g_pen) b_curve = pg.PlotCurveItem(pen=b_pen)
def configure_gui(): import pyqtgraph as pg from pyqtgraph.Qt import QtGui, QtCore #Define global variables global mel_curve global led_plot global r_pen global g_pen global b_pen global r_curve global g_curve global b_curve global x_data global app # Create GUI window app = QtGui.QApplication([]) view = pg.GraphicsView() layout = pg.GraphicsLayout(border=(100, 100, 100)) view.setCentralItem(layout) view.show() view.setWindowTitle('Visualization') view.resize(800, 600) # Mel filterbank plot fft_plot = layout.addPlot(title='Filterbank Output', colspan=4) fft_plot.setRange(yRange=[-0.1, 1.2]) fft_plot.disableAutoRange(axis=pg.ViewBox.YAxis) x_data = np.array(range(1, config.N_FFT_BINS + 1)) mel_curve = pg.PlotCurveItem() mel_curve.setData(x=x_data, y=x_data * 0) fft_plot.addItem(mel_curve) # Visualization plot layout.nextRow() led_plot = layout.addPlot(title='Visualization Output', colspan=4) led_plot.setRange(yRange=[-5, 260]) led_plot.disableAutoRange(axis=pg.ViewBox.YAxis) # Pen for each of the color channel curves r_pen = pg.mkPen((255, 30, 30, 200), width=4) g_pen = pg.mkPen((30, 255, 30, 200), width=4) b_pen = pg.mkPen((30, 30, 255, 200), width=4) # Color channel curves r_curve = pg.PlotCurveItem(pen=r_pen) g_curve = pg.PlotCurveItem(pen=g_pen) b_curve = pg.PlotCurveItem(pen=b_pen) # Define x data x_data = np.array(range(1, config.N_PIXELS + 1)) r_curve.setData(x=x_data, y=x_data * 0) g_curve.setData(x=x_data, y=x_data * 0) b_curve.setData(x=x_data, y=x_data * 0) # Add curves to plot led_plot.addItem(r_curve) led_plot.addItem(g_curve) led_plot.addItem(b_curve) # Frequency range label freq_label = pg.LabelItem('') # Frequency slider def freq_slider_change(tick): minf = freq_slider.tickValue(0)**2.0 * (config.MIC_RATE / 2.0) maxf = freq_slider.tickValue(1)**2.0 * (config.MIC_RATE / 2.0) t = 'Frequency range: {:.0f} - {:.0f} Hz'.format(minf, maxf) freq_label.setText(t) config.MIN_FREQUENCY = minf config.MAX_FREQUENCY = maxf dsp.create_mel_bank() freq_slider = pg.TickSliderItem(orientation='bottom', allowAdd=False) freq_slider.addTick((config.MIN_FREQUENCY / (config.MIC_RATE / 2.0))**0.5) freq_slider.addTick((config.MAX_FREQUENCY / (config.MIC_RATE / 2.0))**0.5) freq_slider.tickMoveFinished = freq_slider_change freq_label.setText('Frequency range: {} - {} Hz'.format( config.MIN_FREQUENCY, config.MAX_FREQUENCY)) # Effect selection active_color = '#16dbeb' inactive_color = '#FFFFFF' def energy_click(x): global visualization_effect visualization_effect = visualize_energy energy_label.setText('Energy', color=active_color) energy_spectr_label.setText('Energy spectr', color=inactive_color) scroll_label.setText('Scroll', color=inactive_color) spectrum_label.setText('Spectrum', color=inactive_color) def energy_spectrum_click(x): global visualization_effect visualization_effect = visualize_energy_spectrum energy_label.setText('Energy', color=inactive_color) energy_spectr_label.setText('Energy spectr', color=active_color) scroll_label.setText('Scroll', color=inactive_color) spectrum_label.setText('Spectrum', color=inactive_color) def scroll_click(x): global visualization_effect visualization_effect = visualize_scroll energy_label.setText('Energy', color=inactive_color) energy_spectr_label.setText('Energy spectr', color=inactive_color) scroll_label.setText('Scroll', color=active_color) spectrum_label.setText('Spectrum', color=inactive_color) def spectrum_click(x): global visualization_effect visualization_effect = visualize_spectrum energy_label.setText('Energy', color=inactive_color) energy_spectr_label.setText('Energy spectr', color=inactive_color) scroll_label.setText('Scroll', color=inactive_color) spectrum_label.setText('Spectrum', color=active_color) # Create effect "buttons" (labels with click event) energy_label = pg.LabelItem('Energy') energy_spectr_label = pg.LabelItem('Energy Spectr') scroll_label = pg.LabelItem('Scroll') spectrum_label = pg.LabelItem('Spectrum') energy_label.mousePressEvent = energy_click energy_spectr_label.mousePressEvent = energy_spectrum_click scroll_label.mousePressEvent = scroll_click spectrum_label.mousePressEvent = spectrum_click energy_click(0) # Layout layout.nextRow() layout.addItem(freq_label, colspan=4) layout.nextRow() layout.addItem(freq_slider, colspan=4) layout.nextRow() layout.addItem(energy_label) layout.addItem(scroll_label) layout.addItem(spectrum_label) layout.addItem(energy_spectr_label)
def setup(self): ## Dummy data Structures (override in func:self.load_data()) self.hyperspec_data = np.arange(10 * 10 * 34).reshape((10, 10, 34)) self.display_image = self.hyperspec_data.sum( -1) # np.random.rand(10,10) self.spec_x_array = np.arange(34) # Call :func:set_scalebar_params() during self.load_data() to add a scalebar! self.scalebar_type = None # Will be filled derived maps and images self.display_images = dict() self.spec_x_arrays = dict() ## Graphs and Interface self.ui = self.dockarea = dockarea.DockArea() self.imview = pg.ImageView() self.imview.getView().invertY(False) # lower left origin self.image_dock = self.dockarea.addDock(name='Image', widget=self.imview) self.graph_layout = pg.GraphicsLayoutWidget() self.spec_dock = self.dockarea.addDock(name='Spec Plot', widget=self.graph_layout) self.line_colors = ['w', 'r', 'g', 'b', 'y', 'm', 'c'] self.spec_plot = self.graph_layout.addPlot() self.spec_plot.setLabel('left', 'Intensity', units='counts') self.rect_plotdata = self.spec_plot.plot(y=[0, 2, 1, 3, 2], pen=self.line_colors[0]) self.point_plotdata = self.spec_plot.plot(y=[0, 2, 1, 3, 2], pen=self.line_colors[1]) self.point_plotdata.setZValue(-1) #correlation plot self.corr_layout = pg.GraphicsLayoutWidget() self.corr_plot = self.corr_layout.addPlot() self.corr_plotdata = pg.ScatterPlotItem(x=[0, 1, 2, 3, 4], y=[0, 2, 1, 3, 2], size=17, pen=pg.mkPen(None), brush=pg.mkBrush( 255, 255, 255, 60)) self.corr_plot.addItem(self.corr_plotdata) self.corr_dock = self.dockarea.addDock(name='correlation', widget=self.corr_layout, position='below', relativeTo=self.spec_dock) self.corr_plotdata.sigClicked.connect(self.corr_plot_clicked) self.spec_dock.raiseDock() # Rectangle ROI self.rect_roi = pg.RectROI([20, 20], [20, 20], pen=self.line_colors[0]) self.rect_roi.addTranslateHandle((0.5, 0.5)) self.imview.getView().addItem(self.rect_roi) self.rect_roi.sigRegionChanged[object].connect(self.on_change_rect_roi) # Point ROI self.circ_roi = pg.CircleROI((0, 0), (2, 2), movable=True, pen=self.line_colors[1]) #self.circ_roi.removeHandle(self.circ_roi.getHandles()[0]) h = self.circ_roi.addTranslateHandle((0.5, .5)) h.pen = pg.mkPen(pen=self.line_colors[1]) h.update() self.imview.getView().addItem(self.circ_roi) self.circ_roi.removeHandle(0) self.circ_roi_plotline = pg.PlotCurveItem([0], pen=self.line_colors[1]) self.imview.getView().addItem(self.circ_roi_plotline) self.circ_roi.sigRegionChanged[object].connect(self.on_update_circ_roi) #font font = QtGui.QFont("Times", 12) font.setBold(True) #settings self.default_display_image_choices = ['default', 'sum'] self.settings.New('display_image', str, choices=self.default_display_image_choices, initial='default') self.settings.display_image.add_listener(self.on_change_display_image) self.default_x_axis_choices = ['default', 'index'] self.x_axis = self.settings.New('x_axis', str, initial='default', choices=self.default_x_axis_choices) self.x_axis.add_listener(self.on_change_x_axis) self.norm_data = self.settings.New('norm_data', bool, initial=False) self.bg_subtract = self.settings.New('bg_subtract', str, initial='None', choices=('None', 'bg_slice', 'costum_const')) self.bg_counts = self.settings.New('bg_value', initial=0, unit='cts/bin') self.settings.New('default_view_on_load', bool, initial=True) self.binning = self.settings.New('binning', int, initial=1, vmin=1) self.spatial_binning = self.settings.New('spatial_binning', int, initial=1, vmin=1) self.cor_X_data = self.settings.New( 'cor_X_data', str, choices=self.default_display_image_choices, initial='default') self.cor_Y_data = self.settings.New( 'cor_Y_data', str, choices=self.default_display_image_choices, initial='sum') # data slicers self.x_slicer = RegionSlicer(self.spec_plot, name='x_slice', brush=QtGui.QColor(0, 255, 0, 70), ZValue=10, font=font, initial=[100, 511]) self.bg_slicer = RegionSlicer(self.spec_plot, name='bg_slice', slicer_updated_func=self.update_display, brush=QtGui.QColor(255, 255, 255, 70), ZValue=11, font=font, initial=[0, 80], label_line=0) # peakutils self.peakutils_settings = LQCollection() self.show_peak_line = self.peakutils_settings.New('show_peak_line', bool, initial=False) self.show_peak_line.add_listener(self.update_display) self.baseline_deg = self.peakutils_settings.New('baseline_deg', int, initial=0, vmin=-1, vmax=100) self.baseline_deg.add_listener(self.update_display) self.thres = self.peakutils_settings.New('thres', float, initial=0.5, vmin=0, vmax=1) self.thres.add_listener(self.update_display) self.peakutils_settings.New('unique_solution', bool, initial=False) self.peakutils_settings.New('min_dist', int, initial=-1) self.peakutils_settings.New('gaus_fit_refinement', bool, initial=True) self.peakutils_settings.New('ignore_phony_refinements', bool, initial=True) self.base_plotdata = self.spec_plot.plot(y=[0, 2, 1, 3, 2], pen=self.line_colors[2]) self.peak_lines = [] # Settings Docks self.settings_dock = self.dockarea.addDock(name='settings', position='left', relativeTo=self.image_dock) self.settings_widgets = [ ] # Hack part 1/2: allows to use settings.New_UI() and have settings defined in scan_specific_setup() self.settings_widgets.append(self.x_slicer.New_UI()) self.settings_widgets.append(self.bg_slicer.New_UI()) self.scan_specific_setup() self.generate_settings_ui( ) # Hack part 2/2: Need to generate settings after scan_specific_setup() self.peakutils_dock = self.dockarea.addDock( name='PeakUtils', position='below', relativeTo=self.settings_dock) self.peakutils_dock.addWidget(self.peakutils_settings.New_UI()) self.settings_dock.raiseDock() self.settings_dock.setStretch(x=0, y=0) self.peakutils_dock.setStretch(x=0, y=0) self.image_dock.setStretch(x=100, y=1) #self.settings_dock.widgetArea.setStyleSheet('Dock > QWidget {border:0px; border-radius:0px}') #self.peakutils_dock.widgetArea.setStyleSheet('Dock > QWidget {border:0px; border-radius:0px}') ### LQ Connections self.norm_data.add_listener(self.update_display) self.bg_subtract.add_listener(self.update_display) self.bg_counts.add_listener(self.update_display) self.binning.add_listener(self.update_display) self.spatial_binning.add_listener(self.bin_spatially) self.cor_X_data.add_listener(self.on_change_corr_settings) self.cor_Y_data.add_listener(self.on_change_corr_settings) self.bg_slicer.activated.add_listener( lambda: self.bg_subtract.update_value('bg_slice') if self.bg_slicer.activated.val else None) self.show_lines = ['show_circ_line', 'show_rect_line'] for x in self.show_lines: lq = self.settings.New(x, bool, initial=True) lq.add_listener(self.on_change_show_lines)
def __init__(self, raw_signal, dt): super().__init__() self._logs = [] self.l = QGridLayout(self) #################### ### Create Signal #################### self.signal = Signal(raw_signal=raw_signal, dt=dt) self.signalPlot = pg.PlotWidget() self.signalCurve1 = self.signalPlot.plot(self.signal.t, self.signal.raw_signal) #################### ### Filter Signal #################### self.signal.filterSignal() self.signalCurve2 = self.signalPlot.plot(self.signal.t, self.signal.filtered_signal, pen=pg.mkPen('m')) #################### ### Detect cycles #################### self.signal.detectCycles() self.signalPlot.plot( self.signal.t[self.signal.raw_peaks[0]], self.signal.filtered_signal[self.signal.raw_peaks[0]], pen=pg.mkPen('y')) #################### ### Detect opening and closing phases #################### self.signal.detectPhases(use_filtered_signal=False) i = 0 cs = [(241, 196, 15), (231, 76, 60)] for o, c in zip(self.signal.opening, self.signal.closing): print(o, c) i1 = pg.PlotCurveItem(self.signal.t[o:c], np.zeros_like(self.signal.t[o:c])) i2 = pg.PlotCurveItem(self.signal.t[o:c], self.signal.raw_signal[o:c]) between = pg.FillBetweenItem(i1, i2, brush=cs[i % len(cs)]) self.signalPlot.addItem(between) i += 1 #################### ### FFT, Cepstrum #################### self.l.addWidget(QLabel("Signal")) self.l.addWidget(self.signalPlot) self.signal.computeFFT(use_hanning=True, use_filtered_signal=True) self.l.addWidget(QLabel("Power Spectrum")) self.powerSpectrum = pg.PlotWidget() self.l.addWidget(self.powerSpectrum) self.powerSpectrum.plot(*self.signal.getPowerSpectrum()) self.signal.computeCepstrum() self.l.addWidget(QLabel("Cepstrum")) self.Cepstrum = pg.PlotWidget() self.l.addWidget(self.Cepstrum) self.Cepstrum.plot(*self.signal.getCepsturm()) ####################### ### Compute some parameters ####################### print(F0fromCycles(self.signal.T)) print(jitterPercent(self.signal.T)) print(shimmerPercent(self.signal.A)) print( cepstralPeakProminence(self.signal.raw_signal, 1 / self.signal.dt)) self.setWindowTitle("Analysis Platform")
def __init__(self, parent=None): super(GraphWidget, self).__init__(parent=parent) self.speed = 1 self.index = 0 self.plotSize = 500 self.isZoomed = True self.state = NORMAL_STATE self.horizontalLayout = QtGui.QHBoxLayout(self) self.dataGenerator = DataGenerator() self.w1 = SpeedButton(self.dataGenerator) self.w1.fullPlotButton.clicked.connect(self.showFullPlot) self.w1.zoomButton.clicked.connect(self.toggleZoom) self.w1.stopButton.clicked.connect(self.reset) # self.w2 = Slider(-1, 1) # self.horizontalLayout.addWidget(self.w2) # self.w3 = Slider(-10, 10) # self.horizontalLayout.addWidget(self.w3) # self.w4 = Slider(-10, 10) # self.horizontalLayout.addWidget(self.w4) self.win = pg.GraphicsWindow(title="UFLS Demo") self.win2 = pg.GraphicsWindow(title="UFLS Demo") #self.update() #self.w1.slider.valueChanged.connect(self.setInterval) self.normalReadings = [60.0 for _ in range(PLOT_SIZE)] self.rasReadings = [60.0 for _ in range(PLOT_SIZE)] #Print the difference between times and see if there's any hope, or else take the average of times #time_list = [(self.normalTimes[i+1] - self.normalTimes[i]).microseconds for i in range(len(self.normalTimes) - 1) ] #print float(sum(time_list)/1000)/float(len(time_list)) #self.win.resize(1000, 600) pg.setConfigOptions(antialias = True) self.vlayout = QtGui.QVBoxLayout() self.vlayout.addWidget(self.win) self.vlayout.addWidget(self.win2) self.horizontalLayout.addLayout(self.vlayout) self.rangeStart = 0 self.rangeEnd = 500 self.rangeCount = 1 self.tickList = [(x, x) for x in range(0, 500, 200)] self.normalPlot = self.win.addPlot(title = "<h2>Without RAS</h2>") self.normalCurve = self.normalPlot.plot(pen = pg.mkPen('r', width = 3)) self.normalPlot.setYRange(49, 60, padding = 0.1, update = False) self.normalPlot.setLabel("left", "Frequency", units = "Hz") self.normalPlot.setLabel("bottom", "Time (ms) ") self.rasPlot = self.win.addPlot(title = "<h2>With RAS</h2>") self.rasPlot.getAxis('bottom').setTicks([self.tickList]) self.rasCurve = self.rasPlot.plot(pen = pg.mkPen('g', width = 3)) self.rasPlot.setYRange(58.1, 60, padding = 0.1, update = False) self.rasPlot.setLabel("left", "Frequency", units = "Hz") self.rasPlot.setLabel("bottom", "Time (ms)") self.bothPlot = self.win2.addPlot(title = "<h2>Comparison</h2>") self.bothPlot.setYRange(49, 60, padding = 0.1, update = False) self.bothPlot.setLabel("left", "Frequency", units = "Hz") self.bothPlot.setLabel("bottom", "Time (ms)") self.bothPlot.getAxis('bottom').setTicks([self.tickList]) self.bothPlot.getAxis('bottom').setGrid(120) self.bothPlot.getAxis('left').setGrid(200) self.normalPlot.getAxis('bottom').setGrid(120) self.normalPlot.getAxis('left').setGrid(200) self.rasPlot.getAxis('bottom').setGrid(120) self.rasPlot.getAxis('left').setGrid(200) self.bothNormalCurve = pg.PlotCurveItem() self.bothNormalCurve.setPen(pg.mkPen('r', width = 3)) self.bothRasCurve = pg.PlotCurveItem() self.bothRasCurve.setPen(pg.mkPen('g', width = 3)) self.bothPlot.addItem(self.bothNormalCurve) self.bothPlot.addItem(self.bothRasCurve) self.systemStateLayout = SystemStateWidget(self) self.horizontalLayout.addWidget(self.systemStateLayout) #self.horizontalLayout.addWidget(self.w1) #self.lineDiagramLabel = QtGui.QLabel(self) #self.lineDiagramPixmap = QtGui.QPixmap(LINE_DIAGRAM) #self.lineDiagramLabel.setPixmap(self.lineDiagramPixmap.scaledToHeight(550)) #self.horizontalLayout.addWidget(self.lineDiagramLabel) self.timer = pg.QtCore.QTimer() self.timer.timeout.connect(self.update) self.timer.start(TIMEOUT)
def reset(self): self._residue_plot.getPlotItem().clear() self._residue_plot.addItem(pg.PlotCurveItem())
def __init__(self): # Set up the UI super(LoudnessGui, self).__init__(None) self.audioRunning = False self.setGeometry(0, 0, 800, 600) self.layout = QtGui.QGridLayout(self) self.startButton = QtGui.QPushButton( "Start Audio") # , self.centralWidget ) #self.startButton.setMinimumSize( 200, 60 ) self.stopButton = QtGui.QPushButton( "Stop Audio") # , self.centralWidget ) #self.stopButton.setMinimumSize( 200, 60 ) self.layout.addWidget( self.startButton, 0, 0) # , QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter ) self.layout.addWidget( self.stopButton, 0, 1) # , QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter ) self.loudnessLabel = QtGui.QLabel('--- dB') # , self.centralWidget ) #self.loudnessLabel.setMinimumSize( 200, 60 ) self.layout.addWidget( self.loudnessLabel, 0, 2) # , QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter ) self.startButton.clicked.connect(self.startAudio) self.stopButton.clicked.connect(self.stopAudio) self.plotWidget = pg.PlotWidget() self.plotWidget.setRange(xRange=(0, numPlotPoints - 1), yRange=(-130.0, 6.0)) self.layout.addWidget(self.plotWidget, 1, 0, 1, 4) self.loudnessPlot = pg.PlotCurveItem() self.plotWidget.addItem(self.loudnessPlot) self.loudnessHist = -120.0 * np.ones(numPlotPoints, dtype=np.float32) self.loudnessPlot.setData(self.loudnessHist) # %% Setup the DSP part self.context = visr.SignalFlowContext( period=blockSize, samplingFrequency=samplingFrequency) self.meter = LoudnessMeter(self.context, 'meter', None, numChannels, measurePeriod=0.4, audioOut=True) audioOptions = ai.AudioInterface.Configuration(numChannels, numChannels, samplingFrequency, blockSize) self.audioInterface = ai.AudioInterfaceFactory.create( audioInterfaceName, audioOptions, audioBackendOptions) self.flow = rrl.AudioSignalFlow(self.meter) self.loudnessPort = self.flow.parameterSendPort('loudnessOut') self.readTimer = QtCore.QTimer(self) self.readTimer.timeout.connect(self.getMeterValues) self.readTimer.setSingleShot(False) self.readTimer.setInterval(100) # ms
def setup_plot(self, scoreindex, scores, nulldist=None): """ Setup the score histogram plot Parameters ---------- scoreindex : int Score index (into OWFeatureSelection.Scores) scores : (N, ) array The scores obtained nulldist (P, N) array optional The scores obtained under P permutations of labels. """ score_name, side, test_type, _ = self.Scores[scoreindex] low, high = self.thresholds.get(score_name, (-np.inf, np.inf)) validmask = np.isfinite(scores) validscores = scores[validmask] nbins = int(max(np.ceil(np.sqrt(len(validscores))), 20)) freq, edges = np.histogram(validscores, bins=nbins) self.histogram.setHistogramCurve( pg.PlotCurveItem(x=edges, y=freq, stepMode=True, pen=pg.mkPen("b", width=2))) if nulldist is not None: nulldist = nulldist.ravel() validmask = np.isfinite(nulldist) validnulldist = nulldist[validmask] nullbins = edges # XXX: extend to the full range of nulldist nullfreq, _ = np.histogram(validnulldist, bins=nullbins) nullfreq = nullfreq * (freq.sum() / nullfreq.sum()) nullitem = pg.PlotCurveItem(x=nullbins, y=nullfreq, stepMode=True, pen=pg.mkPen((50, 50, 50, 100))) # Ensure it stacks behind the main curve nullitem.setZValue(nullitem.zValue() - 10) self.histogram.addItem(nullitem) # Restore saved thresholds eps = np.finfo(float).eps minx, maxx = edges[0] - eps, edges[-1] + eps low, high = max(low, minx), min(high, maxx) if side == OWDifferentialExpression.LowTail: mode = Histogram.Low elif side == OWDifferentialExpression.HighTail: mode = Histogram.High elif side == OWDifferentialExpression.TwoTail: mode = Histogram.TwoSided else: assert False self.histogram.setSelectionMode(mode) self.histogram.setBoundary(low, high) # If this is a two sample test add markers to the left and right # plot indicating which group is over-expressed in that part if test_type == OWDifferentialExpression.TwoSampleTest and \ side == OWDifferentialExpression.TwoTail: maxy = np.max(freq) # XXX: Change use of integer constant if scoreindex == 0: # fold change is centered on 1.0 x1, y1 = (minx + 1) / 2, maxy x2, y2 = (maxx + 1) / 2, maxy else: x1, y1 = minx / 2, maxy x2, y2 = maxx / 2, maxy grp, selected_indices = self.selected_split() values = grp.values selected_values = [values[i] for i in selected_indices] left = ", ".join(v for v in values if v not in selected_values) right = ", ".join(v for v in selected_values) labelitem = pg.TextItem(left, color=(40, 40, 40)) labelitem.setPos(x1, y1) self.histogram.addItem(labelitem) labelitem = pg.TextItem(right, color=(40, 40, 40)) labelitem.setPos(x2, y2) self.histogram.addItem(labelitem) miny, maxy = 0.0, np.max(freq) if nulldist is not None: maxy = max(np.max(nullfreq), maxy) if not np.any(np.isnan([maxx, minx, maxy])): self.histogram.setRange(QRectF(minx, miny, maxx - minx, maxy - miny), padding=0.05)
def __init__(self): # Setup UI QtGui.QWidget.__init__(self) self.ui = Ui_MainWidget() self.ui.setupUi(self) self.setWindowTitle("CPIR Animal Monitor v" + VERSION_STRING) # CONSTANTS self.MIN_DATA_FETCH_PERIOD = 0.0005 self.MIN_PLOT_UPDATE_PERIOD = 0.25 # A little more than 60Hz self.PLOT_TIME_RANGE = 6 # Total seconds of display self.QUEUE_SIZE = int( round(self.PLOT_TIME_RANGE / self.MIN_DATA_FETCH_PERIOD)) self.TIME_SHIFT_PCT = 0.75 self.TEXT_UPDATE_PERIOD = 1 self.NEXT_TEXT_UPDATE = 1 self.SLOW_UPDATE_PERIOD = 5 self.NEXT_SLOW_UPDATE = 1 self.canulaPressureSlope = 1 self.canulaPressureIntercept = 0 # Create data fetching process self.dataFetcher = df.TimedDataFetcher(self.MIN_DATA_FETCH_PERIOD) # Setup queues for plotting data as all NaNs self.time_queue = np.zeros(self.QUEUE_SIZE) self.canula_queue = np.zeros(self.QUEUE_SIZE) #self.trigger_queue=np.zeros(self.QUEUE_SIZE) # Setup for slow plot data self.slow_time_queue = [] self.slow_minPressure_queue = [] self.slow_maxPressure_queue = [] # self.slow_tidalVolume_queue = [] self.ui.fastUpdatePeriod.valueChanged.connect(self.updatePlotTimeRange) self.ui.slowUpdatePeriod.valueChanged.connect( self.updateSlowPlotRefreshRate) # Initialize graphs self.ui.pressurePlot.setMouseEnabled(x=False, y=True) self.ui.pressurePlot.enableAutoRange(x=False, y=True) self.ui.pressurePlot.setLabel('left', "Canula Pressure", units='cmH20') self.ui.pressurePlot.getAxis('left').enableAutoSIPrefix(False) self.ui.pressurePlot.setLabel('bottom', "Time", units='sec') self.minXlim = 0 self.updatePlotTimeRange() self.updateSlowPlotRefreshRate() self.maxXlim = self.minXlim + self.PLOT_TIME_RANGE self.ui.pressurePlot.setXRange(0, self.PLOT_TIME_RANGE, padding=0) # Initialize pressure line self.pressureLine = pg.PlotCurveItem(x=[],y=[], \ pen=pg.mkPen({'color': "0FF"}),antialias=True) self.ui.pressurePlot.addItem(self.pressureLine) # Initialize Min and Max pressure axis self.pressureSlowPlot = self.ui.vitalsPlot.plotItem self.pressureSlowPlot.getAxis('left').setLabel("Canula Pressure", units='cmH20') self.pressureSlowPlot.getAxis('left').enableAutoSIPrefix(False) #self.pressureSlowPlot.showAxis('right') # Add empty lines self.minPressureLine = pg.PlotCurveItem(x=[],y=[], \ pen=pg.mkPen({'color': "FFF"}),antialias=True) self.maxPressureLine = pg.PlotCurveItem(x=[],y=[], \ pen=pg.mkPen({'color': "FFF"}),antialias=True) self.pressureSlowPlot.addItem(self.minPressureLine) self.pressureSlowPlot.addItem(self.maxPressureLine) # Setup dynamic plotting process self.isGraphing = False self.timer = pg.QtCore.QTimer() self.timer.timeout.connect(self.updateUI) self.timer.start(self.MIN_PLOT_UPDATE_PERIOD)
def _get_profiles_curve(self): x, y, con = self.__get_disconnected_curve_data(self.y_data) pen = self.make_pen(self.color) curve = pg.PlotCurveItem(x=x, y=y, connect=con, pen=pen) Updater.update_lines([curve], **self.graph.parameter_setter.line_settings) return curve