def setPlot(self, plot): """setting the ScatterPlotWidget for the node""" self.plot = plot # ScatterPlotItem for the current position of the 'Pointer' self.spiPos = pg.ScatterPlotItem(size=3, pen=pg.mkPen(None), brush=pg.mkBrush(255, 255, 255, 255)) # ScatterPlotItem for the path, while drawing self.spiPath = pg.ScatterPlotItem(size=3, pen=pg.mkPen(None), brush=pg.mkBrush(255, 0, 0, 255)) # ScatterPlotItem for the recognized template self.spiTemplate = pg.ScatterPlotItem(size=3, pen=pg.mkPen(None), brush=pg.mkBrush(0, 100, 255, 255)) # setting the x and y range to width and height of the ir camera field self.plot.setXRange(0, 1024) self.plot.setYRange(0, 768) # appending legend to display which color shows which data self.legend = pg.LegendItem(offset=(-1, 1)) self.legend.addItem(self.spiPos, 'position') self.legend.addItem(self.spiPath, 'path') self.legend.addItem(self.spiTemplate, 'template') self.legend.setParentItem(self.plot)
def _setup_plot(self): self.plot.clear() explained_ratio = self._variance_ratio explained = self._cumulative p = min(len(self._variance_ratio), self.maxp) self.plot.plot(numpy.arange(p), explained_ratio[:p], pen=pg.mkPen(QColor(Qt.red), width=2), antialias=True, name="Variance") self.plot.plot(numpy.arange(p), explained[:p], pen=pg.mkPen(QColor(Qt.darkYellow), width=2), antialias=True, name="Cumulative Variance") cutpos = self._nselected_components() - 1 self._line = pg.InfiniteLine( angle=90, pos=cutpos, movable=True, bounds=(0, p - 1)) self._line.setCursor(Qt.SizeHorCursor) self._line.setPen(pg.mkPen(QColor(Qt.black), width=2)) self._line.sigPositionChanged.connect(self._on_cut_changed) self.plot.addItem(self._line) self.plot_horlines = ( pg.PlotCurveItem(pen=pg.mkPen(QColor(Qt.blue), style=Qt.DashLine)), pg.PlotCurveItem(pen=pg.mkPen(QColor(Qt.blue), style=Qt.DashLine))) self.plot_horlabels = ( pg.TextItem(color=QColor(Qt.black), anchor=(1, 0)), pg.TextItem(color=QColor(Qt.black), anchor=(1, 1))) for item in self.plot_horlabels + self.plot_horlines: self.plot.addItem(item) self._set_horline_pos() self.plot.setRange(xRange=(0.0, p - 1), yRange=(0.0, 1.0)) self._update_axis()
def add_legends(self): style = pg.PlotDataItem(pen=pg.mkPen({'color':'1A64B0','width': 8})) self.plotItem.legend.addItem(style, "In ORF") style = pg.PlotDataItem(pen=pg.mkPen({'color':'777777','width': 8})) self.plotItem.legend.addItem(style, "Not in CDS") style = pg.PlotDataItem(pen=pg.mkPen({'color':'D13A26','width': 8})) self.plotItem.legend.addItem(style, "Start/Stop of CDS")
def test_update_coordinates(self): graph = self.graph xy = self.xy = (np.array([1, 2]), np.array([3, 4])) graph.reset_graph() scatterplot_item = graph.scatterplot_item scatterplot_item_sel = graph.scatterplot_item_sel data = scatterplot_item.data np.testing.assert_almost_equal(scatterplot_item.getData(), xy) np.testing.assert_almost_equal(scatterplot_item_sel.getData(), xy) scatterplot_item.setSize([5, 6]) scatterplot_item.setSymbol([7, 8]) scatterplot_item.setPen([mkPen(9), mkPen(10)]) scatterplot_item.setBrush([11, 12]) data["data"] = np.array([13, 14]) xy[0][0] = 0 graph.update_coordinates() np.testing.assert_almost_equal(graph.scatterplot_item.getData(), xy) np.testing.assert_almost_equal(graph.scatterplot_item_sel.getData(), xy) # Graph updates coordinates instead of creating new items self.assertIs(scatterplot_item, graph.scatterplot_item) self.assertIs(scatterplot_item_sel, graph.scatterplot_item_sel) np.testing.assert_almost_equal(data["size"], [5, 6]) np.testing.assert_almost_equal(data["symbol"], [7, 8]) self.assertEqual(data["pen"][0], mkPen(9)) self.assertEqual(data["pen"][1], mkPen(10)) np.testing.assert_almost_equal(data["brush"], [11, 12]) np.testing.assert_almost_equal(data["data"], [13, 14])
def plotAnalyzer(self): """Visualize the points found by the auto analyzer Returns: None: Description """ if hasattr(self, 'an'): s1 = self.an.analysedSignals[0] s2 = self.an.analysedSignals[1] # signal 1 # ROI self.anROI1 = self.pw2.plot(np.linspace(s1.ROIleft-100, s1.ROIleft)/1000, np.ones(50)*s1.avg, pen=pg.mkPen('w',width=2)) # points self.anPlot1 = self.pw2.plot([s1.peak.idx/1000], [s1.peak.h], symbolBrush=('w'), symbolSize=5) self.anPlot1 = self.pw2.plot([s1.hwLeft.idx/1000], [s1.hwLeft.h], symbolBrush=('w'), symbolSize=5) self.anPlot1 = self.pw2.plot([s1.hwRight.idx/1000], [s1.hwRight.h], symbolBrush=('w'), symbolSize=5) # signal 2 # ROI self.anROI2 = self.pw2.plot(np.linspace(s2.ROIleft-100, s2.ROIleft)/1000, np.ones(50)*s2.avg, pen=pg.mkPen('r',width=2)) # points self.anPlot2 = self.pw2.plot([s2.peak.idx/1000], [s2.peak.h], symbolBrush=('r'), symbolSize=5) self.anPlot2 = self.pw2.plot([s2.hwLeft.idx/1000], [s2.hwLeft.h], symbolBrush=('r'), symbolSize=5) self.anPlot2 = self.pw2.plot([s2.hwRight.idx/1000], [s2.hwRight.h], symbolBrush=('r'), symbolSize=5)
def select_image(self): ''' Select current image sequence to begin DIC setup. ''' self.openFolder.setEnabled(False) self.naprejButton.setEnabled(False) self.nazajButton.setEnabled(True) self.calibButton.setEnabled(True) self.beginButton.setEnabled(True) self.mode_selection.setEnabled(True) pathtext = '<b>Selected directory:</b><br>' + self.dir_path pathtext += '<br>(initial image - specify the region of interest)' self.pathlabel.setText(pathtext) self.default_calibration() self.initialImage = tools.get_sequence(self.mraw_path, file_shape=(self.N_images, self.h, self.w), nmax=1).T self.imw.setImage(self.initialImage) self.imw.ui.histogram.hide() # Add ROI widget to the view: image_shape = self.initialImage.shape roi_pos = (image_shape[0]//2 - self.min_roi_size[0], image_shape[1]//2 - self.min_roi_size[1]) ch_roi_pos = tools.get_roi_center(roi_pos, self.initial_roi_size) roi_bound = QtCore.QRectF(0, 0, image_shape[0], image_shape[1]) self.imw.roi = pg.ROI(roi_pos, self.initial_roi_size, maxBounds=roi_bound, scaleSnap=True, translateSnap=True) self.imw.CHroi = DotROI(ch_roi_pos, size=1, movable=False) self.imw.view.addItem(self.imw.roi) self.imw.view.addItem(self.imw.CHroi) self.imw.roi.sigRegionChanged.connect(self.imw.roiChanged) self.imw.roi.sigRegionChanged.connect(self.moving_roi) self.imw.roi.sigRegionChangeFinished.connect(self.update_roi_position) self.imw.roi.addScaleHandle(pos=(1, 1), center=(0.5, 0.5)) self.imw.roi.setPen(pg.mkPen(color=pg.mkColor('00FF6F'), width=2)) self.imw.CHroi.setPen(pg.mkPen(color=pg.mkColor('FF0000'), width=2)) self.roi_set = True
def generatePicture(self): self.picture = pg.QtGui.QPicture() if self.pen is None or self.pos is None or self.adjacency is None: return p = pg.QtGui.QPainter(self.picture) try: pts = self.pos[self.adjacency] pen = self.pen if isinstance(pen, np.ndarray): lastPen = None for i in range(pts.shape[0]): pen = self.pen[i] if np.any(pen != lastPen): lastPen = pen if pen.dtype.fields is None: p.setPen(pg.mkPen(color=(pen[0], pen[1], pen[2], pen[3]), width=1)) else: p.setPen(pg.mkPen(color=(pen['red'], pen['green'], pen['blue'], pen['alpha']), width=pen['width'])) p.drawLine(pg.QtCore.QPointF(*pts[i][0]), pg.QtCore.QPointF(*pts[i][1])) else: if pen == 'default': pen = pg.getConfigOption('foreground') p.setPen(pg.mkPen(pen)) pts = pts.reshape((pts.shape[0]*pts.shape[1], pts.shape[2])) path = fn.arrayToQPath(x=pts[:,0], y=pts[:,1], connect='pairs') p.drawPath(path) finally: p.end()
def init_traces(self): """ creates the traces, depending on the selected number of ROIs and datasets. """ nActiveROIs = len(self.Main.Options.ROI['active_ROIs']) nActiveTrials = sp.sum(self.Main.Options.view['show_flags']) trial_inds = sp.where(self.Main.Options.view['show_flags'])[0] # delete all present if any if len(self.traces) > 0: self.reset() # one ROI active, normal mode: traces overlaid, colored to stim class # this causes traces to be trial1, trial2, trial4 for active: (1,2,4) if nActiveROIs == 1: colors = self.Main.Options.view['colors'] for n in range(nActiveTrials): pen = pg.mkPen(colors[trial_inds[n]], width=2) trace = self.plotItem.plot(pen=pen) self.traces.append(trace) # multiple ROI active, traces colored to ROI # this results traces to contain roi1 trial1, roi1 trail2, roi1 trial4, roi2 trial1 roi2 trial2, roi2 trial4 for ROI (1,2) trials (1,2,4) if nActiveROIs > 1: colors = self.Main.Processing.calc_colors(nActiveROIs) for i,ROI_id in enumerate(self.Main.Options.ROI['active_ROIs']): for n in range(nActiveTrials): pen = pg.mkPen(colors[i], width=2) trace = self.plotItem.plot(pen=pen) self.traces.append(trace) self.update_traces()
def insertPlot(self, xAry = None, yAry = None, plotArea = None, legend = None, plotName = None, lineColor = (0,0,0,255), lineWidth = 1, lineStyle = QtCore.Qt.SolidLine, dotColor = (0,0,0,255), dotSize = 5, dotSym = 0, addLegend = True ): Sym = [ 'o', 's', 't', 'd', '+' ] if plotName == None: plotName = 'Untitle {0}'.format(self.plotIDCounter) if ( xAry != None and yAry != None): line = plotArea.plot( np.array(xAry), np.array(yAry), name = plotName, pen=pg.mkPen(color = lineColor, width=lineWidth, style=lineStyle), symbol = Sym[dotSym] ) else: plotAry = xAry if xAry != None else yAry xAry = np.linspace( 0, len( plotAry )-1, len( plotAry )) yAry = np.array( plotAry ) line = plotArea.plot( np.array(xAry), np.array(yAry), name = plotName, pen=pg.mkPen(color = lineColor, width = lineWidth, style = lineStyle), symbol = Sym[dotSym] ) self.addLineHolder(line) self.reWrapp_line(line) line.line_val( name = plotName, color = lineColor, width = lineWidth, style = lineStyle, symbol = Sym[dotSym], visible = True, viewNum = plotArea.viewBoxNum) line.symbol_val( color = dotColor, size = dotSize, penC = (0,255,0,255), penW = 2, outLine = False, visible = True ) print line.line_color() plotArea.showGrid(x=True, y=True) if addLegend: legend.addItem( line, plotName ) return line
def __init__(self, position=0., label="", color=(225, 0, 0), report=None): pg.UIGraphicsItem.__init__(self) self.moving = False self.mouseHovering = False self.report = report self.color = color self.isnone = False hp = pg.mkPen(color=color, width=3) np = pg.mkPen(color=color, width=2) self.line = pg.InfiniteLine(angle=90, movable=True, pen=np, hoverPen=hp) self.line.setParentItem(self) self.line.setCursor(Qt.SizeHorCursor) self.label = pg.TextItem("", anchor=(0, 1), angle=-90) self.label.setParentItem(self) self.setValue(position) self.setLabel(label) self.line.sigPositionChangeFinished.connect(self._moveFinished) self.line.sigPositionChanged.connect(lambda: (self._moved(), self.sigMoved.emit(self.value()))) self._lastTransform = None
def __init__(self, angle, col, dangle=5, parent=None): super().__init__(parent) color = QColor(0, 0, 0) if col else QColor(128, 128, 128) angle_d = np.rad2deg(angle) angle_2 = 90 - angle_d - dangle angle_1 = 270 - angle_d + dangle dangle = np.deg2rad(dangle) arrow1 = pg.ArrowItem( parent=self, angle=angle_1, brush=color, pen=pg.mkPen(color) ) arrow1.setPos(np.cos(angle - dangle), np.sin(angle - dangle)) arrow2 = pg.ArrowItem( parent=self, angle=angle_2, brush=color, pen=pg.mkPen(color) ) arrow2.setPos(np.cos(angle + dangle), np.sin(angle + dangle)) arc_x = np.fromfunction( lambda i: np.cos((angle - dangle) + (2 * dangle) * i / 120.), (121,), dtype=int ) arc_y = np.fromfunction( lambda i: np.sin((angle - dangle) + (2 * dangle) * i / 120.), (121,), dtype=int ) pg.PlotCurveItem( parent=self, x=arc_x, y=arc_y, pen=pg.mkPen(color), antialias=False )
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
def _setup_plot(self): self.plot.clear() explained_ratio = self._variance_ratio explained = self._cumulative p = min(len(self._variance_ratio), self.maxp) self.plot.plot(numpy.arange(p), explained_ratio[:p], pen=pg.mkPen(QColor(Qt.red), width=2), antialias=True, name="Variance") self.plot.plot(numpy.arange(p), explained[:p], pen=pg.mkPen(QColor(Qt.darkYellow), width=2), antialias=True, name="Cumulative Variance") self._line = pg.InfiniteLine( angle=90, pos=self._nselected_components() - 1, movable=True, bounds=(0, p - 1) ) self._line.setCursor(Qt.SizeHorCursor) self._line.setPen(pg.mkPen(QColor(Qt.darkGray), width=5)) self._line.sigPositionChanged.connect(self._on_cut_changed) self.plot.addItem(self._line) self.plot.setRange(xRange=(0.0, p - 1), yRange=(0.0, 1.0)) self._update_axis()
def plot(self, Rs=None, Vg=0): pg.setConfigOption('background', 'w') pg.setConfigOption('foreground', 'k') # Generate plot plt = pg.plot(title=self.__class__.__name__, clear=True) plt.setYRange(0, self.IDSS_MAX) plt.setXRange(self.VP_MAX, 0) plt.showGrid(True, True, 1.0) plt.setLabel('left', "Id (mA)") plt.setLabel('bottom', "Vgs (V)") (x, y) = self.id_max_points() plt.plot(x, y, pen=pg.mkPen('g', width=3)) (x, y) = self.id_min_points() plt.plot(x, y, pen=pg.mkPen('b', width=3)) if Rs is not None: (x, y) = self.vg_intercept(Rs, Vg) plt.plot(x, y, pen=pg.mkPen('r', width=3)) # Display plot QtGui.QApplication.instance().exec_() pg.exit()
def __init__(self, clock): pg.ItemGroup.__init__(self) self.size = clock.size self.item = QtGui.QGraphicsEllipseItem(QtCore.QRectF(0, 0, self.size, self.size)) self.item.translate(-self.size*0.5, -self.size*0.5) self.item.setPen(pg.mkPen(100,100,100)) self.item.setBrush(clock.brush) self.hand = QtGui.QGraphicsLineItem(0, 0, 0, self.size*0.5) self.hand.setPen(pg.mkPen('w')) self.hand.setZValue(10) self.flare = QtGui.QGraphicsPolygonItem(QtGui.QPolygonF([ QtCore.QPointF(0, -self.size*0.25), QtCore.QPointF(0, self.size*0.25), QtCore.QPointF(self.size*1.5, 0), QtCore.QPointF(0, -self.size*0.25), ])) self.flare.setPen(pg.mkPen('y')) self.flare.setBrush(pg.mkBrush(255,150,0)) self.flare.setZValue(-10) self.addItem(self.hand) self.addItem(self.item) self.addItem(self.flare) self.clock = clock self.i = 1 self._spaceline = None
def __init__(self,plot_area, marker_name, color): self.name = marker_name self.marker_plot = pg.ScatterPlotItem() self.enabled = False self.selected = False self.data_index = None self.xdata = [] self.ydata = 0 self.trace_index = 0 self.color = color self.draw_color = color self.hovering = False self._plot = plot_area self.coursor_dragged = False cursor_pen = pg.mkPen((0,0,0,0), width = 40) self.cursor_line = infiniteLine(pen = cursor_pen, pos = -100, angle = 90, movable = True) self.cursor_line.setHoverPen(pg.mkPen((0,0,0, 0), width = 40)) def dragged(): self.data_index = np.abs( self.xdata-self.cursor_line.value()).argmin() self.cursor_line.setPen(cursor_pen) self.draw_color = colors.MARKER_HOVER self.cursor_line.sigDragged.connect(dragged) def hovering(): self.draw_color = colors.MARKER_HOVER self.cursor_line.sigHovering.connect(hovering) def not_hovering(): self.draw_color = color self.cursor_line.sigHoveringFinished.connect(not_hovering)
def plot_data(self, data): self.clear() self.showButtons() self.data = data try: points = data.shape[0] lines = data.shape[1] if lines > 1: # self.getViewBox().disableAutoRange() # Color option for separate multiple plots # for i in range(lines): # item = PathItem(np.arange(points), data[:,i].flatten()) # item.setPen(pg.mkPen((i, lines))) # self.widget.addItem(item) xdata = np.tile(np.arange(points), (lines, 1)) # Assume data is vertical item = MultiLine(xdata, data.T) item.setPen(pg.mkPen('w')) self.addItem(item) # self.getViewBox().enableAutoRange() self.autoRange() except IndexError: self.plot(np.arange(len(data)) / self.x_scale, data / self.y_scale, pen=pg.mkPen(width=1)) # Update title text = 'Recording length: %f (s)' % (len(data) / self.x_scale) self.s.title_updated.emit(text)
def violin_plot(ax, data, pos, dist=.0, bp=False): ''' create violin plots on an axis ''' if data is None or len(data) == 0: return # skip trying to do the plot dist = max(pos)-min(pos) w = min(0.15*max(dist,1.0),0.5) for i, d in enumerate(data): if d == [] or len(d) == 0: continue k = scipy.stats.gaussian_kde(d) #calculates the kernel density m = k.dataset.min() #lower bound of violin M = k.dataset.max() #upper bound of violin y = np.arange(m, M, (M-m)/100.) # support for violin v = k.evaluate(y) #violin profile (density curve) v = v / v.max() * w #scaling the violin to the available space c1 = pg.PlotDataItem(y=y, x=pos[i]+v, pen=pg.mkPen('k', width=0.5)) c2 = pg.PlotDataItem(y=y, x=pos[i]-v, pen=pg.mkPen('k', width=0.5)) #mean = k.dataset.mean() #vm = k.evaluate(mean) #vm = vm * w #ax.plot(x=np.array([pos[i]-vm[0], pos[i]+vm[0]]), y=np.array([mean, mean]), pen=pg.mkPen('k', width=1.0)) ax.addItem(c1) ax.addItem(c2) #ax.addItem(hbar) f = pg.FillBetweenItem(curve1=c1, curve2=c2, brush=pg.mkBrush((255, 255, 0, 96))) ax.addItem(f) if bp: pass
def __init__(self, pen=None, brush=None, **opts): """ Arguments for each surface are: x1,x2 - position of center of _physical surface_ r1,r2 - radius of curvature d1,d2 - diameter of optic """ defaults = dict(x1=-2, r1=100, d1=25.4, x2=2, r2=100, d2=25.4) defaults.update(opts) ParamObj.__init__(self) self.surfaces = [CircleSurface(defaults['r1'], defaults['d1']), CircleSurface(-defaults['r2'], defaults['d2'])] pg.GraphicsObject.__init__(self) for s in self.surfaces: s.setParentItem(self) if pen is None: self.pen = pg.mkPen((220,220,255,200), width=1, cosmetic=True) else: self.pen = pg.mkPen(pen) if brush is None: self.brush = pg.mkBrush((230, 230, 255, 30)) else: self.brush = pg.mkBrush(brush) self.setParams(**defaults)
def test_init_spots(): plot = pg.PlotWidget() # set view range equal to its bounding rect. # This causes plots to look the same regardless of pxMode. plot.setRange(rect=plot.boundingRect()) spots = [ {'x': 0, 'y': 1}, {'pos': (1, 2), 'pen': None, 'brush': None, 'data': 'zzz'}, ] s = pg.ScatterPlotItem(spots=spots) # Check we can display without errors plot.addItem(s) app.processEvents() plot.clear() # check data is correct spots = s.points() defPen = pg.mkPen(pg.getConfigOption('foreground')) assert spots[0].pos().x() == 0 assert spots[0].pos().y() == 1 assert spots[0].pen() == defPen assert spots[0].data() is None assert spots[1].pos().x() == 1 assert spots[1].pos().y() == 2 assert spots[1].pen() == pg.mkPen(None) assert spots[1].brush() == pg.mkBrush(None) assert spots[1].data() == 'zzz'
def plot_trace(xy, ids = None, depth = 0, colormap = 'rainbow', line_color = 'k', line_width = 1, point_size = 5, title = None): """Plot trajectories with positions color coded according to discrete ids""" #if ids is not None: uids = np.unique(ids); cmap = cm.get_cmap(colormap); n = len(uids); colors = cmap(range(n), bytes = True); #lines if line_width is not None: #plt.plot(xy[:,0], xy[:,1], color = lines); plot = pg.plot(xy[:,0], xy[:,1], pen = pg.mkPen(color = line_color, width = line_width)) else: plot = pg.plot(title = title); if ids is None: sp = pg.ScatterPlotItem(pos = xy, size=point_size, pen=pg.mkPen(colors[0])); #, pxMode=True); else: sp = pg.ScatterPlotItem(size=point_size); #, pxMode=True); spots = []; for j,i in enumerate(uids): idx = ids == i; spots.append({'pos': xy[idx,:].T, 'data': 1, 'brush':pg.mkBrush(colors[j])}); #, 'size': point_size}); sp.addPoints(spots) plot.addItem(sp); return plot;
def edit(self, index, trigger, event): if trigger == QAbstractItemView.DoubleClicked: print("DoubleClick Killed!") model = self.model() _filename = model.filePath(index) pen1 = pg.mkPen(color=(self.pColor - 1, 32), width=2) pen2 = pg.mkPen(color=(self.pColor - 1, 32), width=1, style=QtCore.Qt.DashLine) data_snr = perf_reader.perf_snr_reader(_filename) data_ber = perf_reader.perf_ber_reader(_filename) data_fer = perf_reader.perf_fer_reader(_filename) self.class_var.clearPlots() self.class_var.clear() self.class_var.plot(x=data_snr, y=data_ber, pen=pen1, symbol="x", name="BER plot") self.class_var.plot(x=data_snr, y=data_fer, pen=pen2, symbol="x", name="FER plot") self.pColor = self.pColor + 1 return False return QTreeView.edit(self, index, trigger, event)
def update_display_settings(self): """ sets the colors for the ROIs and whether or not to show the label """ # handle the labels if self.Main.Options.ROI['show_labels'] == True: [ROI.labelItem.show() for ROI in self.ROI_list] if self.Main.Options.ROI['show_labels'] == False: [ROI.labelItem.hide() for ROI in self.ROI_list] # handle the ROI colors nActiveROIs = len(self.Main.Options.ROI['active_ROIs']) # one ROI active, active/inactive color scheme if nActiveROIs <= 1: for ROI in self.ROI_list: if ROI.active == True: pen = pg.mkPen(self.Main.Options.ROI['active_color'],width=1.8) if ROI.active == False: pen = pg.mkPen(self.Main.Options.ROI['inactive_color'],width=1.8) ROI.set_Pen(pen) # multiple ROI active, traces colored to ROI if nActiveROIs > 1: colors = self.Main.Processing.calc_colors(nActiveROIs) for i,ROI_id in enumerate(self.Main.Options.ROI['active_ROIs']): ROI = self.ROI_list[ROI_id] pen = pg.mkPen(colors[i],width=1.8) ROI.set_Pen(pen) pass
def test_init_spots(): spots = [ {'x': 0, 'y': 1}, {'pos': (1, 2), 'pen': None, 'brush': None, 'data': 'zzz'}, ] s = pg.ScatterPlotItem(spots=spots) # Check we can display without errors plot.addItem(s) app.processEvents() plot.clear() # check data is correct spots = s.points() defPen = pg.mkPen(pg.getConfigOption('foreground')) assert spots[0].pos().x() == 0 assert spots[0].pos().y() == 1 assert spots[0].pen() == defPen assert spots[0].data() is None assert spots[1].pos().x() == 1 assert spots[1].pos().y() == 2 assert spots[1].pen() == pg.mkPen(None) assert spots[1].brush() == pg.mkBrush(None) assert spots[1].data() == 'zzz'
def setupUi(self): self.resize(1200, 900) gr = pg.PlotWidget(parent=self, background=[255, 255, 255]) dtait = pg.PlotDataItem(pen=pg.mkPen('r', width=4)) dtait2 = pg.PlotDataItem(pen=pg.mkPen('b', width=4)) dtait.setVisible(True) gr.plotItem.addItem(dtait) gr.plotItem.addItem(dtait2) pl = gr.getPlotItem() vl = QVBoxLayout(self) vl.addWidget(gr) self.graph = gr self._plot_rms = dtait self._plot_ave = dtait2 hl = QHBoxLayout() vl.addItem(hl) self.dirs = sorted([f for f in os.listdir() if os.path.isdir(f)]) self.cb_dirs = QComboBox(self) self.cb_dirs.addItems(self.dirs) self.cb_dirs.currentTextChanged.connect(self._changedir) hl.addWidget(self.cb_dirs) self.cb_planes = QComboBox(self) self.cb_planes.addItems(self.planes + ('Wlkick', )) self.cb_planes.currentTextChanged.connect(self._changePlane) hl.addWidget(self.cb_planes)
def commit(self): new_stack = None self.Error.nan_in_image.clear() self.Error.invalid_axis.clear() self.plotview.plotItem.clear() if self.data and len(self.data.domain.attributes) and self.attr_x and self.attr_y: try: shifts, new_stack = process_stack(self.data, self.attr_x, self.attr_y, upsample_factor=100, use_sobel=self.sobel_filter, ref_frame_num=self.ref_frame_num-1) except NanInsideHypercube as e: self.Error.nan_in_image(e.args[0]) except InvalidAxisException as e: self.Error.invalid_axis(e.args[0]) else: # TODO: label axes frames = np.linspace(1, shifts.shape[0], shifts.shape[0]) self.plotview.plotItem.plot(frames, shifts[:, 0], pen=pg.mkPen(color=(255, 40, 0), width=3), symbol='o', symbolBrush=(255, 40, 0), symbolPen='w', symbolSize=7) self.plotview.plotItem.plot(frames, shifts[:, 1], pen=pg.mkPen(color=(0, 139, 139), width=3), symbol='o', symbolBrush=(0, 139, 139), symbolPen='w', symbolSize=7) self.plotview.getPlotItem().setLabel('bottom', 'Frame number') self.plotview.getPlotItem().setLabel('left', 'Shift / pixel') self.plotview.getPlotItem().addLine(self.ref_frame_num, pen=pg.mkPen(color=(150, 150, 150), width=3, style=Qt.DashDotDotLine)) self.Outputs.newstack.send(new_stack)
def insertPlot(self, xAry = None, yAry = None, plotArea = None, legend = None, plotName = None, lineColor = (0,0,0,255), lineWidth = 1, lineStyle = QtCore.Qt.SolidLine, dotColor = (0,0,0,255), dotSize = 4, dotSym = 0 ): Sym = [ 'o', 's', 't', 'd', '+' ] if plotName == None: plotName = 'Untitle {0}'.format(self.plotCounter) self.plotCounter += 1 if ( xAry != None and yAry != None): line = plotArea.plot( np.array(xAry), np.array(yAry), name = plotName, pen=pg.mkPen(color = lineColor, width=lineWidth, style=lineStyle), symbol = Sym[dotSym] ) self.plotLineHolder.append(line) else: plotAry = xAry if xAry != None else yAry xAry = np.linspace( 0, len( plotAry )-1, len( plotAry )) yAry = np.array( plotAry ) line = plotArea.plot( np.array(xAry), np.array(yAry), name = plotName, pen=pg.mkPen(color = lineColor, width=lineWidth, style=lineStyle), symbol = Sym[dotSym] ) self.plotLineHolder.append(line) line.setSymbolBrush( pg.mkBrush( color = dotColor )) line.setSymbolPen( None ) line.setSymbolSize( dotSize ) plotArea.showGrid(x=True, y=True) # line.setPen(pg.mkPen(color = (255,0,0,255), width=5, style=QtCore.Qt.SolidLine)) # self.w.setLabel('left', "Y Axis", units='A') # self.w.setLabel('bottom', "Y Axis", units='s') # self.w.setLogMode(x=True, y=False) legend.addItem( line, plotName )
def __init__(self,Main=None,label=None,ViewBox=None): # super(myROI,self).__init__() self.Main = Main self.label = label self.ViewBox = self.parentItem() self.children = [] # a list of GraphicsItems self.active = False self.center = self.get_center() self.labelItem = pg.TextItem(text=label,anchor=(0.5,0.5)) self.update_center() self.ViewBox.addItem(self.labelItem) self.children.append(self.labelItem) # link signals self.sigRemoveRequested.connect(self.Main.ROIs.remove_ROI_request) self.proxy = pg.SignalProxy(self.sigRegionChanged, rateLimit=30, slot=self.Main.ROIs.ROI_region_changed) # rate limit movement self.setAcceptedMouseButtons(QtCore.Qt.LeftButton) self.sigClicked.connect(self.Main.ROIs.ROI_clicked_handler) # self.sigHoverEvent.connect(self.Main.ROIs.ROI_hover_handler) # pens self.active_pen = pg.mkPen(self.Main.Options.ROI['active_color'],width=1.8) self.inactive_pen = pg.mkPen(self.Main.Options.ROI['inactive_color'],width=1.8) self.hover_pen = pg.mkPen(255,255,0,width=1)
def _setup_plot(self): explained_ratio = self._variance_ratio explained = self._cumulative (p, ) = explained.shape self.plot.plot(numpy.arange(p), explained_ratio, pen=pg.mkPen(QColor(Qt.red), width=2), antialias=True, name="Variance") self.plot.plot(numpy.arange(p), explained, pen=pg.mkPen(QColor(Qt.darkYellow), width=2), antialias=True, name="Cumulative Variance") self._line = pg.InfiniteLine( angle=90, pos=self._nselected_components() - 1, movable=True, bounds=(0, p - 1) ) self._line.setCursor(Qt.SizeHorCursor) self._line.setPen(pg.mkPen(QColor(Qt.darkGray), width=1.5)) self._line.sigPositionChanged.connect(self._on_cut_changed) self.plot.addItem(self._line) self.plot.setRange(xRange=(0.0, p - 1), yRange=(0.0, 1.0)) axis = self.plot.getAxis("bottom") axis.setTicks([[(i, "C{}".format(i + 1)) for i in range(p)]])
def __init__(self, viewBox, side, pxs=512): self.showed = False self.vb = viewBox self.side = side # side is 128 or 82, the grid size self.pxs = pxs pen = pg.mkPen(color=(255, 255, 0), width=1, style=QtCore.Qt.SolidLine, antialias=True) pen2 = pg.mkPen(color=(255, 255, 0), width=0.75, style=QtCore.Qt.DotLine, antialias=True) self.rectT = QtGui.QGraphicsRectItem() self.rectT.setPen(pen) self.rectR = QtGui.QGraphicsRectItem() self.rectR.setPen(pen) self.sqrT = QtGui.QGraphicsRectItem() self.sqrT.setPen(pen2) self.sqrR = QtGui.QGraphicsRectItem() self.sqrR.setPen(pen2) self.yLine = pg.InfiniteLine(pen=pen2) self.xLine = pg.InfiniteLine(pen=pen2, angle=0) self.xLineR = pg.InfiniteLine(pen=pen2, angle=0) self.setDimensions()
def trajec_get_original_objid(self): self.set_all_buttons_false() self.get_original_objid = True self.crosshair_pen = pg.mkPen((255, 129, 234), width=1)
def plot_stepsAndSpikes(self, data, posSpike, negSpike): self.glmProcTimeSeries = np.append(self.glmProcTimeSeries, data, axis=1) sz, l = self.glmProcTimeSeries.shape for i in range(sz): if posSpike[i] == 1: if self.posSpikes[str(i)].any(): self.posSpikes[str(i)] = np.append(self.posSpikes[str(i)], l-1) else: self.posSpikes[str(i)] = np.array([l-1]) if negSpike[i] == 1: if self.negSpikes[str(i)].any(): self.negSpikes[str(i)] = np.append(self.negSpikes[str(i)], l-1) else: self.negSpikes[str(i)] = np.array([l-1]) x = np.arange(0, l, dtype=np.float64) plotitem = self.spikes_plot.getPlotItem() plotitem.clear() plots = [] muster = self.drawMusterPlot(plotitem) for i, c in zip(range(sz), config.ROI_PLOT_COLORS): pen = pg.mkPen(color=c, width=config.ROI_PLOT_WIDTH) p = plotitem.plot(pen=pen) plots.append(p) self.plot_stepsAndSpikes.__dict__[plotitem] = plots, muster for p, y in zip(self.plot_stepsAndSpikes.__dict__[plotitem][0], self.glmProcTimeSeries): p.setData(x=x, y=np.array(y)) for i, c in zip(range(sz), config.ROI_PLOT_COLORS): if self.posSpikes[str(i)].any(): brush = pg.mkBrush(color=c) p = plotitem.scatterPlot(symbol='o', size=20, brush=brush) plots.append(p) plots[-1].setData(x=x[self.posSpikes[str(i)]], y=self.glmProcTimeSeries[i, self.posSpikes[str(i)]]) pen = pg.mkPen(color=pg.mkColor(0, 0, 0), width=1.5*config.ROI_PLOT_WIDTH) p = plotitem.plot(pen=pen) plots.append(p) inds = self.posSpikes[str(i)] inds = np.array(list(itertools.chain.from_iterable(zip(inds, inds-1)))) y = np.array(self.glmProcTimeSeries[i,inds]) x1 = inds plots[-1].setData(x=x1, y=y, connect='pairs') if self.negSpikes[str(i)].any(): brush = pg.mkBrush(color=c) p = plotitem.scatterPlot(symbol='d', size=20, brush=brush) plots.append(p) plots[-1].setData(x=x[self.negSpikes[str(i)]], y=self.glmProcTimeSeries[i, self.negSpikes[str(i)]]) pen = pg.mkPen(color=pg.mkColor(0, 0, 0), width=1.5*config.ROI_PLOT_WIDTH) p = plotitem.plot(pen=pen) plots.append(p) inds = self.negSpikes[str(i)] inds = np.array(list(itertools.chain.from_iterable(zip(inds, inds - 1)))) y = np.array(self.glmProcTimeSeries[i,inds]) x1 = inds plots[-1].setData(x=x1, y=y, connect='pairs') cnt = 0; for i in range(sz): cnt = cnt + np.count_nonzero(self.posSpikes[str(i)]) names = ['( Circles ) <br>Positive spikes: ' + str(int(cnt))] cnt = 0; for i in range(sz): cnt = cnt + np.count_nonzero(self.negSpikes[str(i)]) names.append('<br>( Diamonds )<br>Negative spikes: ' + str(int(cnt))) pens = [pg.mkPen(color=config.STAT_PLOT_COLORS[0], width=1.2), pg.mkPen(color=config.STAT_PLOT_COLORS[0], width=1.2)] self.makeTextValueLabel(self.spikesLabel, names, pens) items = plotitem.listDataItems() for m in self.plot_stepsAndSpikes.__dict__[plotitem][1]: items.remove(m) if data.any(): plotitem.setYRange(np.min(self.glmProcTimeSeries), np.max(self.glmProcTimeSeries), padding=0.0)
def __init__(self, sz, xrange, indBas, indCond, musterInfo, parent=None): super().__init__(parent=parent, flags=QtCore.Qt.Window) uic.loadUi(utils.get_ui_file('rtqa.ui'), self) self._fd = FD(xrange) self.names = ['X', 'Y', 'Z', 'Pitch', 'Roll', 'Yaw', 'FD'] self.indBas = indBas self.indCond = indCond self.iterBas = 0 self.iterCond = 0 self.musterInfo = musterInfo self.comboBox.currentTextChanged.connect(self.onComboboxChanged) self.mcrRadioButton.toggled.connect(self.onRadioButtonStateChanged) self.snrplot = pg.PlotWidget(self) self.snrplot.setBackground((255, 255, 255)) self.snrPlot.addWidget(self.snrplot) p = self.snrplot.getPlotItem() p.setLabel('left', "SNR [a.u.]") p.setMenuEnabled(enableMenu=False) p.setMouseEnabled(x=False, y=False) p.showGrid(x=True, y=True, alpha=1) p.installEventFilter(self) p.disableAutoRange(axis=pg.ViewBox.XAxis) p.setXRange(1, xrange, padding=0.0) self.cnrplot = pg.PlotWidget(self) self.cnrplot.setBackground((255, 255, 255)) self.cnrPlot.addWidget(self.cnrplot) p = self.cnrplot.getPlotItem() p.setLabel('left', "CNR [a.u.]") p.setMenuEnabled(enableMenu=False) p.setMouseEnabled(x=False, y=False) p.showGrid(x=True, y=True, alpha=1) p.installEventFilter(self) p.disableAutoRange(axis=pg.ViewBox.XAxis) p.setXRange(1, xrange, padding=0.0) self.meanplot = pg.PlotWidget(self) self.meanplot.setBackground((255, 255, 255)) self.meanPlot.addWidget(self.meanplot) p = self.meanplot.getPlotItem() p.setLabel('left', "Mean [a.u.]") p.setMenuEnabled(enableMenu=False) p.setMouseEnabled(x=False, y=False) p.showGrid(x=True, y=True, alpha=1) p.installEventFilter(self) p.disableAutoRange(axis=pg.ViewBox.XAxis) p.setXRange(1, xrange, padding=0.0) names = ['ROI_1 rMean', 'ROI_1 basMean', 'ROI_1 condMean'] color = [config.STAT_PLOT_COLORS[0], config.ROI_BAS_COLORS[0], config.ROI_COND_COLORS[0]] for i in range(sz-1): names.append('ROI_' + str(i + 2) + ' rMean') names.append('ROI_' + str(i + 2) + ' basMean') names.append('ROI_' + str(i + 2) + ' condMean') color = color + [config.STAT_PLOT_COLORS[i + 1]] + [config.ROI_BAS_COLORS[i + 1]] + [config.ROI_COND_COLORS[i + 1]] pens = [] for i in range(sz*3): pens = pens + [pg.mkPen(color[i], width=1.2)] self.makeRoiPlotLegend(self.labelMean, names, pens) self.varplot = pg.PlotWidget(self) self.varplot.setBackground((255, 255, 255)) self.varPlot.addWidget(self.varplot) p = self.varplot.getPlotItem() p.setLabel('left', "Variance [a.u.]") p.setMenuEnabled(enableMenu=False) p.setMouseEnabled(x=False, y=False) p.showGrid(x=True, y=True, alpha=1) p.installEventFilter(self) p.disableAutoRange(axis=pg.ViewBox.XAxis) p.setXRange(1, xrange, padding=0.0) names = ['ROI_1 rVariance', 'ROI_1 basVariance', 'ROI_1 condVariance'] for i in range(sz - 1): names.append('ROI_' + str(i + 2) + ' rVariance') names.append('ROI_' + str(i + 2) + ' basVariance') names.append('ROI_' + str(i + 2) + ' condVariance') self.makeRoiPlotLegend(self.labelVar, names, pens) self.spikes_plot = pg.PlotWidget(self) self.spikes_plot.setBackground((255, 255, 255)) self.spikesPlot.addWidget(self.spikes_plot) p = self.spikes_plot.getPlotItem() p.setLabel('left', "Amplitude [a.u.]") p.setMenuEnabled(enableMenu=False) p.setMouseEnabled(x=False, y=False) p.showGrid(x=True, y=True, alpha=1) p.installEventFilter(self) p.disableAutoRange(axis=pg.ViewBox.XAxis) p.setXRange(1, xrange, padding=0.0) self._plot_translat = pg.PlotWidget(self) self._plot_translat.setBackground((255, 255, 255)) self.tdPlot.addWidget(self._plot_translat) p = self._plot_translat.getPlotItem() p.setLabel('left', "Amplitude [mm]") p.setMenuEnabled(enableMenu=True) p.setMouseEnabled(x=False, y=False) p.showGrid(x=True, y=True, alpha=1) p.installEventFilter(self) p.disableAutoRange(axis=pg.ViewBox.XAxis) p.setXRange(1, xrange, padding=0.0) names = ['Translationals: '] pens = [config.PLOT_PEN_COLORS[6]] for i in range(3): names.append(self.names[i]) pens.append(config.PLOT_PEN_COLORS[i]) self.makeRoiPlotLegend(self.tdLabel, names, pens) self._plot_rotat = pg.PlotWidget(self) self._plot_rotat.setBackground((255, 255, 255)) self.rdPlot.addWidget(self._plot_rotat) p = self._plot_rotat.getPlotItem() p.setLabel('left', "Angle [rad]") p.setMenuEnabled(enableMenu=True) p.setMouseEnabled(x=False, y=False) p.showGrid(x=True, y=True, alpha=1) p.installEventFilter(self) p.disableAutoRange(axis=pg.ViewBox.XAxis) p.setXRange(1, xrange, padding=0.0) names = ['Rotations: '] pens = [config.PLOT_PEN_COLORS[6]] for i in range(3): names.append(self.names[i+3]) pens.append(config.PLOT_PEN_COLORS[i + 3]) self.makeRoiPlotLegend(self.rdLabel, names, pens) self._plot_fd = pg.PlotWidget(self) self._plot_fd.setBackground((255, 255, 255)) self.fdPlot.addWidget(self._plot_fd) p = self._plot_fd.getPlotItem() p.setLabel('left', "FD [mm]") p.setMenuEnabled(enableMenu=True) p.setMouseEnabled(x=False, y=False) p.showGrid(x=True, y=True, alpha=1) p.installEventFilter(self) p.disableAutoRange(axis=pg.ViewBox.XAxis) p.setXRange(1, xrange, padding=0.0) names = ['Framewise Displacement'] pens = [config.PLOT_PEN_COLORS[0]] for i in range(len(config.DEFAULT_FD_THRESHOLDS)-1): names.append('Threshold ' + str(i+1)) pens.append(config.PLOT_PEN_COLORS[i + 1]) self.makeRoiPlotLegend(self.fdLabel, names, pens) self.tsCheckBox.setChecked(True) self.iteration = 1; self.rMean = np.zeros((sz, xrange)) self.m2 = np.zeros((sz, 1)) self.rVar = np.zeros((sz, xrange)) self.rSNR = np.zeros((sz, xrange)) self.meanBas = np.zeros((sz, xrange)) self.varBas = np.zeros((sz, xrange)) self.m2Bas = np.zeros((sz, 1)) self.meanCond = np.zeros((sz, xrange)) self.varCond = np.zeros((sz, xrange)) self.m2Cond = np.zeros((sz, 1)) self.rCNR = np.zeros((sz, xrange)) self.glmProcTimeSeries = np.zeros((sz, 1)) self.posSpikes = dict.fromkeys(['{:d}'.format(x) for x in range(sz)], np.array(0)) self.negSpikes = dict.fromkeys(['{:d}'.format(x) for x in range(sz)], np.array(0))
def refreshAnodeCathode(self): ''' Draws lines corresponding to the cathode and anode positions for t0 = 0 Red line = anode Blue line = cathode ''' if not self._showAnodeCathode: return max_wire = self._geometry._wRange[self._plane] for tpc in range(0, int(self._geometry.nTPCs())): # Take into account the distance between planes plane_x_ref = self._geometry.getGeometryCore().Plane( 0).GetCenter().X() plane_x = self._geometry.getGeometryCore().Plane( self._plane).GetCenter().X() delta_plane = abs(plane_x - plane_x_ref) offset = self._geometry.triggerOffset() * self._geometry.time2cm( ) - delta_plane x_cathode = (2 * self._geometry.halfwidth() + offset) / self._geometry.time2cm() x_anode = offset / self._geometry.time2cm() # If we are changing the t0, shift the anode and cathode position x_cathode += self._manual_t0 x_anode += self._manual_t0 if tpc % 2 == 1: # Time is flipped for odd TPC x_cathode = self._geometry.tRange() - x_cathode x_anode = self._geometry.tRange() - x_anode # Add the ad-hoc gap between TPCs x_cathode += tpc * self._geometry.cathodeGap() x_anode += tpc * self._geometry.cathodeGap() # Shift up to the appropriate TPC x_cathode += tpc * self._geometry.tRange() x_anode += tpc * self._geometry.tRange() # If we are deleting entries to see the cathodes together, do it here too x_cathode = x_cathode - 2 * tpc * self._removed_entries x_anode = x_anode - 2 * tpc * self._removed_entries # Construct the cathode line and append it line = QtGui.QGraphicsLineItem() line.setLine(0, x_cathode, max_wire, x_cathode) line.setPen(pg.mkPen(30, 144, 255, width=2)) self._cathode_lines.append(line) self._view.addItem(line) # Construct the anode line and append it line = QtGui.QGraphicsLineItem() line.setLine(0, x_anode, max_wire, x_anode) line.setPen(pg.mkPen(250, 128, 114, width=2)) self._anode_lines.append(line) self._view.addItem(line)
def draw_trajectories(self): for plotted_trace in self.plotted_traces: self.ui.qtplot_trajectory.removeItem(plotted_trace) self.ui.qtplot_trajectory.clear() pd_subset = mta.data_slicing.get_data_in_epoch_timerange( self.pd, self.troi) self.dataset = read_hdf5_file_to_pandas.Dataset(self.pd) self.init_bg_image() # plot a heatmap of the trajectories, for error checking h = mta.plot.get_heatmap(pd_subset, self.binsy, self.binsx, position_x='position_y', position_y='position_x', position_z='position_z', position_z_slice=None) indices = np.where(h != 0) img = copy.copy(self.backgroundimg) img[indices] = 0 self.img = pg.ImageItem(img, autoLevels=False) self.ui.qtplot_trajectory.addItem(self.img) self.img.setZValue(-200) # make sure image is behind other data # cross hair mouse stuff self.ui.qtplot_trajectory.scene().sigMouseMoved.connect( self.mouse_moved) self.ui.qtplot_trajectory.scene().sigMouseClicked.connect( self.mouse_clicked) self.crosshair_vLine = pg.InfiniteLine(angle=90, movable=False) self.crosshair_hLine = pg.InfiniteLine(angle=0, movable=False) self.ui.qtplot_trajectory.addItem(self.crosshair_vLine, ignoreBounds=True) self.ui.qtplot_trajectory.addItem(self.crosshair_hLine, ignoreBounds=True) keys = np.unique(pd_subset.objid.values) self.plotted_traces_keys = [] self.plotted_traces = [] if len(keys) < 100: for key in keys: trajec = self.dataset.trajec(key) first_time = np.max([self.troi[0], trajec.time_epoch[0]]) first_time_index = np.argmin( np.abs(trajec.time_epoch - first_time)) last_time = np.min([self.troi[-1], trajec.time_epoch[-1]]) last_time_index = np.argmin( np.abs(trajec.time_epoch - last_time)) #if trajec.length > 5: if key not in self.trajec_to_color_dict.keys(): color = get_random_color() self.trajec_to_color_dict.setdefault(key, color) else: color = self.trajec_to_color_dict[key] if key in self.trajec_width_dict.keys(): width = self.trajec_width_dict[key] else: width = 2 if self.ui.annotated_color_checkbox.checkState(): if key in self.annotated_keys: color = (0, 0, 0) width = 6 if self.ui.annotated_hide_checkbox.checkState(): if key in self.annotated_keys: color = (0, 0, 0, 0) width = 1 pen = pg.mkPen(color, width=width) plotted_trace = self.ui.qtplot_trajectory.plot( trajec.position_y[first_time_index:last_time_index], trajec.position_x[first_time_index:last_time_index], pen=pen) self.plotted_traces.append(plotted_trace) self.plotted_traces_keys.append(key) for i, key in enumerate(self.plotted_traces_keys): self.plotted_traces[i].curve.setClickable( True, width=self.clickable_width) self.plotted_traces[i].curve.key = key self.plotted_traces[i].curve.sigClicked.connect( self.trace_clicked) self.draw_data_to_add() self.draw_vlines_for_selected_trajecs()
def __init__(self, data_filename, bgimg, delta_video_filename, load_original=False, clickable_width=6, draw_interesting_time_points=True, draw_config_function=False): self.load_original = load_original TemplateBaseClass.__init__(self) self.setWindowTitle('Trajectory Viewer GUI v2') # Create the main window #self.app = QtGui.QApplication([]) self.ui = WindowTemplate() self.ui.setupUi(self) #self.show() # options self.draw_interesting_time_points = draw_interesting_time_points self.draw_config_function = draw_config_function # Buttons self.ui.save_trajecs.clicked.connect(self.save_trajectories) self.ui.movie_save.clicked.connect(self.save_image_sequence) self.ui.movie_speed.sliderMoved.connect(self.set_movie_speed) self.ui.trajec_undo.clicked.connect(self.trajec_undo) self.ui.movie_play.clicked.connect(self.movie_play) self.ui.movie_pause.clicked.connect(self.movie_pause) self.ui.trajec_delete.clicked.connect(self.toggle_trajec_delete) self.ui.trajec_cut.clicked.connect(self.toggle_trajec_cut) self.ui.trajec_join_collect.clicked.connect( self.toggle_trajec_join_collect) self.ui.trajec_select_all.clicked.connect(self.select_all_trajecs) self.ui.trajec_join_add_data.clicked.connect( self.toggle_trajec_join_add_data) self.ui.trajec_join_save.clicked.connect(self.trajec_join_save) self.ui.trajec_join_clear.clicked.connect( self.toggle_trajec_join_clear) self.ui.save_annotation.clicked.connect(self.save_annotation) self.ui.load_annotations.clicked.connect(self.load_annotations) self.ui.annotated_color_checkbox.stateChanged.connect( self.toggle_annotated_colors) self.ui.annotated_hide_checkbox.stateChanged.connect( self.toggle_annotated_hide) if not SMALL: self.ui.get_original_objid.clicked.connect( self.trajec_get_original_objid) self.ui.save_colors.clicked.connect(self.save_trajec_colors) self.ui.min_selection_length.setPlainText(str(0)) self.ui.max_selection_length.setPlainText(str(-1)) # -1 means all # parameters self.data_filename = data_filename self.load_data() self.backgroundimg_filename = bgimg self.backgroundimg = None self.binsx = None self.binsy = None trange = np.float( np.max(self.pd.time_epoch.values) - np.min(self.pd.time_epoch.values)) self.troi = [ np.min(self.pd.time_epoch.values), np.min(self.pd.time_epoch.values) + trange * 0.1 ] self.skip_frames = 1 self.frame_delay = 0.03 self.path = os.path.dirname(data_filename) self.clickable_width = clickable_width # load delta video bag if delta_video_filename != 'none': self.dvbag = rosbag.Bag(delta_video_filename) else: self.dvbag = None # Initialize self.trajec_width_dict = {} try: fname = os.path.join(self.path, 'trajec_to_color_dict.pickle') f = open(fname, 'r+') self.trajec_to_color_dict = pickle.load(f) f.close() except: self.trajec_to_color_dict = {} for key in self.pd.objid.unique(): color = get_random_color() self.trajec_to_color_dict.setdefault(key, color) self.plotted_traces_keys = [] self.plotted_traces = [] self.trajectory_ends_vlines = [] self.data_to_add = [] self.selected_trajectory_ends = [] self.object_id_numbers = [] self.annotations = os.path.join(self.path, 'annotations.pickle') if os.path.exists(self.annotations): f = open(self.annotations, 'r+') data = pickle.load(f) f.close() self.annotated_keys = data.keys() else: self.annotated_keys = [] self.time_mouse_click = time.time() self.cut_objects = False self.delete_objects = False self.join_objects = False self.add_data = False self.crosshair_pen = pg.mkPen('w', width=1) self.ui.qtplot_timetrace.enableAutoRange('xy', False) if self.config is not None: print('**** Sensory stimulus: ', self.config.sensory_stimulus_on) for r, row in enumerate(self.config.sensory_stimulus_on): v1 = pg.PlotDataItem([ self.config.sensory_stimulus_on[r][0], self.config.sensory_stimulus_on[r][0] ], [0, 10]) v2 = pg.PlotDataItem([ self.config.sensory_stimulus_on[r][-1], self.config.sensory_stimulus_on[r][-1] ], [0, 10]) try: f12 = pg.FillBetweenItem( curve1=v1, curve2=v2, brush=pg.mkBrush(self.config.sensory_stimulus_rgba[r])) except: f12 = pg.FillBetweenItem(curve1=v1, curve2=v2, brush=pg.mkBrush( (255, 0, 0, 150))) self.ui.qtplot_timetrace.addItem(f12) lr = pg.LinearRegionItem(values=self.troi) f = 'update_time_region' lr.sigRegionChanged.connect(self.__getattribute__(f)) self.ui.qtplot_timetrace.addItem(lr) print('drawing interesting time points') self.draw_timeseries_vlines_for_interesting_timepoints() print('done drawing interesting time points') self.ui.qtplot_timetrace.setRange(xRange=[ np.min(self.time_epoch_continuous), np.max(self.time_epoch_continuous) ], yRange=[0, np.max(self.nflies)]) self.ui.qtplot_timetrace.setLimits(yMin=0, yMax=np.max(self.nflies)) self.ui.qtplot_timetrace.setLimits(minYRange=np.max(self.nflies), maxYRange=np.max(self.nflies)) self.current_time_vline = pg.InfiniteLine(angle=90, movable=False) self.ui.qtplot_timetrace.addItem(self.current_time_vline, ignoreBounds=True) self.current_time_vline.setPos(0) pen = pg.mkPen((255, 255, 255), width=2) self.current_time_vline.setPen(pen) # hide a bunch of the axes self.ui.qtplot_timetrace.hideAxis('left') self.ui.qtplot_timetrace.hideAxis('bottom') self.ui.qtplot_trajectory.hideAxis('left') self.ui.qtplot_trajectory.hideAxis('bottom')
def toggle_trajec_cut(self): self.set_all_buttons_false() self.cut_objects = True self.crosshair_pen = pg.mkPen('y', width=1) print('Cutting objects!')
def set_draw_line_color(self, color): if self.draw_line: pen = pg.mkPen(color) for segment in self.draw_line.segments: segment.currentPen = segment.pen = pen segment.update()
def __init__(self, orientation, model, border_color, mapper): super(SliceWidget, self).__init__() self.ui = Ui_SliceWidget() # Bug in Windows - https://groups.google.com/forum/#!msg/pyqtgraph/O7E2sWaEWDg/7KPVeiO6qooJ if os.name == 'nt': pg.functions.USE_WEAVE = False else: pg.functions.USE_WEAVE = True self.mapper = mapper # Contains info on whether views should be flipped or not self.scalebar = None self.ui.setupUi(self) self.ui.labelSliceNumber.setFixedWidth(30) self.orientation = orientation self.model = model self.slice_color = border_color self.id = SliceWidget.object_counter SliceWidget.object_counter += 1 self.overlay = InformationOverlay(self) self.overlay.show() # ViewBox. Holds the pg.ImageItems self.viewbox = ViewBox() self.viewbox.wheel_scroll_signal.connect(self.wheel_scroll) self.ui.graphicsView.centralWidget.addItem(self.viewbox) self.viewbox.setAspectLocked() # testing self.viewbox.sigRangeChangedManually.connect(self.range_changed) self.ui.graphicsView.setAntialiasing(True) # self.ui.graphicsView.useOpenGL(True) # Slows things down and seems to mess up antialiasing self.viewbox.enableAutoRange() self.viewbox.scene().sigMouseMoved.connect(self.mouse_moved) self.viewbox.scene().sigMouseClicked.connect(self.mouse_pressed) # Reduce the padding/border between slice views self.ui.graphicsView.ci.layout.setContentsMargins(0, 0, 0, 0) self.ui.graphicsView.ci.layout.setSpacing(1) self.setStyleSheet( 'QWidget#controlsWidget{{ background-color: {} }}'.format( border_color)) self.current_slice_idx = 0 self.viewbox.setAspectLocked(True) # Slice control signals ######################################################################################## self.ui.sliderSlice.valueChanged.connect(self.on_change_slice) self.ui.sliderSlice.sliderPressed.connect(self.slice_slider_pressed) self.ui.sliderSlice.sliderReleased.connect(self.slice_slider_released) self.ui.pushButtonScrollLeft.pressed.connect( self.left_scroll_button_pressed) self.ui.pushButtonScrollLeft.released.connect( self.scroll_button_released) self.ui.pushButtonScrollRight.pressed.connect( self.right_scroll_button_pressed) self.ui.pushButtonScrollRight.released.connect( self.scroll_button_released) self.button_scrolling = False ################################################################################################################ self.ui.pushButtonManageVolumes.clicked.connect(self.on_manage_views) self.vLine = pg.InfiniteLine(angle=90, movable=False) self.hLine = pg.InfiniteLine(angle=0, movable=False) self.hLine.setZValue(10) self.vLine.setZValue(10) self.vLine.setOpacity(0.0) self.hLine.setOpacity(0.0) cross_hair_pen = pg.mkPen(color=(229, 255, 0)) self.vLine.setPen(cross_hair_pen) self.hLine.setPen(cross_hair_pen) self.viewbox.addItem(self.vLine) self.viewbox.addItem(self.hLine) self.setMouseTracking(1) self.roi = RoiOverlay(self) self.annotation_marker = AnnotationOverlay(self) self.ui.seriesSlider.hide() self.layers = self.register_layers() self.orientation_indicator = OrientationIndicator(self) self.show()
def plot_2(self, x, y, plotname, color,symbol): pen = mkPen(color=color,style=QtCore.Qt.DashLine) self.graphWidget.plot(x, y, name=plotname, symbol=symbol,pen=pen, symbolSize=10, symbolBrush=(color))
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())))
def paint(self, p, *args): p.setPen(pg.mkPen(self.border_color)) p.setBrush(pg.mkBrush(self.fill_color)) p.drawRect(self.boundingRect())
def _setup_plot(self): def get_minmax(points): minmax = [float('inf'), float('-inf'), float('inf'), float('-inf')] for pp in points: for p in pp: minmax[0] = min(p[0], minmax[0]) minmax[1] = max(p[0], minmax[1]) minmax[2] = min(p[1], minmax[2]) minmax[3] = max(p[1], minmax[3]) return minmax self.plot.clear() points = self.ca variables = self.selected_vars() colors = colorpalettes.LimitedDiscretePalette(len(variables)) p_axes = self._p_axes() if points is None: return if len(variables) == 2: row_points = self.ca.row_factors[:, p_axes] col_points = self.ca.col_factors[:, p_axes] points = [row_points, col_points] else: points = self.ca.row_factors[:, p_axes] counts = [len(var.values) for var in variables] range_indices = np.cumsum([0] + counts) ranges = zip(range_indices, range_indices[1:]) points = [points[s:e] for s, e in ranges] minmax = get_minmax(points) margin = abs(minmax[0] - minmax[1]) margin = margin * 0.05 if margin > 1e-10 else 1 self.plot.setXRange(minmax[0] - margin, minmax[1] + margin) margin = abs(minmax[2] - minmax[3]) margin = margin * 0.05 if margin > 1e-10 else 1 self.plot.setYRange(minmax[2] - margin, minmax[3] + margin) for i, (v, points) in enumerate(zip(variables, points)): color_outline = colors[i] color_outline.setAlpha(200) color = QColor(color_outline) color.setAlpha(120) item = ScatterPlotItem( x=points[:, 0], y=points[:, 1], brush=QBrush(color), pen=pg.mkPen(color_outline.darker(120), width=1.5), size=np.full((points.shape[0],), 10.1), ) self.plot.addItem(item) for name, point in zip(v.values, points): item = pg.TextItem(name, anchor=(0.5, 0)) self.plot.addItem(item) item.setPos(point[0], point[1]) inertia = self.ca.inertia_of_axis() if np.sum(inertia) == 0: inertia = 100 * inertia else: inertia = 100 * inertia / np.sum(inertia) ax = self.plot.getAxis("bottom") ax.setLabel("Component {} ({:.1f}%)" .format(p_axes[0] + 1, inertia[p_axes[0]])) ax = self.plot.getAxis("left") ax.setLabel("Component {} ({:.1f}%)" .format(p_axes[1] + 1, inertia[p_axes[1]]))
def __init__(self, ctr: si_tt.Client, log: LogClient, config, ui='histogram', **kwargs): """ Instantiates TimeTrace measurement :param ctr: (si_tt.Client) client to timetagger hardware :param log: (LogClient) instance of logclient for logging :param config: (str) name of config file :param ui: (str) name of ui file :param **kwargs: additional keyword arguments TODO: in future, can implement multiple histograms if useful """ # Setup GUI self.gui = Window(gui_template='histogram', host=get_ip()) # Setup stylesheet. self.gui.apply_stylesheet() # Store config self.config = config self.correlation = False if 'type' in self.config: if self.config['type'] == 'correlation': self.correlation = True super().__init__(ctr=ctr, log=log, click_ch=self.config['click_ch'], start_ch=self.config['start_ch'], binwidth=int(self._get_binwidth()), n_bins=self.gui.n_bins.value(), update_interval=0, correlation=self.correlation) if not type(self.config['click_ch']) == int: combined_click_channel = f"{self.config['click_ch'][0]}+{self.config['click_ch'][1]}" ctr.create_combined_channel(channel_name=combined_click_channel, channel_list=self.config['click_ch']) self.config['click_ch'] = [combined_click_channel] self.gates = {} if 'gate_ch' in self.config: # Handle singular input if not isinstance(self.config['gate_ch'], list): self.config['gate_ch'] = [self.config['gate_ch']] # Update GUI to handle gates self._configure_gui_gates() # Setup gated channels for gate_ch in self.config['gate_ch']: ch_name = f'Gated histogram channel {gate_ch}' ctr.create_gated_channel(ch_name, self.config['click_ch'], gate_ch, delay=self.delays[ch_name].value()) self.gates[ch_name] = TimeTrace( ctr=ctr, log=log, click_ch=ch_name, start_ch=self.config['start_ch'], binwidth=int(self._get_binwidth()), n_bins=self.gui.n_bins.value(), update_interval=0, correlation=self.correlation) # Configure clicks self.gui.configure.clicked.connect( lambda: self.update_parameters(binwidth=int(self._get_binwidth()), n_bins=self.gui.n_bins.value())) self.gui.clear.clicked.connect(self.clear_all) self.gui.save.clicked.connect( lambda: self.save(filename=self.gui.save_name.text(), directory=self.config['save_path'])) self.gui.run.clicked.connect(self.run) #### CHANGED CHANGED CHANGED self.gui.fit.clicked.connect(self.fit_config) self._configure_delay_updates() # Configure window length preview self.gui.n_bins.valueChanged.connect(self.update_window_length_label) self.gui.binwidth.valueChanged.connect(self.update_window_length_label) # Configure window length preview self.update_window_length_label() # Initialize plot info self.curve = self.gui.graph.plot(pen=pg.mkPen( color=self.gui.COLOR_LIST[0])) self.gui.graph.getPlotItem().setLabel('bottom', 'Time (s)') self.legend = get_legend_from_graphics_view(self.gui.legend) add_to_legend(self.legend, self.curve, 'Histogram') self.gate_curves = {} index = 1 for gate in self.gates: self.gate_curves[gate] = self.gui.graph.plot(pen=pg.mkPen( color=self.gui.COLOR_LIST[index])) index += 1 add_to_legend(self.legend, self.gate_curves[gate], gate) self.gui.apply_stylesheet() self.fitting = False
def correct(self): self.pushCorrect.setEnabled(False) self.filter_list.setEnabled(False) self.savgol_window.setEnabled(False) self.savgol_poly.setEnabled(False) self.pushAnalyze.setEnabled(False) self.scan_range.setEnabled(False) QtWidgets.QApplication.processEvents() print('def_correct') # extend to avoid edge handling extended = numpy.zeros(3 * self.number_of_projections, dtype=float) print('extended', extended.shape) #, extended) print(extended[0:self.number_of_projections].shape) extended[0:self.number_of_projections] = self.summe print('extended', extended.shape) #, extended) extended[self.number_of_projections:2 * self.number_of_projections] = self.summe + self.summe[-1] print('extended', extended.shape) #, extended) extended[2 * self.number_of_projections:3 * self.number_of_projections] = self.summe + 2 * self.summe[-1] print('extended', extended.shape) #, extended) if (self.savgol_window.value() % 2) != 1: even_value = self.savgol_window.value() self.savgol_window.setValue(even_value + 1) self.filter = self.filter_list.currentText() if self.filter == 'Savitzky_Golay': filtered_trace = signal.savgol_filter(extended, self.savgol_window.value(), self.savgol_poly.value()) print('Applying Savitzky-Golay') if self.filter == 'Low_Pass': kern = signal.firwin(31, cutoff=1 / (2 * self.number_of_sequences), window="hamming") filtered_trace = Smooth = signal.lfilter(kern, 1, extended) print('Applying Low-Pass') # cut from extended filtered_trace_cut = filtered_trace[ self.number_of_projections:2 * self.number_of_projections] - self.summe[-1] print('summe', self.summe.shape) #, self.summe) print('filtered_trace_cut', filtered_trace_cut.shape) #, filtered_trace_cut) self.correction_list = self.summe - filtered_trace_cut print('correction_list', self.correction_list.shape) #, self.correction_list) if self.max_theta < 270: x = numpy.arange( self.number_of_projections) * 180 / self.number_of_projections else: x = numpy.arange( self.number_of_projections) * 360 / self.number_of_projections pen = pg.mkPen(color=(255, 0, 0), width=5) #, style=QtCore.Qt.DashLine) self.Graph.plot(x, self.summe, name="original", pen='b', clear=True) self.Graph.plot(x, filtered_trace_cut, name="corrected", pen=pen) self.Graph.plot(x, self.correction_list, name="adjustment", pen='g') self.corrected_sinogram = numpy.zeros( (self.full_size, self.number_of_projections), dtype=float) n = 0 while n < self.number_of_projections: self.progressBar.setValue( (n + 1) * 100 / self.number_of_projections) QtWidgets.QApplication.processEvents() #print('correcting n', n, self.sino.shape) self.corrected_sinogram[:, n] = ndimage.shift(self.sino[:, n], self.correction_list[n], mode='nearest', prefilter=True) n = n + 1 print('corrected_sinogram', self.corrected_sinogram.shape) img = Image.fromarray(self.corrected_sinogram) self.filename_out2 = self.path_out_corr + '/Sinogram_comparison' + self.namepart + 'sinogram_corrected' + '.tif' img.save(self.filename_out2) print('saved corrected sinogram') print('prepare display') myarray = self.corrected_sinogram * 256 / 16000 # * contrast - (contrast - 128) # 2048 - 1920 myarray = myarray.repeat(2, axis=0).repeat(2, axis=1) yourQImage = qimage2ndarray.array2qimage(myarray) self.corrected_sino.setPixmap(QPixmap(yourQImage)) print('done') self.pushReconstruct.setEnabled(True) self.pushCorrect.setEnabled(True) self.filter_list.setEnabled(True) self.savgol_window.setEnabled(True) self.savgol_poly.setEnabled(True) self.pushAnalyze.setEnabled(True) self.pushApplyVolume.setEnabled(True) self.scan_range.setEnabled(True)
#vb = p.getViewBox() # vb.autoRange(padding=0.1) #curve.setFillBrush((0, 0, 100, 100)) #curve.setFillLevel(0) #lr = pg.LinearRegionItem([100, 4900]) #p.addItem(lr) init_vals = get_vals() # prepare Pen objects for curve styles pen0 = pg.mkPen( color=mpl2pg('C0'), width=1, style=QtCore.Qt.SolidLine, ) pen1 = pg.mkPen( color=mpl2pg('C0'), width=1, style=QtCore.Qt.DashLine, ) pen2 = pg.mkPen( color=mpl2pg('C3'), width=1, style=QtCore.Qt.SolidLine, ) # initalize data data0 = np.array([init_vals[0]])
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( str(v) for v in values if v not in selected_values) right = ", ".join(str(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, directory='.', **kwargs): super(astraPlotWidget, self).__init__(**kwargs) self.beam = raf.beam() self.twiss = rtf.twiss() self.directory = directory ''' twissPlotWidget ''' self.twissPlotView = GraphicsView(useOpenGL=True) self.twissPlotWidget = GraphicsLayout() self.twissPlotView.setCentralItem(self.twissPlotWidget) self.latticePlotData = imageio.imread( os.path.dirname(os.path.abspath(__file__)) + '/lattice_plot.png') self.latticePlots = {} self.twissPlots = {} i = -1 for entry in self.twissplotLayout: if entry == 'next_row': self.twissPlotWidget.nextRow() else: i += 1 p = self.twissPlotWidget.addPlot(title=entry['name']) p.showGrid(x=True, y=True) vb = p.vb vb.setYRange(*entry['range']) latticePlot = ImageItem(self.latticePlotData) latticePlot.setOpts(axisOrder='row-major') vb.addItem(latticePlot) latticePlot.setZValue(-1) # make sure this image is on top # latticePlot.setOpacity(0.5) self.twissPlots[entry['name']] = p.plot( pen=mkPen('b', width=3)) self.latticePlots[p.vb] = latticePlot p.vb.sigRangeChanged.connect(self.scaleLattice) ''' beamPlotWidget ''' self.beamPlotWidget = QWidget() self.beamPlotLayout = QVBoxLayout() self.beamPlotWidget.setLayout(self.beamPlotLayout) # # self.beamPlotChoice = # self.beamPlotAxisWidget = QWidget() self.beamPlotAxisWidget.setMaximumHeight(100) Form = self.beamPlotAxisWidget self.beamPlotXAxisDict = OrderedDict() self.beamPlotXAxisDict['x'] = {'scale': 1e3, 'axis': 'x [mm]'} self.beamPlotXAxisDict['y'] = {'scale': 1e3, 'axis': 'y [mm]'} self.beamPlotXAxisDict['z'] = { 'scale': 1e6, 'axis': 'z [micron]', 'norm': True } self.beamPlotXAxisDict['t'] = { 'scale': 1e12, 'axis': 't [ps]', 'norm': True } self.beamPlotXAxisDict['cpx'] = {'scale': 1e3, 'axis': 'cpx [keV]'} self.beamPlotXAxisDict['cpy'] = {'scale': 1e3, 'axis': 'cpy [keV]'} self.beamPlotXAxisDict['BetaGamma'] = { 'scale': 0.511, 'axis': 'cp [MeV]' } # Form.setObjectName(("Form")) # Form.resize(874, 212) sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(Form.sizePolicy().hasHeightForWidth()) Form.setSizePolicy(sizePolicy) self.horizontalLayout = QHBoxLayout(Form) self.horizontalLayout.setObjectName("horizontalLayout") self.beamPlotXAxisCombo = QComboBox(Form) self.beamPlotXAxisCombo.addItems(list(self.beamPlotXAxisDict.keys())) self.beamPlotXAxisCombo.setCurrentIndex(2) self.horizontalLayout.addWidget(self.beamPlotXAxisCombo) self.beamPlotYAxisCombo = QComboBox(Form) self.beamPlotYAxisCombo.addItems(list(self.beamPlotXAxisDict.keys())) self.beamPlotYAxisCombo.setCurrentIndex(6) self.horizontalLayout.addWidget(self.beamPlotYAxisCombo) self.groupBox = QGroupBox(Form) self.groupBox.setObjectName("groupBox") self.formLayout = QFormLayout(self.groupBox) self.formLayout.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow) self.formLayout.setObjectName("formLayout") self.chooseSliceWidth = QRadioButton(self.groupBox) self.chooseSliceWidth.setObjectName(("chooseSliceWidth")) self.formLayout.setWidget(0, QFormLayout.LabelRole, self.chooseSliceWidth) self.sliceWidth = QDoubleSpinBox(self.groupBox) self.sliceWidth.setDecimals(6) self.sliceWidth.setObjectName("sliceWidth") self.formLayout.setWidget(0, QFormLayout.FieldRole, self.sliceWidth) self.chooseSliceNumber = QRadioButton(self.groupBox) self.chooseSliceNumber.setChecked(True) self.chooseSliceNumber.setObjectName("chooseSliceNumber") self.formLayout.setWidget(1, QFormLayout.LabelRole, self.chooseSliceNumber) self.sliceNumber = QSpinBox(self.groupBox) self.sliceNumber.setObjectName(("sliceNumber")) self.formLayout.setWidget(1, QFormLayout.FieldRole, self.sliceNumber) self.horizontalLayout.addWidget(self.groupBox) self.chooseSliceWidth.setText(_translate("Form", "Slice Width", None)) self.chooseSliceNumber.setText( _translate("Form", "Number of Slices", None)) self.sliceWidth.setRange(1e-6, 1) self.sliceWidth.setSingleStep(0.00001) self.histogramWidth = 0.0005 self.sliceWidth.setValue(self.histogramWidth) # self.sliceNumber = QSpinBox() self.sliceNumber.setRange(10, 10000) self.sliceNumber.setSingleStep(10) self.histogramBins = 100 self.sliceNumber.setValue(self.histogramBins) # self.beamPlotXAxisCombo = QComboBox() # self.beamPlotAxisLayout = QHBoxLayout() # self.beamPlotAxisWidget.setLayout(self.beamPlotAxisLayout) # self.beamPlotAxisLayout.addWidget(self.beamPlotXAxisCombo) # self.beamPlotAxisLayout.addWidget(self.beamPlotYAxisCombo) # self.beamPlotAxisLayout.addWidget(self.beamPlotNumberBins) self.beamPlotXAxisCombo.currentIndexChanged.connect(self.plotDataBeam) self.beamPlotYAxisCombo.currentIndexChanged.connect(self.plotDataBeam) self.chooseSliceNumber.toggled.connect(self.plotDataBeam) self.sliceNumber.valueChanged.connect(self.plotDataBeam) self.sliceWidth.valueChanged.connect(self.plotDataBeam) # self.beamPlotXAxisCombo.setCurrentIndex(2) # self.beamPlotYAxisCombo.setCurrentIndex(5) self.canvasWidget = QWidget() l = QVBoxLayout(self.canvasWidget) self.sc = MyStaticMplCanvas(self.canvasWidget, width=1, height=1, dpi=150) l.addWidget(self.sc) self.beamPlotLayout.addWidget(self.beamPlotAxisWidget) self.beamPlotLayout.addWidget(self.canvasWidget) ''' slicePlotWidget ''' self.sliceParams = [ { 'name': 'slice_normalized_horizontal_emittance', 'units': 'm-rad', 'text': 'enx' }, { 'name': 'slice_normalized_vertical_emittance', 'units': 'm-rad', 'text': 'eny' }, { 'name': 'slice_peak_current', 'units': 'A', 'text': 'PeakI' }, { 'name': 'slice_relative_momentum_spread', 'units': '%', 'text': 'sigma-p' }, { 'name': 'slice_beta_x', 'units': 'm', 'text': 'beta_x' }, { 'name': 'slice_beta_y', 'units': 'm', 'text': 'beta_y' }, ] self.slicePlotWidget = QWidget() self.slicePlotLayout = QVBoxLayout() self.slicePlotWidget.setLayout(self.slicePlotLayout) # self.slicePlotView = GraphicsView(useOpenGL=True) self.slicePlotWidgetGraphicsLayout = GraphicsLayoutWidget() # self.slicePlots = {} self.slicePlotCheckbox = {} self.curve = {} self.sliceaxis = {} self.slicePlotCheckboxWidget = QWidget() self.slicePlotCheckboxLayout = QVBoxLayout() self.slicePlotCheckboxWidget.setLayout(self.slicePlotCheckboxLayout) self.slicePlot = self.slicePlotWidgetGraphicsLayout.addPlot( title='Slice', row=0, col=50) self.slicePlot.showAxis('left', False) self.slicePlot.showGrid(x=True, y=True) i = -1 colors = ['b', 'r', 'g', 'k', 'y', 'm', 'c'] for param in self.sliceParams: i += 1 axis = AxisItem("left") labelStyle = {'color': '#' + colorStr(mkColor(colors[i]))[0:-2]} axis.setLabel(text=param['text'], units=param['units'], **labelStyle) viewbox = ViewBox() axis.linkToView(viewbox) viewbox.setXLink(self.slicePlot.vb) self.sliceaxis[param['name']] = [axis, viewbox] self.curve[param['name']] = PlotDataItem(pen=colors[i], symbol='+') viewbox.addItem(self.curve[param['name']]) col = self.findFirstEmptyColumnInGraphicsLayout() self.slicePlotWidgetGraphicsLayout.ci.addItem(axis, row=0, col=col, rowspan=1, colspan=1) self.slicePlotWidgetGraphicsLayout.ci.addItem(viewbox, row=0, col=50) p.showGrid(x=True, y=True) # self.slicePlots[param] = self.slicePlot.plot(pen=colors[i], symbol='+') self.slicePlotCheckbox[param['name']] = QCheckBox(param['text']) self.slicePlotCheckboxLayout.addWidget( self.slicePlotCheckbox[param['name']]) self.slicePlotCheckbox[param['name']].stateChanged.connect( self.plotDataSlice) # self.slicePlotView.setCentralItem(self.slicePlotWidgetGraphicsLayout) self.slicePlotSliceWidthWidget = QSpinBox() self.slicePlotSliceWidthWidget.setMaximum(500) self.slicePlotSliceWidthWidget.setValue(100) self.slicePlotSliceWidthWidget.setSingleStep(10) self.slicePlotSliceWidthWidget.setSuffix(" slices") self.slicePlotSliceWidthWidget.setSpecialValueText('Automatic') self.slicePlotAxisWidget = QWidget() self.slicePlotAxisLayout = QHBoxLayout() self.slicePlotAxisWidget.setLayout(self.slicePlotAxisLayout) self.slicePlotAxisLayout.addWidget(self.slicePlotCheckboxWidget) self.slicePlotAxisLayout.addWidget(self.slicePlotSliceWidthWidget) # self.slicePlotXAxisCombo.currentIndexChanged.connect(self.plotDataSlice) self.slicePlotSliceWidthWidget.valueChanged.connect( self.changeSliceLength) # self.beamPlotXAxisCombo.setCurrentIndex(2) # self.beamPlotYAxisCombo.setCurrentIndex(5) self.slicePlotLayout.addWidget(self.slicePlotAxisWidget) self.slicePlotLayout.addWidget(self.slicePlotWidgetGraphicsLayout) self.layout = QVBoxLayout() self.setLayout(self.layout) self.tabWidget = QTabWidget() self.folderButton = QPushButton('Select Directory') self.folderLineEdit = QLineEdit() self.folderLineEdit.setReadOnly(True) self.folderLineEdit.setText(self.directory) self.reloadButton = QPushButton() self.reloadButton.setIcon(qApp.style().standardIcon( QStyle.SP_BrowserReload)) self.folderWidget = QGroupBox() self.folderLayout = QHBoxLayout() self.folderLayout.addWidget(self.folderButton) self.folderLayout.addWidget(self.folderLineEdit) self.folderLayout.addWidget(self.reloadButton) self.folderWidget.setLayout(self.folderLayout) self.folderWidget.setMaximumWidth(800) self.reloadButton.clicked.connect( lambda: self.changeDirectory(self.directory)) self.folderButton.clicked.connect(self.changeDirectory) self.fileSelector = QComboBox() self.fileSelector.currentIndexChanged.connect(self.updateScreenCombo) self.screenSelector = QComboBox() self.screenSelector.currentIndexChanged.connect(self.changeScreen) self.beamWidget = QGroupBox() self.beamLayout = QHBoxLayout() self.beamLayout.addWidget(self.fileSelector) self.beamLayout.addWidget(self.screenSelector) self.beamWidget.setLayout(self.beamLayout) self.beamWidget.setMaximumWidth(800) self.beamWidget.setVisible(False) self.folderBeamWidget = QWidget() self.folderBeamLayout = QHBoxLayout() self.folderBeamLayout.setAlignment(Qt.AlignLeft) self.folderBeamWidget.setLayout(self.folderBeamLayout) self.folderBeamLayout.addWidget(self.folderWidget) self.folderBeamLayout.addWidget(self.beamWidget) self.tabWidget.addTab(self.twissPlotView, 'Twiss Plots') self.tabWidget.addTab(self.beamPlotWidget, 'Beam Plots') self.tabWidget.addTab(self.slicePlotWidget, 'Slice Beam Plots') # self.log = lw.loggerWidget() # self.log.addLogger(logger) # sys.stdout = lw.redirectLogger(self.log, 'stdout') # self.tabWidget.addTab(self.log,'Log') self.tabWidget.currentChanged.connect(self.changeTab) self.layout.addWidget(self.folderBeamWidget) self.layout.addWidget(self.tabWidget) self.plotType = 'Twiss' self.changeDirectory(self.directory)
def update_plot_data_3(self): pen = pg.mkPen(color=(200, 0, 0)) #self.x3 = xaxis[0:self.i3] #move the first y element. self.y3 = self.data3[0:] # Remove the first self.data_line3.setData(self.y3, pen=pen) # Update the data. self.i3 += 1
import pyqtgraph as pg mapCoord = {'x0': 0, 'y0': 0, 'x1': 10018, 'y1': 17946, 'cmap_x0': 0, 'cmap_y0': 0, 'cmap_x1': 10018, 'cmap_y1': 17946, 'proj_x0': -637925, 'proj_x1': 864625, 'proj_y0': -657675, 'proj_y1': -3349425, 'cmap_proj_x0': -637925, 'cmap_proj_x1': 864625, 'cmap_proj_y0': -657675, 'cmap_proj_y1': -3349425} skinnyBlackPlotPen = pg.mkPen(color=(0, 0, 0), width=1) whitePlotPen = pg.mkPen(color=(255, 255, 255), width=2) skinnyWhitePlotPen = pg.mkPen(color=(255, 255, 255), width=1) blackPlotPen = pg.mkPen(color=(0, 0, 0), width=2) greyPlotPen = pg.mkPen(color=(200, 200, 200), width=2) redPlotPen = pg.mkPen(color=(100, 0, 0), width=2) bluePlotPen = pg.mkPen(color=(0, 0, 255), width=2) greenPlotPen = pg.mkPen(color=(76, 153, 0), width=2) purplePlotPen = pg.mkPen(color=(102, 0, 204), width=2) orangePlotPen = pg.mkPen(color=(255, 128, 0), width=2) bluePlotPen = pg.mkPen(color=(0, 0, 255), width=2) tealPlotPen = pg.mkPen(color=(0, 204, 204), width=2) pinkPlotPen = pg.mkPen(color=(153, 0, 153), width=2) brownPlotPen = pg.mkPen(color=(92, 64, 51), width=2) dataFileName = './data/GreenlandInBedCoord_V2.h5' cmFileName = './data/dataCMValues_V2.h5'
def makePen(self, label): color = QtGui.QColor(self.config.configDict[self.config.PlotDataItemColor % label]) width = self.config.configDict[self.config.PlotDataItemWidth % label] style = self.config.configDict[self.config.PlotDataItemPattern % label] return pg.mkPen(color=color, width=width, style=style)
w2 = view.addViewBox() w2.setAspectLocked(True) view.nextRow() w3 = view.addPlot() w4 = view.addPlot() print("Generating data, this takes a few seconds...") # There are a few different ways we can draw scatter plots; each is optimized for different types of data: # 1) All spots identical and transform-invariant (top-left plot). # In this case we can get a huge performance boost by pre-rendering the spot # image and just drawing that image repeatedly. n = 300 s1 = pg.ScatterPlotItem(size=10, pen=pg.mkPen( None), brush=pg.mkBrush(255, 255, 255, 120)) pos = np.random.normal(size=(2, n), scale=1e-5) spots = [{'pos': pos[:, i], 'data': 1} for i in range(n)] + [{'pos': [0, 0], 'data': 1}] s1.addPoints(spots) w1.addItem(s1) # Make all plots clickable lastClicked = [] def clicked(plot, points): global lastClicked for p in lastClicked: p.resetPen() print("clicked points", points)
from PyQt5 import QtCore, QtGui, QtWidgets import numpy as np import pyqtgraph as pg STYLE = { 'pen': pg.mkPen(0, 0, 0), 'pen-hover': pg.mkPen(255, 255, 255, width=1), 'brush': pg.mkBrush(100, 100, 100), 'brush-hover': pg.mkBrush(150, 150, 150), 'brush-selected': pg.mkBrush(200, 200, 200), 'underline-central': pg.mkPen(176, 35, 48, width=3), 'underline-flanker': pg.mkPen(51, 152, 188, width=3) } STYLE['underline-central'].setCapStyle(QtCore.Qt.FlatCap) STYLE['underline-flanker'].setCapStyle(QtCore.Qt.FlatCap) class ClickableBar(QtWidgets.QGraphicsRectItem): def __init__(self, barplot, x, y, w, h): self.barplot = barplot self.x = x _scale = 10000 QtWidgets.QGraphicsRectItem.__init__(self, QtCore.QRectF(x * _scale, y * _scale, w * _scale, h * _scale)) self.setScale(1 / _scale) self.setPen(STYLE['pen']) self.setBrush(STYLE['brush']) self.setAcceptHoverEvents(True) self.is_current_flag = False def hoverEnterEvent(self, ev): self.savedPen = self.pen()
def update_plot_data_2(self): pen = pg.mkPen(color=(0, 0, 200)) #self.x2 = data[:self.i2,0] #move the first y element. self.y2 = self.data2[:] # Remove the first self.data_line2.setData(self.y2, pen=pen) # Update the data. self.i2 += 1
def error_pen(self, pen): self._pen_stash['error_pen_on'] = pg.mkPen(pen) if self.error is not None: self.error.setOpts(pen=pg.mkPen(pen))
def __init__(self, title, **kwargs): super().__init__(title, **kwargs) self.setMinimumHeight(550) self.setMinimumWidth(550) self.axsumy = self.plots.addPlot(title="") self.axsumy.setFixedWidth(100) self.sumy = self.axsumy.plot() self.sumy_fit = self.axsumy.plot( pen=pg.mkPen(style=QtCore.Qt.DashLine, color=color_palette[1])) self.img = pg.ImageItem() self.aximg = self.plots.addPlot(title="") self.aximg.addItem(self.img) self.axsumy.setYLink(self.aximg) # Isocurve draplotsg self.iso = pg.IsocurveItem(level=1000, pen=color_palette[2]) self.iso.setParentItem(self.img) self.iso.setZValue(5) # Contrast/color control self.hist = pg.HistogramLUTItem() self.hist.setImageItem(self.img) self.plots.addItem(self.hist) # Draggable line for setting isocurve level self.isoLine = pg.InfiniteLine(angle=0, movable=True, pen=color_palette[2]) self.hist.vb.addItem(self.isoLine) self.hist.vb.setMouseEnabled( y=False) # makes user interaction a little easier self.isoLine.setValue(1000) self.isoLine.setZValue(1000) # bring iso line above contrast controls self.isoLine.sigDragged.connect(self.updateIsocurve) # Monkey-patch the image to use our custom hover function. # This is generally discouraged (you should subclass ImageItem instead), # but it works for a very simple use like this. self.img.hoverEvent = self.imageHoverEvent self.plots.nextRow() self.plots.nextColumn() self.axsumx = self.plots.addPlot() self.axsumx.setFixedHeight(100) self.axsumx.setXLink(self.aximg) self.sumx = self.axsumx.plot() self.sumx_fit = self.axsumx.plot( pen=pg.mkPen(style=QtCore.Qt.DashLine, color=color_palette[1])) self.table.setMinimumHeight(85) self.img.translate(-0.5, -0.5) self.scalex = 1 self.scaley = 1 self.cx = 0 self.cy = 0
from psort.dependencies.neo_package import spike2io import sys import os import subprocess import pkg_resources installed_pkg = {pkg.key for pkg in pkg_resources.working_set} ## ############################################################################# #%% VARIABLES (PROJECT_FOLDER, _) = os.path.split(os.path.dirname(os.path.abspath(__file__))) GLOBAL_FONT = QtGui.QFont() GLOBAL_FONT.setStyleHint(QtGui.QFont.Helvetica) GLOBAL_FONT.setPointSize(10) GLOBAL_FONT.setWeight(QtGui.QFont.Normal) GLOBAL_PG_PEN = pg.mkPen(color='k', width=1, style=QtCore.Qt.SolidLine) nanLabel = -9999 ## ############################################################################# #%% Set widget Defaults def set_plotWidget(plot_widget, bkg=True): if bkg: plot_widget.setBackground('w') plot_widget.setTitle("Y: Variable_Name(au) | X: Variable_Name(au)", color='k', size='12') plot_widget.showLabel('left', show=False) plot_widget.showLabel('bottom', show=False) plot_widget.getAxis('left').setPen(GLOBAL_PG_PEN) plot_widget.getAxis('left').tickFont = GLOBAL_FONT
def mask_pen(self, pen): self._pen_stash['mask_pen_on'] = pg.mkPen(pen) if self.error is not None: self.error.setPen(pen=pg.mkPen(pen))
########################### ###### VISUALIZATION ###### ########################### import pyqtgraph as pg import steps.visual as visual # Visualization initialization app = pg.mkQApp() # Create plot display plots = visual.PlotDisplay("3d fine astrocytic process model", size=(600, 400)) # Create Plots pen = pg.mkPen(color=(255, 255, 255), width=2) p = plots.addCompSpecPlot("<span style='font-size: 16pt'>Number of GCaMP_ca", sim, "cyto", "ca_GCaMP6s", data_size=1000, measure="count", pen=(255, 0.647 * 255, 0)) p.getAxis('left').setPen(pen) p.getAxis('bottom').setPen(pen) p.showGrid(x=True, y=True) labelStyle = {'color': '#ffffff', 'font-size': '16px'} p.setLabel('bottom', 'Time', 's', **labelStyle) plots.nextRow()
def setup(self, win): # Data plots self.data_plots = [] self.data_curves = [] for i in range(self.num_depths): title = "{:.0f} cm".format(100 * self.depths[i]) plot = win.addPlot(row=0, col=i, title=title) plot.setMenuEnabled(False) plot.setMouseEnabled(x=False, y=False) plot.hideButtons() plot.showGrid(x=True, y=True) plot.setYRange(0, 2**16) plot.hideAxis("left") plot.hideAxis("bottom") plot.plot(np.arange(self.sweeps_per_frame), 2**15 * np.ones(self.sweeps_per_frame)) curve = plot.plot(pen=utils.pg_pen_cycler()) self.data_plots.append(plot) self.data_curves.append(curve) # Spectral density plot self.sd_plot = win.addPlot(row=1, col=0, colspan=self.num_depths) self.sd_plot.setMenuEnabled(False) self.sd_plot.setMouseEnabled(x=False, y=False) self.sd_plot.hideButtons() self.sd_plot.setLabel("left", "Normalized PSD (dB)") self.sd_plot.showGrid(x=True, y=True) self.sd_curve = self.sd_plot.plot(pen=utils.pg_pen_cycler()) dashed_pen = pg.mkPen("k", width=2, style=QtCore.Qt.DashLine) self.sd_threshold_line = pg.InfiniteLine(angle=0, pen=dashed_pen) self.sd_plot.addItem(self.sd_threshold_line) self.smooth_max = utils.SmoothMax( self.est_update_rate, tau_decay=0.5, tau_grow=0, hysteresis=0.2, ) # Rolling speed plot self.vel_plot = pg.PlotItem() self.vel_plot.setMenuEnabled(False) self.vel_plot.setMouseEnabled(x=False, y=False) self.vel_plot.hideButtons() self.vel_plot.setLabel("bottom", "Time (s)") self.vel_plot.showGrid(x=True, y=True) self.vel_plot.setXRange(-EST_VEL_HISTORY_LENGTH, 0) self.vel_max_line = pg.InfiniteLine(angle=0, pen=pg.mkPen("k", width=1)) self.vel_plot.addItem(self.vel_max_line) self.vel_scatter = pg.ScatterPlotItem(size=8) self.vel_plot.addItem(self.vel_scatter) self.vel_html_fmt = '<span style="color:#000;font-size:24pt;">{:.1f} {}</span>' self.vel_text_item = pg.TextItem(anchor=(0.5, 0)) self.vel_plot.addItem(self.vel_text_item) # Sequence speed plot self.sequences_plot = pg.PlotItem() self.sequences_plot.setMenuEnabled(False) self.sequences_plot.setMouseEnabled(x=False, y=False) self.sequences_plot.hideButtons() self.sequences_plot.setLabel("bottom", "History") self.sequences_plot.showGrid(y=True) self.sequences_plot.setXRange(-NUM_SAVED_SEQUENCES + 0.5, 0.5) tmp = np.flip(np.arange(NUM_SAVED_SEQUENCES) == 0) brushes = [pg.mkBrush(utils.color_cycler(n)) for n in tmp] self.bar_graph = pg.BarGraphItem( x=np.arange(-NUM_SAVED_SEQUENCES, 0) + 1, height=np.zeros(NUM_SAVED_SEQUENCES), width=0.8, brushes=brushes, ) self.sequences_plot.addItem(self.bar_graph) self.sequences_text_item = pg.TextItem(anchor=(0.5, 0)) self.sequences_plot.addItem(self.sequences_text_item) sublayout = win.addLayout(row=2, col=0, colspan=self.num_depths) sublayout.addItem(self.vel_plot, col=0) sublayout.addItem(self.sequences_plot, col=1) self.setup_is_done = True self.update_processing_config()