Episode 5: Your Own Widget

Write a widget of your own by subclassing gp.Scope: setup() and step() on the pipeline’s thread, _update() on the GUI thread, and no Qt at import.

A widget is a sink that draws. Subclass gp.Scope for a plot and register it with app.add_widget: the pipeline builds its chain, and MainApp gives it a place in the window. LevelBars draws one bar per channel, its RMS over the last half second.

A scope subclass

A limit parameter for the axis, a lock, and the bars built later. gp.Scope builds no plot where this process does not draw and leaves self.widget at None, so the constructor returns before touching one.

16class LevelBars(gp.Scope):
17    """One bar per channel: its RMS over the last half second."""
18
19    #: Seconds of signal each bar is computed over.
20    WINDOW_SECONDS = 0.5
21
22    class Configuration(gp.Scope.Configuration):
23        class Keys(gp.Scope.Configuration.Keys):
24            LIMIT = "limit"
25
26    def __init__(self, limit: float = 20.0, **kwargs):
27        input_ports = kwargs.pop(KEYS.INPUT_PORTS,
28                                 [gp.IPort.Configuration(name=PORT_IN)])
29        super().__init__(input_ports=input_ports, limit=limit, **kwargs)
30        self._lock = threading.Lock()
31        self._window = None
32        self._labels = None
33        self._bars = None
34        #: How often the bars were redrawn.
35        self.repaints = 0
36        # gp.Scope built no plot where this process does not draw.
37        if self.widget is None:
38            return
39        self._plot_item.setYRange(0, limit)
40        self.set_labels("channel", "RMS")
On the pipeline’s thread

setup() sizes the buffer from the sampling rate and draws nothing; step() keeps the newest samples, under the lock.

42    def setup(self, data, port_context_in):
43        # Runs on the pipeline's thread: size the buffer, draw nothing.
44        context = port_context_in[PORT_IN]
45        samples = int(context[KEYS.SAMPLING_RATE] * self.WINDOW_SECONDS)
46        count = context[KEYS.CHANNEL_COUNT]
47        self._window = np.zeros((samples, count), dtype=np.float32)
48        labels = context.get(KEYS.CHANNEL_LABELS)
49        self._labels = labels or [f"CH{i + 1}" for i in range(count)]
50        return super().setup(data, port_context_in)
51
52    def step(self, data):
53        frame = data[PORT_IN]
54        with self._lock:
55            kept = np.vstack((self._window, frame))
56            self._window = kept[-len(self._window):]
57        return {}
On the GUI thread

_update() is called by the widget’s own timer, ten times a second whatever the data rate, and it is the only place a graphics item may be touched. So it builds the bars on its first call and moves them after. A subclass draws with three underscored members of gp.Scope: _update(), which it overrides, _plot_item, the pyqtgraph plot, and _pen, the pen in the scope’s line colour. Pass refresh_rate= for another rate.

59    def _update(self):
60        # Called by the Qt timer, on the GUI thread: the one place a
61        # graphics item may be touched.
62        if self._window is None:
63            return
64        import pyqtgraph as pg
65
66        with self._lock:
67            levels = np.sqrt(np.mean(self._window ** 2, axis=0))
68        if self._bars is None:
69            ticks = list(enumerate(self._labels))
70            self._plot_item.getAxis("bottom").setTicks([ticks])
71            self._bars = pg.BarGraphItem(x=np.arange(len(levels)),
72                                         height=levels, width=0.6,
73                                         brush=self._pen.color())
74            self._plot_item.addItem(self._bars)
75        else:
76            self._bars.setOpts(height=levels)
77        self.repaints += 1
Feed it

Two channels of 10 Hz alpha beside two of noise, through a Router.

 82    app = gp.MainApp()
 83    p = gp.Pipeline()
 84
 85    # Two channels of alpha beside two of noise.
 86    alpha = gp.Generator(sampling_rate=250, channel_count=2,
 87                         signal_frequency=10, signal_amplitude=10.0,
 88                         noise_amplitude=1.0, name="alpha")
 89    noise = gp.Generator(sampling_rate=250, channel_count=2,
 90                         noise_amplitude=3.0, name="noise")
 91    both = gp.Router(input_channels=[gp.Router.ALL, gp.Router.ALL])
 92    bars = LevelBars(limit=10.0, name="levels")
 93
 94    p.connect(alpha, both["in1"])
 95    p.connect(noise, both["in2"])
 96    p.connect(both, bars)
 97    app.add_widget(bars)
 98
 99    p.start()
100    app.run()
101    p.stop()
102    p.close()
Result

Run the script. Two bars stand near 7, the RMS of a 10 µV sine, and two near 3, the noise’s.

Four bars, two tall and two short

Figure 41: One bar per channel, redrawn ten times a second.

No Qt at import

pyqtgraph and PySide6 are imported inside the methods that draw, never at the top of the module. A server builds the widget to describe what an edge will draw, and may have no Qt installed. A class whose base is a Qt type, or a Qt class as a default argument, breaks that as surely as an import.

Not a plot

For a readout, a button or anything else that is not a plot, subclass gp.Widget beside gp.INode, as (gp.INode, gp.Widget), and build the Qt widget yourself; ResultScope is built that way. It gets the same chain, but not gp.Scope’s decision, and no public call yet says when to build no Qt. Pass widget=None where gp.LaunchConfig.get().residency is gp.Constants.Residency.SERVER and a server stays Qt-free; an edge the widget is not assigned to still builds its Qt widget.

Summary

In this episode, you learned how to:

  • subclass gp.Scope and split the work between the two threads

  • draw with the scope’s plot item and pen, on the GUI thread only

  • keep Qt out of the import, so a server can build the widget too

Proceed to Episode 6, where a plain function becomes a node without a class at all.

Nodes in this episode: Generator, Router, Scope, and the file’s own LevelBars

File s7e5_your_own_widget.py – View file on GitHub

  1"""Season 7, Episode 5: a widget of your own, drawn on the GUI thread.
  2
  3Requires the gui extra.
  4"""
  5
  6import threading
  7
  8import numpy as np
  9
 10import gpype as gp
 11
 12KEYS = gp.Constants.Keys
 13PORT_IN = gp.Constants.Defaults.PORT_IN
 14
 15
 16class LevelBars(gp.Scope):
 17    """One bar per channel: its RMS over the last half second."""
 18
 19    #: Seconds of signal each bar is computed over.
 20    WINDOW_SECONDS = 0.5
 21
 22    class Configuration(gp.Scope.Configuration):
 23        class Keys(gp.Scope.Configuration.Keys):
 24            LIMIT = "limit"
 25
 26    def __init__(self, limit: float = 20.0, **kwargs):
 27        input_ports = kwargs.pop(KEYS.INPUT_PORTS,
 28                                 [gp.IPort.Configuration(name=PORT_IN)])
 29        super().__init__(input_ports=input_ports, limit=limit, **kwargs)
 30        self._lock = threading.Lock()
 31        self._window = None
 32        self._labels = None
 33        self._bars = None
 34        #: How often the bars were redrawn.
 35        self.repaints = 0
 36        # gp.Scope built no plot where this process does not draw.
 37        if self.widget is None:
 38            return
 39        self._plot_item.setYRange(0, limit)
 40        self.set_labels("channel", "RMS")
 41
 42    def setup(self, data, port_context_in):
 43        # Runs on the pipeline's thread: size the buffer, draw nothing.
 44        context = port_context_in[PORT_IN]
 45        samples = int(context[KEYS.SAMPLING_RATE] * self.WINDOW_SECONDS)
 46        count = context[KEYS.CHANNEL_COUNT]
 47        self._window = np.zeros((samples, count), dtype=np.float32)
 48        labels = context.get(KEYS.CHANNEL_LABELS)
 49        self._labels = labels or [f"CH{i + 1}" for i in range(count)]
 50        return super().setup(data, port_context_in)
 51
 52    def step(self, data):
 53        frame = data[PORT_IN]
 54        with self._lock:
 55            kept = np.vstack((self._window, frame))
 56            self._window = kept[-len(self._window):]
 57        return {}
 58
 59    def _update(self):
 60        # Called by the Qt timer, on the GUI thread: the one place a
 61        # graphics item may be touched.
 62        if self._window is None:
 63            return
 64        import pyqtgraph as pg
 65
 66        with self._lock:
 67            levels = np.sqrt(np.mean(self._window ** 2, axis=0))
 68        if self._bars is None:
 69            ticks = list(enumerate(self._labels))
 70            self._plot_item.getAxis("bottom").setTicks([ticks])
 71            self._bars = pg.BarGraphItem(x=np.arange(len(levels)),
 72                                         height=levels, width=0.6,
 73                                         brush=self._pen.color())
 74            self._plot_item.addItem(self._bars)
 75        else:
 76            self._bars.setOpts(height=levels)
 77        self.repaints += 1
 78
 79
 80if __name__ == "__main__":
 81
 82    app = gp.MainApp()
 83    p = gp.Pipeline()
 84
 85    # Two channels of alpha beside two of noise.
 86    alpha = gp.Generator(sampling_rate=250, channel_count=2,
 87                         signal_frequency=10, signal_amplitude=10.0,
 88                         noise_amplitude=1.0, name="alpha")
 89    noise = gp.Generator(sampling_rate=250, channel_count=2,
 90                         noise_amplitude=3.0, name="noise")
 91    both = gp.Router(input_channels=[gp.Router.ALL, gp.Router.ALL])
 92    bars = LevelBars(limit=10.0, name="levels")
 93
 94    p.connect(alpha, both["in1"])
 95    p.connect(noise, both["in2"])
 96    p.connect(both, bars)
 97    app.add_widget(bars)
 98
 99    p.start()
100    app.run()
101    p.stop()
102    p.close()