def generatePicture(self): # pre-computing a QPicture object allows paint() to run much more quickly, # rather than re-drawing the shapes every time. self.picture = QtGui.QPicture() p = QtGui.QPainter(self.picture) for bi in self.data: if bi.biType == 'up': p.setPen(pg.mkPen('r')) p.drawLine( QtCore.QPointF( chan.chanBars[bi.barIndex1].closeIndex, chan.lowBar[chan.chanBars[bi.barIndex1].closeIndex]), QtCore.QPointF( chan.chanBars[bi.barIndex2].closeIndex, chan.highBar[chan.chanBars[bi.barIndex2].closeIndex])) else: p.setPen(pg.mkPen('g')) p.drawLine( QtCore.QPointF( chan.chanBars[bi.barIndex1].closeIndex, chan.highBar[chan.chanBars[bi.barIndex1].closeIndex]), QtCore.QPointF( chan.chanBars[bi.barIndex2].closeIndex, chan.lowBar[chan.chanBars[bi.barIndex2].closeIndex])) p.end()
def draw(self, data, width=1. / 3.): """draw(self, data, width=1./3.) -> None draw an item of boxplot Parameters ---------- data : tuple data has the following format: timestamp : int outliers : array-like lower whisker : float first quartile : float median : float third quartile : float upper whisker : float width : float (default : 1/3) width of an item of boxplot """ t_, out, low_w, q1, q2, q3, up_w = data[:] self.p.drawLine(QtCore.QPointF(t_, low_w), QtCore.QPointF(t_, up_w)) self.p.drawLine(QtCore.QPointF(t_ - width, low_w), QtCore.QPointF(t_ + width, low_w)) self.p.drawLine(QtCore.QPointF(t_ - width, up_w), QtCore.QPointF(t_ + width, up_w)) for out_ in out: self.p.drawEllipse(QtCore.QPointF(t_, out_), width, width) self.p.setBrush(pg.mkBrush("#000000")) self.p.drawRect(QtCore.QRectF(t_ - width, q1, width * 2, q3 - q1)) self.p.setBrush(pg.mkBrush("#FFFFFF")) self.p.drawLine(QtCore.QPointF(t_ - width, q2), QtCore.QPointF(t_ + width, q2))
def paintEvent(self, event): painter = QtGui.QPainter(self) width = self.width() height = self.height() top, bottom = height * .1, height * .8 left, right = width * .1, width * .8 rect = QtCore.QRect(left, top, right, bottom) painter.fillRect(rect, QtGui.QColor('black')) #painter.setWindow(rect) dist = bottom - top relval = self.threshold.signal.buffer[-1] / self.MAX relval = min(1.0, relval) reltop = (1.0 - relval) * bottom + top relbottom = height * 0.9 - reltop rect = QtCore.QRect(left, reltop, right, relbottom) color = QtGui.QColor( 'green' if self.threshold.passfail.buffer[-1] else 'red') painter.fillRect(rect, color) thr_height = self.threshold.threshold / self.MAX thr_top = (1.0 - thr_height) * bottom + top rect = QtCore.QRect(left, thr_top, right, 2) painter.fillRect(rect, QtGui.QColor('white'))
def generatePicture(self): ## pre-computing a QPicture object allows paint() to run much more quickly, ## rather than re-drawing the shapes every time. global last_pf self.picture = QtGui.QPicture() p = QtGui.QPainter(self.picture) w = 1.0/3 #(self.data[1][0] - self.data[0][0]) / 3. #last_pf = self.data[0][2] first = True for (t, open, close, min, max, pf) in self.data: if open > close: #p.setBrush(pg.mkBrush('g')) p.setPen(pg.mkPen('g')) elif open < close: #p.setBrush(pg.mkBrush('r')) p.setPen(pg.mkPen('r')) else: p.setPen(pg.mkPen('w')) if min < max: p.drawLine(QtCore.QPointF(t, min), QtCore.QPointF(t, max)) p.drawRect(QtCore.QRectF(t-w, open, w*2, close-open)) p.setPen(pg.mkPen('y', width=1.5, style=QtCore.Qt.DashLine)) if not first: p.drawLine(QtCore.QPointF(t-1, last_pf), QtCore.QPointF(t, pf)) first = False last_pf = pf p.end()
def generatePicture(self): self.picture = QtGui.QPicture() p = QtGui.QPainter(self.picture) p.setPen(pg.mkPen('w', width=1 / 2.)) for (t, v) in self.data: p.drawLine(QtCore.QPointF(t, v - 2), QtCore.QPointF(t, v + 2)) p.end()
def small_square(p, colors=['w', 0], linecolor='g'): w1, h1, w2, h2 = [2.5, 1.5, 2, 1] # Exterior square p.setBrush(pg.mkBrush(colors[1])) p.setPen(pg.mkPen('k')) p.translate(-w1 / 2, -h1 / 2) # translate from center to low-x, low-y position. rectangle = QtCore.QRectF(0, 0, w1, h1) p.drawRoundedRect(rectangle, 0.05, 0.05) p.translate(w1 / 2, h1 / 2) # go back to center positio # Interior square p.setBrush(pg.mkBrush(colors[0])) p.setPen(pg.mkPen(linecolor)) p.translate(-w2 / 2, -h2 / 2) rectangle = QtCore.QRectF(0, 0, w2, h2) p.drawRoundedRect(rectangle, 0.05, 0.05) p.translate(w2 / 2, h2 / 2) # go back to center positio # Inter-Internal p.setPen(pg.mkPen('k')) w = w2 * 0.8 h = h2 * 0.5 p.translate(-w / 2, -h / 2) rectangle = QtCore.QRectF(0, 0, w, h) p.drawRoundedRect(rectangle, 0.5, 0.5) p.translate(w / 2, h / 2) # go back to center position
def __init__(self, sampleinterval=2000): """ Monitor System Statistics Input Args: sampleinterval (int) = polling interval for collecting data """ self.sampleinterval = sampleinterval self.data = deque(maxlen=20) self.device_info = info.InformationStatistics() self.app = QtGui.QApplication([]) self.win = pg.GraphicsWindow(title="Monitor System Statistics") self.win.resize(800, 600) self.plot = self.win.addPlot( title='CPU and Swap Mem Usage', axisItems={'bottom': TimeAxisItem(orientation='bottom')}) self.plot.addLegend() self.plot.setLimits(yMin=0, yMax=100, xMin=0) self.plot.showGrid(x=True, y=True) self.plot.setMouseEnabled(False, False) self.plot.setRange(yRange=(0, 100), disableAutoRange=True) # Trying to fix y-axis at 0,100 self.plot.setLabel('left', "Percentage Utilization") self.plot.setLabel('bottom', "Time (s)") self.cpu_stats = self.plot.plot(pen='r', name="CPU Usage") self.swap_mem_stats = self.plot.plot(pen='b', name="Swap Mem Usage") self.time = QtCore.QTime() self.time.start() self.timer = QtCore.QTimer() self.timer.timeout.connect(self.update_plot) self.timer.start(self.sampleinterval)
def boundingRect(self): if self._data: x_min = np.float(-1) x_max = np.float(len(self._data) + 1) y_min = np.float(-1) y_max = np.float(max([v[0] for v in self._data])) return QtCore.QRectF(x_min, y_min, x_max-x_min, y_max-y_min) return QtCore.QRectF(self._picture.boundingRect())
def parent(self, index): if not index.isValid(): return QtCore.QModelIndex() childItem = self.getItem(index) parentItem = childItem.parent() if parentItem == self.rootItem: # is the left side childItem or parentItem? return QtCore.QModelIndex() return self.createIndex(parentItem.parent().childNumber(), 0, parentItem)
class ImageItem(pg.ImageItem): sigLevelsChanged = QtCore.Signal() sigLookupTableChanged = QtCore.Signal() def __init__(self, image=None, **kargs): pg.ImageItem.__init__(self, image, **kargs) def setLevels(self, levels, update=True): """ Set image scaling levels. Can be one of: * [blackLevel, whiteLevel] * [[minRed, maxRed], [minGreen, maxGreen], [minBlue, maxBlue]] Only the first format is compatible with lookup tables. See :func:`makeARGB <pyqtgraph.makeARGB>` for more details on how levels are applied. """ emit = self.levels is None or not np.allclose(self.levels, levels) pg.ImageItem.setLevels(self, levels, update) if emit: self.sigLevelsChanged.emit() def setLookupTable(self, lut, update=True, emit=True): """ Set the lookup table (numpy array) to use for this image. (see :func:`makeARGB <pyqtgraph.makeARGB>` for more information on how this is used). Optionally, lut can be a callable that accepts the current image as an argument and returns the lookup table to use. Ordinarily, this table is supplied by a :class:`HistogramLUTItem <pyqtgraph.HistogramLUTItem>` or :class:`GradientEditorItem <pyqtgraph.GradientEditorItem>`. """ pg.ImageItem.setLookupTable(self, lut, update) if emit: self.sigLookupTableChanged.emit() def setImage(self, image=None, autoLevels=True, levels=None, **kwargs): """ Add behaviour that if autoLevels is False and levels is None, levels is set to current (if that is not None). (In original, this causes an error.) :param image: :param autoLevels: :param levels: :param kwargs: :return: """ if levels is None and not autoLevels: if self.levels is not None: logger.debug('setImage retaining levels') levels = self.levels else: autoLevels = True pg.ImageItem.setImage(self, image=image, autoLevels=autoLevels, levels=levels, **kwargs)
def boundingRect(self): # If not use numpy, then very small value will not paint if self._data: x_min = np.float(-1) x_max = np.float(len(self._data) + 1) y_min = np.float(-1) y_max = np.float(max([item[1] for item in self._data])) return QtCore.QRectF(x_min, y_min, x_max - x_min, y_max - y_min) return QtCore.QRectF(self._picture.boundingRect())
def index(self, row, column, parent=QtCore.QModelIndex()): parentNode = self.getNode(parent) childItem = parentNode.child(row) if childItem: return self.createIndex(row, column, childItem) else: return QtCore.QModelIndex()
def _get_line_chart(self): """Return QPicture() with line chart by self._data""" picture = QtGui.QPicture() pen = QtGui.QPainter(picture) pen.setPen(pg.mkPen(self.border_color)) for ind in range(0, len(self._data) - 1): pen.drawLine(QtCore.QPointF(ind, self._data[ind][3]), QtCore.QPointF(ind + 1, self._data[ind + 1][3])) pen.end() return picture
def index(self, row, column, parent=QtCore.QModelIndex()): if parent.isValid() and parent.column()!= 0: return QtCore.QModelIndex() parentItem = self.getItem(parent) if parentItem is None: return QtCore.QModelIndex() childItem = parentItem.child(row) if childItem: return self.createIndex(row, column, childItem) else: return QtCore.QModelIndex()
def readSettings(self): settings = QtCore.QSettings('dataviz', 'dataviz') self.lastDir = settings.value('lastDir', '.', str) pos = settings.value('pos', QtCore.QPoint(200, 200)) if isinstance(pos, QtCore.QVariant): pos = pos.toPyObject() self.move(pos) size = settings.value('size', QtCore.QSize(400, 400)) if isinstance(size, QtCore.QVariant): size = size.toPyObject() self.resize(size)
def SSModule(self, opt, pwr, p): print(opt, pwr) # lengths framessx = 144.1 framessy = 125 sssensorx = 102.7 sssensory = 94.2 epsilon = sssensorx * 0.1 w1, h1, w2, h2 = [sssensorx, sssensory, framessx, framessy] p.rotate(-90) # rotate to put empty part to the left # frame |_| frame1+frame3+frame2 p.setBrush(pg.mkBrush(GetPowerColor(pwr))) p.setPen(0) xoff = -w2 / 2 yoff = -h2 / 2 p.translate( xoff, yoff) # translate from center to low-x, low-y position. w = (w2 - w1) * 0.5 h = h2 frame1 = QtCore.QRectF(0, 0, w + epsilon, h) p.drawRect(frame1) p.translate(w + w1 - epsilon, 0) w = (w2 - w1) * 0.5 h = h2 frame2 = QtCore.QRectF(0, 0, w + epsilon, h) p.drawRect(frame2) p.translate(-w - w1 + epsilon, (h2 - h1) * 0.5 + h1) w = w2 h = (h2 - h1) * 0.5 frame3 = QtCore.QRectF(0, 0, w, h) p.drawRect(frame3) p.translate(0, -epsilon) #p.drawRect(rectangle) p.translate(0, epsilon) # sensor p.setBrush(pg.mkBrush('#778899')) p.setPen(pg.mkPen(GetOpticalColor(opt))) p.translate((w2 - w1) * 0.5, -h1) sensor = QtCore.QRectF(0, 0, w1, h1) p.drawRect(sensor) p.translate(w1 * 0.5, h1 * 0.5) # go back to center position p.rotate(90) # rotate to put empty part to the left
def boundingRect(self): if self._boundingRect is None: (xmn, xmx) = self.dataBounds(ax=0) (ymn, ymx) = self.dataBounds(ax=1) if xmn is None or ymn is None: return QtCore.QRectF() px = py = 0.0 self._boundingRect = QtCore.QRectF(xmn - px, ymn - py, (2 * px) + xmx - xmn, (2 * py) + ymx - ymn) return self._boundingRect
def generatePicture(self): self.picture = QtGui.QPicture() p = QtGui.QPainter(self.picture) p.setPen(pg.mkPen('w')) w = (self.data[1][0] - self.data[0][0]) / 3. for (t, open, close, min, max) in self.data: p.drawLine(QtCore.QPointF(t, min), QtCore.QPointF(t, max)) if open > close: p.setBrush(pg.mkBrush('r')) else: p.setBrush(pg.mkBrush('g')) p.drawRect(QtCore.QRectF(t - w, open, w * 2, close - open)) p.end()
def generate_picture(self, boundingRect): w = self.datasrc.period * 0.7 w2 = w * 0.5 left,right = boundingRect.left(), boundingRect.right() p = self.painter p.begin(self.picture) p.setPen(pg.mkPen(self.bear_color)) p.setBrush(pg.mkBrush(self.bear_color)) for t,open,close,volume in self.datasrc.bear_rows(4, left, right, yscale=self.ax.vb.yscale): p.drawRect(QtCore.QRectF(t-w2, 0, w, volume)) p.setPen(pg.mkPen(self.bull_color)) p.setBrush(pg.mkBrush(self.bull_color)) for t,open,close,volume in self.datasrc.bull_rows(4, left, right, yscale=self.ax.vb.yscale): p.drawRect(QtCore.QRectF(t-w2, 0, w, volume)) p.end()
def generatePicture(self): ## pre-computing a QPicture object allows paint() to run much more quickly, ## rather than re-drawing the shapes every time. self.picture = QtGui.QPicture() p = QtGui.QPainter(self.picture) p.setPen(pg.mkPen('w')) w = (self.data[1][0] - self.data[0][0]) / 3. for (t, open, close, min, max) in self.data: p.drawLine(QtCore.QPointF(t, min), QtCore.QPointF(t, max)) if open > close: p.setBrush(pg.mkBrush('r')) else: p.setBrush(pg.mkBrush('g')) p.drawRect(QtCore.QRectF(t-w, open, w*2, close-open)) p.end()
class UDPThread(QtCore.QThread): newPacket = QtCore.pyqtSignal(object) def __init__(self, port=8888): super(UDPThread, self).__init__() self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) self.socket.bind(('127.0.0.1', port)) self.buffer = [] def run(self): if chooseMuse: while True: unpacker = struct.Struct("fffff") data = self.socket.recv(unpacker.size) data = unpacker.unpack(data) self.newPacket.emit(data) else: while True: data, addr = self.socket.recvfrom(1024) data = eval(data) self.newPacket.emit(eval(str(data)))
def __init__(self, sampleinterval, timewindow, size=(600, 350)): # Data stuff self.tick_idx = 0 self._bufsize = int(timewindow / sampleinterval) self.databuffer = collections.deque([0.0] * self._bufsize, self._bufsize) self.x = np.linspace(0.0, timewindow, self._bufsize) self.y = np.zeros(self._bufsize, dtype=np.float) # Candlestick data self.candlestick_item = CandlestickItem() # PyQtGraph stuff self.app = QtGui.QApplication([]) self.plt = pg.plot(title='Plot Viewer') self.plt.resize(*size) self.plt.showGrid(x=True, y=True) self.plt.setLabel('left', 'amplitude', 'V') self.plt.setLabel('bottom', 'time', 's') self.plt.setXRange(0., timewindow) self.plt.setYRange(0., 30) self.curve = self.plt.plot(self.x, self.y, pen=(255, 0, 0)) self.plt.addItem(self.candlestick_item) # QTimer self.timer = QtCore.QTimer() self.timer.timeout.connect(self.updateplot) self.timer.start(1000)
class MyThread(QtCore.QThread): new_data = QtCore.pyqtSignal(object, object, object) def __init__(self, parent=None): QtCore.QThread.__init__(self, parent) self.exiting = False def __del__(self): self.exiting = True self.wait() def run(self): queue = mp.Queue() p = mp.Process(target=sw.wave(queue)) p.start() p.join() while not self.exiting: points = 100 #number of data points X = np.arange(points) Y = np.sin(np.arange(points) / points * 3 * np.pi + time.time()) data = queue.get() if data == 'done': break else: self.new_data.emit(data, X, Y)
class FloatModel(QtCore.QObject): """A cursor position is either a float or int (determined at instantiation) and preserves the type in assignment. Furthermore, the object emits either an int or float pyqtSignal when the value is changed through the setter.""" value_changed = QtCore.Signal(float) def __init__(self, val: float): super().__init__() self._val = val @property def val(self): return self._val @val.setter def val(self, newval): if isinstance(newval, float): self._val = newval else: try: self._val = float(newval) except TypeError as e: raise e self.value_changed.emit(self._val) @QtCore.pyqtSlot(float) def on_value_changed(self, newval): self.val = newval
def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) self.graphWidget = pg.PlotWidget() self.setCentralWidget(self.graphWidget) data = np.random.normal(size=(10, 1000)) signal_chunks = self.load_signal_chunks_list('1574634652027') wave_pair_wrapper = self.load_wave_pair_wrapper('1574634652027') wave_pair_wrappers = (signal_chunk.get_wave_pair_wrapper() for signal_chunk in signal_chunks) tension_wave_wrapper = wave_pair_wrapper.get_wave_a_wrapper() tension_wave = tension_wave_wrapper.get_wave() # tension_data = np.vstack((tension_wave.ts, tension_wave.ys)) # plot data: x, y values self.graphWidget.setLabel('bottom', 'Time (s)', size='30') self.graphWidget.setBackground('w') self.graphWidget.showGrid(x=True, y=True) pen = pg.mkPen(color=(0, 0, 255), style=QtCore.Qt.SolidLine) # self.graphWidget.plot(tension_wave.ts, tension_wave.ys, pen=pen) # tension_curve = self.plot("Tension", 'b') curves = [] chunkSize = 100 # Remove chunks after we have 10 maxChunks = 10 tension_data = np.empty((chunkSize + 1, 2)) tension_ptr = 0 startTime = pg.ptime.time() def tension_update(): global tension_curve, tension_data, tension_ptr now = pg.ptime.time() for c in curves: c.setPos(-(now - startTime), 0) i = tension_ptr % chunkSize if i == 0: tension_curve = self.plot() curves.append(tension_curve) last = tension_data[-1] data5 = np.empty((chunkSize + 1, 2)) data5[0] = last while len(curves) > maxChunks: c = curves.pop(0) self.removeItem(c) else: curve = curves[-1] tension_data[i + 1, 0] = now - startTime tension_data[i + 1, 1] = np.random.normal() curve.setData(x=tension_data[:i + 2, 0], y=tension_data[:i + 2, 1]) tension_ptr += 1 timer = QtCore.QTimer() # timer.timeout.connect(update) timer.timeout.connect(tension_update) timer.start(50)
def _calc_robot_polygon(self, x, y, theta): """ Prepare a QPolygonF representing the robot by a triangle, given a pose @return: a QPolygonF object. """ # angle coordinates translation theta = math.radians(theta) # 3 points around the gravity center (x, y) # all oriented following the theta angle x1 = (self.ROBOT_WIDTH_MM // 2) * math.cos(theta) y1 = (self.ROBOT_WIDTH_MM // 2) * math.sin(theta) x2 = (self.ROBOT_WIDTH_MM // 2) * math.cos(theta + 2.5 * (math.pi / 3.)) y2 = (self.ROBOT_WIDTH_MM // 2) * math.sin(theta + 2.5 * (math.pi / 3.)) x3 = (self.ROBOT_WIDTH_MM // 2) * math.cos(theta + 3.5 * (math.pi / 3.)) y3 = (self.ROBOT_WIDTH_MM // 2) * math.sin(theta + 3.5 * (math.pi / 3.)) points = [(x + x1, y + y1), (x + x2, y + y2), (x + x3, y + y3)] qpoints = [QtCore.QPointF(x, y) for (x, y) in points] qpoly = QtGui.QPolygonF(qpoints) return qpoly
def boundingRect(self): ## boundingRect _must_ indicate the entire area that will be drawn on ## or else we will get artifacts and possibly crashing. # This constructor is (x_topleft, y_topleft, width, height) topleftx = self.x - self.r toplefty = self.y - self.r return QtCore.QRectF(topleftx, toplefty, 2 * self.r, 2 * self.r)
def paint_position(painter, x, y, direction): painter.setBrush(mkBrush(RED)) painter.setPen(mkPen(None)) if direction in ['E', 'W']: robot_width = 50 robot_height = 100 else: robot_width = 100 robot_height = 50 x_compensation = 0 y_compensation = 0 if direction == 'E': y_compensation = robot_height / 2 elif direction == 'S': x_compensation = (CELL_WIDTH - robot_width) / 2 elif direction == 'W': x_compensation = CELL_WIDTH - robot_width y_compensation = robot_height / 2 elif direction == 'N': x_compensation = (CELL_WIDTH - robot_width) / 2 y_compensation = CELL_WIDTH - robot_height painter.drawRect( QtCore.QRectF( x * CELL_WIDTH + x_compensation, -(y + 1) * CELL_WIDTH + y_compensation, robot_width, robot_height, ))
def createPoly(self, n, r, s, xx, yy, act): polygon = QtGui.QPolygonF() w = 360 / n # angle per step for i in range(n): # add the points of polygon t = w * i + s y = r * math.sin(math.radians(t)) x = r * math.cos(math.radians(t)) if i == 0: if act > 0: polygon.append(QtCore.QPointF(xx + x, 2 + (yy + y))) elif act < 0: polygon.append(QtCore.QPointF(xx + x, (yy + y) - 2)) else: polygon.append(QtCore.QPointF(xx + x, yy + y)) return polygon
def setRect(self, *args): """ setRect(rect) or setRect(x,y,w,h) Sets translation and scaling of this ImageItem to display the current image within the rectangle given as ``QtCore.QRect`` or ``QtCore.QRectF`` `rect`, or described by parameters `x, y, w, h`, defining starting position, width and height. This method cannot be used before an image is assigned. See the :ref:`examples <ImageItem_examples>` for how to manually set transformations. """ if len(args) == 0: self.resetTransform( ) # reset scaling and rotation when called without argument return if isinstance(args[0], (QtCore.QRectF, QtCore.QRect)): rect = args[0] # use QRectF or QRect directly else: if hasattr(args[0], '__len__'): args = args[0] # promote tuple or list of values rect = QtCore.QRectF( *args) # QRectF(x,y,w,h), but also accepts other initializers tr = QtGui.QTransform() tr.translate(rect.left(), rect.top()) tr.scale(rect.width() / self.width(), rect.height() / self.height()) self.setTransform(tr)