Module audian.traceitem

PlotDataItem for time series trace as a function of time.

Functions

def down_sample_peak(data, step)

Classes

class TraceItem (data, channel, *args, **kwargs)

Bases: :class:GraphicsObject <pyqtgraph.GraphicsObject>

:class:PlotDataItem provides a unified interface for displaying plot curves, scatter plots, or both. It also contains methods to transform or decimate the original data before it is displayed.

As pyqtgraph's standard plotting object, plot() methods such as :func:pyqtgraph.plot and :func:PlotItem.plot() <pyqtgraph.PlotItem.plot> create instances of :class:PlotDataItem.

While it is possible to use :class:PlotCurveItem <pyqtgraph.PlotCurveItem> or :class:ScatterPlotItem <pyqtgraph.ScatterPlotItem> individually, this is recommended only where performance is critical and the limited functionality of these classes is sufficient.

================================== ============================================== Signals: sigPlotChanged(self) Emitted when the data in this item is updated. sigClicked(self, ev) Emitted when the item is clicked. sigPointsClicked(self, points, ev) Emitted when a plot point is clicked Sends the list of points under the mouse. sigPointsHovered(self, points, ev) Emitted when a plot point is hovered over. Sends the list of points under the mouse. ================================== ==============================================

There are many different ways to create a PlotDataItem.

Data initialization arguments: (x,y data only)

========================== =========================================
PlotDataItem(x, y)         x, y: array_like coordinate values
PlotDataItem(y)            y values only -- x will be
                           automatically set to <code>range(len(y))</code>
PlotDataItem(x=x, y=y)     x and y given by keyword arguments
PlotDataItem(ndarray(N,2)) single 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 record array with ``dtype=[('x', float),
                             ('y', float), ...]``
PlotDataItem(list-of-dicts)  ``[{'x': x, 'y': y, ...},   ...]``
PlotDataItem(dict-of-lists)  ``{'x': [...], 'y': [...],  ...}``
============================ ===============================================

Line style keyword arguments:

============ ==============================================================================
connect      Specifies how / whether vertexes should be connected. See below for details.
pen          Pen to use for drawing the lines between points.
             Default is solid grey, 1px width. Use None to disable line drawing.
             May be a <code>QPen</code> or 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 a <code>QPen</code> or any single argument accepted by 
             :func:`mkPen() <pyqtgraph.mkPen>`
fillLevel    If specified, the area between the curve and fillLevel is filled.
fillOutline  (bool) If True, an outline surrounding the *fillLevel* area is drawn.
fillBrush    Fill to use in the *fillLevel* area. May be any single argument accepted by 
             :func:`mkBrush() <pyqtgraph.mkBrush>`
stepMode     (str or None) If specified and not None, a stepped curve is drawn.
             For 'left' the specified points each describe the left edge of a step.
             For 'right', they describe the right edge. 
             For 'center', the x coordinates specify the location of the step boundaries.
             This mode is commonly used for histograms. Note that it requires an additional
             x value, such that len(x) = len(y) + 1 .

============ ==============================================================================

connect supports the following arguments:

  • 'all' connects all points.
  • 'pairs' generates lines between every other point.
  • 'finite' creates a break when a nonfinite points is encountered.
  • If an ndarray is passed, it should contain N int32 values of 0 or 1. Values of 1 indicate that the respective point will be connected to the next.
  • In the default 'auto' mode, PlotDataItem will normally use 'all', but if any nonfinite data points are detected, it will automatically switch to 'finite'.

See :func:arrayToQPath() <pyqtgraph.arrayToQPath> for more details.

Point style keyword arguments: (see :func:ScatterPlotItem.setData() <pyqtgraph.ScatterPlotItem.setData> for more information)

============ ======================================================
symbol       Symbol to use for drawing points, or a list of symbols
             for each. The default is no symbol.
symbolPen    Outline pen for drawing points, or a list of pens, one
             per point. May be any single argument accepted by
             :func:`mkPen() <pyqtgraph.mkPen>`.
symbolBrush  Brush for filling points, or a 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.
============ ======================================================

Any symbol recognized by :class:ScatterPlotItem <pyqtgraph.ScatterPlotItem> can be specified, including 'o' (circle), 's' (square), 't', 't1', 't2', 't3' (triangles of different orientation), 'd' (diamond), '+' (plus sign), 'x' (x mark), 'p' (pentagon), 'h' (hexagon) and 'star'.

Symbols can also be directly given in the form of a :class:QtGui.QPainterPath instance.

Optimization keyword arguments:

================= =======================================================================
useCache          (bool) By default, generated point graphics items are cached to
                  improve performance. Setting this to False can improve image quality
                  in certain situations.
antialias         (bool) By default, antialiasing is disabled to improve performance.
                  Note that in some cases (in particular, when ``pxMode=True``), points
                  will be rendered antialiased even if this is set to <code>False</code>.
downsample        (int) Reduce the number of samples displayed by the given factor.
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 <code>True</code>, 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 <code>True</code>, only data visible within the X range of the containing
                  :class:<code>ViewBox</code> is plotted. This can improve performance when plotting
                  very large data sets where only a fraction of the data is visible
                  at any time.
dynamicRangeLimit (float or <code>None</code>) Limit off-screen y positions of data points. 
                  <code>None</code> disables the limiting. This can increase performance but may
                  cause plots to disappear at high levels of magnification.
                  The default of 1e6 limits data to approximately 1,000,000 times the 
                  :class:<code>ViewBox</code> height.
dynamicRangeHyst  (float) Permits changes in vertical zoom up to the given hysteresis
                  factor (the default is 3.0) before the limit calculation is repeated.
skipFiniteCheck   (bool, default <code>False</code>) Optimization flag that can speed up plotting by not 
                  checking and compensating for NaN values.  If set to <code>True</code>, and NaN 
                  values exist, unpredictable behavior will occur. The data may not be
                  displayed or the plot may take a significant performance hit.

                  In the default 'auto' connect mode, <code>PlotDataItem</code> will automatically
                  override this setting.
================= =======================================================================

Meta-info keyword arguments:

==========   ================================================
name         (string) Name of item for use in the plot legend
==========   ================================================

Notes on performance:

Plotting lines with the default single-pixel width is the fastest available option. For such lines, translucent colors (alpha < 1) do not result in a significant slowdown.

Wider lines increase the complexity due to the overlap of individual line segments. Translucent colors require merging the entire plot into a single entity before the alpha value can be applied. For plots with more than a few hundred points, this can result in excessive slowdown.

Since version 0.12.4, this slowdown is automatically avoided by an algorithm that draws line segments separately for fully opaque lines. Setting alpha < 1 reverts to the previous, slower drawing method.

For lines with a width of more than 4 pixels, :func:pyqtgraph.mkPen() <pyqtgraph.mkPen> will automatically create a QPen with Qt.PenCapStyle.RoundCap to ensure a smooth connection of line segments. This incurs a small performance penalty.

Expand source code
class TraceItem(pg.PlotDataItem):
    
    def __init__(self, data, channel, *args, **kwargs):
        self.data = data
        self.rate = self.data.rate
        self.channel = channel
        self.step = 1
        self.color = self.data.color
        self.lw_thin = self.data.lw_thin
        self.lw_thick = self.data.lw_thick

        self.data.plot_items[self.channel] = self
        
        pg.PlotDataItem.__init__(self, *args, connect='all',
                                 antialias=False, skipFiniteCheck=True,
                                 **kwargs)
        self.setPen(dict(color=self.color, width=self.lw_thin))
        self.setSymbolSize(8)
        self.setSymbolBrush(color=self.color)
        self.setSymbolPen(color=self.color)
        self.setSymbol(None)


    def update_plot(self):
        vb = self.getViewBox()
        if not isinstance(vb, pg.ViewBox):
            return
        t0, t1 = vb.viewRange()[0]
        
        start = max(0, int(t0*self.rate))
        tstop = int(t1*self.rate+1)
        stop = min(len(self.data), tstop)
        max_pixel = QApplication.desktop().screenGeometry().width()
        self.step = max(1, (tstop - start)//max_pixel)
        if self.step > 1:
            start = int(floor(start/self.step)*self.step)
            stop = int(ceil(stop/self.step + 1)*self.step)
            self.setPen(dict(color=self.color, width=self.lw_thin))
            self.setSymbol(None)
            n = (stop - start)//self.step
            pdata = np.zeros(2*n)
            i = 0
            nb = (self.data.bufferframes//self.step)*self.step
            for dd in self.data.blocks(nb, 0, start, stop):
                dsd = down_sample_peak(dd[:, self.channel], self.step)
                pdata[i:i+len(dsd)] = dsd
                i += len(dsd)
            #pdata = down_sample_peak(self.data[start:stop, self.channel], self.step)
            step2 = self.step/2
            time = np.arange(start, start + len(pdata)*step2, step2)/self.rate
            self.setData(time, pdata)
        elif self.step > 1:  # TODO: not used
            # subsample:
            self.setData(np.arange(start, stop, self.step)/self.rate,
                         self.data[start:stop:self.step, self.channel])
            self.setPen(dict(color=self.color, width=self.lw_thin))
        else:
            # all data:
            self.setData(np.arange(start, stop)/self.rate,
                         self.data[start:stop, self.channel])
            self.setPen(dict(color=self.color, width=self.lw_thick))
            if max_pixel/(stop - start) >= 10:
                self.setSymbol('o')
            else:
                self.setSymbol(None)
        self.data.buffer_changed[self.channel] = False


    def get_amplitude(self, x, y, x1=None):
        """Get trace amplitude next to cursor position. """
        idx = int(np.round(x*self.rate))
        step = self.step
        if x1 is not None:
            idx1 = int(np.round(x1*self.rate))
            step = max(1, idx1 - idx)
        if step > 1:
            idx = (idx//step)*step
            data_block = self.data[idx:idx + step, self.channel]
            mini = np.argmin(data_block)
            maxi = np.argmax(data_block)
            amin = data_block[mini]
            amax = data_block[maxi]
            if fabs(y - amax) < fabs(y - amin):
                return (idx+maxi)/self.rate, amax
            else:
                return (idx+mini)/self.rate, amin
        else:
            return idx/self.rate, self.data[idx, self.channel]

Ancestors

  • pyqtgraph.graphicsItems.PlotDataItem.PlotDataItem
  • pyqtgraph.graphicsItems.GraphicsObject.GraphicsObject
  • pyqtgraph.graphicsItems.GraphicsItem.GraphicsItem
  • PyQt5.QtWidgets.QGraphicsObject
  • PyQt5.QtCore.QObject
  • PyQt5.QtWidgets.QGraphicsItem
  • sip.wrapper
  • sip.simplewrapper

Methods

def update_plot(self)
def get_amplitude(self, x, y, x1=None)

Get trace amplitude next to cursor position.