PlotCurveItem.py 17.3 KB
Newer Older
1 2 3 4
from pyqtgraph.Qt import QtGui, QtCore
from scipy.fftpack import fft
import numpy as np
import scipy.stats
5
from .GraphicsObject import GraphicsObject
6 7 8
import pyqtgraph.functions as fn
from pyqtgraph import debug
from pyqtgraph.Point import Point
9
import pyqtgraph as pg
10
import struct, sys
11 12 13 14 15

__all__ = ['PlotCurveItem']
class PlotCurveItem(GraphicsObject):
    
    
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
    """
    Class representing a single plot curve. Instances of this class are created
    automatically as part of PlotDataItem; these rarely need to be instantiated
    directly.
    
    Features:
    
    - Fast data update
    - FFT display mode (accessed via PlotItem context menu)
    - Fill under curve
    - Mouse interaction
    
    ====================  ===============================================
    **Signals:**
    sigPlotChanged(self)  Emitted when the data being plotted has changed
    sigClicked(self)      Emitted when the curve is clicked
    ====================  ===============================================
33 34 35 36 37
    """
    
    sigPlotChanged = QtCore.Signal(object)
    sigClicked = QtCore.Signal(object)
    
38
    def __init__(self, *args, **kargs):
39
        """
40 41 42 43
        Forwards all arguments to :func:`setData <pyqtgraph.PlotCurveItem.setData>`.
        
        Some extra arguments are accepted as well:
        
44 45
        ==============  =======================================================
        **Arguments:**
46
        parent          The parent GraphicsObject (optional)
47
        clickable       If True, the item will emit sigClicked when it is 
48
                        clicked on. Defaults to False.
49 50
        ==============  =======================================================
        """
51
        GraphicsObject.__init__(self, kargs.get('parent', None))
52 53 54
        self.clear()
        self.path = None
        self.fillPath = None
Luke Campagnola's avatar
Luke Campagnola committed
55
        self._boundsCache = [None, None]
56 57 58 59 60 61
            
        ## this is disastrous for performance.
        #self.setCacheMode(QtGui.QGraphicsItem.DeviceCoordinateCache)
        
        self.metaData = {}
        self.opts = {
62
            'pen': fn.mkPen('w'),
63
            'shadowPen': None,
64 65
            'fillLevel': None,
            'brush': None,
66
            'stepMode': False,
67 68
            'name': None,
            'antialias': pg.getConfigOption('antialias'),
69
        }
70 71
        self.setClickable(kargs.get('clickable', False))
        self.setData(*args, **kargs)
72 73 74 75 76 77 78 79
        
    def implements(self, interface=None):
        ints = ['plotData']
        if interface is None:
            return ints
        return interface in ints
    
    def setClickable(self, s):
80
        """Sets whether the item responds to mouse clicks."""
81 82 83 84
        self.clickable = s
        
        
    def getData(self):
85
        return self.xData, self.yData
86
        
87
    def dataBounds(self, ax, frac=1.0, orthoRange=None):
Luke Campagnola's avatar
Luke Campagnola committed
88 89 90 91 92 93
        ## Need this to run as fast as possible.
        ## check cache first:
        cache = self._boundsCache[ax]
        if cache is not None and cache[0] == (frac, orthoRange):
            return cache[1]
        
94 95 96 97 98 99
        (x, y) = self.getData()
        if x is None or len(x) == 0:
            return (0, 0)
            
        if ax == 0:
            d = x
100
            d2 = y
101 102
        elif ax == 1:
            d = y
103 104 105 106 107 108 109
            d2 = x

        if orthoRange is not None:
            mask = (d2 >= orthoRange[0]) * (d2 <= orthoRange[1])
            d = d[mask]
            d2 = d2[mask]

110 111
            
        if frac >= 1.0:
Luke Campagnola's avatar
Luke Campagnola committed
112
            b = (d.min(), d.max())
113 114 115
        elif frac <= 0.0:
            raise Exception("Value for parameter 'frac' must be > 0. (got %s)" % str(frac))
        else:
Luke Campagnola's avatar
Luke Campagnola committed
116 117 118 119 120 121 122
            b = (scipy.stats.scoreatpercentile(d, 50 - (frac * 50)), scipy.stats.scoreatpercentile(d, 50 + (frac * 50)))
        self._boundsCache[ax] = [(frac, orthoRange), b]
        return b
        
    def invalidateBounds(self):
        self._boundingRect = None
        self._boundsCache = [None, None]
123
            
124
    def setPen(self, *args, **kargs):
125
        """Set the pen used to draw the curve."""
126
        self.opts['pen'] = fn.mkPen(*args, **kargs)
Luke Campagnola's avatar
Luke Campagnola committed
127
        self.invalidateBounds()
128 129
        self.update()
        
130
    def setShadowPen(self, *args, **kargs):
131 132 133 134
        """Set the shadow pen used to draw behind tyhe primary pen.
        This pen must have a larger width than the primary 
        pen to be visible.
        """
135
        self.opts['shadowPen'] = fn.mkPen(*args, **kargs)
Luke Campagnola's avatar
Luke Campagnola committed
136
        self.invalidateBounds()
137
        self.update()
138 139

    def setBrush(self, *args, **kargs):
140
        """Set the brush used when filling the area under the curve"""
141
        self.opts['brush'] = fn.mkBrush(*args, **kargs)
Luke Campagnola's avatar
Luke Campagnola committed
142
        self.invalidateBounds()
143 144
        self.update()
        
145
    def setFillLevel(self, level):
146
        """Set the level filled to when filling under the curve"""
147 148
        self.opts['fillLevel'] = level
        self.fillPath = None
Luke Campagnola's avatar
Luke Campagnola committed
149
        self.invalidateBounds()
150
        self.update()
151 152

    def setData(self, *args, **kargs):
153
        """
154
        ==============  ========================================================
155 156 157 158 159 160 161 162 163 164 165 166
        **Arguments:**
        x, y            (numpy arrays) Data to show 
        pen             Pen to use when drawing. Any single argument accepted by
                        :func:`mkPen <pyqtgraph.mkPen>` is allowed.
        shadowPen       Pen for drawing behind the primary pen. Usually this
                        is used to emphasize the curve by providing a 
                        high-contrast border. Any single argument accepted by
                        :func:`mkPen <pyqtgraph.mkPen>` is allowed.
        fillLevel       (float or None) Fill the area 'under' the curve to
                        *fillLevel*
        brush           QBrush to use when filling. Any single argument accepted
                        by :func:`mkBrush <pyqtgraph.mkBrush>` is allowed.
167 168 169
        antialias       (bool) Whether to use antialiasing when drawing. This
                        is disabled by default because it decreases performance.
        ==============  ========================================================
170 171 172 173 174 175
        
        If non-keyword arguments are used, they will be interpreted as
        setData(y) for a single argument and setData(x, y) for two
        arguments.
        
        
176
        """
177
        self.updateData(*args, **kargs)
178
        
179
    def updateData(self, *args, **kargs):
180
        prof = debug.Profiler('PlotCurveItem.updateData', disabled=True)
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195

        if len(args) == 1:
            kargs['y'] = args[0]
        elif len(args) == 2:
            kargs['x'] = args[0]
            kargs['y'] = args[1]
        
        if 'y' not in kargs or kargs['y'] is None:
            kargs['y'] = np.array([])
        if 'x' not in kargs or kargs['x'] is None:
            kargs['x'] = np.arange(len(kargs['y']))
            
        for k in ['x', 'y']:
            data = kargs[k]
            if isinstance(data, list):
Luke Campagnola's avatar
Luke Campagnola committed
196 197
                data = np.array(data)
                kargs[k] = data
198 199
            if not isinstance(data, np.ndarray) or data.ndim > 1:
                raise Exception("Plot data must be 1D ndarray.")
200 201
            if 'complex' in str(data.dtype):
                raise Exception("Can not plot complex data types.")
202
            
203 204
        prof.mark("data checks")
        
205
        #self.setCacheMode(QtGui.QGraphicsItem.NoCache)  ## Disabling and re-enabling the cache works around a bug in Qt 4.6 causing the cached results to display incorrectly
206
                                                        ##    Test this bug with test_PlotWidget and zoom in on the animated plot
Luke Campagnola's avatar
Luke Campagnola committed
207
        self.invalidateBounds()
208
        self.prepareGeometryChange()
Luke Campagnola's avatar
Luke Campagnola committed
209
        self.informViewBoundsChanged()
210 211 212
        self.yData = kargs['y'].view(np.ndarray)
        self.xData = kargs['x'].view(np.ndarray)
        
213 214
        prof.mark('copy')
        
215 216 217 218 219 220 221 222 223
        if 'stepMode' in kargs:
            self.opts['stepMode'] = kargs['stepMode']
        
        if self.opts['stepMode'] is True:
            if len(self.xData) != len(self.yData)+1:  ## allow difference of 1 for step mode plots
                raise Exception("len(X) must be len(Y)+1 since stepMode=True (got %s and %s)" % (str(x.shape), str(y.shape)))
        else:
            if self.xData.shape != self.yData.shape:  ## allow difference of 1 for step mode plots
                raise Exception("X and Y arrays must be the same shape--got %s and %s." % (str(x.shape), str(y.shape)))
224 225
        
        self.path = None
226 227 228
        self.fillPath = None
        #self.xDisp = self.yDisp = None
        
Luke Campagnola's avatar
Luke Campagnola committed
229 230 231
        if 'name' in kargs:
            self.opts['name'] = kargs['name']
        
232 233 234 235 236 237 238 239
        if 'pen' in kargs:
            self.setPen(kargs['pen'])
        if 'shadowPen' in kargs:
            self.setShadowPen(kargs['shadowPen'])
        if 'fillLevel' in kargs:
            self.setFillLevel(kargs['fillLevel'])
        if 'brush' in kargs:
            self.setBrush(kargs['brush'])
240 241
        if 'antialias' in kargs:
            self.opts['antialias'] = kargs['antialias']
242
        
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
        
        prof.mark('set')
        self.update()
        prof.mark('update')
        self.sigPlotChanged.emit(self)
        prof.mark('emit')
        prof.finish()
        
    def generatePath(self, x, y):
        prof = debug.Profiler('PlotCurveItem.generatePath', disabled=True)
        path = QtGui.QPainterPath()
        
        ## Create all vertices in path. The method used below creates a binary format so that all 
        ## vertices can be read in at once. This binary format may change in future versions of Qt, 
        ## so the original (slower) method is left here for emergencies:
        #path.moveTo(x[0], y[0])
        #for i in range(1, y.shape[0]):
        #    path.lineTo(x[i], y[i])
            
        ## Speed this up using >> operator
        ## Format is:
        ##    numVerts(i4)   0(i4)
        ##    x(f8)   y(f8)   0(i4)    <-- 0 means this vertex does not connect
        ##    x(f8)   y(f8)   1(i4)    <-- 1 means this vertex connects to the previous vertex
        ##    ...
        ##    0(i4)
        ##
        ## All values are big endian--pack using struct.pack('>d') or struct.pack('>i')
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
        
        if self.opts['stepMode']:
            ## each value in the x/y arrays generates 2 points.
            x2 = np.empty((len(x),2), dtype=x.dtype)
            x2[:] = x[:,np.newaxis]
            if self.opts['fillLevel'] is None:
                x = x2.reshape(x2.size)[1:-1]
                y2 = np.empty((len(y),2), dtype=y.dtype)
                y2[:] = y[:,np.newaxis]
                y = y2.reshape(y2.size)
            else:
                ## If we have a fill level, add two extra points at either end
                x = x2.reshape(x2.size)
                y2 = np.empty((len(y)+2,2), dtype=y.dtype)
                y2[1:-1] = y[:,np.newaxis]
                y = y2.reshape(y2.size)[1:-1]
                y[0] = self.opts['fillLevel']
                y[-1] = self.opts['fillLevel']
                
                
            
        
        
Luke Campagnola's avatar
Luke Campagnola committed
294
        if sys.version_info[0] == 2:   ## So this is disabled for python 3... why??
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
            n = x.shape[0]
            # create empty array, pad with extra space on either end
            arr = np.empty(n+2, dtype=[('x', '>f8'), ('y', '>f8'), ('c', '>i4')])
            # write first two integers
            prof.mark('allocate empty')
            arr.data[12:20] = struct.pack('>ii', n, 0)
            prof.mark('pack header')
            # Fill array with vertex values
            arr[1:-1]['x'] = x
            arr[1:-1]['y'] = y
            arr[1:-1]['c'] = 1
            prof.mark('fill array')
            # write last 0
            lastInd = 20*(n+1)
            arr.data[lastInd:lastInd+4] = struct.pack('>i', 0)
            prof.mark('footer')
            # create datastream object and stream into path
            buf = QtCore.QByteArray(arr.data[12:lastInd+4])  # I think one unnecessary copy happens here
            prof.mark('create buffer')
            ds = QtCore.QDataStream(buf)
            prof.mark('create datastream')
            ds >> path
            prof.mark('load')
            
            prof.finish()
        else:
            path.moveTo(x[0], y[0])
            for i in range(1, y.shape[0]):
                path.lineTo(x[i], y[i])
324 325 326 327 328 329 330 331 332 333 334 335 336
        
        return path


    def shape(self):
        if self.path is None:
            try:
                self.path = self.generatePath(*self.getData())
            except:
                return QtGui.QPainterPath()
        return self.path

    def boundingRect(self):
Luke Campagnola's avatar
Luke Campagnola committed
337 338 339 340 341 342 343 344 345 346 347
        if self._boundingRect is None:
            (x, y) = self.getData()
            if x is None or y is None or len(x) == 0 or len(y) == 0:
                return QtCore.QRectF()
                
                
            if self.opts['shadowPen'] is not None:
                lineWidth = (max(self.opts['pen'].width(), self.opts['shadowPen'].width()) + 1)
            else:
                lineWidth = (self.opts['pen'].width()+1)
                
348
            
Luke Campagnola's avatar
Luke Campagnola committed
349 350 351 352 353 354 355 356
            pixels = self.pixelVectors()
            if pixels == (None, None):
                pixels = [Point(0,0), Point(0,0)]
                
            xmin = x.min()
            xmax = x.max()
            ymin = y.min()
            ymax = y.max()
357
            
Luke Campagnola's avatar
Luke Campagnola committed
358 359 360 361 362 363 364 365
            if self.opts['fillLevel'] is not None:
                ymin = min(ymin, self.opts['fillLevel'])
                ymax = max(ymax, self.opts['fillLevel'])
                
            xmin -= pixels[0].x() * lineWidth
            xmax += pixels[0].x() * lineWidth
            ymin -= abs(pixels[1].y()) * lineWidth
            ymax += abs(pixels[1].y()) * lineWidth
366
            
Luke Campagnola's avatar
Luke Campagnola committed
367 368
            self._boundingRect = QtCore.QRectF(xmin, ymin, xmax-xmin, ymax-ymin)
        return self._boundingRect
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391

    def paint(self, p, opt, widget):
        prof = debug.Profiler('PlotCurveItem.paint '+str(id(self)), disabled=True)
        if self.xData is None:
            return
        #if self.opts['spectrumMode']:
            #if self.specPath is None:
                
                #self.specPath = self.generatePath(*self.getData())
            #path = self.specPath
        #else:
        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')
392
        
393 394
        if self._exportOpts is not False:
            aa = self._exportOpts.get('antialias', True)
395 396 397 398 399
        else:
            aa = self.opts['antialias']
        
        p.setRenderHint(p.Antialiasing, aa)
        
400
            
401
        if self.opts['brush'] is not None and self.opts['fillLevel'] is not None:
402 403 404 405
            if self.fillPath is None:
                if x is None:
                    x,y = self.getData()
                p2 = QtGui.QPainterPath(self.path)
406 407 408
                p2.lineTo(x[-1], self.opts['fillLevel'])
                p2.lineTo(x[0], self.opts['fillLevel'])
                p2.lineTo(x[0], y[0])
409 410 411
                p2.closeSubpath()
                self.fillPath = p2
                
Luke Campagnola's avatar
Luke Campagnola committed
412
            prof.mark('generate fill path')
413
            p.fillPath(self.fillPath, self.opts['brush'])
Luke Campagnola's avatar
Luke Campagnola committed
414
            prof.mark('draw fill path')
415
            
416 417 418
        sp = fn.mkPen(self.opts['shadowPen'])
        cp = fn.mkPen(self.opts['pen'])
 
419
        ## Copy pens and apply alpha adjustment
420 421
        #sp = QtGui.QPen(self.opts['shadowPen'])
        #cp = QtGui.QPen(self.opts['pen'])
422 423 424 425 426 427 428
        #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)
429
            
Luke Campagnola's avatar
Luke Campagnola committed
430 431
            
            
432
        if sp is not None and sp.style() != QtCore.Qt.NoPen:
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
            p.setPen(sp)
            p.drawPath(path)
        p.setPen(cp)
        p.drawPath(path)
        prof.mark('drawPath')
        
        #print "Render hints:", int(p.renderHints())
        prof.finish()
        #p.setPen(QtGui.QPen(QtGui.QColor(255,0,0)))
        #p.drawRect(self.boundingRect())
        
        
    def clear(self):
        self.xData = None  ## raw values
        self.yData = None
        self.xDisp = None  ## display values (after log / fft)
        self.yDisp = None
        self.path = None
        #del self.xData, self.yData, self.xDisp, self.yDisp, self.path
        
    def mouseClickEvent(self, ev):
        if not self.clickable or ev.button() != QtCore.Qt.LeftButton:
            return
        ev.accept()
        self.sigClicked.emit(self)


class ROIPlotItem(PlotCurveItem):
    """Plot curve that monitors an ROI and image for changes to automatically replot."""
    def __init__(self, roi, data, img, axes=(0,1), xVals=None, color=None):
        self.roi = roi
        self.roiData = data
        self.roiImg = img
        self.axes = axes
        self.xVals = xVals
        PlotCurveItem.__init__(self, self.getRoiData(), x=self.xVals, color=color)
        #roi.connect(roi, QtCore.SIGNAL('regionChanged'), self.roiChangedEvent)
        roi.sigRegionChanged.connect(self.roiChangedEvent)
        #self.roiChangedEvent()
        
    def getRoiData(self):
        d = self.roi.getArrayRegion(self.roiData, self.roiImg, axes=self.axes)
        if d is None:
            return
        while d.ndim > 1:
            d = d.mean(axis=1)
        return d
        
    def roiChangedEvent(self):
        d = self.getRoiData()
        self.updateData(d, self.xVals)