Esempio n. 1
0
def test_spinbox_formatting():
    sb = pg.SpinBox()
    assert sb.opts['decimals'] == 6
    assert sb.opts['int'] is False

    # table  of test conditions:
    # value, text, options
    conds = [
        (0, '0', dict(suffix='', siPrefix=False, dec=False, int=False)),
        (100, '100', dict()),
        (1000000, '1e+06', dict()),
        (1000, '1e+03', dict(decimals=2)),
        (1000000, '1e+06', dict(int=True, decimals=6)),
        (12345678955, '12345678955', dict(int=True, decimals=100)),
        (1.45e-9, '1.45e-09 A',
         dict(int=False, decimals=6, suffix='A', siPrefix=False)),
        (1.45e-9, '1.45 nA',
         dict(int=False, decimals=6, suffix='A', siPrefix=True)),
        (-2500.3427, '$-2500.34', dict(int=False, format='${value:0.02f}')),
    ]

    for (value, text, opts) in conds:
        sb.setOpts(**opts)
        sb.setValue(value)
        assert sb.value() == value
        assert pg.asUnicode(sb.text()) == text
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_getViewWidget():
    view = pg.PlotWidget()
    vref = weakref.ref(view)
    item = pg.InfiniteLine()
    view.addItem(item)
    assert item.getViewWidget() is view
    del view
    gc.collect()
    assert vref() is None
    assert item.getViewWidget() is None
def test_getViewWidget_deleted():
    view = pg.PlotWidget()
    item = pg.InfiniteLine()
    view.addItem(item)
    assert item.getViewWidget() is view

    # Arrange to have Qt automatically delete the view widget
    obj = pg.QtGui.QWidget()
    view.setParent(obj)
    del obj
    gc.collect()

    assert not pg.Qt.isQObjectAlive(view)
    assert item.getViewWidget() is None
Esempio n. 5
0
def test_dock():
    name = pg.asUnicode("évènts_zàhéér")
    dock = da.Dock(name=name)
    # make sure unicode names work correctly
    assert dock.name() == name
    # no surprises in return type.
    assert type(dock.name()) == type(name)
Esempio n. 6
0
def test_combobox():
    cb = pg.ComboBox()
    items = {'a': 1, 'b': 2, 'c': 3}
    cb.setItems(items)
    cb.setValue(2)
    assert str(cb.currentText()) == 'b'
    assert cb.value() == 2

    # Clear item list; value should be None
    cb.clear()
    assert cb.value() == None

    # Reset item list; value should be set automatically
    cb.setItems(items)
    assert cb.value() == 2

    # Clear item list; repopulate with same names and new values
    items = {'a': 4, 'b': 5, 'c': 6}
    cb.clear()
    cb.setItems(items)
    assert cb.value() == 5

    # Set list instead of dict
    cb.setItems(list(items.keys()))
    assert str(cb.currentText()) == 'b'

    cb.setValue('c')
    assert cb.value() == str(cb.currentText())
    assert cb.value() == 'c'

    cb.setItemValue('c', 7)
    assert cb.value() == 7
Esempio n. 7
0
def test_nan_image():
    img = np.ones((10,10))
    img[0,0] = np.nan
    v = pg.image(img)
    v.imageItem.getHistogram()
    app.processEvents()
    v.window().close()
Esempio n. 8
0
def test_simple():
    tempfilename = tempfile.NamedTemporaryFile(suffix='.svg').name
    print("using %s as a temporary file" % tempfilename)
    scene = pg.QtGui.QGraphicsScene()
    #rect = pg.QtGui.QGraphicsRectItem(0, 0, 100, 100)
    #scene.addItem(rect)
    #rect.setPos(20,20)
    #rect.translate(50, 50)
    #rect.rotate(30)
    #rect.scale(0.5, 0.5)

    #rect1 = pg.QtGui.QGraphicsRectItem(0, 0, 100, 100)
    #rect1.setParentItem(rect)
    #rect1.setFlag(rect1.ItemIgnoresTransformations)
    #rect1.setPos(20, 20)
    #rect1.scale(2,2)

    #el1 = pg.QtGui.QGraphicsEllipseItem(0, 0, 100, 100)
    #el1.setParentItem(rect1)
    ##grp = pg.ItemGroup()
    #grp.setParentItem(rect)
    #grp.translate(200,0)
    ##grp.rotate(30)

    #rect2 = pg.QtGui.QGraphicsRectItem(0, 0, 100, 25)
    #rect2.setFlag(rect2.ItemClipsChildrenToShape)
    #rect2.setParentItem(grp)
    #rect2.setPos(0,25)
    #rect2.rotate(30)
    #el = pg.QtGui.QGraphicsEllipseItem(0, 0, 100, 50)
    #el.translate(10,-5)
    #el.scale(0.5,2)

    #el.setParentItem(rect2)

    grp2 = pg.ItemGroup()
    scene.addItem(grp2)
    grp2.scale(100, 100)

    rect3 = pg.QtGui.QGraphicsRectItem(0, 0, 2, 2)
    rect3.setPen(pg.mkPen(width=1, cosmetic=False))
    grp2.addItem(rect3)

    ex = pg.exporters.SVGExporter(scene)
    ex.export(fileName=tempfilename)
    os.unlink(tempfilename)
def test_subArray():
    a = np.array([
        0, 0, 111, 112, 113, 0, 121, 122, 123, 0, 0, 0, 211, 212, 213, 0, 221,
        222, 223, 0, 0, 0, 0
    ])
    b = pg.subArray(a, offset=2, shape=(2, 2, 3), stride=(10, 4, 1))
    c = np.array([[[111, 112, 113], [121, 122, 123]],
                  [[211, 212, 213], [221, 222, 223]]])
    assert np.all(b == c)

    # operate over first axis; broadcast over the rest
    aa = np.vstack([a, a / 100.]).T
    cc = np.empty(c.shape + (2, ))
    cc[..., 0] = c
    cc[..., 1] = c / 100.
    bb = pg.subArray(aa, offset=2, shape=(2, 2, 3), stride=(10, 4, 1))
    assert np.all(bb == cc)
Esempio n. 10
0
def test_dividebyzero():
    import PyQtGraph as pg
    im = pg.image(pg.np.random.normal(size=(100, 100)))
    im.imageItem.setAutoDownsample(True)
    im.view.setRange(xRange=[-5 + 25, 5e+25], yRange=[-5e+25, 5e+25])
    app.processEvents()
    QtTest.QTest.qWait(1000)
    # must manually call im.imageItem.render here or the exception
    # will only exist on the Qt event loop
    im.imageItem.render()
Esempio n. 11
0
def init_viewbox():
    """Helper function to init the ViewBox
    """
    global win, vb

    win = pg.GraphicsWindow()
    win.ci.layout.setContentsMargins(0, 0, 0, 0)
    win.resize(200, 200)
    win.show()
    vb = win.addViewBox()

    # set range before viewbox is shown
    vb.setRange(xRange=[0, 10], yRange=[0, 10], padding=0)

    # required to make mapFromView work properly.
    qtest.qWaitForWindowShown(win)

    g = pg.GridItem()
    vb.addItem(g)

    app.processEvents()
Esempio n. 12
0
    def mkobjs(*args, **kwds):
        w = pg.PlotWidget(*args, **kwds)
        data = pg.np.array([1, 5, 2, 4, 3])
        c = w.plot(data, name='stuff')
        w.addLegend()

        # test that connections do not keep objects alive
        w.plotItem.vb.sigRangeChanged.connect(mkrefs)
        app.focusChanged.connect(w.plotItem.vb.invertY)

        # return weakrefs to a bunch of objects that should die when the scope exits.
        return mkrefs(w, c, data, w.plotItem, w.plotItem.vb,
                      w.plotItem.getMenu(), w.plotItem.getAxis('left'))
Esempio n. 13
0
def testSolve3D():
    p1 = np.array([[0, 0, 0, 1], [1, 0, 0, 1], [0, 1, 0, 1], [0, 0, 1, 1]],
                  dtype=float)

    # transform points through random matrix
    tr = np.random.normal(size=(4, 4))
    tr[3] = (0, 0, 0, 1)
    p2 = np.dot(tr, p1.T).T[:, :3]

    # solve to see if we can recover the transformation matrix.
    tr2 = pg.solve3DTransform(p1, p2)

    assert_array_almost_equal(tr[:3], tr2[:3])
Esempio n. 14
0
def test_plotscene():
    tempfilename = tempfile.NamedTemporaryFile(suffix='.svg').name
    print("using %s as a temporary file" % tempfilename)
    pg.setConfigOption('foreground', (0, 0, 0))
    w = pg.GraphicsWindow()
    w.show()
    p1 = w.addPlot()
    p2 = w.addPlot()
    p1.plot([1, 3, 2, 3, 1, 6, 9, 8, 4, 2, 3, 5, 3], pen={'color': 'k'})
    p1.setXRange(0, 5)
    p2.plot([1, 5, 2, 3, 4, 6, 1, 2, 4, 2, 3, 5, 3],
            pen={
                'color': 'k',
                'cosmetic': False,
                'width': 0.3
            })
    app.processEvents()
    app.processEvents()

    ex = pg.exporters.SVGExporter(w.scene())
    ex.export(fileName=tempfilename)
    # clean up after the test is done
    os.unlink(tempfilename)
Esempio n. 15
0
def testMatrix():
    """
    SRTTransform3D => Transform3D => SRTTransform3D
    """
    tr = pg.SRTTransform3D()
    tr.setRotate(45, (0, 0, 1))
    tr.setScale(0.2, 0.4, 1)
    tr.setTranslate(10, 20, 40)
    assert tr.getRotation() == (45, QtGui.QVector3D(0, 0, 1))
    assert tr.getScale() == QtGui.QVector3D(0.2, 0.4, 1)
    assert tr.getTranslation() == QtGui.QVector3D(10, 20, 40)

    tr2 = pg.Transform3D(tr)
    assert np.all(tr.matrix() == tr2.matrix())
    
    # This is the most important test:
    # The transition from Transform3D to SRTTransform3D is a tricky one.
    tr3 = pg.SRTTransform3D(tr2)
    assert_array_almost_equal(tr.matrix(), tr3.matrix())
    assert_almost_equal(tr3.getRotation()[0], tr.getRotation()[0])
    assert_array_almost_equal(tr3.getRotation()[1], tr.getRotation()[1])
    assert_array_almost_equal(tr3.getScale(), tr.getScale())
    assert_array_almost_equal(tr3.getTranslation(), tr.getTranslation())
def test_PlotCurveItem():
    p = pg.GraphicsWindow()
    p.ci.layout.setContentsMargins(4, 4, 4, 4)  # default margins vary by platform
    v = p.addViewBox()
    p.resize(200, 150)
    data = np.array([1,4,2,3,np.inf,5,7,6,-np.inf,8,10,9,np.nan,-1,-2,0])
    c = pg.PlotCurveItem(data)
    v.addItem(c)
    v.autoRange()
    
    # Check auto-range works. Some platform differences may be expected..
    checkRange = np.array([[-1.1457564053237301, 16.145756405323731], [-3.076811473165955, 11.076811473165955]])
    assert np.allclose(v.viewRange(), checkRange)
    
    assertImageApproved(p, 'plotcurveitem/connectall', "Plot curve with all points connected.")
    
    c.setData(data, connect='pairs')
    assertImageApproved(p, 'plotcurveitem/connectpairs', "Plot curve with pairs connected.")
    
    c.setData(data, connect='finite')
    assertImageApproved(p, 'plotcurveitem/connectfinite', "Plot curve with finite points connected.")
    
    c.setData(data, connect=np.array([1,1,1,0,1,1,0,0,1,0,0,0,1,1,0,0]))
    assertImageApproved(p, 'plotcurveitem/connectarray', "Plot curve with connection array.")
Esempio n. 17
0
def test_CSVExporter():
    tempfilename = tempfile.NamedTemporaryFile(suffix='.csv').name
    print("using %s as a temporary file" % tempfilename)

    plt = pg.plot()
    y1 = [1, 3, 2, 3, 1, 6, 9, 8, 4, 2]
    plt.plot(y=y1, name='myPlot')

    y2 = [3, 4, 6, 1, 2, 4, 2, 3, 5, 3, 5, 1, 3]
    x2 = pg.np.linspace(0, 1.0, len(y2))
    plt.plot(x=x2, y=y2)

    y3 = [1, 5, 2, 3, 4, 6, 1, 2, 4, 2, 3, 5, 3]
    x3 = pg.np.linspace(0, 1.0, len(y3) + 1)
    plt.plot(x=x3, y=y3, stepMode=True)

    ex = pg.exporters.CSVExporter(plt.plotItem)
    ex.export(fileName=tempfilename)

    r = csv.reader(open(tempfilename, 'r'))
    lines = [line for line in r]
    header = lines.pop(0)
    assert header == [
        'myPlot_x', 'myPlot_y', 'x0001', 'y0001', 'x0002', 'y0002'
    ]

    i = 0
    for vals in lines:
        vals = list(map(str.strip, vals))
        assert (i >= len(y1) and vals[0] == '') or approxeq(float(vals[0]), i)
        assert (i >= len(y1) and vals[1] == '') or approxeq(
            float(vals[1]), y1[i])

        assert (i >= len(x2) and vals[2] == '') or approxeq(
            float(vals[2]), x2[i])
        assert (i >= len(y2) and vals[3] == '') or approxeq(
            float(vals[3]), y2[i])

        assert (i >= len(x3) and vals[4] == '') or approxeq(
            float(vals[4]), x3[i])
        assert (i >= len(y3) and vals[5] == '') or approxeq(
            float(vals[5]), y3[i])
        i += 1

    os.unlink(tempfilename)
def test_fft():
    f = 20.
    x = np.linspace(0, 1, 1000)
    y = np.sin(2 * np.pi * f * x)
    pd = pg.PlotDataItem(x, y)
    pd.setFftMode(True)    
    x, y = pd.getData()
    assert abs(x[np.argmax(y)] - f) < 0.03
    
    x = np.linspace(0, 1, 1001)
    y = np.sin(2 * np.pi * f * x)
    pd.setData(x, y)
    x, y = pd.getData()
    assert abs(x[np.argmax(y)]- f) < 0.03
    
    pd.setLogMode(True, False)
    x, y = pd.getData()
    assert abs(x[np.argmax(y)] - np.log10(f)) < 0.01
    
def test_scatterplotitem():
    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())
    for i, pxMode in enumerate([True, False]):
        for j, useCache in enumerate([True, False]):
            s = pg.ScatterPlotItem()
            s.opts['useCache'] = useCache
            plot.addItem(s)
            s.setData(x=np.array([10, 40, 20, 30]) + i * 100,
                      y=np.array([40, 60, 10, 30]) + j * 100,
                      pxMode=pxMode)
            s.addPoints(x=np.array([60, 70]) + i * 100,
                        y=np.array([60, 70]) + j * 100,
                        size=[20, 30])

            # Test uniform spot updates
            s.setSize(10)
            s.setBrush('r')
            s.setPen('g')
            s.setSymbol('+')
            app.processEvents()

            # Test list spot updates
            s.setSize([10] * 6)
            s.setBrush([pg.mkBrush('r')] * 6)
            s.setPen([pg.mkPen('g')] * 6)
            s.setSymbol(['+'] * 6)
            s.setPointData([s] * 6)
            app.processEvents()

            # Test array spot updates
            s.setSize(np.array([10] * 6))
            s.setBrush(np.array([pg.mkBrush('r')] * 6))
            s.setPen(np.array([pg.mkPen('g')] * 6))
            s.setSymbol(np.array(['+'] * 6))
            s.setPointData(np.array([s] * 6))
            app.processEvents()

            # Test per-spot updates
            spot = s.points()[0]
            spot.setSize(20)
            spot.setBrush('b')
            spot.setPen('g')
            spot.setSymbol('o')
            spot.setData(None)
            app.processEvents()

    plot.clear()
Esempio n. 20
0
def test_mouseInteraction():
    plt = pg.plot()
    plt.scene().minDragTime = 0  # let us simulate mouse drags very quickly.
    vline = plt.addLine(x=0, movable=True)
    plt.addItem(vline)
    hline = plt.addLine(y=0, movable=True)
    hline2 = plt.addLine(y=-1, movable=False)
    plt.setXRange(-10, 10)
    plt.setYRange(-10, 10)

    # test horizontal drag
    pos = plt.plotItem.vb.mapViewToScene(pg.Point(0, 5)).toPoint()
    pos2 = pos - QtCore.QPoint(200, 200)
    mouseMove(plt, pos)
    assert vline.mouseHovering is True and hline.mouseHovering is False
    mouseDrag(plt, pos, pos2, QtCore.Qt.LeftButton)
    px = vline.pixelLength(pg.Point(1, 0), ortho=True)
    assert abs(vline.value() - plt.plotItem.vb.mapSceneToView(pos2).x()) <= px

    # test missed drag
    pos = plt.plotItem.vb.mapViewToScene(pg.Point(5, 0)).toPoint()
    pos = pos + QtCore.QPoint(0, 6)
    pos2 = pos + QtCore.QPoint(-20, -20)
    mouseMove(plt, pos)
    assert vline.mouseHovering is False and hline.mouseHovering is False
    mouseDrag(plt, pos, pos2, QtCore.Qt.LeftButton)
    assert hline.value() == 0

    # test vertical drag
    pos = plt.plotItem.vb.mapViewToScene(pg.Point(5, 0)).toPoint()
    pos2 = pos - QtCore.QPoint(50, 50)
    mouseMove(plt, pos)
    assert vline.mouseHovering is False and hline.mouseHovering is True
    mouseDrag(plt, pos, pos2, QtCore.Qt.LeftButton)
    px = hline.pixelLength(pg.Point(1, 0), ortho=True)
    assert abs(hline.value() - plt.plotItem.vb.mapSceneToView(pos2).y()) <= px

    # test non-interactive line
    pos = plt.plotItem.vb.mapViewToScene(pg.Point(5, -1)).toPoint()
    pos2 = pos - QtCore.QPoint(50, 50)
    mouseMove(plt, pos)
    assert hline2.mouseHovering == False
    mouseDrag(plt, pos, pos2, QtCore.Qt.LeftButton)
    assert hline2.value() == -1
Esempio n. 21
0
def test_rescaleData():
    dtypes = list(
        map(np.dtype, ('ubyte', 'uint16', 'byte', 'int16', 'int', 'float')))
    for dtype1 in dtypes:
        for dtype2 in dtypes:
            data = (np.random.random(size=10) * 2**32 - 2**31).astype(dtype1)
            for scale, offset in [(10, 0), (10., 0.), (1, -50), (0.2, 0.5),
                                  (0.001, 0)]:
                if dtype2.kind in 'iu':
                    lim = np.iinfo(dtype2)
                    lim = lim.min, lim.max
                else:
                    lim = (-np.inf, np.inf)
                s1 = np.clip(float(scale) * (data - float(offset)),
                             *lim).astype(dtype2)
                s2 = pg.rescaleData(data, scale, offset, dtype2)
                assert s1.dtype == s2.dtype
                if dtype2.kind in 'iu':
                    assert np.all(s1 == s2)
                else:
                    assert np.allclose(s1, s2)
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'
Esempio n. 23
0
from __future__ import print_function
from builtins import str
import PyQtGraph as pg

pg.mkQApp()


def test_combobox():
    cb = pg.ComboBox()
    items = {'a': 1, 'b': 2, 'c': 3}
    cb.setItems(items)
    cb.setValue(2)
    assert str(cb.currentText()) == 'b'
    assert cb.value() == 2

    # Clear item list; value should be None
    cb.clear()
    assert cb.value() == None

    # Reset item list; value should be set automatically
    cb.setItems(items)
    assert cb.value() == 2

    # Clear item list; repopulate with same names and new values
    items = {'a': 4, 'b': 5, 'c': 6}
    cb.clear()
    cb.setItems(items)
    assert cb.value() == 5

    # Set list instead of dict
    cb.setItems(list(items.keys()))
import PyQtGraph as pg
import numpy as np
app = pg.mkQApp()
app.processEvents()


def test_scatterplotitem():
    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())
    for i, pxMode in enumerate([True, False]):
        for j, useCache in enumerate([True, False]):
            s = pg.ScatterPlotItem()
            s.opts['useCache'] = useCache
            plot.addItem(s)
            s.setData(x=np.array([10, 40, 20, 30]) + i * 100,
                      y=np.array([40, 60, 10, 30]) + j * 100,
                      pxMode=pxMode)
            s.addPoints(x=np.array([60, 70]) + i * 100,
                        y=np.array([60, 70]) + j * 100,
                        size=[20, 30])

            # Test uniform spot updates
            s.setSize(10)
            s.setBrush('r')
            s.setPen('g')
            s.setSymbol('+')
            app.processEvents()

            # Test list spot updates
from builtins import str
from builtins import range
import PyQtGraph as pg
import numpy as np
from PyQtGraph.pgcollections import OrderedDict

app = pg.mkQApp()


listOfTuples = [('text_%d' % i, i, i/9.) for i in range(12)]
listOfLists = [list(row) for row in listOfTuples]
plainArray = np.array(listOfLists, dtype=object)
recordArray = np.array(listOfTuples, dtype=[('string', object), 
                                            ('integer', int), 
                                            ('floating', float)])
dictOfLists = OrderedDict([(name, list(recordArray[name])) for name in recordArray.dtype.names])
listOfDicts = [OrderedDict([(name, rec[name]) for name in recordArray.dtype.names]) for rec in recordArray]
transposed = [[row[col] for row in listOfTuples] for col in range(len(listOfTuples[0]))]

def assertTableData(table, data):
    assert len(data) == table.rowCount()
    rows = list(range(table.rowCount()))
    columns = list(range(table.columnCount()))
    for r in rows:
        assert len(data[r]) == table.columnCount()
        row = []
        for c in columns:
            item = table.item(r, c)
            if item is not None:
                row.append(item.value)
            else:
 def fmt(item):
     if isinstance(item.value, float):
         return "%d %f" % (item.index, item.value)
     else:
         return pg.asUnicode(item.value)
Esempio n. 27
0
# -*- coding: utf-8 -*-
#import sip
#sip.setapi('QString', 1)

import PyQtGraph as pg
pg.mkQApp()

import PyQtGraph.dockarea as da


def test_dock():
    name = pg.asUnicode("évènts_zàhéér")
    dock = da.Dock(name=name)
    # make sure unicode names work correctly
    assert dock.name() == name
    # no surprises in return type.
    assert type(dock.name()) == type(name)
def test_TableWidget():
    w = pg.TableWidget(sortable=False)
    
    # Test all input data types
    w.setData(listOfTuples)
    assertTableData(w, listOfTuples)
    
    w.setData(listOfLists)
    assertTableData(w, listOfTuples)
    
    w.setData(plainArray)
    assertTableData(w, listOfTuples)
    
    w.setData(recordArray)
    assertTableData(w, listOfTuples)
    
    w.setData(dictOfLists)
    assertTableData(w, transposed)
    
    w.appendData(dictOfLists)
    assertTableData(w, transposed * 2)
        
    w.setData(listOfDicts)
    assertTableData(w, listOfTuples)
    
    w.appendData(listOfDicts)
    assertTableData(w, listOfTuples * 2)

    # Test sorting
    w.setData(listOfTuples)
    w.sortByColumn(0, pg.QtCore.Qt.AscendingOrder)
    assertTableData(w, sorted(listOfTuples, key=lambda a: a[0]))
    
    w.sortByColumn(1, pg.QtCore.Qt.AscendingOrder)
    assertTableData(w, sorted(listOfTuples, key=lambda a: a[1]))
    
    w.sortByColumn(2, pg.QtCore.Qt.AscendingOrder)
    assertTableData(w, sorted(listOfTuples, key=lambda a: a[2]))
    
    w.setSortMode(1, 'text')
    w.sortByColumn(1, pg.QtCore.Qt.AscendingOrder)
    assertTableData(w, sorted(listOfTuples, key=lambda a: str(a[1])))

    w.setSortMode(1, 'index')
    w.sortByColumn(1, pg.QtCore.Qt.AscendingOrder)
    assertTableData(w, listOfTuples)

    # Test formatting
    item = w.item(0, 2)
    assert item.text() == ('%0.3g' % item.value)
    
    w.setFormat('%0.6f')
    assert item.text() == ('%0.6f' % item.value)
    
    w.setFormat('X%0.7f', column=2)
    assert isinstance(item.value, float)
    assert item.text() == ('X%0.7f' % item.value)
    
    # test setting items that do not exist yet
    w.setFormat('X%0.7f', column=3)
    
    # test append uses correct formatting
    w.appendRow(('x', 10, 7.3))
    item = w.item(w.rowCount()-1, 2)
    assert isinstance(item.value, float)
    assert item.text() == ('X%0.7f' % item.value)
    
    # test reset back to defaults
    w.setFormat(None, column=2)
    assert isinstance(item.value, float)
    assert item.text() == ('%0.6f' % item.value)
    
    w.setFormat(None)
    assert isinstance(item.value, float)
    assert item.text() == ('%0.3g' % item.value)
    
    # test function formatter
    def fmt(item):
        if isinstance(item.value, float):
            return "%d %f" % (item.index, item.value)
        else:
            return pg.asUnicode(item.value)
    w.setFormat(fmt)
    assert isinstance(item.value, float)
    assert isinstance(item.index, int)
    assert item.text() == ("%d %f" % (item.index, item.value))
Esempio n. 29
0
def test_ImageItem(transpose=False):

    w = pg.GraphicsWindow()
    view = pg.ViewBox()
    w.setCentralWidget(view)
    w.resize(200, 200)
    w.show()
    img = TransposedImageItem(border=0.5, transpose=transpose)

    view.addItem(img)

    # test mono float
    np.random.seed(0)
    data = np.random.normal(size=(20, 20))
    dmax = data.max()
    data[:10, 1] = dmax + 10
    data[1, :10] = dmax + 12
    data[3, :10] = dmax + 13
    img.setImage(data)

    QtTest.QTest.qWaitForWindowShown(w)
    time.sleep(0.1)
    app.processEvents()
    assertImageApproved(
        w, 'imageitem/init',
        'Init image item. View is auto-scaled, image axis 0 marked by 1 line, axis 1 is marked by 2 lines. Origin in bottom-left.'
    )

    # ..with colormap
    cmap = pg.ColorMap([0, 0.25, 0.75, 1],
                       [[0, 0, 0, 255], [255, 0, 0, 255], [255, 255, 0, 255],
                        [255, 255, 255, 255]])
    img.setLookupTable(cmap.getLookupTable())
    assertImageApproved(w, 'imageitem/lut', 'Set image LUT.')

    # ..and different levels
    img.setLevels([dmax + 9, dmax + 13])
    assertImageApproved(w, 'imageitem/levels1', 'Levels show only axis lines.')

    img.setLookupTable(None)

    # test mono int
    data = np.fromfunction(lambda x, y: x + y * 10,
                           (129, 128)).astype(np.int16)
    img.setImage(data)
    assertImageApproved(w, 'imageitem/gradient_mono_int', 'Mono int gradient.')

    img.setLevels([640, 641])
    assertImageApproved(w, 'imageitem/gradient_mono_int_levels',
                        'Mono int gradient w/ levels to isolate diagonal.')

    # test mono byte
    data = np.fromfunction(lambda x, y: x + y, (129, 128)).astype(np.ubyte)
    img.setImage(data)
    assertImageApproved(w, 'imageitem/gradient_mono_byte',
                        'Mono byte gradient.')

    img.setLevels([127, 128])
    assertImageApproved(w, 'imageitem/gradient_mono_byte_levels',
                        'Mono byte gradient w/ levels to isolate diagonal.')

    # test monochrome image
    data = np.zeros((10, 10), dtype='uint8')
    data[:5, :5] = 1
    data[5:, 5:] = 1
    img.setImage(data)
    assertImageApproved(w, 'imageitem/monochrome',
                        'Ubyte image with only 0,1 values.')

    # test bool
    data = data.astype(bool)
    img.setImage(data)
    assertImageApproved(w, 'imageitem/bool', 'Boolean mask.')

    # test RGBA byte
    data = np.zeros((100, 100, 4), dtype='ubyte')
    data[..., 0] = np.linspace(0, 255, 100).reshape(100, 1)
    data[..., 1] = np.linspace(0, 255, 100).reshape(1, 100)
    data[..., 3] = 255
    img.setImage(data)
    assertImageApproved(w, 'imageitem/gradient_rgba_byte',
                        'RGBA byte gradient.')

    img.setLevels([[128, 129], [128, 255], [0, 1], [0, 255]])
    assertImageApproved(
        w, 'imageitem/gradient_rgba_byte_levels',
        'RGBA byte gradient. Levels set to show x=128 and y>128.')

    # test RGBA float
    data = data.astype(float)
    img.setImage(data / 1e9)
    assertImageApproved(w, 'imageitem/gradient_rgba_float',
                        'RGBA float gradient.')

    # checkerboard to test alpha
    img2 = TransposedImageItem(transpose=transpose)
    img2.setImage(np.fromfunction(lambda x, y: (x + y) % 2, (10, 10)),
                  levels=[-1, 2])
    view.addItem(img2)
    img2.scale(10, 10)
    img2.setZValue(-10)

    data[..., 0] *= 1e-9
    data[..., 1] *= 1e9
    data[..., 3] = np.fromfunction(lambda x, y: np.sin(0.1 * (x + y)),
                                   (100, 100))
    img.setImage(data, levels=[[0, 128e-9], [0, 128e9], [0, 1], [-1, 1]])
    assertImageApproved(w, 'imageitem/gradient_rgba_float_alpha',
                        'RGBA float gradient with alpha.')

    # test composition mode
    img.setCompositionMode(QtGui.QPainter.CompositionMode_Plus)
    assertImageApproved(
        w, 'imageitem/gradient_rgba_float_additive',
        'RGBA float gradient with alpha and additive composition mode.')

    img2.hide()
    img.setCompositionMode(QtGui.QPainter.CompositionMode_SourceOver)

    # test downsampling
    data = np.fromfunction(lambda x, y: np.cos(0.002 * x**2), (800, 100))
    img.setImage(data, levels=[-1, 1])
    assertImageApproved(w, 'imageitem/resolution_without_downsampling',
                        'Resolution test without downsampling.')

    img.setAutoDownsample(True)
    assertImageApproved(w, 'imageitem/resolution_with_downsampling_x',
                        'Resolution test with downsampling axross x axis.')
    assert img._lastDownsample == (4, 1)

    img.setImage(data.T, levels=[-1, 1])
    assertImageApproved(w, 'imageitem/resolution_with_downsampling_y',
                        'Resolution test with downsampling across y axis.')
    assert img._lastDownsample == (1, 4)

    view.hide()
Esempio n. 30
0
def test_InfiniteLine():
    # Test basic InfiniteLine API
    plt = pg.plot()
    plt.setXRange(-10, 10)
    plt.setYRange(-10, 10)
    plt.resize(600, 600)

    # seemingly arbitrary requirements; might need longer wait time for some platforms..
    QtTest.QTest.qWaitForWindowShown(plt)
    QtTest.QTest.qWait(100)

    vline = plt.addLine(x=1)
    assert vline.angle == 90
    br = vline.mapToView(QtGui.QPolygonF(vline.boundingRect()))
    assert br.containsPoint(pg.Point(1, 5), QtCore.Qt.OddEvenFill)
    assert not br.containsPoint(pg.Point(5, 0), QtCore.Qt.OddEvenFill)
    hline = plt.addLine(y=0)
    assert hline.angle == 0
    assert hline.boundingRect().contains(pg.Point(5, 0))
    assert not hline.boundingRect().contains(pg.Point(0, 5))

    vline.setValue(2)
    assert vline.value() == 2
    vline.setPos(pg.Point(4, -5))
    assert vline.value() == 4

    oline = pg.InfiniteLine(angle=30)
    plt.addItem(oline)
    oline.setPos(pg.Point(1, -1))
    assert oline.angle == 30
    assert oline.pos() == pg.Point(1, -1)
    assert oline.value() == [1, -1]

    # test bounding rect for oblique line
    br = oline.mapToScene(oline.boundingRect())
    pos = oline.mapToScene(pg.Point(2, 0))
    assert br.containsPoint(pos, QtCore.Qt.OddEvenFill)
    px = pg.Point(-0.5, -1.0 / 3**0.5)
    assert br.containsPoint(pos + 5 * px, QtCore.Qt.OddEvenFill)
    assert not br.containsPoint(pos + 7 * px, QtCore.Qt.OddEvenFill)