def __init__(self, parent=None):
     QtGui.QSplitter.__init__(self, QtCore.Qt.Horizontal)
     self.ctrlPanel = QtGui.QSplitter(QtCore.Qt.Vertical)
     self.addWidget(self.ctrlPanel)
     self.fieldList = QtGui.QListWidget()
     self.fieldList.setSelectionMode(self.fieldList.ExtendedSelection)
     self.ptree = ptree.ParameterTree(showHeader=False)
     self.filter = DataFilterParameter()
     self.colorMap = ColorMapParameter()
     self.params = ptree.Parameter.create(name='params', type='group', children=[self.filter, self.colorMap])
     self.ptree.setParameters(self.params, showTop=False)
     
     self.plot = PlotWidget()
     self.ctrlPanel.addWidget(self.fieldList)
     self.ctrlPanel.addWidget(self.ptree)
     self.addWidget(self.plot)
     
     bg = pg.mkColor(pg.getConfigOption('background'))
     bg.setAlpha(150)
     self.filterText = pg.TextItem(border=pg.getConfigOption('foreground'), color=bg)
     self.filterText.setPos(60,20)
     self.filterText.setParentItem(self.plot.plotItem)
     
     self.data = None
     self.mouseOverField = None
     self.scatterPlot = None
     self.style = dict(pen=None, symbol='o')
     
     self.fieldList.itemSelectionChanged.connect(self.fieldSelectionChanged)
     self.filter.sigFilterChanged.connect(self.filterChanged)
     self.colorMap.sigColorMapChanged.connect(self.updatePlot)
    def __init__(self, parent=None):
        QtGui.QSplitter.__init__(self, QtCore.Qt.Horizontal)
        self.ctrlPanel = QtGui.QSplitter(QtCore.Qt.Vertical)
        self.addWidget(self.ctrlPanel)
        self.fieldList = QtGui.QListWidget()
        self.fieldList.setSelectionMode(self.fieldList.ExtendedSelection)
        self.ptree = ptree.ParameterTree(showHeader=False)
        self.filter = DataFilterParameter()
        self.colorMap = ColorMapParameter()
        self.params = ptree.Parameter.create(name="params", type="group", children=[self.filter, self.colorMap])
        self.ptree.setParameters(self.params, showTop=False)

        self.plot = PlotWidget()
        self.ctrlPanel.addWidget(self.fieldList)
        self.ctrlPanel.addWidget(self.ptree)
        self.addWidget(self.plot)

        bg = pg.mkColor(pg.getConfigOption("background"))
        bg.setAlpha(150)
        self.filterText = pg.TextItem(border=pg.getConfigOption("foreground"), color=bg)
        self.filterText.setPos(60, 20)
        self.filterText.setParentItem(self.plot.plotItem)

        self.data = None
        self.mouseOverField = None
        self.scatterPlot = None
        self.style = dict(pen=None, symbol="o")

        self.fieldList.itemSelectionChanged.connect(self.fieldSelectionChanged)
        self.filter.sigFilterChanged.connect(self.filterChanged)
        self.colorMap.sigColorMapChanged.connect(self.updatePlot)
    def test_config(self):
        '''Test PyQtGraph configurations edited with RENDERING'''

        state = qt_config.RENDERING['useOpenGL']
        self.assertEquals(state, pg.getConfigOption('useOpenGL'))

        qt_config.RENDERING['useOpenGL'] = not state
        self.assertEquals(not state, pg.getConfigOption('useOpenGL'))

        qt_config.RENDERING['useOpenGL'] = state
    def test_config(self):
        '''Test PyQtGraph configurations edited with RENDERING'''

        state = qt_config.RENDERING['useOpenGL']
        self.assertEquals(state, pg.getConfigOption('useOpenGL'))

        qt_config.RENDERING['useOpenGL'] = not state
        self.assertEquals(not state, pg.getConfigOption('useOpenGL'))

        qt_config.RENDERING['useOpenGL'] = state
Exemple #5
0
def test_ensuring_substrate():
    prev_setting = pg.getConfigOption("useCupy")
    try:
        pg.setConfigOption("useCupy", True)
        ii = pg.ImageItem()

        data = cupy.random.randint(0, 255, size=(32, 32)).astype(cupy.uint8)
        assert data is ii._ensure_proper_substrate(data, cupy)
        assert isinstance(ii._ensure_proper_substrate(data, cupy),
                          cupy.ndarray)
        assert data is not ii._ensure_proper_substrate(data, np)
        assert isinstance(ii._ensure_proper_substrate(data, np), np.ndarray)

        data = np.random.randint(0, 255, size=(32, 32)).astype(np.uint8)
        assert data is ii._ensure_proper_substrate(data, np)
        assert isinstance(ii._ensure_proper_substrate(data, np), np.ndarray)
        assert data is not ii._ensure_proper_substrate(data, cupy)
        assert isinstance(ii._ensure_proper_substrate(data, cupy),
                          cupy.ndarray)

        data = range(0, 255)
        assert data is not ii._ensure_proper_substrate(data, np)
        assert isinstance(ii._ensure_proper_substrate(data, np), np.ndarray)
        assert data is not ii._ensure_proper_substrate(data, cupy)
        assert isinstance(ii._ensure_proper_substrate(data, cupy),
                          cupy.ndarray)
    finally:
        pg.setConfigOption("useCupy", prev_setting)
    def generatePicture(self):
        self.picture = QtGui.QPicture()
        if self.pen is None or self.pos is None or self.adjacency is None:
            return
        p = QtGui.QPainter(self.picture)
        pen = self.pen
        if pen == 'default':
            pen = getConfigOption('foreground')
        p.setPen(fn.mkPen((165, 42, 42), width=3))

        pts = self.pos[self.adjacency]
        pts = pts.reshape((pts.shape[0] * pts.shape[1], pts.shape[2]))
        x = pts[:, 0]
        y = pts[:, 1]
        path = QtGui.QPainterPath()
        path.moveTo(x[0], y[0])
        for i in range(1, y.shape[0]):
            if i % 2 != 0:
                c1x = x[i - 1] + 0.4 * (x[i] - x[i - 1])
                c1y = y[i - 1] + 0.05 * (y[i] - y[i - 1])
                c2x = x[i] + 0.2 * (x[i] - x[i - 1])
                c2y = y[i] - 0.5 * (y[i] - y[i - 1])
                c1 = pg.QtCore.QPointF(c1x, c1y)
                c2 = pg.QtCore.QPointF(c2x, c2y)
                endPoint = pg.QtCore.QPointF(x[i], y[i])
                path.cubicTo(c1, c2, endPoint)
            else:
                path.moveTo(x[i], y[i])
        p.drawPath(path)
Exemple #7
0
 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()
Exemple #8
0
 def __init__(self, parent=None, useOpenGL=None, background='k'):
     """Re-implementation of QGraphicsView that removes scrollbars and allows unambiguous control of the 
     viewed coordinate range. Also automatically creates a QGraphicsScene and a central QGraphicsWidget
     that is automatically scaled to the full view geometry.
     
     By default, the view coordinate system matches the widget's pixel coordinates and 
     automatically updates when the view is resized. This can be overridden by setting 
     autoPixelRange=False. The exact visible range can be set with setRange().
     
     The view can be panned using the middle mouse button and scaled using the right mouse button if
     enabled via enableMouse()  (but ordinarily, we use ViewBox for this functionality)."""
     self.closed = False
     
     QtGui.QGraphicsView.__init__(self, parent)
     
     if useOpenGL is None:
         useOpenGL = pyqtgraph.getConfigOption('useOpenGL')
     
     self.useOpenGL(useOpenGL)
     
     self.setCacheMode(self.CacheBackground)
     
     if background is not None:
         brush = fn.mkBrush(background)
         self.setBackgroundBrush(brush)
     
     self.setFocusPolicy(QtCore.Qt.StrongFocus)
     self.setFrameShape(QtGui.QFrame.NoFrame)
     self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
     self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
     self.setTransformationAnchor(QtGui.QGraphicsView.NoAnchor)
     self.setResizeAnchor(QtGui.QGraphicsView.AnchorViewCenter)
     self.setViewportUpdateMode(QtGui.QGraphicsView.MinimalViewportUpdate)
     
     
     #self.setSceneRect(QtCore.QRectF(-1e10, -1e10, 2e10, 2e10))
     
     self.lockedViewports = []
     self.lastMousePos = None
     self.setMouseTracking(True)
     self.aspectLocked = False
     #self.yInverted = True
     self.range = QtCore.QRectF(0, 0, 1, 1)
     self.autoPixelRange = True
     self.currentItem = None
     self.clearMouse()
     self.updateMatrix()
     self.sceneObj = GraphicsScene()
     self.setScene(self.sceneObj)
     
     ## by default we set up a central widget with a grid layout.
     ## this can be replaced if needed.
     self.centralWidget = None
     self.setCentralItem(QtGui.QGraphicsWidget())
     self.centralLayout = QtGui.QGraphicsGridLayout()
     self.centralWidget.setLayout(self.centralLayout)
     
     self.mouseEnabled = False
     self.scaleCenter = False  ## should scaling center around view center (True) or mouse click (False)
     self.clickAccepted = False
Exemple #9
0
 def __init__(self, *args, **kargs):
     """
     Accepts the same arguments as setData()
     """
     prof = debug.Profiler('ScatterPlotItem.__init__', disabled=True)
     GraphicsObject.__init__(self)
     
     self.picture = None   # QPicture used for rendering when pxmode==False
     self.fragments = None # fragment specification for pxmode; updated every time the view changes.
     self.fragmentAtlas = SymbolAtlas()
     
     self.data = np.empty(0, dtype=[('x', float), ('y', float), ('size', float), ('symbol', object), ('pen', object), ('brush', object), ('data', object), ('fragCoords', object), ('item', object)])
     self.bounds = [None, None]  ## caches data bounds
     self._maxSpotWidth = 0      ## maximum size of the scale-variant portion of all spots
     self._maxSpotPxWidth = 0    ## maximum size of the scale-invariant portion of all spots
     self.opts = {
         'pxMode': True, 
         'useCache': True,  ## If useCache is False, symbols are re-drawn on every paint. 
         'antialias': pg.getConfigOption('antialias'),
     }   
     
     self.setPen(200,200,200, update=False)
     self.setBrush(100,100,150, update=False)
     self.setSymbol('o', update=False)
     self.setSize(7, update=False)
     prof.mark('1')
     self.setData(*args, **kargs)
     prof.mark('setData')
     prof.finish()
 def paint(self, p, *args, **kwargs):
     if self.picture == None:
         self.generatePicture()
     if pg.getConfigOption("antialias") is True:
         print("setting antialias")
     p.setRenderHint(True)
     self.picture.play(p)
Exemple #11
0
 def __init__(self, *args, **kargs):
     """
     Forwards all arguments to :func:`setData <pyqtgraph.PlotCurveItem.setData>`.
     
     Some extra arguments are accepted as well:
     
     ==============  =======================================================
     **Arguments:**
     parent          The parent GraphicsObject (optional)
     clickable       If True, the item will emit sigClicked when it is 
                     clicked on. Defaults to False.
     ==============  =======================================================
     """
     GraphicsObject.__init__(self, kargs.get('parent', None))
     self.clear()
     self.path = None
     self.fillPath = None
     self._boundsCache = [None, None]
         
     ## this is disastrous for performance.
     #self.setCacheMode(QtGui.QGraphicsItem.DeviceCoordinateCache)
     
     self.metaData = {}
     self.opts = {
         'pen': fn.mkPen('w'),
         'shadowPen': None,
         'fillLevel': None,
         'brush': None,
         'stepMode': False,
         'name': None,
         'antialias': pg.getConfigOption('antialias'),
     }
     self.setClickable(kargs.get('clickable', False))
     self.setData(*args, **kargs)
Exemple #12
0
def update(antialias=pg.getConfigOption('antialias'),
           connect='all',
           skipFiniteCheck=False):
    global curve, data, ptr, elapsed, fpsLastUpdate

    if connect == 'array':
        connect = connect_array

    # Measure
    t_start = perf_counter()
    curve.setData(data[ptr],
                  antialias=antialias,
                  connect=connect,
                  skipFiniteCheck=skipFiniteCheck)
    app.processEvents(QtCore.QEventLoop.ProcessEventsFlag.AllEvents)
    t_end = perf_counter()
    elapsed.append(t_end - t_start)
    ptr = (ptr + 1) % data.shape[0]

    # update fps at most once every 0.2 secs
    if t_end - fpsLastUpdate > 0.2:
        fpsLastUpdate = t_end
        average = np.mean(elapsed)
        fps = 1 / average
        pw.setTitle('%0.2f fps - %0.1f ms avg' % (fps, average * 1_000))
Exemple #13
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        GraphicsObject.__init__(self)

        self.qpicture = None  ## rendered picture for display

        self.axisOrder = getConfigOption('imageAxisOrder')

        if 'edgecolors' in kwargs.keys():
            self.edgecolors = kwargs['edgecolors']
        else:
            self.edgecolors = None

        if 'antialiasing' in kwargs.keys():
            self.antialiasing = kwargs['antialiasing']
        else:
            self.antialiasing = False

        if 'cmap' in kwargs.keys():
            if kwargs['cmap'] in Gradients.keys():
                self.cmap = kwargs['cmap']
            else:
                raise NameError(
                    'Undefined colormap, should be one of the following: ' +
                    ', '.join(['"' + i + '"' for i in Gradients.keys()]) + '.')
        else:
            self.cmap = 'viridis'

        # If some data have been sent we directly display it
        if len(args) > 0:
            self.setData(*args)

        self.levels = None
Exemple #14
0
 def __init__(self, *args, **kargs):
     """
     Accepts the same arguments as setData()
     """
     prof = debug.Profiler('ScatterPlotItem.__init__', disabled=True)
     GraphicsObject.__init__(self)
     
     self.picture = None   # QPicture used for rendering when pxmode==False
     self.fragments = None # fragment specification for pxmode; updated every time the view changes.
     self.fragmentAtlas = SymbolAtlas()
     
     self.data = np.empty(0, dtype=[('x', float), ('y', float), ('size', float), ('symbol', object), ('pen', object), ('brush', object), ('data', object), ('fragCoords', object), ('item', object)])
     self.bounds = [None, None]  ## caches data bounds
     self._maxSpotWidth = 0      ## maximum size of the scale-variant portion of all spots
     self._maxSpotPxWidth = 0    ## maximum size of the scale-invariant portion of all spots
     self.opts = {
         'pxMode': True, 
         'useCache': True,  ## If useCache is False, symbols are re-drawn on every paint. 
         'antialias': pg.getConfigOption('antialias'),
     }   
     
     self.setPen(200,200,200, update=False)
     self.setBrush(100,100,150, update=False)
     self.setSymbol('o', update=False)
     self.setSize(7, update=False)
     prof.mark('1')
     self.setData(*args, **kargs)
     prof.mark('setData')
     prof.finish()
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'
Exemple #16
0
def test_getArrayRegion(transpose=False):
    pr = pg.PolyLineROI([[0, 0], [27, 0], [0, 28]], closed=True)
    pr.setPos(1, 1)
    rois = [
        (pg.ROI([1, 1], [27, 28], pen='y'), 'baseroi'),
        (pg.RectROI([1, 1], [27, 28], pen='y'), 'rectroi'),
        (pg.EllipseROI([1, 1], [27, 28], pen='y'), 'ellipseroi'),
        (pr, 'polylineroi'),
    ]
    for roi, name in rois:
        # For some ROIs, resize should not be used.
        testResize = not isinstance(roi, pg.PolyLineROI)

        origMode = pg.getConfigOption('imageAxisOrder')
        try:
            if transpose:
                pg.setConfigOptions(imageAxisOrder='row-major')
                check_getArrayRegion(roi,
                                     'roi/' + name,
                                     testResize,
                                     transpose=True)
            else:
                pg.setConfigOptions(imageAxisOrder='col-major')
                check_getArrayRegion(roi, 'roi/' + name, testResize)
        finally:
            pg.setConfigOptions(imageAxisOrder=origMode)
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'
Exemple #18
0
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 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'
Exemple #20
0
    def set_style(self, style=None):
        """PgUserAxisItem의 모양을 설정한다.

        Args:
          style : Dict형태로 모양을 입력한다.
            {'font_family': 'Courier New',
             'label_font_size': 15,
             'tick_font_size': 15,
             'tick_thickness': 2,
             'tickTextOffset': 10}

        """
        if style is None:
            return

        if "tick_thickness" in style:
            self.setPen(pg.getConfigOption("foreground"),
                        width=style["tick_thickness"])
        if "tickTextOffset" in style:
            self.setStyle(tickTextOffset=style["tickTextOffset"])
        if "font_family" in style and "tick_font_size" in style:
            self.setTickFont(
                QFont(style["font_family"], style["tick_font_size"]))
        elif "font_family" in style:
            self.setTickFont(QFont(style["font_family"]))
        elif "tick_font_size" in style:
            self.setTickFont(QFont("Courier New", style["tick_font_size"]))

        if "font_family" in style and "label_font_size" in style:
            self.label.setFont(
                QFont(style["font_family"], style["label_font_size"]))
        elif "font_family" in style:
            self.label.setFont(QFont(style["font_family"]))
        elif "label_font_size" in style:
            self.label.setFont(QFont("Courier New", style["label_font_size"]))
Exemple #21
0
    def __init__(
        self,
        *,
        x: np.ndarray = None,
        y: np.ndarray = None,
        z: np.ndarray = None,
        **kwargs,
    ):
        super().__init__()

        self.qpicture: Optional[QPicture] = None
        self.axisOrder = getConfigOption("imageAxisOrder")

        self.edgecolors = kwargs.get("edgecolors", None)
        self.antialiasing = kwargs.get("antialiasing", False)

        # set up colormap
        if "cmap" in kwargs.keys():
            if kwargs["cmap"] in cc_cmaps:
                cmap = kwargs["cmap"]
            else:
                raise NameError(
                    "Undefined colormap, should be one of the following: "
                    + ", ".join([f'"{i}"' for i in cc_cmaps])  # TODO: make this legible
                    + "."
                )
        else:
            cmap = "fire"

        lut = cc.palette[cmap]
        lut = [QColor(*hex2uint8(v)) for v in lut]
        self.lut = lut

        # set up data
        self.setData(x, y, z)
Exemple #22
0
 def __init__(self, image=None, **kargs):
     """
     See :func:`setImage <pyqtgraph.ImageItem.setImage>` for all allowed initialization arguments.
     """
     GraphicsObject.__init__(self)
     self.menu = None
     self.image = None   ## original image data
     self.qimage = None  ## rendered image for display
     
     self.paintMode = None
     
     self.levels = None  ## [min, max] or [[redMin, redMax], ...]
     self.lut = None
     self.autoDownsample = False
     
     self.axisOrder = getConfigOption('imageAxisOrder')
     
     # In some cases, we use a modified lookup table to handle both rescaling
     # and LUT more efficiently
     self._effectiveLut = None
     
     self.drawKernel = None
     self.border = None
     self.removable = False
     
     if image is not None:
         self.setImage(image, **kargs)
     else:
         self.setOpts(**kargs)
    def __init__(self,
                 size,
                 width=5,
                 brush=None,
                 pen=None,
                 suffix='m',
                 offset=None):
        GraphicsObject.__init__(self)
        GraphicsWidgetAnchor.__init__(self)
        self.setFlag(self.ItemHasNoContents)
        self.setAcceptedMouseButtons(QtCore.Qt.NoButton)

        if brush is None:
            brush = getConfigOption('foreground')
        self.brush = fn.mkBrush(brush)
        self.pen = fn.mkPen(pen)
        self._width = width
        self.size = size
        if offset == None:
            offset = (0, 0)
        self.offset = offset

        self.bar = QtGui.QGraphicsRectItem()
        self.bar.setPen(self.pen)
        self.bar.setBrush(self.brush)
        self.bar.setParentItem(self)

        self.text = TextItem(text=fn.siFormat(size, suffix=suffix),
                             anchor=(0.5, 1),
                             angle=90,
                             color=(0, 0, 0))
        self.text.setParentItem(self)
Exemple #24
0
    def update_plot(self):
        point = self.trace_attrs['Point']

        symbol = point['symbol']
        if symbol == 'None':
            symbol = None

        point = {
            'symbol': symbol,
            'symbolSize': point['Size'],
            'symbolBrush': tuple(point['Brush'])
        }

        line = self.trace_attrs['Line']
        width = line['width']
        line = {'color': line['color'], 'style': line_styles[line['style']]}

        if pg.getConfigOption('useOpenGL'):
            line['width'] = width

        pen = pg.mkPen(**line)

        if 'Fill' in self.trace_attrs and self.trace_attrs['Fill'][
                'Fill Annotation']:
            point['fillBrush'] = tuple(self.trace_attrs['Fill']['Brush'])
            point['fillLevel'] = 0

        if self.trace is None:
            self.trace = self.plot_view.plot([0, 1, 2, 3], [0, 0, 0, 0],
                                             pen=pen,
                                             **point)
        else:
            self.trace.setData([0, 1, 2, 3], [0, 0, 0, 0], pen=pen, **point)

        self.attrs = {'pen': pen, 'point': point}
Exemple #25
0
    def __init__(self, parent=None, useOpenGL=None, background='k'):
        """Re-implementation of QGraphicsView that removes scrollbars and allows unambiguous control of the 
        viewed coordinate range. Also automatically creates a QGraphicsScene and a central QGraphicsWidget
        that is automatically scaled to the full view geometry.
        
        By default, the view coordinate system matches the widget's pixel coordinates and 
        automatically updates when the view is resized. This can be overridden by setting 
        autoPixelRange=False. The exact visible range can be set with setRange().
        
        The view can be panned using the middle mouse button and scaled using the right mouse button if
        enabled via enableMouse()  (but ordinarily, we use ViewBox for this functionality)."""
        self.closed = False

        QtGui.QGraphicsView.__init__(self, parent)

        if useOpenGL is None:
            useOpenGL = pyqtgraph.getConfigOption('useOpenGL')

        self.useOpenGL(useOpenGL)

        self.setCacheMode(self.CacheBackground)

        if background is not None:
            brush = fn.mkBrush(background)
            self.setBackgroundBrush(brush)

        self.setFocusPolicy(QtCore.Qt.StrongFocus)
        self.setFrameShape(QtGui.QFrame.NoFrame)
        self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.setTransformationAnchor(QtGui.QGraphicsView.NoAnchor)
        self.setResizeAnchor(QtGui.QGraphicsView.AnchorViewCenter)
        self.setViewportUpdateMode(QtGui.QGraphicsView.MinimalViewportUpdate)

        #self.setSceneRect(QtCore.QRectF(-1e10, -1e10, 2e10, 2e10))

        self.lockedViewports = []
        self.lastMousePos = None
        self.setMouseTracking(True)
        self.aspectLocked = False
        #self.yInverted = True
        self.range = QtCore.QRectF(0, 0, 1, 1)
        self.autoPixelRange = True
        self.currentItem = None
        self.clearMouse()
        self.updateMatrix()
        self.sceneObj = GraphicsScene()
        self.setScene(self.sceneObj)

        ## by default we set up a central widget with a grid layout.
        ## this can be replaced if needed.
        self.centralWidget = None
        self.setCentralItem(QtGui.QGraphicsWidget())
        self.centralLayout = QtGui.QGraphicsGridLayout()
        self.centralWidget.setLayout(self.centralLayout)

        self.mouseEnabled = False
        self.scaleCenter = False  ## should scaling center around view center (True) or mouse click (False)
        self.clickAccepted = False
Exemple #26
0
 def paint(self, p, *args):
     if self.path is None:
         self.drawPath()
     pen = self.opts['pen']
     if pen is None:
         pen = pg.getConfigOption('foreground')
     p.setPen(pg.mkPen(pen))
     p.drawPath(self.path)
Exemple #27
0
def test_ImageItem_axisorder():
    # All image tests pass again using the opposite axis order
    origMode = pg.getConfigOption('imageAxisOrder')
    altMode = 'row-major' if origMode == 'col-major' else 'col-major'
    pg.setConfigOptions(imageAxisOrder=altMode)
    try:
        test_ImageItem(transpose=True)
    finally:
        pg.setConfigOptions(imageAxisOrder=origMode)
def test_ImageItem_axisorder():
    # All image tests pass again using the opposite axis order
    origMode = pg.getConfigOption('imageAxisOrder')
    altMode = 'row-major' if origMode == 'col-major' else 'col-major'
    pg.setConfigOptions(imageAxisOrder=altMode)
    try:
        test_ImageItem(transpose=True)
    finally:
        pg.setConfigOptions(imageAxisOrder=origMode)
Exemple #29
0
def rowmajor_axisorder():
    """
    Context manager that sets the PyQtGraph image axis order to row-major. 
    The environment is reset to the initial value after context close.
    """
    old_image_axis_order = pg.getConfigOption("imageAxisOrder")
    pg.setConfigOptions(imageAxisOrder="row-major")
    yield
    pg.setConfigOptions(imageAxisOrder=old_image_axis_order)
Exemple #30
0
 def __init__(self, parent=None, scaled=False):
     QtOpenGL.QGLWidget.__init__(self, parent)
     self.scaled = scaled
     self.image = None
     self.uploaded = False
     self.smooth = False
     self.opts = None
     self.row_major = getConfigOption('imageAxisOrder') == 'row-major'
     self.texture = None
 def stackItemDblClicked(self, item):
     editor = self.editor
     if editor is None:
         editor = pg.getConfigOption("editorCommand")
     if editor is None:
         return
     tb = self.currentFrame()
     lineNum = tb.tb_lineno
     fileName = tb.tb_frame.f_code.co_filename
     subprocess.Popen(self.editor.format(fileName=fileName, lineNum=lineNum), shell=True)
    def setLut(self, lut):
        """ Sets the lookup table to the image item.

            :param ndarray Array: an N x 3 array.
        """
        logger.debug("------ setLut called")
        assertIsLut(lut)

        pgVersionInfo = versionStrToTuple(pg.__version__)
        if pgVersionInfo < (0, 11):
            if not isExtended(lut):
                # The lookup table in the imageItem must be extended. See extentLut doc string
                logger.debug(
                    "Side effect: duplicating last item of LUT in image item.")
                extendedLut = extentLut(lut)
            else:
                # The lookup table in the imageItem already is extended. Draw the original
                extendedLut = lut
                lut = np.copy(lut[0:-1, :])

            assert len(lut) == len(extendedLut) - 1, "Sanity check"
        else:
            extendedLut = lut

        if self._imageItem:
            logger.debug("Setting image item to extended lut")
            self._imageItem.setLookupTable(extendedLut)

        # Draw a color scale that shows the LUT.
        barWidth = 1
        imgAxOrder = pg.getConfigOption('imageAxisOrder')
        if imgAxOrder == 'col-major':
            lutImg = np.ones(shape=(barWidth, len(lut), 3), dtype=lut.dtype)
            lutImg[...] = lut[np.newaxis, :, :]
        elif imgAxOrder == 'row-major':
            lutImg = np.ones(shape=(len(lut), barWidth, 3), dtype=lut.dtype)
            lutImg[...] = lut[:, np.newaxis, :]
        else:
            raise AssertionError(
                "Unexpected imageAxisOrder config value: {}".format(
                    imgAxOrder))

        logger.debug("lutImg.shape: {}".format(lutImg.shape))
        self.colorScaleImageItem.setImage(lutImg)

        yRange = [0, len(lut)]
        logger.debug("Setting colorScaleViewBox yrange to: {}".format(yRange))

        # Do not set disableAutoRange to True in setRange; it triggers 'one last' auto range.
        # This is why the viewBox' autorange must be False at construction.
        self.colorScaleViewBox.setRange(xRange=[0, barWidth],
                                        yRange=yRange,
                                        padding=0.0,
                                        update=False,
                                        disableAutoRange=False)
Exemple #33
0
 def setBackground(self, background):
     """
     Set the background color of the GraphicsView.
     To use the defaults specified py pyqtgraph.setConfigOption, use background='default'.
     To make the background transparent, use background=None.
     """
     self._background = background
     if background == 'default':
         background = pyqtgraph.getConfigOption('background')
     brush = fn.mkBrush(background)
     self.setBackgroundBrush(brush)
Exemple #34
0
 def setBackground(self, background):
     """
     Set the background color of the GraphicsView.
     To use the defaults specified py pyqtgraph.setConfigOption, use background='default'.
     To make the background transparent, use background=None.
     """
     self._background = background
     if background == 'default':
         background = pyqtgraph.getConfigOption('background')
     brush = fn.mkBrush(background)
     self.setBackgroundBrush(brush)
Exemple #35
0
 def stackItemDblClicked(self, item):
     editor = self.editor
     if editor is None:
         editor = pg.getConfigOption('editorCommand')
     if editor is None:
         return
     tb = self.currentFrame()
     lineNum = tb.tb_lineno
     fileName = tb.tb_frame.f_code.co_filename
     subprocess.Popen(self.editor.format(fileName=fileName,
                                         lineNum=lineNum),
                      shell=True)
Exemple #36
0
 def setPen(self, pen):
     """
     Set the pen used for drawing text, axes, ticks, and grid lines.
     if pen == None, the default will be used (see :func:`setConfigOption 
     <pyqtgraph.setConfigOption>`)
     """
     self._pen = pen
     self.picture = None
     if pen is None:
         pen = pg.getConfigOption('foreground')
     self.labelStyle['color'] = '#' + pg.colorStr(pg.mkPen(pen).color())[:6]
     self.setLabel()
     self.update()
Exemple #37
0
 def setPen(self, pen):
     """
     Set the pen used for drawing text, axes, ticks, and grid lines.
     if pen == None, the default will be used (see :func:`setConfigOption 
     <pyqtgraph.setConfigOption>`)
     """
     self._pen = pen
     self.picture = None
     if pen is None:
         pen = pg.getConfigOption("foreground")
     self.labelStyle["color"] = "#" + pg.colorStr(pg.mkPen(pen).color())[:6]
     self.setLabel()
     self.update()
 def __init__(self, parent=None):
     pg.QtGui.QSplitter.__init__(self, pg.QtCore.Qt.Horizontal)
     self.ctrlPanel = pg.QtGui.QSplitter(pg.QtCore.Qt.Vertical)
     self.addWidget(self.ctrlPanel)
     self.fieldList = pg.QtGui.QListWidget()
     self.fieldList.setSelectionMode(self.fieldList.ExtendedSelection)
     self.ptree = pg.parametertree.ParameterTree(showHeader=False)
     self.filter = DataFilterParameter()
     self.colorMap = ColorMapParameter()
     self.style = StyleMapParameter()
     self.params = pg.parametertree.Parameter.create(name='params', type='group', children=[self.filter, self.colorMap, self.style])
     self.ptree.setParameters(self.params, showTop=False)
     
     self.plot = PlotWidget()
     self.ctrlPanel.addWidget(self.fieldList)
     self.ctrlPanel.addWidget(self.ptree)
     self.addWidget(self.plot)
     
     fg = pg.mkColor(pg.getConfigOption('foreground'))
     fg.setAlpha(150)
     self.filterText = pg.TextItem(border=pg.getConfigOption('foreground'), color=fg)
     self.filterText.setPos(60,20)
     self.filterText.setParentItem(self.plot.plotItem)
     
     self.data = None
     self.indices = None
     self.mouseOverField = None
     self.scatterPlot = None
     self.selectionScatter = None
     self.selectedIndices = []
     self._visibleXY = None  # currently plotted points
     self._visibleData = None  # currently plotted records
     self._visibleIndices = None
     self._indexMap = None
     
     self.fieldList.itemSelectionChanged.connect(self.fieldSelectionChanged)
     self.filter.sigFilterChanged.connect(self.filterChanged)
     self.colorMap.sigColorMapChanged.connect(self.updatePlot)
     self.style.sigStyleChanged.connect(self.updatePlot)
Exemple #39
0
def getCupy():
    if getConfigOption("useCupy"):
        try:
            import cupy
        except ImportError:
            warn("cupy library could not be loaded, but 'useCupy' is set.")
            return None
        if os.name == "nt" and cupy.cuda.runtime.runtimeGetVersion() < 11000:
            warn(
                "In Windows, CUDA toolkit should be version 11 or higher, or some functions may misbehave."
            )
        return cupy
    else:
        return None
Exemple #40
0
 def setBackground(self, background):
     """
     Set the background color of the GraphicsView.
     To use the defaults specified py pyqtgraph.setConfigOption, use background='default'.
     To make the background transparent, use background=None.
     """
     self._background = background
     if background == "default":
         background = pyqtgraph.getConfigOption("background")
     if background is None:
         self.setBackgroundRole(QtGui.QPalette.NoRole)
     else:
         brush = fn.mkBrush(background)
         self.setBackgroundBrush(brush)
Exemple #41
0
    def __init__(self,
                 size,
                 val=-1,
                 width=5,
                 brush=None,
                 pen=None,
                 suffix='px',
                 offset=None):
        """
        Displays a rectangular bar to indicate the relative scale of objects on
        the view.

        Args:
            size (float): The width of the scalebar in view pixels.

        Keyword Args:
            val (float): The value displayed in the scalebar text label.
            width (int): The width of the scale bar rectangle.
            brush
            pen
            suffix (str): The units displayed in the scalebar text label.
            offset (int tuple):
        """
        pg.GraphicsObject.__init__(self)
        pg.GraphicsWidgetAnchor.__init__(self)
        self.setFlag(self.ItemHasNoContents)
        self.setAcceptedMouseButtons(QtCore.Qt.NoButton)

        if brush is None:
            brush = pg.getConfigOption('foreground')
        self.brush = pg.fn.mkBrush(brush)
        self.pen = pg.fn.mkPen(pen)
        self._width = width
        self.size = size
        if offset is None:
            offset = (0, 0)
        self.offset = offset

        self.bar = QtWidgets.QGraphicsRectItem()
        self.bar.setPen(self.pen)
        self.bar.setBrush(self.brush)
        self.bar.setParentItem(self)

        if val == -1:
            val = size

        self.text = pg.TextItem(text=pg.fn.siFormat(val, suffix=suffix),
                                anchor=(0.5, 1))
        self.text.setParentItem(self)
    def add_param_tree(self):
        self.ptree = ptree.ParameterTree(showHeader=False)
        self.filter = DataFilterParameter()
        params = ptree.Parameter.create(name='params',
                                        type='group',
                                        children=[self.filter])
        self.ptree.setParameters(params, showTop=False)

        self.filter_layout.addWidget(self.ptree)

        self.filterText = TextItem(border=getConfigOption('foreground'))
        self.filterText.setPos(60, 20)
        self.filterText.setParentItem(self.plot.plotItem)
        self.filter.sigFilterChanged.connect(self.filterChanged)
        self.filter.setFields([('butterFilter', {'units': 'Hz'})])
Exemple #43
0
def test_useCupy_can_be_set_after_init():
    prev_setting = pg.getConfigOption("useCupy")
    try:
        pg.setConfigOption("useCupy", False)
        w = pg.GraphicsLayoutWidget()
        w.show()
        view = pg.ViewBox()
        w.setCentralWidget(view)
        w.resize(200, 200)
        img = cupy.random.randint(0, 255, size=(32, 32)).astype(cupy.uint8)
        ii = pg.ImageItem()
        view.addItem(ii)
        pg.setConfigOption("useCupy", True)
        ii.setImage(img)
        w.hide()
    finally:
        pg.setConfigOption("useCupy", prev_setting)
Exemple #44
0
 def __init__(self, size, width=5, brush=None, pen=None, suffix='m'):
     GraphicsObject.__init__(self)
     GraphicsWidgetAnchor.__init__(self)
     self.setFlag(self.ItemHasNoContents)
     self.setAcceptedMouseButtons(QtCore.Qt.NoButton)
     
     if brush is None:
         brush = pg.getConfigOption('foreground')
     self.brush = fn.mkBrush(brush)
     self.pen = fn.mkPen(pen)
     self._width = width
     self.size = size
     
     self.bar = QtGui.QGraphicsRectItem()
     self.bar.setPen(self.pen)
     self.bar.setBrush(self.brush)
     self.bar.setParentItem(self)
     
     self.text = TextItem(text=fn.siFormat(size, suffix=suffix), anchor=(0.5,1))
     self.text.setParentItem(self)
Exemple #45
0
    def change_width(self, size):
        """
        Change the width of every plot data item rendered on the plot. This
        currently does not include uncertainty indicators.

        Notes
        -----
            Enabling a width greater than 1 will automatically enable opengl
            and use the user's gpu to render the plot. If the user has not
            set the global pyqtgraph opengl option to true, opengl will be
            disabled when the user returns the size to 1.

        Parameters
        ----------
        size : int
            The new width of the rendered lines.
        """
        if not pg.getConfigOption('useOpenGL'):
            self.useOpenGL(True if size > 1 else False)

        for item in self.items():
            if isinstance(item, PlotDataItem):
                item.width = size
Exemple #46
0
def test_getArrayRegion(transpose=False):
    pr = pg.PolyLineROI([[0, 0], [27, 0], [0, 28]], closed=True)
    pr.setPos(1, 1)
    rois = [
        (pg.ROI([1, 1], [27, 28], pen='y'), 'baseroi'),
        (pg.RectROI([1, 1], [27, 28], pen='y'), 'rectroi'),
        (pg.EllipseROI([1, 1], [27, 28], pen='y'), 'ellipseroi'),
        (pr, 'polylineroi'),
    ]
    for roi, name in rois:
        # For some ROIs, resize should not be used.
        testResize = not isinstance(roi, pg.PolyLineROI)
        
        origMode = pg.getConfigOption('imageAxisOrder')
        try:
            if transpose:
                pg.setConfigOptions(imageAxisOrder='row-major')
                check_getArrayRegion(roi, 'roi/'+name, testResize, transpose=True)
            else:
                pg.setConfigOptions(imageAxisOrder='col-major')
                check_getArrayRegion(roi, 'roi/'+name, testResize)
        finally:
            pg.setConfigOptions(imageAxisOrder=origMode)
Exemple #47
0
    def setText(self, text, **args):
        """Set the text and text properties in the label. Accepts optional arguments for auto-generating
        a CSS style string:

        ==================== ==============================
        **Style Arguments:**
        color                (str) example: 'CCFF00'
        size                 (str) example: '8pt'
        bold                 (bool)
        italic               (bool)
        ==================== ==============================
        """
        self.text = text
        opts = self.opts
        for k in args:
            opts[k] = args[k]
        
        optlist = []
        
        color = self.opts['color']
        if color is None:
            color = pg.getConfigOption('foreground')
        color = fn.mkColor(color)
        optlist.append('color: #' + fn.colorStr(color)[:6])
        if 'size' in opts:
            optlist.append('font-size: ' + opts['size'])
        if 'bold' in opts and opts['bold'] in [True, False]:
            optlist.append('font-weight: ' + {True:'bold', False:'normal'}[opts['bold']])
        if 'italic' in opts and opts['italic'] in [True, False]:
            optlist.append('font-style: ' + {True:'italic', False:'normal'}[opts['italic']])
        full = "<span style='%s'>%s</span>" % ('; '.join(optlist), text)
        #print full
        self.item.setHtml(full)
        self.updateMin()
        self.resizeEvent(None)
        self.updateGeometry()
Exemple #48
0
    def paint(self, p, opt, widget):
        prof = debug.Profiler('PlotCurveItem.paint '+str(id(self)), disabled=True)
        if self.xData is None:
            return
        
        if HAVE_OPENGL and pg.getConfigOption('enableExperimental') and isinstance(widget, QtOpenGL.QGLWidget):
            self.paintGL(p, opt, widget)
            return
        
        x = None
        y = None
        if self.path is None:
            x,y = self.getData()
            if x is None or len(x) == 0 or y is None or len(y) == 0:
                return
            self.path = self.generatePath(x,y)
            self.fillPath = None
            
        path = self.path
        prof.mark('generate path')
        
        if self._exportOpts is not False:
            aa = self._exportOpts.get('antialias', True)
        else:
            aa = self.opts['antialias']
        
        p.setRenderHint(p.Antialiasing, aa)
        
            
        if self.opts['brush'] is not None and self.opts['fillLevel'] is not None:
            if self.fillPath is None:
                if x is None:
                    x,y = self.getData()
                p2 = QtGui.QPainterPath(self.path)
                p2.lineTo(x[-1], self.opts['fillLevel'])
                p2.lineTo(x[0], self.opts['fillLevel'])
                p2.lineTo(x[0], y[0])
                p2.closeSubpath()
                self.fillPath = p2
                
            prof.mark('generate fill path')
            p.fillPath(self.fillPath, self.opts['brush'])
            prof.mark('draw fill path')
            
        sp = fn.mkPen(self.opts['shadowPen'])
        cp = fn.mkPen(self.opts['pen'])
 
        ## Copy pens and apply alpha adjustment
        #sp = QtGui.QPen(self.opts['shadowPen'])
        #cp = QtGui.QPen(self.opts['pen'])
        #for pen in [sp, cp]:
            #if pen is None:
                #continue
            #c = pen.color()
            #c.setAlpha(c.alpha() * self.opts['alphaHint'])
            #pen.setColor(c)
            ##pen.setCosmetic(True)
            
            
            
        if sp is not None and sp.style() != QtCore.Qt.NoPen:
            p.setPen(sp)
            p.drawPath(path)
        p.setPen(cp)
        p.drawPath(path)
        prof.mark('drawPath')
        
        #print "Render hints:", int(p.renderHints())
        prof.finish()
Exemple #49
0
    def __init__(self, parent=None, border=None, lockAspect=False, enableMouse=True, invertY=False, enableMenu=True, name=None):
        """
        =============  =============================================================
        **Arguments**
        *parent*       (QGraphicsWidget) Optional parent widget
        *border*       (QPen) Do draw a border around the view, give any 
                       single argument accepted by :func:`mkPen <pyqtgraph.mkPen>`
        *lockAspect*   (False or float) The aspect ratio to lock the view 
                       coorinates to. (or False to allow the ratio to change)
        *enableMouse*  (bool) Whether mouse can be used to scale/pan the view 
        *invertY*      (bool) See :func:`invertY <pyqtgraph.ViewBox.invertY>`
        =============  =============================================================
        """
        
        
        
        GraphicsWidget.__init__(self, parent)
        self.name = None
        self.linksBlocked = False
        self.addedItems = []
        #self.gView = view
        #self.showGrid = showGrid
        
        self.state = {
            
            ## separating targetRange and viewRange allows the view to be resized
            ## while keeping all previously viewed contents visible
            'targetRange': [[0,1], [0,1]],   ## child coord. range visible [[xmin, xmax], [ymin, ymax]]
            'viewRange': [[0,1], [0,1]],     ## actual range viewed
        
            'yInverted': invertY,
            'aspectLocked': False,    ## False if aspect is unlocked, otherwise float specifies the locked ratio.
            'autoRange': [True, True],  ## False if auto range is disabled, 
                                          ## otherwise float gives the fraction of data that is visible
            'autoPan': [False, False],         ## whether to only pan (do not change scaling) when auto-range is enabled
            'autoVisibleOnly': [False, False], ## whether to auto-range only to the visible portion of a plot 
            'linkedViews': [None, None],  ## may be None, "viewName", or weakref.ref(view)
                                          ## a name string indicates that the view *should* link to another, but no view with that name exists yet.
            
            'mouseEnabled': [enableMouse, enableMouse],
            'mouseMode': ViewBox.PanMode if pyqtgraph.getConfigOption('leftButtonPan') else ViewBox.RectMode,  
            'enableMenu': enableMenu,
            'wheelScaleFactor': -1.0 / 8.0,

            'background': None,
        }
        self._updatingRange = False  ## Used to break recursive loops. See updateAutoRange.
        self._itemBoundsCache = weakref.WeakKeyDictionary()
        
        self.locateGroup = None  ## items displayed when using ViewBox.locate(item)
        
        self.setFlag(self.ItemClipsChildrenToShape)
        self.setFlag(self.ItemIsFocusable, True)  ## so we can receive key presses
        
        ## childGroup is required so that ViewBox has local coordinates similar to device coordinates.
        ## this is a workaround for a Qt + OpenGL bug that causes improper clipping
        ## https://bugreports.qt.nokia.com/browse/QTBUG-23723
        self.childGroup = ChildGroup(self)
        self.childGroup.sigItemsChanged.connect(self.itemsChanged)
        
        self.background = QtGui.QGraphicsRectItem(self.rect())
        self.background.setParentItem(self)
        self.background.setZValue(-1e6)
        self.background.setPen(fn.mkPen(None))
        self.updateBackground()
        
        #self.useLeftButtonPan = pyqtgraph.getConfigOption('leftButtonPan') # normally use left button to pan
        # this also enables capture of keyPressEvents.
        
        ## Make scale box that is shown when dragging on the view
        self.rbScaleBox = QtGui.QGraphicsRectItem(0, 0, 1, 1)
        self.rbScaleBox.setPen(fn.mkPen((255,255,100), width=1))
        self.rbScaleBox.setBrush(fn.mkBrush(255,255,0,100))
        self.rbScaleBox.hide()
        self.addItem(self.rbScaleBox)
        
        self.axHistory = [] # maintain a history of zoom locations
        self.axHistoryPointer = -1 # pointer into the history. Allows forward/backward movement, not just "undo"
        
        self.setZValue(-100)
        self.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding))
        
        self.setAspectLocked(lockAspect)
        
        self.border = fn.mkPen(border)
        self.menu = ViewBoxMenu(self)
        
        self.register(name)
        if name is None:
            self.updateViewLists()
Exemple #50
0
    def __init__(self, parent=None, useOpenGL=None, background="default"):
        """
        ============  ============================================================
        Arguments:
        parent        Optional parent widget
        useOpenGL     If True, the GraphicsView will use OpenGL to do all of its
                      rendering. This can improve performance on some systems,
                      but may also introduce bugs (the combination of 
                      QGraphicsView and QGLWidget is still an 'experimental' 
                      feature of Qt)
        background    Set the background color of the GraphicsView. Accepts any
                      single argument accepted by 
                      :func:`mkColor <pyqtgraph.mkColor>`. By 
                      default, the background color is determined using the
                      'backgroundColor' configuration option (see 
                      :func:`setConfigOption <pyqtgraph.setConfigOption>`.
        ============  ============================================================
        """

        self.closed = False

        QtGui.QGraphicsView.__init__(self, parent)

        if useOpenGL is None:
            useOpenGL = pyqtgraph.getConfigOption("useOpenGL")

        self.useOpenGL(useOpenGL)

        self.setCacheMode(self.CacheBackground)

        ## This might help, but it's probably dangerous in the general case..
        # self.setOptimizationFlag(self.DontSavePainterState, True)

        self.setBackground(background)

        self.setFocusPolicy(QtCore.Qt.StrongFocus)
        self.setFrameShape(QtGui.QFrame.NoFrame)
        self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.setTransformationAnchor(QtGui.QGraphicsView.NoAnchor)
        self.setResizeAnchor(QtGui.QGraphicsView.AnchorViewCenter)
        self.setViewportUpdateMode(QtGui.QGraphicsView.MinimalViewportUpdate)

        self.lockedViewports = []
        self.lastMousePos = None
        self.setMouseTracking(True)
        self.aspectLocked = False
        self.range = QtCore.QRectF(0, 0, 1, 1)
        self.autoPixelRange = True
        self.currentItem = None
        self.clearMouse()
        self.updateMatrix()
        self.sceneObj = GraphicsScene()
        self.setScene(self.sceneObj)

        ## Workaround for PySide crash
        ## This ensures that the scene will outlive the view.
        if pyqtgraph.Qt.USE_PYSIDE:
            self.sceneObj._view_ref_workaround = self

        ## by default we set up a central widget with a grid layout.
        ## this can be replaced if needed.
        self.centralWidget = None
        self.setCentralItem(QtGui.QGraphicsWidget())
        self.centralLayout = QtGui.QGraphicsGridLayout()
        self.centralWidget.setLayout(self.centralLayout)

        self.mouseEnabled = False
        self.scaleCenter = False  ## should scaling center around view center (True) or mouse click (False)
        self.clickAccepted = False
Exemple #51
0
    def __init__(self, parent=None):
        super(ScatterPlotWidget, self).__init__(self)
        self._hidden = True

        bg = fn.mkColor(getConfigOption('background'))
        bg.setAlpha(255)  # we need to do that, since in default widget alpha is set to 50, but we want it BLACK!
Exemple #52
0
    def drawPicture(self):
        self.picture = QtGui.QPicture()
        p = QtGui.QPainter(self.picture)

        pen = self.opts['pen']
        pens = self.opts['pens']

        if pen is None and pens is None:
            pen = pg.getConfigOption('foreground')

        brush = self.opts['brush']
        brushes = self.opts['brushes']
        if brush is None and brushes is None:
            brush = (128, 128, 128)

        def asarray(x):
            if x is None or np.isscalar(x) or isinstance(x, np.ndarray):
                return x
            return np.array(x)


        x = asarray(self.opts.get('x'))
        x0 = asarray(self.opts.get('x0'))
        x1 = asarray(self.opts.get('x1'))
        width = asarray(self.opts.get('width'))

        if x0 is None:
            if width is None:
                raise Exception('must specify either x0 or width')
            if x1 is not None:
                x0 = x1 - width
            elif x is not None:
                x0 = x - width/2.
            else:
                raise Exception('must specify at least one of x, x0, or x1')
        if width is None:
            if x1 is None:
                raise Exception('must specify either x1 or width')
            width = x1 - x0

        y = asarray(self.opts.get('y'))
        y0 = asarray(self.opts.get('y0'))
        y1 = asarray(self.opts.get('y1'))
        height = asarray(self.opts.get('height'))

        if y0 is None:
            if height is None:
                y0 = 0
            elif y1 is not None:
                y0 = y1 - height
            elif y is not None:
                y0 = y - height/2.
            else:
                y0 = 0
        if height is None:
            if y1 is None:
                raise Exception('must specify either y1 or height')
            height = y1 - y0

        p.setPen(pg.mkPen(pen))
        p.setBrush(pg.mkBrush(brush))
        for i in range(len(x0)):
            if pens is not None:
                p.setPen(pg.mkPen(pens[i]))
            if brushes is not None:
                p.setBrush(pg.mkBrush(brushes[i]))

            if np.isscalar(y0):
                y = y0
            else:
                y = y0[i]
            if np.isscalar(width):
                w = width
            else:
                w = width[i]
            p.drawRect(QtCore.QRectF(x0[i], y, w, height[i]))
        p.end()
        self.prepareGeometryChange()
Exemple #53
0
 def __init__(self, *args, **kargs):
     """
     There are many different ways to create a PlotDataItem:
     
     **Data initialization arguments:** (x,y data only)
     
         =================================== ======================================
         PlotDataItem(xValues, yValues)      x and y values may be any sequence (including ndarray) of real numbers
         PlotDataItem(yValues)               y values only -- x will be automatically set to range(len(y))
         PlotDataItem(x=xValues, y=yValues)  x and y given by keyword arguments
         PlotDataItem(ndarray(Nx2))          numpy array with shape (N, 2) where x=data[:,0] and y=data[:,1]
         =================================== ======================================
     
     **Data initialization arguments:** (x,y data AND may include spot style)
     
         ===========================   =========================================
         PlotDataItem(recarray)        numpy array with dtype=[('x', float), ('y', float), ...]
         PlotDataItem(list-of-dicts)   [{'x': x, 'y': y, ...},   ...] 
         PlotDataItem(dict-of-lists)   {'x': [...], 'y': [...],  ...}           
         PlotDataItem(MetaArray)       1D array of Y values with X sepecified as axis values 
                                       OR 2D array with a column 'y' and extra columns as needed.
         ===========================   =========================================
     
     **Line style keyword arguments:**
         ==========   ================================================
         pen          Pen to use for drawing line between points. 
                      Default is solid grey, 1px width. Use None to disable line drawing.
                      May be any single argument accepted by :func:`mkPen() <pyqtgraph.mkPen>`
         shadowPen    Pen for secondary line to draw behind the primary line. disabled by default.
                      May be any single argument accepted by :func:`mkPen() <pyqtgraph.mkPen>`
         fillLevel    Fill the area between the curve and fillLevel
         fillBrush    Fill to use when fillLevel is specified. 
                      May be any single argument accepted by :func:`mkBrush() <pyqtgraph.mkBrush>`
         ==========   ================================================
     
     **Point style keyword arguments:**  (see :func:`ScatterPlotItem.setData() <pyqtgraph.ScatterPlotItem.setData>` for more information)
     
         ============   ================================================
         symbol         Symbol to use for drawing points OR list of symbols, one per point. Default is no symbol.
                        Options are o, s, t, d, +, or any QPainterPath
         symbolPen      Outline pen for drawing points OR list of pens, one per point.
                        May be any single argument accepted by :func:`mkPen() <pyqtgraph.mkPen>`
         symbolBrush    Brush for filling points OR list of brushes, one per point.
                        May be any single argument accepted by :func:`mkBrush() <pyqtgraph.mkBrush>`
         symbolSize     Diameter of symbols OR list of diameters.
         pxMode         (bool) If True, then symbolSize is specified in pixels. If False, then symbolSize is 
                        specified in data coordinates.
         ============   ================================================
     
     **Optimization keyword arguments:**
     
         ================ =====================================================================
         antialias        (bool) By default, antialiasing is disabled to improve performance.
                          Note that in some cases (in particluar, when pxMode=True), points 
                          will be rendered antialiased even if this is set to False.
         decimate         deprecated.
         downsample       (int) Reduce the number of samples displayed by this value
         downsampleMethod 'subsample': Downsample by taking the first of N samples. 
                             This method is fastest and least accurate.
                          'mean': Downsample by taking the mean of N samples.
                          'peak': Downsample by drawing a saw wave that follows the min 
                             and max of the original data. This method produces the best 
                             visual representation of the data but is slower.
         autoDownsample   (bool) If True, resample the data before plotting to avoid plotting
                          multiple line segments per pixel. This can improve performance when
                          viewing very high-density data, but increases the initial overhead 
                          and memory usage.
         clipToView       (bool) If True, only plot data that is visible within the X range of
                          the containing ViewBox. This can improve performance when plotting
                          very large data sets where only a fraction of the data is visible
                          at any time.
         identical        *deprecated*
         ================ =====================================================================
     
     **Meta-info keyword arguments:**
     
         ==========   ================================================
         name         name of dataset. This would appear in a legend
         ==========   ================================================
     """
     GraphicsObject.__init__(self)
     self.setFlag(self.ItemHasNoContents)
     self.xData = None
     self.yData = None
     self.xDisp = None
     self.yDisp = None
     self.dataMask = None
     #self.curves = []
     #self.scatters = []
     self.curve = PlotCurveItem()
     self.scatter = ScatterPlotItem()
     self.curve.setParentItem(self)
     self.scatter.setParentItem(self)
     
     self.curve.sigClicked.connect(self.curveClicked)
     self.scatter.sigClicked.connect(self.scatterClicked)
     
     
     #self.clear()
     self.opts = {
         'fftMode': False,
         'logMode': [False, False],
         'alphaHint': 1.0,
         'alphaMode': False,
         
         'pen': (200,200,200),
         'shadowPen': None,
         'fillLevel': None,
         'fillBrush': None,
         
         'symbol': None,
         'symbolSize': 10,
         'symbolPen': (200,200,200),
         'symbolBrush': (50, 50, 150),
         'pxMode': True,
         
         'antialias': pg.getConfigOption('antialias'),
         'pointMode': None,
         
         'downsample': 1,
         'autoDownsample': False,
         'downsampleMethod': 'peak',
         'clipToView': False,
         
         'data': None,
     }
     self.setData(*args, **kargs)
Exemple #54
0
 def __init__(self, parent=None, border=None, lockAspect=False, enableMouse=True, invertY=False, name=None):
     GraphicsWidget.__init__(self, parent)
     self.name = None
     self.linksBlocked = False
     self.addedItems = []
     #self.gView = view
     #self.showGrid = showGrid
     
     self.state = {
         
         ## separating targetRange and viewRange allows the view to be resized
         ## while keeping all previously viewed contents visible
         'targetRange': [[0,1], [0,1]],   ## child coord. range visible [[xmin, xmax], [ymin, ymax]]
         'viewRange': [[0,1], [0,1]],     ## actual range viewed
     
         'yInverted': invertY,
         'aspectLocked': False,    ## False if aspect is unlocked, otherwise float specifies the locked ratio.
         'autoRange': [True, True],  ## False if auto range is disabled, 
                                       ## otherwise float gives the fraction of data that is visible
         'linkedViews': [None, None],
         
         'mouseEnabled': [enableMouse, enableMouse],
         'mouseMode': ViewBox.PanMode if pyqtgraph.getConfigOption('leftButtonPan') else ViewBox.RectMode,  
         'wheelScaleFactor': -1.0 / 8.0,
     }
     
     
     self.exportMethods = collections.OrderedDict([
         ('SVG', self.saveSvg),
         ('Image', self.saveImage),
         ('Print', self.savePrint),
     ])
     
     self.setFlag(self.ItemClipsChildrenToShape)
     self.setFlag(self.ItemIsFocusable, True)  ## so we can receive key presses
     
     ## childGroup is required so that ViewBox has local coordinates similar to device coordinates.
     ## this is a workaround for a Qt + OpenGL but that causes improper clipping
     ## https://bugreports.qt.nokia.com/browse/QTBUG-23723
     self.childGroup = ChildGroup(self)
     self.childGroup.sigItemsChanged.connect(self.itemsChanged)
     
     #self.useLeftButtonPan = pyqtgraph.getConfigOption('leftButtonPan') # normally use left button to pan
     # this also enables capture of keyPressEvents.
     
     ## Make scale box that is shown when dragging on the view
     self.rbScaleBox = QtGui.QGraphicsRectItem(0, 0, 1, 1)
     self.rbScaleBox.setPen(fn.mkPen((255,0,0), width=1))
     self.rbScaleBox.setBrush(fn.mkBrush(255,255,0,100))
     self.rbScaleBox.hide()
     self.addItem(self.rbScaleBox)
     
     self.axHistory = [] # maintain a history of zoom locations
     self.axHistoryPointer = -1 # pointer into the history. Allows forward/backward movement, not just "undo"
     
     self.setZValue(-100)
     self.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding))
     
     self.setAspectLocked(lockAspect)
     
     self.border = border
     self.menu = ViewBoxMenu(self)
     
     self.register(name)
     if name is None:
         self.updateViewLists()
Exemple #55
0
def set_temp_options(**options):
    oldopts = {key:pg.getConfigOption(key) for key in options}
    validoptions = {k:v for k, v in options.items() if v is not None}
    pg.setConfigOptions(**validoptions)
    return oldopts
Exemple #56
0
 def paint(self, p, *args):
     if self.picture == None:
         self.generatePicture()
     if pg.getConfigOption('antialias') is True:
         p.setRenderHint(p.Antialiasing)
     self.picture.play(p)
Exemple #57
0
 def pen(self):
     if self._pen is None:
         return fn.mkPen(pg.getConfigOption("foreground"))
     return pg.mkPen(self._pen)
Exemple #58
0
#log.startLogging(sys.stdout)
from autobahn.twisted.websocket import (
    WebSocketClientProtocol, WebSocketClientFactory, connectWS
)

# Message queue for messaging between WebSockets thread and Qt thread
MESSAGE_QUEUE = Queue()
# Global variables to hold the data subscriptions
SUBSCRIPTIONS = None


### DEFAULTS
DEFAULTS = {
    'x_window': 600,
    'jump_ahead': 0.2,
    'color': pg.getConfigOption('foreground'),
    'line_width': 2,
    'unit': '',
    'column_defs': ('color', 'label', 'x', 'y'),
    'column_headers': ('', 'Label', 'Time', 'Value'),
    'column_widths': (None, None, 100, None),  # The last one is ignored
    'ylogscale': False,
    'xaxis': 'time',
    'xformat': 'HH:mm:ss',
    'yformat': '.2f',
    'table_padding': 5,
    'title_size': 26,
    # Data reduction
    'x_absolute': 10,
}
### DEFAULTS