plots

Classes to plot data in the GUI.

Todo

Add all possible plot objects and options in list.

Note

Plot objects need to be added to PLOT_LIST in order to be reachable.

Classes

HLine()

A Horizontal line.

ImageItem_TimedUpdate(*args, **kwargs)

Reclass of pyqtgraph.ImageItem to update with a fixed fps.

Line([color, size])

A simple line

Plot(pilot[, x_width, parent])

Widget that hosts a pyqtgraph.PlotWidget and manages graphical objects for one pilot depending on the task.

Plot_Widget()

Main plot widget that holds plots for all pilots

Point([color, size])

A simple point.

Roll_Mean([winsize])

Shaded area underneath a rolling average.

Segment(**kwargs)

A line segment that draws from 0.5 to some endpoint.

Shaded(**kwargs)

Shaded area for a continuous plot

Timer()

A simple timer that counts…

Video(videos[, fps])

Display Video data as it is collected.

Data

PLOT_LIST

A dictionary connecting plot keys to objects.

Functions

gui_event(fn)

Wrapper/decorator around an event that posts GUI events back to the main thread that our window is running in.

gui_event(fn)[source]

Wrapper/decorator around an event that posts GUI events back to the main thread that our window is running in.

Parameters

fn (callable) – a function that does something to the GUI

class Plot_Widget[source]

Bases: PySide2.QtWidgets.QWidget

Main plot widget that holds plots for all pilots

Essentially just a container to give plots a layout and handle any logic that should apply to all plots.

Variables
  • logger (logging.Logger) – The ‘main’ logger

  • plots (dict) – mapping from pilot name to Plot

Methods

init_plots(pilot_list)

For each pilot, instantiate a Plot and add to layout.

init_plots(pilot_list)[source]

For each pilot, instantiate a Plot and add to layout.

Parameters

pilot_list (list) – the keys from Terminal.pilots

staticMetaObject = <PySide2.QtCore.QMetaObject object>
class Plot(pilot, x_width=50, parent=None)[source]

Bases: PySide2.QtWidgets.QWidget

Widget that hosts a pyqtgraph.PlotWidget and manages graphical objects for one pilot depending on the task.

listens

Key

Method

Description

‘START’

l_start()

starting a new task

‘DATA’

l_data()

getting a new datapoint

‘STOP’

l_stop()

stop the task

‘PARAM’

l_param()

change some parameter

Methods

init_plots()

Make pre-task GUI objects and set basic visual parameters of self.plot

l_data(value)

Receive some data, if we were told to plot it, stash the data and update the assigned plot.

l_param(value)

Warning

Not implemented

l_start(value)

Starting a task, initialize task-specific plot objects described in the Task.PLOT attribute.

l_state(value)

Pilot letting us know its state has changed.

l_stop(value)

Clean up the plot objects.

Plot Parameters

The plot is built from the PLOT={data:plot_element} mappings described in the Task class. Additional parameters can be specified in the PLOT dictionary. Currently:

  • continuous (bool): whether the data should be plotted against the trial number (False or NA) or against time (True)

  • chance_bar (bool): Whether to draw a red horizontal line at chance level (default: 0.5)

  • chance_level (float): The position in the y-axis at which the chance_bar should be drawn

  • roll_window (int): The number of trials Roll_Mean take the average over.

Variables
  • pilot (str) –

    The name of our pilot, used to set the identity of our socket, specifically:

    'P_{pilot}'
    

  • infobox (QtWidgets.QFormLayout) – Box to plot basic task information like trial number, etc.

  • info (dict) –

    Widgets in infobox:

    • ’N Trials’: QtWidgets.QLabel,

    • ’Runtime’ : Timer,

    • ’Session’ : QtWidgets.QLabel,

    • ’Protocol’: QtWidgets.QLabel,

    • ’Step’ : QtWidgets.QLabel

  • plot (pyqtgraph.PlotWidget) – The widget where we draw our plots

  • plot_params (dict) – A dictionary of plot parameters we receive from the Task class

  • data (dict) – A dictionary of the data we’ve received

  • plots (dict) – The collection of plots we instantiate based on plot_params

  • node (Net_Node) – Our local net node where we listen for data.

  • state (str) – state of the pilot, used to keep plot synchronized.

Parameters
  • pilot (str) – The name of our pilot

  • x_width (int) – How many trials in the past should we plot?

init_plots()[source]

Make pre-task GUI objects and set basic visual parameters of self.plot

l_start(value)[source]

Starting a task, initialize task-specific plot objects described in the Task.PLOT attribute.

Matches the data field name (keys of Task.PLOT ) to the plot object that represents it, eg, to make the standard nafc plot:

{'target'   : 'point',
 'response' : 'segment',
 'correct'  : 'rollmean'}
Parameters

value (dict) – The same parameter dictionary sent by Terminal.toggle_start(), including

  • current_trial

  • step

  • session

  • step_name

  • task_type

l_data(value)[source]

Receive some data, if we were told to plot it, stash the data and update the assigned plot.

Parameters

value (dict) – Value field of a data message sent during a task.

l_stop(value)[source]

Clean up the plot objects.

Parameters

value (dict) – if “graduation” is a key, don’t stop the timer.

l_param(value)[source]

Warning

Not implemented

Parameters

value

l_state(value)[source]

Pilot letting us know its state has changed. Mostly for the case where we think we’re running but the pi doesn’t.

Parameters

value (Pilot.state) – the state of our pilot

staticMetaObject = <PySide2.QtCore.QMetaObject object>
class Point(color=0, 0, 0, size=5, **kwargs)[source]

Bases: pyqtgraph.graphicsItems.PlotDataItem.PlotDataItem

A simple point.

Variables
  • brush (QtWidgets.QBrush) –

  • pen (QtWidgets.QPen) –

Parameters
  • color (tuple) – RGB color of points

  • size (int) – width in px.

Methods

update(data)

Parameters

data (numpy.ndarray) – an x_width x 2 array where

update(data)[source]
Parameters

data (numpy.ndarray) – an x_width x 2 array where column 0 is trial number and column 1 is the value, where value can be “L”, “C”, “R” or a float.

staticMetaObject = <PySide2.QtCore.QMetaObject object>
class Line(color=0, 0, 0, size=1, **kwargs)[source]

Bases: pyqtgraph.graphicsItems.PlotDataItem.PlotDataItem

A simple line

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]

Methods

update(self, rect)

update(self, x: float, y: float, width: float, height: float)

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:

connect

Specifies how / whether vertexes should be connected. See arrayToQPath()

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 mkPen()

shadowPen

Pen for secondary line to draw behind the primary line. disabled by default. May be any single argument accepted by mkPen()

fillLevel

Fill the area between the curve and fillLevel

fillOutline

(bool) If True, an outline surrounding the fillLevel area is drawn.

fillBrush

Fill to use when fillLevel is specified. May be any single argument accepted by mkBrush()

stepMode

If True, two orthogonal lines are drawn for each sample as steps. This is commonly used when drawing histograms. Note that in this case, len(x) == len(y) + 1 (added in version 0.9.9)

Point style keyword arguments: (see 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 mkPen()

symbolBrush

Brush for filling points OR list of brushes, one per point. May be any single argument accepted by 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

update(self, rect: PySide2.QtCore.QRectF = Default(QRectF))[source]

update(self, x: float, y: float, width: float, height: float)

staticMetaObject = <PySide2.QtCore.QMetaObject object>
class Segment(**kwargs)[source]

Bases: pyqtgraph.graphicsItems.PlotDataItem.PlotDataItem

A line segment that draws from 0.5 to some endpoint.

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]

Methods

update(data)

data is doubled and then every other value is set to 0.5,

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:

connect

Specifies how / whether vertexes should be connected. See arrayToQPath()

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 mkPen()

shadowPen

Pen for secondary line to draw behind the primary line. disabled by default. May be any single argument accepted by mkPen()

fillLevel

Fill the area between the curve and fillLevel

fillOutline

(bool) If True, an outline surrounding the fillLevel area is drawn.

fillBrush

Fill to use when fillLevel is specified. May be any single argument accepted by mkBrush()

stepMode

If True, two orthogonal lines are drawn for each sample as steps. This is commonly used when drawing histograms. Note that in this case, len(x) == len(y) + 1 (added in version 0.9.9)

Point style keyword arguments: (see 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 mkPen()

symbolBrush

Brush for filling points OR list of brushes, one per point. May be any single argument accepted by 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

update(data)[source]

data is doubled and then every other value is set to 0.5, then setData() is used with connect=’pairs’ to make line segments.

Parameters

data (numpy.ndarray) – an x_width x 2 array where column 0 is trial number and column 1 is the value, where value can be “L”, “C”, “R” or a float.

staticMetaObject = <PySide2.QtCore.QMetaObject object>
class Roll_Mean(winsize=10, **kwargs)[source]

Bases: pyqtgraph.graphicsItems.PlotDataItem.PlotDataItem

Shaded area underneath a rolling average.

Typically used as a rolling mean of corrects, so area above and below 0.5 is drawn.

Parameters

winsize (int) – number of trials in the past to take a rolling mean of

Methods

update(data)

Parameters

data (numpy.ndarray) – an x_width x 2 array where

update(data)[source]
Parameters

data (numpy.ndarray) – an x_width x 2 array where column 0 is trial number and column 1 is the value.

staticMetaObject = <PySide2.QtCore.QMetaObject object>
class Shaded(**kwargs)[source]

Bases: pyqtgraph.graphicsItems.PlotDataItem.PlotDataItem

Shaded area for a continuous plot

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]

Methods

update(data)

Parameters

data (numpy.ndarray) – an x_width x 2 array where

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:

connect

Specifies how / whether vertexes should be connected. See arrayToQPath()

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 mkPen()

shadowPen

Pen for secondary line to draw behind the primary line. disabled by default. May be any single argument accepted by mkPen()

fillLevel

Fill the area between the curve and fillLevel

fillOutline

(bool) If True, an outline surrounding the fillLevel area is drawn.

fillBrush

Fill to use when fillLevel is specified. May be any single argument accepted by mkBrush()

stepMode

If True, two orthogonal lines are drawn for each sample as steps. This is commonly used when drawing histograms. Note that in this case, len(x) == len(y) + 1 (added in version 0.9.9)

Point style keyword arguments: (see 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 mkPen()

symbolBrush

Brush for filling points OR list of brushes, one per point. May be any single argument accepted by 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

update(data)[source]
Parameters

data (numpy.ndarray) – an x_width x 2 array where column 0 is time and column 1 is the value.

staticMetaObject = <PySide2.QtCore.QMetaObject object>
class Timer[source]

Bases: PySide2.QtWidgets.QLabel

A simple timer that counts… time…

Uses a QtCore.QTimer connected to Timer.update_time() .

Methods

start_timer([update_interval])

Parameters

update_interval (float) – How often (in ms) the timer should be updated.

stop_timer()

you can read the sign ya punk

update_time()

Called every (update_interval) milliseconds to set the text of the timer.

start_timer(update_interval=1000)[source]
Parameters

update_interval (float) – How often (in ms) the timer should be updated.

stop_timer()[source]

you can read the sign ya punk

update_time()[source]

Called every (update_interval) milliseconds to set the text of the timer.

staticMetaObject = <PySide2.QtCore.QMetaObject object>
class Video(videos, fps=None)[source]

Bases: PySide2.QtWidgets.QWidget

Display Video data as it is collected.

Uses the ImageItem_TimedUpdate class to do timed frame updates.

Parameters
  • videos (list, tuple) – Names of video streams that will be displayed

  • fps (int) – if None, draw according to prefs.DRAWFPS. Otherwise frequency of widget update

Variables
  • videos (list, tuple) – Names of video streams that will be displayed

  • fps (int) – if None, draw according to prefs.DRAWFPS. Otherwise frequency of widget update

  • ifps (int) – 1/fps, duration of frame in s

  • qs (dict) – Dictionary of :class:`~queue.Queue`s in which frames will be dumped

  • quitting (threading.Event) – Signal to quit drawing

  • update_thread (threading.Thread) – Thread with target=:meth:~.Video._update_frame

  • layout (PySide2.QtWidgets.QGridLayout) – Widget layout

  • vid_widgets (dict) – dict containing widgets for each of the individual video streams.

Methods

_update_frame()

Pulls frames from Video.qs and feeds them to the video widgets.

init_gui()

release()

update_frame(video, data)

Put a frame for a video stream into its queue.

init_gui()[source]
_update_frame()[source]

Pulls frames from Video.qs and feeds them to the video widgets.

Internal method, run in thread.

update_frame(video, data)[source]

Put a frame for a video stream into its queue.

If there is a waiting frame, pull it from the queue first – it’s old now.

Parameters
  • video (str) – name of video stream

  • data (numpy.ndarray) – video frame

release()[source]
staticMetaObject = <PySide2.QtCore.QMetaObject object>
class HLine[source]

Bases: PySide2.QtWidgets.QFrame

A Horizontal line.

staticMetaObject = <PySide2.QtCore.QMetaObject object>
class ImageItem_TimedUpdate(*args, **kwargs)[source]

Bases: pyqtgraph.graphicsItems.ImageItem.ImageItem

Reclass of pyqtgraph.ImageItem to update with a fixed fps.

Rather than calling update() every time a frame is updated, call it according to the timer.

fps is set according to prefs.DRAWFPS, if not available, draw at 10fps

Variables

timer (QTimer) – Timer held in globals() that synchronizes frame updates across image items

Methods

setImage([image, autoLevels])

Update the image displayed by this item.

update_img()

Call update()

See setImage for all allowed initialization arguments.

setImage(image=None, autoLevels=None, **kargs)[source]

Update the image displayed by this item. For more information on how the image is processed before displaying, see makeARGB ================= ========================================================================= Arguments: image (numpy array) Specifies the image data. May be 2D (width, height) or

3D (width, height, RGBa). The array dtype must be integer or floating point of any bit depth. For 3D arrays, the third dimension must be of length 3 (RGB) or 4 (RGBA). See notes below.

autoLevels (bool) If True, this forces the image to automatically select

levels based on the maximum and minimum values in the data. By default, this argument is true unless the levels argument is given.

lut (numpy array) The color lookup table to use when displaying the image.

See setLookupTable.

levels (min, max) The minimum and maximum values to use when rescaling the image

data. By default, this will be set to the minimum and maximum values in the image. If the image array has dtype uint8, no rescaling is necessary.

opacity (float 0.0-1.0) compositionMode See setCompositionMode border Sets the pen used when drawing the image border. Default is None. autoDownsample (bool) If True, the image is automatically downsampled to match the

screen resolution. This improves performance for large images and reduces aliasing. If autoDownsample is not specified, then ImageItem will choose whether to downsample the image based on its size.

staticMetaObject = <PySide2.QtCore.QMetaObject object>
update_img()[source]

Call update()

PLOT_LIST = {'line': <class 'autopilot.core.plots.Line'>, 'point': <class 'autopilot.core.plots.Point'>, 'rollmean': <class 'autopilot.core.plots.Roll_Mean'>, 'segment': <class 'autopilot.core.plots.Segment'>, 'shaded': <class 'autopilot.core.plots.Shaded'>}

A dictionary connecting plot keys to objects.

Todo

Just reference the plot objects.