Reference
Widgets
Widget classes you construct once and render with .ui(...) from inside @app.ui. See the Widgets concept page for the contract and the widget gallery for a visual index of all of them on one page.
Signal viewers
SignalViewer
SignalViewer(
stream_name: str,
*,
size: tuple[float, float] = (-1, -1),
n_pixels: int | None = None,
channel_height: float = 0.0,
show_diagnostics: bool = False,
show_connect: bool = True,
stream_type: str | None = None,
selectable: bool = False,
exclude: Iterable[str] = (),
scale_mode: str = 'auto',
y_range: tuple[float, float] = (-1.0, 1.0),
show_markers: bool = False,
window_s: float = 5.0,
initial_channels: Iterable[int] | None = None,
widget_id: str | None = None,
title: str | None = None,
show_controls: bool = True,
show_title: bool = True,
channel_scope: Iterable[int] | None = None,
) -> None
Real-time multi-channel signal viewer.
Construct once with the stable config, then call [ui][] with the
live ctx each frame. Includes decimation, pause, auto/manual Y
scale, visual-only display filters, channel toggles, stats, stream
retargeting, and label markers.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
stream_name | str |
The stable widget ID / stream to view. When | |
widget_id | str | None |
Explicit state / ImGui id scope. Defaults to | None |
exclude | Iterable[str] |
Stream names omitted from the selectable viewer, such as target feedback. | () |
channel_scope | Iterable[int] | None |
The columns this viewer may ever show — a hard restriction, unlike
| None |
title | str | None |
Panel header text. Defaults to | None |
show_connect | bool |
Offer a Connect button in the empty state while the stream is detached.
Turn it off in an app where another widget owns connecting — a
Left on by default: an app that is just | True |
stream_type | str | None |
The LSL type ( | None |
show_controls | bool |
Whether the panel's chrome — toolbar, popups and footer —
starts expanded (default | True |
show_title | bool |
Whether to draw the header row at all (default | True |
n_pixels | int | None |
Optional hard cap on the points drawn per channel. | None |
scale_mode | str |
| 'auto' |
window_s | float |
The initial display window in seconds — the user can still drag
the slider afterwards. Defaults to 5 s. The stream's | 5.0 |
initial_channels | Iterable[int] | None |
Which channels open enabled, e.g. | None |
Examples
>>> from myogestic.widgets import SignalViewer>>> viewer = SignalViewer("emg", selectable=True)>>> viewer.ui(ctx)ui
ui(ctx: Context) -> None
Render the viewer. Call once per frame inside @app.ui.

RawSignalViewer
RawSignalViewer(
stream_name: str,
*,
size: tuple[float, float] = (-1, 300),
channel_height: float = 0.0,
show_connect: bool = True,
stream_type: str | None = None,
widget_id: str | None = None,
show_title: bool = True,
) -> None
Raw signal viewer with window and channel selection.
Construct once and call [ui][] each frame. The header names the stream;
the mono footer reports sample rate, selected channels, raw points and FPS.
Disconnected and empty states explain the next step in the plot's space.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
stream_name | str |
Stream to draw, as registered with | |
size | tuple[float, float] |
Plot size in UI-scaled pixels, by default | (-1, 300) |
show_connect | bool |
Offer a Connect button while detached. Turn it off when a StreamPanel or DevicePicker owns connecting, to avoid duplicate Connect controls. | True |
stream_type | str | None |
LSL type of the other streams the empty state offers, as in
| None |
channel_height | float |
Trace spacing in signal units. | 0.0 |
widget_id | str | None |
State and ImGui identity, defaulting to | None |
show_title | bool |
Show the panel title, by default | True |
Examples
>>> from myogestic.widgets import RawSignalViewer>>> viewer = RawSignalViewer("emg", widget_id="raw:left")>>> viewer.ui(ctx)ui
ui(ctx: Context) -> None
Render the raw viewer. Call once per frame inside @app.ui.
Simulator controls
SimulatorControls
SimulatorControls(
presets: list[tuple[str, float]],
*,
outlet: StreamOutlet | None = None,
widget_id: str = 'simulator',
) -> None
Steer synthetic EMG independently of the active workflow step.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
presets | list[tuple[str, float]] |
Label and control-value pairs, such as | |
outlet | StreamOutlet | None |
Control-stream outlet. If omitted, create | None |
widget_id | str |
Stable ImGui identity; use a distinct ID for each card in the same window. | 'simulator' |
Notes
Manual controls are disabled while recording. Call set from the recording
gesture callback to keep the generator and selected chip in sync.
value
value: float
Current control value; any matching preset chip is selected.
set
set(value: float) -> None
Publish a value and select any matching preset, including during recording.
ui
ui(ctx: Context) -> None
Draw one compact card; the recording gesture owns the value during a take.

Place SimulatorControls([("Rest", 0.0), ("Fist", 1.0)]) in a compact Grid row
under the signal and call simulator.ui(ctx) on every step. Preset chips publish
the selected class value to the generator. The default control outlet is created
on the first ui or set call; pass outlet= to reuse an existing stream.
Call simulator.set(value) from the recording gesture callback to keep the card
and signal in sync. During recording the manual controls are disabled, with a
visible explanation that the simulator follows the recorded gesture.
Device selection
DevicePicker
DevicePicker(
stream: str,
*,
devices: Sequence[DeviceSpec] = DEFAULT_DEVICES,
show_header: bool = True,
selectable: bool = False,
on_add: Callable[[str], object] | None = None,
on_remove: Callable[[str], object] | None = None,
exclude: Iterable[str] = (),
widget_id: str | None = None,
) -> None
Pick a device, configure it, and connect the stream to it.
Use for a named stream in place of StreamPanel. The header dot shows
connection state. Connect applies device settings and attaches hardware;
changes stay pending until it is pressed. Nothing connects automatically,
so a plot cannot switch devices under an active recording.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
stream | str |
Name of the stream to attach to, as registered with | |
devices | Sequence[DeviceSpec] |
What the dropdown offers. Defaults to [ | DEFAULT_DEVICES |
widget_id | str | None |
ImGui id scope and state key. Defaults to the stream name. Give each
instance its own value. ImGui combines labels with the enclosing scope
for control identity. A | None |
selectable | bool |
Show sorted stream chips from | False |
on_add | Callable[[str], object] | None |
Optional callback receiving a cleaned stream name. With | None |
on_remove | Callable[[str], object] | None |
Optional callback receiving the selected stream's name; pass
| None |
exclude | Iterable[str] |
Stream names to exclude. Use for sources owned by another widget, such
as a | () |
show_header | bool |
Render the standard | True |
Examples
>>> from myogestic.widgets import DevicePicker, OTB_DEVICES>>> picker = DevicePicker("emg", devices=OTB_DEVICES)>>> picker.ui(ctx)ui
ui(ctx: Context) -> None
Render the picker. Call once per frame.
Wraps all controls in the widget_id ImGui scope. ImGui combines
labels with that scope for identity; a Grid cell is one child window.
Distinct scopes keep panels in one cell from sharing controls. A scope
around the whole body avoids relying on a prefix at every label site.
Describing a device
DEFAULT_DEVICES covers the shipped amplifiers. Build a DeviceSpec only for hardware the picker does not already list.
DeviceSpec
DeviceSpec(
label: str,
factory: Callable[..., Any],
options: Sequence[DeviceOption] = tuple(),
scan: bool = False,
live: Sequence[DeviceParam] = tuple(),
hint: str = '',
steps: Sequence[str] = tuple(),
) -> None
One selectable entry in a [DevicePicker][] dropdown.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
label | str |
Shown in the dropdown, e.g. | |
factory | Callable[..., Any] |
Source class or | |
options | Sequence[DeviceOption] |
The [ | tuple() |
scan | bool |
| False |
live | Sequence[DeviceParam] |
[ | tuple() |
hint | str |
One line on what this device is, or how it connects. Shown behind an ⓘ button beside the dropdown to keep first-time setup text off the panel. The button is hidden if both hint and steps are empty. | '' |
steps | Sequence[str] |
The setup procedure, one instruction per entry, rendered as a numbered list under the hint. Write physical actions in order, such as holding a button, joining a network and pressing Connect, so the operator does not have to infer their sequence from a paragraph. | tuple() |
Examples
>>> from functools import partial>>> from myogestic.sources.otb import MuoviSource>>> DeviceSpec(... "Muovi+ — 64 ch",... partial(MuoviSource, plus=True),... (DeviceOption("emg", "Signal", {"EMG": True, "EEG": False}),),... hint="Join the probe's Wi-Fi network, then Connect.",... ).label'Muovi+ — 64 ch'DeviceOption
DeviceOption(kwarg: str, label: str, choices: Mapping[str, Any]) -> None
One labelled row of choices in a [DeviceSpec][]'s configuration.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
kwarg | str |
Constructor keyword the chosen value is passed as. | |
label | str |
Row label with the operator's unit, such as | |
choices | Mapping[str, Any] |
|
DeviceParam
DeviceParam(
attr: str,
label: str,
lo: float,
hi: float,
fmt: str = '%.2f',
) -> None
One slider that tunes a connected source while it streams.
A [DeviceOption][] sets a constructor argument on Connect.
A DeviceParam writes a live source attribute for the next chunk,
preserving the connection, plot history and recording geometry.
The source must therefore expose that attribute publicly and read it fresh each chunk. Assigning a float is atomic under the GIL, so no lock is needed between the UI thread and the acquire thread.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
attr | str |
Public attribute on the source to read and write. | |
label | str |
Row label, spelled out in the unit the operator thinks in. | |
lo | float |
Slider range. | |
hi | float |
Slider range. | |
fmt | str |
| '%.2f' |
Examples
>>> DeviceParam("noise", "Noise", 0.0, 1.0).attr'noise'DEFAULT_DEVICES
DEFAULT_DEVICES: tuple[DeviceSpec, ...] = (*OTB_DEVICES, LSL_DEVICE, SYNTHETIC_DEVICE)
OTB_DEVICES
OTB_DEVICES: tuple[DeviceSpec, ...] = (DeviceSpec('Muovi — 32 ch', MuoviSource, (_MUOVI_SIGNAL, _MUOVI_AUX), hint=_MUOVI_HINT, steps=_MUOVI_STEPS), DeviceSpec('Muovi+ — 64 ch', partial(MuoviSource, plus=True), (_MUOVI_SIGNAL, _MUOVI_AUX), hint=_MUOVI_HINT, steps=_MUOVI_STEPS), DeviceSpec('Sessantaquattro / +', SessantaquattroSource, (DeviceOption('nch_mode', 'Channels', {'8': 0, '16': 1, '32': 2, '64': 3}), DeviceOption('fs_mode', 'Sample rate', {'500': 0, '1000': 1, '2000': 2, '4000': 3}), DeviceOption('mode', 'Detection', _DETECTION), _SESSANTAQUATTRO_AUX), hint=_SESSANTAQUATTRO_HINT, steps=_SESSANTAQUATTRO_STEPS), DeviceSpec('Quattrocento', QuattrocentoSource, (DeviceOption('nch_mode', 'Channels', {'96': 0, '192': 1, '288': 2, '384': 3}), DeviceOption('fs_mode', 'Sample rate', {'512': 0, '2048': 1, '5120': 2, '10240': 3}), DeviceOption('detection', 'Detection', _DETECTION), _QUATTROCENTO_AUX), hint=_QUATTROCENTO_HINT, steps=_QUATTROCENTO_STEPS))
LSL_DEVICE
LSL_DEVICE = DeviceSpec('LSL stream', lambda: LSLSource(''), scan=True, hint='Any Lab Streaming Layer outlet advertised on this network.', steps=('Press Scan.', 'Pick the outlet from the list.', 'Press Connect.'))
SYNTHETIC_DEVICE
SYNTHETIC_DEVICE = DeviceSpec('Synthetic (no hardware)', SyntheticSource, (DeviceOption('n_channels', 'Channels', {'8': 8, '16': 16, '32': 32, '64': 64}), DeviceOption('fs', 'Sample rate', {'512': 512.0, '1000': 1000.0, '2048': 2048.0})), live=(DeviceParam('activation', 'Activation', 0.0, 1.0), DeviceParam('direction', 'Direction', -1.0, 1.0), DeviceParam('noise', 'Noise', 0.0, 1.0), DeviceParam('hum', 'Hum', 0.0, 1.0), DeviceParam('hum_hz', 'Hum (Hz)', 50.0, 60.0, '%.0f Hz')), hint='In-process sine waves and mains hum. A test signal, not data.', steps=('Pick a channel count and sample rate.', 'Press Connect — nothing has to be plugged in.', 'Drag Activation to contract the imaginary muscle; you are the subject.', 'Direction steers that effort between the first and second half of the channels, so a two-way gesture reads differently each way.', 'Noise, Hum and Hum (Hz) retune the signal live, without a reconnect.'))
Recording and sessions
ParticipantPanel
ParticipantPanel(
*,
key_file: str | Path = '~/myogestic/participant-key.csv',
widget_id: str = 'participant',
sessions_dir: str | Path = 'data',
on_drive: Callable[[str, Path], None] | None = None,
) -> None
Choose a pseudonymised ID with an optional local name lookup.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
key_file | str or Path |
Local CSV mapping IDs to names, by default
| '~/myogestic/participant-key.csv' |
widget_id | str |
Stable input-state and popup identity, by default | 'participant' |
sessions_dir | str or Path |
Data root, by default | 'data' |
on_drive | callable or None |
Called as | None |
Notes
Names stay in widget memory and the key file. Only the slugged ID is
assigned to ctx.participant. Selection is disabled while the app is
recording, training or predicting; Start session selects the participant
without starting a recording.
open
open() -> None
Request the participant modal on the next call to ui(ctx).
The request is discarded if the context is not idle on that frame. It is safe to call this method outside an ImGui frame.
ui
ui(ctx: Context) -> None
Draw the participant chip and its selection modal.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
ctx | Context |
Live app context. Only its pseudonymised |
The header chip opens Recorded when readable takes exist under sessions_dir
(default "data"), otherwise New participant. Recorded participants are listed
by latest recording, with gesture dots (or cursor), take counts, duration and saved
model availability. Search uses IDs; Show names also enables local name search.
Names start masked and are hidden again when the dialog closes. Continue with ID
selects an existing participant without changing the key file.
New participant offers the next free ID, optional first and family names, and a preview of the labelled recording and model paths. Returning names match without regard to case or accents. Start session selects the ID; recording still starts through the recording controls. The chip is disabled during recording, training and prediction, and an open dialog closes when the app becomes busy.
Pass on_drive=callback to offer Drive with saved model for participants with a
saved .joblib model. The callback receives (participant_id, model_path) after
ctx.participant has been set; model_path is a Path to the most recently modified
model in that participant’s models/ folder. Takes are scanned once each time the dialog
opens, using the same pending-save exclusions as SessionManager.
Names stay in widget memory and the local ~/myogestic/participant-key.csv key file;
only the safe ID reaches ctx.participant and saved data. Keep a custom key_file
outside the sessions directory. See the standalone
participant_panel.py example.
RecordingControls
RecordingControls(
class_names: list[str] | None = None,
*,
on_record: Callable[[], None],
on_stop: Callable[[], None],
on_gesture: Callable[[int], None] | None = None,
show_header: bool = True,
take_lengths: Sequence[float] = (),
warmups: Sequence[float] = (0.0,),
timed: bool = False,
take_length: float | None = None,
warmup: float | None = None,
) -> None
Record labelled takes, with an optional warm-up and fixed duration.
Construct once, then call ui(ctx) every frame. take is an immutable
snapshot for an app's countdown or signal overlay. For unlabelled capture
with a naming dialog, use RecordButton.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
class_names | list[str] | None |
Gesture tiles. The first is selected when idle without a valid label.
Idle clicks choose the next take's label; start/stop mode also permits
label changes during capture. Timed takes lock it.
Names are copied to | None |
on_record | Callable[[], None] |
Begin capture, normally | |
on_stop | Callable[[], None] |
Stop and save capture, normally | |
on_gesture | Callable[[int], None] | None |
Optional side effect when a gesture tile is selected. | None |
show_header | bool |
Render the standard panel header. | True |
take_lengths | Sequence[float] |
Positive durations in seconds. Empty keeps start/stop only. | () |
warmups | Sequence[float] |
Nonnegative countdown durations in seconds; zero means Off. Must contain at least one value. | (0.0,) |
timed | bool |
Open in Timed mode instead of Start / stop. Defaults to | False |
take_length | float or None |
Initially selected entry of | None |
warmup | float or None |
Initially selected entry of | None |
take
take: TakeStatus
Read the take as of the most recent ui call, without side effects.
ui
ui(ctx: Context, *, visible: bool = True) -> None
Advance once per frame, and optionally render the controls.
Call with visible=False while another workflow step is open so a
timed take still stops on its first frame at or after the deadline.

RecordButton
RecordButton(
*,
on_record: Callable[[], None],
on_stop: Callable[[], None],
on_discard: Callable[[], None] | None = None,
show_header: bool = True,
widget_id: str | None = None,
) -> None
One button that records, and asks what to call the take when it stops.
The plain-recording counterpart to RecordingControls: no per-class label
buttons, no gesture protocol — press Record, press Stop, name what you just
captured. For an app whose job is collect some data, rather than one
building a labelled training set.
Capture ends the instant Stop is pressed — the streams are detached before
the dialog opens — so the seconds spent typing a name are never recorded.
The name is written to the session's meta.json and into the archive
filename, so it shows up in SessionManager and is findable on disk.
Shows elapsed time during capture and previews the filename while naming. Record is disabled when a required participant ID is missing.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
on_record | Callable[[], None] |
Called when Record is clicked (idle → recording). Pass
| |
on_stop | Callable[[], None] |
Called when the dialog is saved. Pass | |
on_discard | Callable[[], None] | None |
Called when the dialog is discarded. Pass | None |
widget_id | str | None |
ImGui id scope and state key. Defaults to | None |
show_header | bool |
Render the standard | True |
Examples
>>> from myogestic.widgets import RecordButton>>> recorder = RecordButton(... on_record=app.start_recording,... on_stop=app.stop_recording,... on_discard=app.discard_recording,... )>>> recorder.ui(ctx)ui
ui(ctx: Context) -> None
Render the recorder. Call once per frame inside @app.ui.
A status dot in the header accompanies the capture or naming row. The archive icon distinguishes the title from the recording state dot.
Drawn inside an ImGui id scope named by widget_id, so two recorders
in one Grid cell do not share a button and a naming dialog.
StreamManager
StreamManager(
*,
on_add: Callable[[str], object],
on_remove: Callable[[str], object],
show_header: bool = True,
widget_id: str | None = None,
) -> None
Stream chips with status dots, selection, and inline add or remove actions.
For an app whose sources are not known when it is written — a second
amplifier, a force transducer on its own device — rather than one that
declares every stream up front with app.streams(...). Pair it with a
DevicePicker per stream to choose what each one is attached to.
Select a chip to reveal its remove action; the last stream is kept. The trailing plus opens a name field, Add, and cancel. Chips are dimmed while recording and a caption explains the lock: a session sizes one Zarr array per stream when recording starts, so a stream appearing afterwards has nowhere to write, and one vanishing mid-take is never finalised.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
on_add | Callable[[str], object] |
Called with a cleaned stream name when Add is pressed. Build the
| |
on_remove | Callable[[str], object] |
Called with the stream's name when its Remove is pressed. Pass
| |
show_header | bool |
Render the standard | True |
widget_id | str | None |
ImGui id scope. Defaults to | None |
Examples
>>> from myogestic.widgets import StreamManager>>> manager = StreamManager(... on_add=lambda name: app.add_stream(Stream(name, source=..., window_ms=200)),... on_remove=app.remove_stream,... )>>> manager.ui(ctx)ui
ui(ctx: Context) -> None
Render the manager. Call once per frame.
SessionManager
SessionManager(
base_path: str = 'data',
*,
title: str = 'Sessions',
class_names: list[str] | None = None,
) -> None
One-line takes grouped by day, with gesture filters and a selection summary.
Construct once with the base path / title / class names, then call
[ui][] each frame. The widget has two training filters: selected
session files and included class indices. Compact, clickable take rows are
about 26 logical pixels tall. Only the newest day starts open;
the list scrolls while its header, summary and gesture chips stay visible.
Files loaded outside the scanned folder appear under Loaded. Read
selection() for selected-take counts and included gesture seconds.
Assign the returned value to
pipeline.training_data to make it visible to @pipeline.train::
sessions = SessionManager("data", class_names=CLASSES)
@app.uidef ui(ctx): pipeline.training_data = sessions.ui()Parameters
| Name | Type | Description | Default |
|---|---|---|---|
base_path | str |
Data root, default | 'data' |
title | str |
Panel header text. Also part of the widget's ImGui id scope, so two managers over the same folder need different titles to keep separate selections. | 'Sessions' |
class_names | list[str] | None |
Human-readable names for the label class indices, used to render the
gesture chips (with totals across all listed takes). | None |
Examples
>>> from myogestic.widgets import SessionManager>>> manager = SessionManager("data", class_names=["Rest", "Fist"])>>> training_data = manager.ui()select_all
select_all(participant: str) -> None
Scan and tick every saved training take of a participant without drawing a frame.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
participant | str |
Nonempty participant ID, reduced to the same safe slug used by
recordings. Replaces the previous selection and clears class
exclusions and pending file dialogs. Takes still being saved are
excluded, as are drive runs identified by |
Raises
| Name | Type | Description | Default |
|---|---|---|---|
| ValueError |
If the ID has no usable characters. Pass a nonempty participant ID. |
ui
ui(participant: str | None = None) -> TrainingData
Render the picker and return the current training selection.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
participant | str | None |
Participant ID whose subfolder to scan, using the same safe slug
as recordings. A nonempty ID lists its takes automatically, unticked
except newly recorded takes. Changing it clears the training selection
and class filters. | None |
Returns
| Name | Type | Description | Default |
|---|---|---|---|
| TrainingData |
Selected session paths and active classes for training. |
selection
selection() -> SelectionSummary
Return selected-take counts and seconds for included gestures.
Returns
| Name | Type | Description | Default |
|---|---|---|---|
| SelectionSummary |
An independent snapshot of the current selection. Follows folders into their packed archives and drops missing takes without rescanning for new takes, changing filters, or requiring an ImGui context. |

Force tracking
See Track a force target for the whole loop, including how the transducer reaches the stream and why calibration takes two captures.
TrackingTask
TrackingTask(
stream: str = '',
*,
channel: int = 0,
trapezoid: Trapezoid | None = None,
target: TargetSource | None = None,
tail_ms: float = 100.0,
mvc_capture_s: float = 3.0,
plot_height: float = 220.0,
look_ahead_s: float = 4.0,
widget_id: str | None = None,
) -> None
Force-tracking task: follow a trapezoidal target on an auxiliary channel.
Pick Stream and Channel, then capture a resting Calibration.zero and a maximum
Calibration.mvc in the calibration row. Its warning names the next step and its
countdown stays beside the capture buttons. The target row previews one repetition;
its settings icon opens the five durations, Level, Reps and Look ahead. Press Start.
The target and the subject's normalised force are then drawn on one pair of
axes — x is task time in seconds, y is percent of MVC — because a following error is
only readable when both traces share a range. Target and Force chips toggle trace
visibility. A mono summary below the plot states the total block duration.
While running, setup is dimmed and locked. The status row shows the repetition, phase, current force and signed error (force minus target), with Stop beside it. Captions sit above controls in two columns, stacking in narrow cells; long row readouts ellipsize and expose their full text on hover.
The live force is the mean of the last tail_ms of the chosen channel, not one
sample: a single raw sample from a load cell is noise with a force in it.
Nothing is stored per stream. The stream name and the channel index are what the widget holds, and the index is clamped only where it is used — so an amplifier that reconnects at a different channel count does not silently rewrite the operator's choice.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
stream | str |
Stream name to start on, as registered with | '' |
channel | int |
Channel index within that stream carrying the force signal. | 0 |
trapezoid | Trapezoid | None |
Initial target shape. Every segment is editable in the settings popover; this is only
where it starts. Defaults to | None |
target | TargetSource | None |
Optional | None |
tail_ms | float |
How much of the window the live reading averages over. Long enough to be steady, short enough that the trace still follows the subject. | 100.0 |
mvc_capture_s | float |
How long the MVC action watches for a peak after it is pressed. | 3.0 |
widget_id | str | None |
ImGui id scope and state key. Defaults to the stream name. Give each
instance its own when an app renders more than one — two transducers in
one study is the obvious case: ImGui derives a control's identity from
its label plus the enclosing scope, and a | None |
look_ahead_s | float |
How far past "now" the target is drawn, in seconds. The subject sees the trajectory only as far as it is about to be: a block whose ending is visible from the start is one they can plan around instead of track. | 4.0 |
plot_height | float |
Plot height in pixels at UI scale 1.0; follows the current UI scale. | 220.0 |
Examples
>>> from myogestic.tracking import Trapezoid>>> from myogestic.widgets import TrackingTask>>> task = TrackingTask("emg", channel=64, trapezoid=Trapezoid(level_pct=20.0))>>> task.ui(ctx)ui
ui(ctx: Context) -> None
Render one card, with setup rows, target settings and a shared-range plot.
Call once per frame. Every control and popup is scoped by widget_id;
source selection, calibration, target settings and legend choices belong
to this instance even when another task shows the same stream.
Task trajectories
What a subject is asked to follow. myogestic.tracking is plain data — no ImGui, nothing that talks to a device — so the same trajectory can be evaluated in a test, in an offline script and by whatever draws it, with no second implementation to drift. TrackingTask forwards every edit to the TargetSource it was handed, so what is drawn and what is recorded cannot diverge.
Trajectory is the structural protocol these shapes satisfy by having its three members, not by inheriting anything. They differ in unit and in what they are for: Trapezoid is percent of MVC for isometric force tracking; Pursuit is signed [-1, +1] control units for proportional-control training, and it exists because a block cueing only Down / Rest / Up asks for three distinct target values, so what a fit produces between them comes from the estimator rather than from the recording — for the tree ensembles shipped here, nothing at all.
Trajectory
Bases: Protocol
What a trajectory has to offer to be streamed and recorded.
Structural, so Trapezoid, Pursuit and any shape added later satisfy it by
having these three members rather than by inheriting anything. It is deliberately
narrower than either concrete class: TargetSource reads exactly this much, so a
shape is free to differ in everything else — segments, levels, units.
The unit of value_at is the trajectory's own, and is not part of this contract —
percent of MVC for Trapezoid, signed control units for Pursuit. What is part
of it is that phase_at returns a name from the recorded phase table, so a
recording can be sliced by phase whatever shape produced it.
total_duration
total_duration: float
Seconds for the whole block, after which the target is over.
value_at
value_at(t: float) -> float
Target level at task time t seconds, in the trajectory's own unit.
phase_at
phase_at(t: float) -> str
Which segment task time t falls in — a key of PHASE_CODES.
Trapezoid
Trapezoid(
rest_s: float = 3.0,
ramp_up_s: float = 5.0,
hold_s: float = 10.0,
ramp_down_s: float = 5.0,
recover_s: float = 5.0,
level_pct: float = 30.0,
reps: int = 1,
) -> None
A trapezoidal force-tracking target: rest, ramp up, hold, ramp down, recover.
Named for the shape, not the study — a triangular or sinusoidal target is a different shape and gets its own name in this module rather than a flag on this one.
Every segment is independently configurable and may be zero: hold_s=0 is a
legal triangle, rest_s=0 starts the ramp immediately. A zero-length segment is
simply skipped; the trajectory steps straight to the next level.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
rest_s | float |
Baseline seconds before the ramp begins. | 3.0 |
ramp_up_s | float |
Seconds spent rising linearly from baseline to | 5.0 |
hold_s | float |
Seconds at | 10.0 |
ramp_down_s | float |
Seconds spent falling linearly back to baseline. | 5.0 |
recover_s | float |
Baseline seconds after the ramp, before the next repetition. | 5.0 |
level_pct | float |
Plateau height as a percentage of MVC. | 30.0 |
reps | int |
How many times the shape repeats back to back. | 1 |
Examples
>>> from myogestic.tracking import Trapezoid>>> task = Trapezoid(rest_s=1.0, ramp_up_s=2.0, hold_s=4.0, ramp_down_s=2.0,... recover_s=1.0, level_pct=40.0)>>> task.duration10.0>>> task.value_at(2.0), task.phase_at(2.0)(20.0, 'ramp_up')>>> task.value_at(5.0), task.phase_at(5.0)(40.0, 'hold')>>> task.value_at(10.0), task.phase_at(10.0)(0.0, 'done')duration
duration: float
Seconds for one repetition.
total_duration
total_duration: float
Seconds for the whole block — one repetition times reps.
value_at
value_at(t: float) -> float
Target level in percent of MVC at task time t seconds.
Baseline segments are 0.0, ramps are linear, the hold is level_pct.
Before the block starts and once it has finished, the target is 0.0.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
t | float |
Task time in seconds since the block started. |
phase_at
phase_at(t: float) -> str
Which segment task time t falls in.
One of "rest", "ramp_up", "hold", "ramp_down", "recover",
or "done" once the whole block has elapsed.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
t | float |
Task time in seconds since the block started. |
Pursuit
Pursuit(
rest_s: float = 5.0,
hop_s: float = 2.0,
hops: int = 24,
recover_s: float = 5.0,
reps: int = 1,
) -> None
A signed pursuit target: rest, then a smooth aperiodic wander over [-1, +1].
Why this shape and not a trapezoid. A cued block that only ever asks for "down", "rest" and "up" holds three distinct target values, so a regressor trained on it has never seen an intermediate one: nothing in the data says what half a contraction should produce, and what the fit does between the cued levels is whatever its own inductive bias supplies. For the tree ensembles shipped here that is an average of the targets it saw, which cannot be an intermediate level at all; least squares, at the other end, draws the straight line through them and needs nothing more. This trajectory instead spends its whole length at intermediate levels, so the mapping from effort to output is measured rather than assumed, and monotonicity in effort is something the fit is actually held to.
The shape is a chain of hops equal-length segments between waypoints, each
interpolated with a smootherstep (:math:6x^5 - 15x^4 + 10x^3). That gives three
things a proportional decoder needs:
- Dense, even coverage of the level axis. Waypoints come from the golden-ratio orbit, whose defining property is that it spreads a sequence as evenly as any sequence can be spread. The interpolation eases to a standstill at each waypoint, so dwell time follows waypoint density and every level is trained on, not just the ones between the extremes. With the defaults no twentieth of the range takes less than 2% of the wander — 1.7% of the whole block, the difference being the rest and recover segments, which sit at one level and are not part of the sweep.
- Rate largely decoupled from level. Segments are equal in time but not in height, so the same level is crossed slowly on one pass and quickly on another. Under a single sinusoid the target is always slowest at the extremes and fastest at zero, and a decoder can learn that confound instead of the level; here the correlation between level and speed falls from about -0.92 to -0.21. Not to zero, and the residue is at the extremes: ±1 are waypoints and the interpolation eases to a standstill at every waypoint, so full deflection is still only ever reached slowly (mean rate 0.18 units/s beyond |v| > 0.9, against 0.52 below |v| < 0.5).
- Nothing to anticipate. The orbit is irrational, so the path never repeats
within a repetition and the subject has to track rather than recall — yet it is
pure arithmetic on the hop index, so two sessions record the identical trajectory
and a test can assert an exact value.
repsabove 1 repeats the same path deliberately, to make repetitions comparable, and every rep after the first is therefore learnable: raisehopsrather thanrepsto lengthen a block the subject should not be able to anticipate.
The rest segments matter as much as the wander: they are exactly 0.0 and stay
there, which is where a decoder learns its baseline. A target that is always moving
never says where zero is.
Values are continuous everywhere, including across repetitions, and the slope is bounded — a target that steps cannot be followed, and every jump would land in the training set as effort the subject never produced.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
rest_s | float |
Baseline seconds before the wander begins. | 5.0 |
hop_s | float |
Seconds per waypoint-to-waypoint segment. The difficulty knob: halving it doubles every rate without changing the levels visited. | 2.0 |
hops | int |
How many segments one repetition is made of. Fewer than about 16 and the coverage starts to clump. | 24 |
recover_s | float |
Baseline seconds after the wander, before the next repetition. | 5.0 |
reps | int |
How many times the trajectory repeats back to back. Identical each time, so repetitions are directly comparable. | 1 |
Examples
>>> from myogestic.tracking import Pursuit>>> task = Pursuit(rest_s=2.0, hop_s=1.0, hops=4, recover_s=2.0)>>> task.duration8.0>>> task.value_at(1.0), task.phase_at(1.0)(0.0, 'rest')>>> task.value_at(4.0), task.phase_at(4.0)(-1.0, 'ramp_up')>>> round(task.value_at(4.5), 6), task.phase_at(4.5)(0.0, 'ramp_up')>>> task.value_at(8.0), task.phase_at(8.0)(0.0, 'done')duration
duration: float
Seconds for one repetition.
total_duration
total_duration: float
Seconds for the whole block — one repetition times reps.
value_at
value_at(t: float) -> float
Target level in signed control units at task time t seconds.
In [-1, +1]. Rest and recover are exactly 0.0, as are the times before
the block starts and after it has finished.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
t | float |
Task time in seconds since the block started. |
phase_at
phase_at(t: float) -> str
Which segment task time t falls in.
One of "rest", "ramp_up" or "ramp_down" for a segment heading up or
down, "hold" for one whose endpoints are level, "recover", or "done"
once the whole block has elapsed. The same vocabulary Trapezoid uses, so an
analysis script can select the rising windows out of either without caring which
trajectory produced the recording.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
t | float |
Task time in seconds since the block started. |
Calibration
Calibration(zero: float, mvc: float) -> None
Maps a raw force reading onto the percent-of-MVC scale the targets live on.
Two numbers, not one: a load cell reads some non-zero value with nobody touching it,
so dividing by mvc alone leaves that resting offset in the result and puts every
target at the wrong force. zero is subtracted first, from both the sample and the
maximum, so 30% really is 30% of the subject's voluntary range.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
zero | float |
The resting reading, in the force channel's own signal units. | |
mvc | float |
The maximum voluntary contraction reading, in the same units. |
Examples
>>> from myogestic.tracking import Calibration>>> cal = Calibration(zero=1.0, mvc=3.0)>>> cal.normalise(1.0), cal.normalise(2.0), cal.normalise(3.0)(0.0, 50.0, 100.0)normalise
normalise(x: float) -> float
Convert a raw reading to percent of MVC.
Returns 0.0 when mvc equals zero — an uncalibrated subject reads as no
effort rather than blowing up mid-trial.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
x | float |
A sample from the force channel, in the channel's own signal units. |
Proportional-control game
PongTask
PongTask(
*,
ball_speed: float = 0.55,
paddle_size: float = 0.36,
opponent_paddle_size: float | None = None,
control: str = 'velocity',
opponent: float | None = None,
court_height: float = 260.0,
widget_id: str = 'pong',
win_score: int | None = 11,
opponent_name: str | None = None,
on_harder: Callable[[], None] | None = None,
) -> None
Pong driven by one signed command — a proportional-control training game.
Call ui every frame with the command, in [-1, +1]. What the command means is
control: by default it sets the paddle's velocity, so +1 drives the paddle
up at full speed and 0 holds it where it is; with control="position" the
command is the paddle's height instead, +1 at the top. Nothing moves until
Serve is pressed, so a layout pass, a freshly opened tab and a subject still
finding their range all draw a still field.
Serve lives inside the court, or press Space while the app has focus and no
text field is active. The signed command meter shows the velocity dead band.
First to win_score ends the game; game_over stays true until Play again.
The paddle follows the command even between rallies, which is how a subject finds
the range of their own contraction before the ball is in play. A command that is
not finite — a diverged model reads as NaN — leaves the paddle where it was
rather than throwing it to an end of the court.
Pass ui a target and the reference a subject tracks while a training block
records is drawn for that command: a line across the court at the level, and a hollow
bracket where a paddle obeying it would sit. The line is what you follow — the error
is the gap between it and your bar. Generating that trajectory and recording against
it belong to the app — see myogestic.tracking.Pursuit — and the widget only draws
the number it is handed.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
ball_speed | float |
Ball speed in court widths per second. The court is 1.0 wide, so 0.55 crosses it in a little under two seconds. | 0.55 |
paddle_size | float |
Subject's paddle height in court | 0.36 |
opponent_paddle_size | float | None |
Opponent's paddle height in the same units and with the same bounds as
| None |
control | str |
What the command does to the paddle. Neither mode is the right one in general.
| 'velocity' |
opponent | float | None |
Speed factor of a paddle playing back from the far wall, or | None |
court_height | float |
Court height in pixels at UI scale 1.0, or | 260.0 |
widget_id | str |
ImGui id scope. Give each instance its own when an app renders more than one:
ImGui derives a control's identity from its label plus the enclosing scope, and
a | 'pong' |
win_score | int | None |
First to this many points wins. Pass | 11 |
opponent_name | str | None |
Optional name beside CPU, such as | None |
on_harder | Callable[[], None] | None |
Optional callback for the game-over Harder action. The app owns difficulty. | None |
Examples
>>> from myogestic.widgets import PongTask>>> pong = PongTask(paddle_size=0.5)>>> pong.ui(0.0)game_over
game_over: bool
Whether either side has reached the winning score.
ui
ui(
command: float,
target: float | None = None,
effort: float | None = None,
) -> None
Render the game. Call once per frame.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
command | float |
The control signal, in | |
target | float | None |
The command the subject is being asked to produce, in the same
| None |
effort | float | None |
How hard the subject is contracting now, on | None |
The command is signed: +1 is the top of the court, -1 the bottom, and -1 is a real value rather than the absence of +1. The widget is only the game — it reads no stream, no session and no model, so whatever produces the float (a decoder, a force channel, a slider) stays the app’s business. examples/start_here/pong.py drives it from a directional_decoder; examples/panels/pong.py drives it from a slider.
control decides what the command does, and neither mode is right in general. "velocity", the default, integrates it, which turns even a three-output decoder into a complete controller — up / hold / down reach every height in the court — at the cost of accumulating the decoder’s resting bias. The dead zone it carries slows that and does not stop it — a constant command inside the band integrates to nothing, but bias plus ordinary noise rectifies to something positive and walks the paddle onto a wall in tens of seconds while the subject holds still, so expect them to be correcting and press Serve to recentre. "position" maps the command onto the paddle’s travel, the full range across the full travel: it cannot drift, and where the paddle sits is what the model just emitted scaled to the court, which makes it the honest mode to debug against and the better one once the command is genuinely continuous.
ui(command, target=…) draws a ghost paddle for that command — the reference a subject tracks while a training block records, typically Pursuit.value_at. target is in the same signed [-1, +1] as command, not a court coordinate: it is mapped onto the paddle’s travel by the same line control="position" uses, so a subject sitting on the ghost has produced exactly the number the session recorded. The ghost does not play the ball and is not a second player. Generating the trajectory and recording against it belong to the app, not the widget.
Without opponent the far wall simply returns the ball, and the score is hits against misses. Pass opponent and a second paddle plays it back, with each side’s points drawn on its own half — the same rally, now with something to win. opponent sets that paddle’s top tracking speed as a multiple of ball_speed, so slowing the ball also slows the CPU at every difficulty.
paddle_size sets the player’s paddle height in court units: the court is 2.0 tall, so the default 0.36 covers 18% and 0.6 covers 30%. The keyword-only opponent_paddle_size=None uses the same height for both paddles, preserving existing games. Set it separately to give the player more reach without enlarging the CPU: PongTask(ball_speed=0.35, paddle_size=0.6, opponent_paddle_size=0.36, opponent=0.6). Both sizes are clamped to [0.02, 2.0]. The CPU’s drawing, tracking bounds and returns use its own height; the player’s travel and pursuit ghost use the player’s height.
The start-here example exposes BALL_SPEED, PADDLE_SIZE and OPPONENT_PADDLE_SIZE near its other tunables. Its ball crosses the court in about 2.9 s at 0.35 court widths per second, compared with about 1.8 s at the widget’s default 0.55.
win_score=11 stops the ball on the winning point and sets the read-only game_over property. Play again resets the score, paddles, longest rally and clock; win_score=None keeps the game endless. opponent_name="Fair" labels the CPU, and an optional on_harder callback adds Harder to the game-over overlay so the app can rebuild at its next difficulty. These constructor arguments are keyword-only.
Serve is inside the court. Space also serves when the app window has focus and no text field is active. The CMD meter shows the signed command and shades the velocity dead band; when target is supplied, EFFORT instead shows the unsigned effort magnitude with a tick at abs(target). The ghost and effort gauge do not infer the contraction’s direction.
Process management
ProcessLauncher
ProcessLauncher(
processes: list[Process],
*,
widget_id: str = '',
log_height: float = 0.0,
) -> None
Select a process, launch it, and read its running or failed state.
Shows PID and elapsed time while running, with output in a popout. Failed processes can be relaunched.
Construct once with the process list, then call [ui][] each frame.
Multiple launchers can coexist — each gets unique ImGui IDs via
widget_id (unique per instance when empty). The
live subprocess registry is app-global, so processes are still killed on
exit (atexit + App.run cleanup) regardless of instance lifetime.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
processes | list[Process] |
The launchable processes, as | |
widget_id | str |
ImGui id scope for this launcher. A unique instance ID is generated when empty; an explicit ID can preserve state across reconstruction. | '' |
log_height | float |
Height in pixels of an optional inline log. | 0.0 |
Examples
>>> import sys>>> from myogestic.widgets import ProcessLauncher>>> launcher = ProcessLauncher([("Worker", [sys.executable, "worker.py"])])>>> launcher.ui()ui
ui() -> None
Render the launcher. Call once per frame inside @app.ui.
launch
launch(name: str) -> None
Start a configured process, unless it is already running.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
name | str |
The process name from the configured |
Raises
| Name | Type | Description | Default |
|---|---|---|---|
| ValueError |
If |
stop
stop(name: str) -> None
Stop a process started by this launcher.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
name | str |
The process name from the configured |
Raises
| Name | Type | Description | Default |
|---|---|---|---|
| ValueError |
If |
running
running(name: str) -> bool
Whether the process called name is alive because this panel started it.
For an app that has something to do once a target is up — bind a control map to a target it just launched, enable a control that needs it — rather than asking the operator to press a second button confirming the press they already made.
Says nothing about a process started outside the app: the registry only holds what
this panel launched, so a target that was already running reads False. Treat it
as "I started this", not as "this is reachable"; the target's own handshake is what
answers reachability.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
name | str |
The process name, as given in the |

TargetPanel
TargetPanel(
targets: Sequence[_Launchable],
*,
connectors: Mapping[str, ControlLinkConnector] | None = None,
title: str = 'Targets',
icon: str | None = fa.ICON_FA_PLUG,
widget_id: str = '',
) -> None
Launch the processes an app drives, or connect to ones already running.
One card, one row per target: a dot and tint for its state, its name, the state in
words with PID and elapsed time beside it, the one action that moves it on, and its
output. A target with a connector is connected first and launched only if none
answers, so a target someone already started is never started twice; one without
is launched and stopped. Stop appears only for a process this card started. Processes
are killed on exit, like ProcessLauncher's.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
targets | Sequence[_Launchable] |
Anything shaped like | |
connectors | Mapping[str, ControlLinkConnector] | None |
A | None |
title | str |
The card's | 'Targets' |
icon | str |
The card's | 'Targets' |
widget_id | str |
Scope for this card's processes and popouts. Defaults to | '' |
Examples
>>> from myogestic.vhi import virtual_hand>>> from myogestic.widgets import TargetPanel>>> hands = TargetPanel([virtual_hand()], title="Hands")>>> hands.ui()start
start(name: str) -> None
Do what the row's forward action does: connect, or launch.
Raises
| Name | Type | Description | Default |
|---|---|---|---|
| ValueError |
If no target is called |
stop
stop(name: str) -> None
Stop the process this card started for name, and drop its controls.
running
running(name: str) -> bool
Whether name is alive because this card started it.
ui
ui(*, details: Mapping[str, str] | None = None) -> None
Render the card. Call once per frame inside @app.ui.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
details | Mapping[str, str] | None |
Per target name, values only the app knows, shown after the row's own, such as the serial port a hand also drives. | None |

Plotting
Scatter2D
Scatter2D(
label: str,
*,
size: tuple[float, float] = (-1, 300),
marker_size: float = 3.0,
widget_id: str | None = None,
show_title: bool = True,
) -> None
2D scatter plot with a panel header and PALETTE-dot class legend chips.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
label | str |
Plot label shown above the scatter. | |
size | tuple[float, float] |
Plot size in UI-scaled pixels, by default | (-1, 300) |
marker_size | float |
Marker radius in UI-scaled pixels, by default | 3.0 |
widget_id | str | None |
Explicit ImGui id scope, defaulting to | None |
show_title | bool |
Show the panel header, by default | True |
Examples
>>> import numpy as np>>> from myogestic.widgets import Scatter2D>>> scatter = Scatter2D("Embedding")>>> scatter.ui(np.array([[0.0, 0.0], [1.0, 1.0]]))ui
ui(
points: np.ndarray,
labels: np.ndarray | None = None,
class_names: list[str] | None = None,
) -> None
Render the 2D scatter for the given frame.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
points | np.ndarray |
Point coordinates of shape | |
labels | np.ndarray | None |
Per-point integer class labels for coloring. If omitted, all points share a single series. | None |
class_names | list[str] | None |
Legend names indexed by class label. Falls back to the label value. | None |
Scatter3D
Scatter3D(
label: str,
*,
size: tuple[float, float] = (-1, 400),
axis_names: tuple[str, str, str] = ('X', 'Y', 'Z'),
widget_id: str | None = None,
show_title: bool = True,
) -> None
Theme-styled 3D scatter with an orbit camera and PALETTE-dot legend chips.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
label | str |
Plot label shown above the scatter. | |
size | tuple[float, float] |
Plot size in UI-scaled pixels, by default | (-1, 400) |
axis_names | tuple[str, str, str] |
Names for the X, Y and Z axes, by default | ('X', 'Y', 'Z') |
widget_id | str | None |
Explicit ImGui id scope, defaulting to | None |
show_title | bool |
Show the panel header, by default | True |
Examples
>>> import numpy as np>>> from myogestic.widgets import Scatter3D>>> scatter = Scatter3D("Embedding")>>> scatter.ui(np.array([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]]))ui
ui(
points: np.ndarray,
labels: np.ndarray | None = None,
class_names: list[str] | None = None,
) -> None
Render the 3D scatter for the given frame.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
points | np.ndarray |
Point coordinates of shape | |
labels | np.ndarray | None |
Per-point integer class labels for coloring. If omitted, all points share a single series. | None |
class_names | list[str] | None |
Legend names indexed by class label. Falls back to the label value. | None |
Heatmap
Heatmap(
label: str,
*,
size: tuple[float, float] = (-1, 300),
label_fmt: str = '%.1f',
colormap: int | None = None,
widget_id: str | None = None,
show_title: bool = True,
) -> None
2D heatmap with a panel header, mono range and continuous colour strip.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
label | str |
Plot label shown above the heatmap. | |
size | tuple[float, float] |
Plot size in UI-scaled pixels, by default | (-1, 300) |
label_fmt | str |
Printf-style format for the per-cell value labels, by default | '%.1f' |
colormap | int | None |
An | None |
widget_id | str | None |
Explicit ImGui id scope, defaulting to | None |
show_title | bool |
Show the panel header, by default | True |
Examples
>>> import numpy as np>>> from myogestic.widgets import Heatmap>>> heatmap = Heatmap("Confusion", label_fmt="%.2f")>>> heatmap.ui(np.array([[0.9, 0.1], [0.2, 0.8]]))ui
ui(
data: np.ndarray,
x_tick_labels: list[str] | None = None,
y_tick_labels: list[str] | None = None,
vrange: tuple[float, float] | None = None,
) -> None
Render the heatmap for the given frame.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
data | np.ndarray |
2D array of values to render, row-major (row 0 is drawn at the top). | |
x_tick_labels | list[str] |
Per-column / per-row axis labels (e.g. class names for a confusion matrix). When omitted, columns/rows are labelled by index. Extra labels beyond the grid size are ignored. | None |
y_tick_labels | list[str] |
Per-column / per-row axis labels (e.g. class names for a confusion matrix). When omitted, columns/rows are labelled by index. Extra labels beyond the grid size are ignored. | None |
vrange | tuple[float, float] |
Explicit | None |
LinePlot
LinePlot(
label: str,
*,
size: tuple[float, float] = (-1, 200),
widget_id: str | None = None,
show_title: bool = True,
y_range: tuple[float, float] | None = None,
) -> None
Multi-channel line plot with a panel header and PALETTE-dot legend chips.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
label | str |
Plot label shown above the lines. | |
size | tuple[float, float] |
Plot size in UI-scaled pixels, by default | (-1, 200) |
widget_id | str | None |
Explicit ImGui id scope, defaulting to | None |
show_title | bool |
Show the panel header, by default | True |
y_range | tuple[float, float] | None |
Shared amplitude limits for comparisons. When supplied, start in Shared
mode and offer an Auto / Shared control beside the header. | None |
Examples
>>> import numpy as np>>> from myogestic.widgets import LinePlot>>> plot = LinePlot("Channels")>>> plot.ui(np.array([[0.0, 1.0], [1.0, 0.0]]))ui
ui(data: np.ndarray, channel_names: list[str] | None = None) -> None
Render the line plot for the given frame.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
data | np.ndarray |
Samples of shape | |
channel_names | list[str] | None |
Per-channel legend names. Falls back to | None |
Output processing
PostProcessor
PostProcessor(
hz: float = 50.0,
*,
widget_id: str = 'output_filter',
compact: bool = True,
) -> None
Bases: FilterProcessor
Preset [FilterProcessor][] for post-prediction output smoothing.
The three built-in filters and one_euro selected by default, shown as
a compact Smoothing row. Settings opens the filter description, captioned
sliders with mono values, and Reset. For a custom palette, use
[FilterProcessor][] directly.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
hz | float |
Sample rate forwarded to filters that need it (e.g. | 50.0 |
widget_id | str |
ImGui id scope — give each instance a unique value if you render more than one. | 'output_filter' |
compact | bool |
| True |
Examples
>>> from myogestic.widgets import PostProcessor>>> processor = PostProcessor(hz=20.0)>>> processor.ui()name
name: str
key of the currently selected filter.
filter
filter: VectorFilter
The live filter instance.
Read-only handle for inspection; mutating or calling it directly bypasses the processor's lock and parameter tracking.
reset
reset() -> None
Clear the active filter's smoothing history.
ui
ui() -> None
Render the full panel or the compact Smoothing row and settings popover.

FilterProcessor
FilterProcessor(
filters: Sequence[FilterSpec] = BUILTIN_FILTERS,
*,
hz: float = 50.0,
default: str | None = None,
title: str = 'FILTER',
widget_id: str = 'filter',
) -> None
Pick-one-and-tune filter widget over an extensible palette.
Construct once with the filters it offers, call it on a vector inside
@pipeline.predict, and render it each frame with [ui][]. The
active filter is applied by __call__; parameter values are cached
per filter across selection changes (switching away and back builds a
fresh filter — no stale history). The full panel has an icon-only Reset,
a mono delay readout, and captioned sliders with right-aligned mono values.
Parameter controls use two columns when space permits and one in narrow cells.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
filters | Sequence[FilterSpec] |
Ordered palette of [ | BUILTIN_FILTERS |
hz | float |
Sample rate forwarded to filters that need it (e.g. one_euro). | 50.0 |
default | str | None |
| None |
title | str |
Panel header text. | 'FILTER' |
widget_id | str |
ImGui id scope — give each instance a unique value if you render more than one. | 'filter' |
Examples
>>> from myogestic.widgets import FilterProcessor>>> processor = FilterProcessor(default="identity")>>> processor.ui()name
name: str
key of the currently selected filter.
filter
filter: VectorFilter
The live filter instance.
Read-only handle for inspection; mutating or calling it directly bypasses the processor's lock and parameter tracking.
reset
reset() -> None
Clear the active filter's smoothing history.
ui
ui() -> None
Render the full panel. Call once per frame inside @app.ui.
FilterSpec
FilterSpec(
key: str,
name: str,
build: Callable[..., VectorFilter],
params: tuple[FilterParam, ...] = (),
description: str = '',
reconfigure: Callable[..., VectorFilter] | None = None,
delay: Callable[[float, Mapping[str, Any]], float] | None = None,
) -> None
One selectable filter in a [FilterProcessor][] palette.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
key | str |
Stable identifier (e.g. | |
name | str |
Button label shown in the panel (e.g. | |
build | Callable[..., VectorFilter] |
Factory | |
params | tuple[FilterParam, ...] |
Tunable sliders. Empty for a fixed filter (e.g. identity). | () |
description | str |
Muted description shown above the parameter controls. | '' |
reconfigure | Callable[..., VectorFilter] | None |
Optional in-place update | None |
delay | Callable[[float, Mapping[str, Any]], float] | None |
Optional | None |
Examples
>>> from myogestic.outputs.filters import IdentityFilter>>> from myogestic.widgets import FilterSpec>>> spec = FilterSpec(key="identity", name="Identity", build=lambda **_: IdentityFilter())FilterParam
FilterParam(
key: str,
label: str,
min: float,
max: float,
default: float,
kind: Literal['int', 'float'] = 'float',
fmt: str = '',
log: bool = False,
) -> None
One tunable slider for a [FilterSpec][].
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
key | str |
Keyword name passed to the spec's | |
label | str |
Slider label shown in the panel. | |
min | float |
Slider bounds and initial value. | |
max | float |
Slider bounds and initial value. | |
default | float |
Slider bounds and initial value. | |
kind | Literal['int', 'float'] |
| 'float' |
fmt | str |
ImGui display format; a sensible default is used per | '' |
log | bool |
Logarithmic slider (float only) — handy for wide ranges like | False |
Examples
>>> from myogestic.widgets import FilterParam>>> parameter = FilterParam("sigma", "sigma", 0.1, 10.0, 1.0)Feature selection
FeatureSelector
FeatureSelector(
features: dict[str, FeatureFn],
default: Iterable[str] | None = None,
*,
widget_id: str = 'features',
show_header: bool = True,
) -> None
Wrapping toggle chips for named feature functions.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
features | dict[str, FeatureFn] |
Ordered map of feature name → callable. Each callable
takes an EMG window | |
default | Iterable[str] | None |
Optional iterable of feature names to start active.
| None |
show_header | bool |
Render the standard panel header. | True |
Raises
| Name | Type | Description | Default |
|---|---|---|---|
| ValueError |
if a name in |
Examples
>>> from myogestic.recipes.features import rms>>> from myogestic.widgets import FeatureSelector>>> selector = FeatureSelector({"RMS": rms}, default=["RMS"])>>> selector.ui()active_names
active_names: list[str]
Feature names currently active, in registration order.
n_active
n_active: int
Number of active features.
is_active
is_active(name: str) -> bool
Check whether a specific feature is active.
set_active
set_active(name: str, active: bool) -> None
Programmatically activate / deactivate a feature.
Useful for restoring saved selections from a checkpoint, or for scripted training runs that bypass the UI.
ui
ui() -> None
Render feature toggle chips.
Updates take effect on the next prediction tick.

Training and inspection
TemplateInspector
TemplateInspector(
widget_id: str,
*,
title: str = 'Templates',
height: float = 240.0,
label_colors: dict[str, tuple[float, float, float, float]] | None = None,
) -> None
Review templates with kept/out chips, gesture filters and source selection.
Construct once with a stable widget_id (+ optional title / height /
label colors), then call [ui][] each frame with the current rows.
ui() returns the selected row's key (or None).
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
widget_id | str |
Stable identity string. Two inspectors with the same widget_id share selection and gesture-filter state; different widget_ids are independent. | |
title | str |
Header text shown above the table. | 'Templates' |
height | float |
Table height at UI scale 1.0, scaled with the rest of the interface. | 240.0 |
label_colors | dict[str, tuple[float, float, float, float]] | None |
Optional | None |
Notes
All / None changes every row, including rows hidden by a gesture filter. Click an active gesture chip again to show all gestures. Filtering leaves the selected preview unchanged; removing its row clears the selection.
Examples
>>> from myogestic.widgets import TemplateInspector, TemplateInspectorRow>>> rows = [TemplateInspectorRow("session#0", "Fist")]>>> inspector = TemplateInspector("templates")>>> selected = inspector.ui(rows)ui
ui(rows: list[TemplateInspectorRow]) -> str | None
Render the table for rows; return the selected row's key.
rows is mutated in place (only accepted is touched). Returns
None when no row is selected or the selection was removed.
TemplateInspectorRow
TemplateInspectorRow(
key: str,
label: str,
accepted: bool = True,
info_text: str | None = None,
energy: float | None = None,
) -> None
One row in the inspector table.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
key | str |
Stable identity (e.g. | |
label | str |
Short class/category badge (e.g. | |
accepted | bool |
Mutable. True = include in training. Toggled in place by the kept/out chip, or the All / None buttons. | True |
info_text | str | None |
Optional secondary text shown in the table (e.g.
session name, source path). May be | None |
energy | float | None |
Optional scalar shown as a normalised progress bar in
the energy column. Caller's choice of metric — RMS energy,
peak amplitude, anything monotonic. | None |
Examples
>>> from myogestic.widgets import TemplateInspectorRow>>> row = TemplateInspectorRow("session#0", "Fist", accepted=True, energy=0.8)TrialPreview
TrialPreview(
*,
widget_id: str,
data_layout: Literal['channels_first', 'samples_first'] = 'channels_first',
title: str | None = None,
size: tuple[float, float] = (-1.0, 240.0),
channel_names: list[str] | None = None,
band: tuple[float, float] | None = None,
band_color: tuple[float, float, float, float] | None = None,
gain: float = 1.0,
display_filter: Literal['none', 'rectify', 'dc_removal', 'rms_env'] = 'none',
scale_mode: Literal['auto', 'manual'] = 'auto',
y_range: tuple[float, float] = (-1.0, 1.0),
as_window: bool = False,
) -> None
Preview stacked waveforms under a header and mono window read-out.
The optional region band uses the shared translucent TRIAL_BAND
token, so the traces remain visible in both light and dark themes.
Examples
>>> import numpy as np>>> from myogestic.widgets import TrialPreview>>> preview = TrialPreview(widget_id="trial")>>> preview.ui(np.zeros((8, 400), dtype=np.float32), fs=2000.0)Configure the trial-preview widget.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
widget_id | str |
Stable identity string for ImPlot (combined into plot ids so
two | |
data_layout | Literal['channels_first', 'samples_first'] |
| 'channels_first' |
title | str | None |
Header above the plot; | None |
size | tuple[float, float] |
ImPlot size as | (-1.0, 240.0) |
channel_names | list[str] | None |
Optional per-channel labels. When omitted, channels
are shown as | None |
band | tuple[float, float] | None |
Optional | None |
band_color | tuple[float, float, float, float] | None |
RGBA in | None |
gain | float |
Multiplier applied to each channel before plotting. Match this to your live viewer's gain knob if you want the preview to look like what was on screen. | 1.0 |
display_filter | Literal['none', 'rectify', 'dc_removal', 'rms_env'] |
Visual-only transform applied to a copy of
| 'none' |
scale_mode | Literal['auto', 'manual'] |
| 'auto' |
y_range | tuple[float, float] |
| (-1.0, 1.0) |
as_window | bool |
When | False |
ui
ui(data: np.ndarray, fs: float) -> None
Render stacked multi-channel waveform with optional band overlay.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
data | np.ndarray |
Multi-channel signal. Shape | |
fs | float |
Sampling rate in Hz, used for the x-axis labels in seconds. |
Layout helpers
panel_header
panel_header(
title: str,
icon: str | None = None,
*,
reserve: float = 0.0,
status: imgui.ImVec4 | None = None,
) -> None
Render a uniform panel-header line: muted, all-caps, optional FA icon.
Pairs with the button + slider styling used by the other widgets in this package. Use it at the top of any custom panel to match the look::
panel_header("MODEL", icons_fontawesome_6.ICON_FA_BRAIN)train_button(pipeline)...When the panel is too narrow for the full title, the title is truncated
with a … ellipsis; when there is no room for any label, only the icon
is shown. Pass reserve to leave that many pixels for controls placed
after the header on the same row (e.g. a right-aligned button), so the
title collapses instead of pushing those controls off the panel.
Pass status — one of SUCCESS, IDLE, DANGER, WARNING — to put a filled
circle in that colour at the right end of the header row. Right-aligned so the
titles of stacked panels line up on their first glyph: a dot before the title would
indent the ones that have state and leave the ones that don't hanging. Colour is the
only thing the dot carries, so it must not be the only place the state is
available: give the header a tooltip with the detail (a PID, an exit code) for
anyone who cannot read the hue.
It sits inside reserve, so a right-aligned control placed after the header —
panel_header_button does this — still gets its space, with the dot to its left.
Examples
>>> from myogestic.widgets import panel_header>>> panel_header("MODEL")popout_panel
popout_panel(
title: str,
gui_fn: Callable[[], None],
*,
default_open: bool = True,
can_be_closed: bool = True,
remember_is_visible: bool | None = None,
) -> None
Render gui_fn inside a dockable, tearable ImGui window.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
title | str |
Window title — also used as the ImGui id and as the dedup key for repeated calls. | |
gui_fn | Callable[[], None] |
Zero-arg callable invoked by ImGui every frame. Treat it
like the body of a | |
default_open | bool |
Initial visibility of the window on first launch.
Subsequent launches restore from | True |
can_be_closed | bool |
Whether the user can close the window with the X button. Closed windows reappear via the "View" menu. | True |
remember_is_visible | bool | None |
Whether visibility is persisted in the imgui ini file. Defaults to True for existing behavior. | None |
Notes
When App(docking=True) is not active, this just runs gui_fn()
inline so the call site stays the same.
Examples
>>> from myogestic.widgets import panel_header, popout_panel>>> popout_panel("Details", lambda: panel_header("Details"))Status and logs
StatusBar
StatusBar(
stream: str = 'emg',
*,
sessions_dir: str | Path = 'data',
pipeline: Pipeline | None = None,
widget_id: str = 'status_bar',
) -> None
Show acquisition, participant storage and an optional fitted model.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
stream | str |
Acquisition stream to describe, by default | 'emg' |
sessions_dir | str or Path |
Root of the participant folders, by default | 'data' |
pipeline | Pipeline or None |
Read | None |
widget_id | str |
Stable ImGui identity, by default | 'status_bar' |
Notes
Place in a bare Px(26) Grid row. No caller style pushes are needed.
Long acquisition details and model names ellipsize; hover for the full text.
ui
ui(ctx: Context) -> None
Draw the footer from the context's live streams and participant.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
ctx | Context |
Acquisition state and the participant whose folder is displayed. |

Place StatusBar("emg") in a bare Px(26) Grid row and call status.ui(ctx).
It shows the stream’s connection and channel details, participant and session
folder, with the full text on hover. Pass sessions_dir for a custom storage
root and pipeline to add a right-aligned fitted or saved model readout.
Long details ellipsize; no caller style pushes are needed.
StreamPanel
StreamPanel(
*,
selectable: bool = True,
show_header: bool = True,
widget_id: str | None = None,
) -> None
One-line stream states with reconnect, abort, retry, and outlet picks.
Connected rows show a mono name, sample rate, channels and sample age. Detached streams are idle with Connect; failures show the error with Retry. Connecting rows show elapsed time and Abort. The header dot summarises the worst state and its rescan action refreshes discovered outlets.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
selectable | bool |
Connect opens a popover of discovered outlets when the source supports
| True |
show_header | bool |
Render the standard Streams header, state dot and rescan action. | True |
widget_id | str | None |
ImGui identity, defaulting to this instance. Give a stable unique ID when rendering multiple panels. Connection state belongs to each instance; only outlet discovery is deliberately shared with viewers. | None |
Examples
>>> from myogestic.widgets import StreamPanel>>> panel = StreamPanel()>>> panel.ui(ctx)ui
ui(ctx: Context) -> None
Render one compact row per registered stream, once per frame.
LogPanel
LogPanel(
*,
height: float = -1.0,
title: str = 'Log',
show_header: bool = True,
widget_id: str | None = None,
) -> None
Render the app log as a scrollable, read-only panel.
Examples
>>> from myogestic.widgets import LogPanel>>> panel = LogPanel()>>> panel.ui(ctx)Configure the log panel.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
height | float |
Panel height in pixels. Pass a value | -1.0 |
title | str |
Header label (only shown when | 'Log' |
show_header | bool |
Render the button-style | True |
widget_id | str | None |
Optional per-instance ImGui id scope. Defaults to | None |
ui
ui(ctx: Context) -> None
Render the app log.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
ctx | Context |
App context; reads from |
Branding
AppHeader
AppHeader(
title: str,
*,
steps: StepBar | None = None,
participant: ParticipantPanel | None = None,
show_state: bool = True,
widget_id: str = 'app_header',
) -> None
Lead an app with its logo, title, optional workflow and session state.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
title | str |
Muted application title. Without steps, long titles ellipsize and show their full text on hover; with steps, the title yields to navigation. | |
steps | StepBar or None |
Workflow navigation, by default absent. | None |
participant | ParticipantPanel or None |
Participant selector, by default absent. Its chip yields to the state. | None |
show_state | bool |
Show the context's state at the right edge, by default True. | True |
widget_id | str |
Stable ImGui and instance-local measurement identity, by default
| 'app_header' |
Notes
Place in a bare Px(52) Grid row. No caller style pushes are needed.
ui
ui(ctx: Context, done: list[bool] | None = None) -> int | None
Draw the header and return the active step, or None without steps.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
ctx | Context |
Live participant and application state. | |
done | list[bool] or None |
One completion flag per step. None marks all steps incomplete. Ignored when no StepBar was supplied. | None |
Returns
| Name | Type | Description | Default |
|---|---|---|---|
| int or None |
The active step, including a click made this frame, or None. |

Place AppHeader in a bare Px(52) Grid row. It draws the line logo, muted
title and state pill, with optional StepBar navigation and a ParticipantPanel
chip. Call header.ui(ctx, done) inside the cell; no style pushes are needed.
Without steps, done is optional and the return value is None. Long titles
ellipsize and reveal their full text on hover. With steps, the title yields
first, then step padding tightens; the participant chip yields to the state pill.
At smaller widths only the active step retains its label, and the others show
their number or checkmark with the full label on hover.
Grid caps vertical padding in short bare rows so a control fits inside the row.
See the standalone
app_header.py example
for headers with and without workflow steps.
Image
Image(
asset: str,
*,
max_size: float | None = None,
padding: float = 12.0,
missing_label: str | None = None,
widget_id: str | None = None,
) -> None
Generic fit-to-cell image widget.
Reads the available content area inside the current panel and renders
the image as the largest aspect-preserving rectangle that fits both
dimensions (minus padding), then centres it. In a cell whose
aspect matches the image, it fills edge-to-edge minus the padding
margin; in a different aspect, it fills the tighter dimension and leaves
balanced padding along the other.
Notes
Uses image_and_size_from_asset + raw imgui.image rather than the
higher-level image_from_asset(..., size=...) helper, which in this
version of hello_imgui ignored the explicit size and rendered at the
natural pixel dimensions of the image.
Examples
>>> from myogestic.widgets import Image>>> image = Image("app_settings/icon.png", max_size=256)>>> image.ui()Configure the image widget.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
asset | str |
Path to the image, relative to MyoGestic's registered assets folder (resolved via HelloImGui's asset system). | |
max_size | float | None |
Optional cap on the rendered width in pixels. | None |
padding | float |
Margin in pixels reserved on every side. Default 12 px. | 12.0 |
missing_label | str | None |
Text shown (muted) when the asset can't be found. Defaults to
| None |
widget_id | str | None |
Optional per-instance ImGui id scope. Defaults to | None |
ui
ui() -> None
Render the image asset fit-to-cell, aspect-preserving, centred.
AppLogo
AppLogo(
*,
variant: Literal['stacked', 'line'] = 'stacked',
height: float | None = None,
max_size: float | None = None,
padding: float = 12.0,
widget_id: str | None = None,
) -> None
Render the MyoGestic wordmark in a cell or inline at a fixed height.
Thin wrapper over Image pinned to the shipped
wordmark. See that widget for the fit/centre behaviour.
Examples
>>> from myogestic.widgets import AppLogo>>> logo = AppLogo(max_size=240)>>> logo.ui()Configure the wordmark widget.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
variant | Literal['stacked', 'line'] |
| 'stacked' |
height | float | None |
Optional fixed height in pixels, with width derived from the asset's
aspect ratio. Draws at the cursor without cell centring or padding;
takes precedence over | None |
max_size | float | None |
Optional cap on the wordmark's width in pixels. | None |
padding | float |
Margin in pixels reserved on every side. Default 12 px gives the wordmark breathing room against the panel border. | 12.0 |
widget_id | str | None |
Optional per-instance ImGui id scope. | None |
ui
ui() -> None
Draw the chosen logo, or the display text wordmark if it is missing.

ML readout
PredictionLabel
PredictionLabel(
pipeline: Pipeline,
class_names: Sequence[str],
*,
class_key: str = 'class',
probability_key: str = 'proba',
title: str = 'Prediction',
show_probability: bool = False,
font_scale: float = 2.0,
widget_id: str | None = None,
) -> None
Render the predicted class, cadence and per-class probability bars.
The class index is looked up in pipeline.predictions[class_key] and the
name is taken from class_names. Colour-coded from the shared PALETTE,
so a class keeps the same colour as its recording / session-manager chips.
Examples
>>> from myogestic.widgets import PredictionLabel>>> label = PredictionLabel(pipeline, ["Rest", "Fist"])>>> label.ui()Configure the prediction label.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
pipeline | Pipeline |
The Pipeline whose predictions to read. Untrained or
first-frame state ( | |
class_names | Sequence[str] |
Class names indexed the same way as the model —
| |
class_key | str |
Dict key in | 'class' |
probability_key | str |
Dict key holding the per-class probability vector,
consumed only when | 'proba' |
title | str |
Card identity and tooltip text. | 'Prediction' |
show_probability | bool |
When True, render one thin categorical bar and mono percentage for every class below the name. | False |
font_scale | float |
Multiplier applied to the class name's text size. Defaults to 2× the panel font. | 2.0 |
widget_id | str | None |
Optional per-instance ImGui id scope. Defaults to | None |
ui
ui() -> None
Render the prediction or idle reason.
Probability bars share a fixed 0–1 range.

Virtual Hand integration
VhiMovementPanel
VhiMovementPanel(
client: RecordingClient,
on_movement: Callable[[str], None],
*,
min_interval_s: float = 1.0,
title: str = 'Hand movements',
widget_id: str | None = None,
) -> None
Stateful widget — instantiate once at module level, call .ui() per frame.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
client | RecordingClient |
The | |
on_movement | Callable[[str], None] |
Click handler for a movement button — required. Wire it to a
discrete DOF, e.g. | |
min_interval_s | float |
Minimum seconds between background state refreshes. Default 1 s. | 1.0 |
title | str |
Panel header text rendered above the wrapping movement chips. | 'Hand movements' |
widget_id | str | None |
Stable UI identity. Defaults to this panel instance, independently of its client. | None |
Examples
>>> from myogestic.widgets import VhiMovementPanel>>> panel = VhiMovementPanel(... vhi.recording_client(),... lambda state: bus.select("gesture", state),... )>>> panel.ui()ui
ui(*, auto_refresh: bool = True) -> None
Render the panel — call once per frame inside @app.ui.
Set auto_refresh=False in latency-sensitive phases such as live
prediction. The last cached state remains visible and the panel's explicit
Refresh button still starts one background request, but no periodic gRPC
work is scheduled from the frame loop.

Lower-level pieces
VhiMovementPanel wraps these for the common case. Reach for them directly when you want to share one state cache across multiple panels, or render the palette without owning a client.
vhi_movement_palette
vhi_movement_palette(
movements: Sequence[str],
*,
on_movement: Callable[[str], None],
on_refresh: Callable[[], None] | None = None,
current_movement: str = '',
connected: bool = False,
status: str = '',
title: str = 'Hand movements',
widget_id: str = 'vhi_movements',
) -> None
Render wrapping movement chips with the current movement selected.
Pure ImGui: performs no RPC and owns no client. on_movement(name) fires
on click; wire it to a discrete DOF such as bus.select("gesture", name).
While disconnected, launch instructions and an optional Refresh action replace
the cached list. widget_id isolates multiple palettes in the same window.
Examples
>>> from myogestic.widgets import vhi_movement_palette>>> vhi_movement_palette(... ["Rest", "Fist"], connected=True, on_movement=vhi_client.set_movement... )VhiStateCache
VhiStateCache(
movements: list[str] = list(),
current_movement: str = '',
current_state: str = '',
mode: str = '',
trajectory_running: bool = False,
trajectory_movement: str = '',
connected: bool = False,
refreshing: bool = False,
message: str = 'Launch VHI, then refresh.',
last_attempt_s: float = 0.0,
lock: threading.Lock = threading.Lock(),
) -> None
Last-known VHI state, refreshed off-thread. Use snapshot() to read.
Examples
>>> from myogestic.widgets import VhiStateCache>>> state = VhiStateCache()>>> snapshot = state.snapshot()snapshot
snapshot() -> VhiStateSnapshot
Return a consistent, immutable view — safe to read all frame.
VhiStateSnapshot
VhiStateSnapshot(
movements: tuple[str, ...],
current_movement: str,
current_state: str,
mode: str,
connected: bool,
message: str,
trajectory_running: bool = False,
trajectory_movement: str = '',
) -> None
An immutable, lock-free view of VhiStateCache for one UI frame.
Examples
>>> from myogestic.widgets import VhiStateCache, VhiStateSnapshot>>> snapshot: VhiStateSnapshot = VhiStateCache(movements=["Rest"]).snapshot()>>> snapshot.movements('Rest',)request_vhi_state_refresh
request_vhi_state_refresh(
client: RecordingClient,
cache: VhiStateCache,
*,
force: bool = False,
min_interval_s: float = 1.0,
disconnected_interval_s: float = 5.0,
probe_timeout_s: float = 0.5,
) -> None
Start at most one throttled background GetRecordingSessionState refresh.
Safe to call every frame from @app.ui: it returns immediately unless a
refresh is due and none is already in flight. The blocking state()
runs on a daemon thread; the result lands in cache under its lock.
While VHI is unreachable the poll backs off to disconnected_interval_s
and (historically) used a short probe_timeout_s deadline — so a down server is probed
only occasionally with a fast-failing call, never a 2 s blocking RPC that is
~always in flight. (A continuously in-flight failing call keeps the
gRPC channel in connect/reconnect churn, which stutters the 60 fps render
loop.) Once connected it polls every min_interval_s again. An explicit
force refresh ignores the interval and uses the client's full deadline
(a cold connect can be slower than probe_timeout_s).
Examples
>>> from myogestic.widgets import VhiStateCache, request_vhi_state_refresh>>> state = VhiStateCache()>>> request_vhi_state_refresh(vhi_client, state)Follow the control hand
FollowRun
FollowRun(
gestures: Sequence[str],
*,
drive: Callable[[int, float], Any] | None = None,
operator: ControlLink | None = None,
aliases: Sequence[str] = (),
poses: Mapping[str, ArrayLike] | None = None,
rest: ArrayLike | None = None,
on_record: Callable[[], None],
on_stop: Callable[[], None],
hz: float = 32.0,
trajectory: Sinusoid | None = None,
prediction_stream: str = 'controls',
prediction_channel: str | int = 'prediction',
max_lag_s: float = 1.0,
widget_id: str = 'follow',
) -> None
Run and score a smooth relaxed-to-gesture target in a dedicated take.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
gestures | Sequence[str] |
Non-empty gesture names. The exposed index addresses this exact sequence. | |
on_record | Callable[[], None] |
Start and stop callbacks, usually | |
on_stop | Callable[[], None] |
Start and stop callbacks, usually | |
drive | Callable[[int, float], Any] | None |
Called with | None |
operator | ControlLink | None |
Link to drive directly with blended pose vectors. Its bus is read on every step; an unbound link is a no-op and is never bound by this card. | None |
aliases | Sequence[str] |
Operator mode's ordered aliases, gesture-name-to-pose mapping, and relaxed pose. Every gesture must have a finite one-dimensional pose with exactly one value per alias. Shapes and values are validated at construction. | () |
poses | Sequence[str] |
Operator mode's ordered aliases, gesture-name-to-pose mapping, and relaxed pose. Every gesture must have a finite one-dimensional pose with exactly one value per alias. Shapes and values are validated at construction. | () |
rest | Sequence[str] |
Operator mode's ordered aliases, gesture-name-to-pose mapping, and relaxed pose. Every gesture must have a finite one-dimensional pose with exactly one value per alias. Shapes and values are validated at construction. | () |
hz | float |
Finite, positive drive rate in Hz; defaults to 32. | 32.0 |
trajectory | Sinusoid | None |
Initial editable shape; defaults to | None |
prediction_stream | str |
Saved scalar prediction to score in the same fractional units as the target.
A channel name or zero-based index; defaults to the delivered control bus's
| 'controls' |
prediction_channel | str |
Saved scalar prediction to score in the same fractional units as the target.
A channel name or zero-based index; defaults to the delivered control bus's
| 'controls' |
max_lag_s | float |
Finite, non-negative correlation search radius. | 1.0 |
widget_id | str |
Stable ImGui identity. Give each card its own ID. | 'follow' |
Notes
The operator hand runs on its own clock, independent of EMG, the GUI and
predict. Give its link ctx=app.ctx, record_as="controls.operator" and
no smoothing to record it separately. hold no-ops while running.
Call sync every UI frame, even when hidden, to stop at the deadline and
score after saving. ui also calls sync. Register stop in the app's
cleanup hooks. stop joins the driver and, in operator mode, pushes rest before
on_stop, including after an external recording stop. Lifecycle methods belong
on the UI thread; drive must return and must not call lifecycle methods or GUI code.
running
running: bool
Whether this card owns an active run.
target
target: tuple[int, float] | None
Latest driver step's gesture index and fraction, or None outside a run.
score
score: dict[str, float | None] | None
Metrics read from the saved take, or None before scoring finishes.
hold
hold(pose: ArrayLike | None = None) -> Mapping[str, float | str] | None
Push a held pose (rest by default) on the UI thread and return its delivery.
Return None while running, unbound, or using drive=. Never binds a link.
start
start(ctx: Context) -> bool
Start a new take; return False if busy or the callback refuses recording.
stop
stop(ctx: Context) -> None
Close this run, save its partial interval and leave other takes alone.
sync
sync(ctx: Context) -> None
Finish expired/interrupted runs and score only once the save completes.
ui
ui(ctx: Context, *, disabled_reason: str = '') -> None
Draw the card; a visible disabled_reason gates new starts only.
Sinusoid
Sinusoid(
move_s: float = 2.0,
hold_high_s: float = 2.0,
hold_low_s: float = 2.0,
peak: float = 1.0,
reps: int = 5,
lead_s: float = 3.0,
) -> None
Relaxed hold, half-cosine rise, peak hold and half-cosine return.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
move_s | float |
Positive seconds for each smooth movement. | 2.0 |
hold_high_s | float |
Non-negative seconds at the peak and relaxed endpoints. | 2.0 |
hold_low_s | float |
Non-negative seconds at the peak and relaxed endpoints. | 2.0 |
peak | float |
Fraction of the gesture, between zero and one. | 1.0 |
reps | int |
Positive integer number of cycles. | 5 |
lead_s | float |
Non-negative relaxed preparation time before the first cycle. | 3.0 |
duration
duration: float
Seconds per cycle, excluding the lead-in.
total_duration
total_duration: float
Seconds for the lead-in and all cycles.
value_at
value_at(t: float) -> float
Fraction of the gesture at t seconds; zero outside the run.
phase_at
phase_at(t: float) -> str
Existing phase name at t; lead-in and low holds use rest.
blend_pose
blend_pose(relaxed: ArrayLike, gesture: ArrayLike, level: float) -> np.ndarray
Blend equally shaped finite pose vectors by a fraction in [0, 1].
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
relaxed | ArrayLike |
One-dimensional pose vectors in the app's own control units. | |
gesture | ArrayLike |
One-dimensional pose vectors in the app's own control units. | |
level | float |
Fraction of the gesture. Values outside [0, 1] are rejected. |
score_tracking
score_tracking(
t_target: ArrayLike,
target: ArrayLike,
t_pred: ArrayLike,
pred: ArrayLike,
*,
start_s: float | None = None,
end_s: float | None = None,
max_lag_s: float = 1.0,
step_s: float = 0.01,
) -> dict[str, float | None]
Score scalar tracking on a common uniform time grid without extrapolation.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
t_target | ArrayLike |
Strictly increasing finite timestamps in the same clock domain. | |
t_pred | ArrayLike |
Strictly increasing finite timestamps in the same clock domain. | |
target | ArrayLike |
Scalar levels paired with those timestamps. Non-finite levels are discarded. | |
pred | ArrayLike |
Scalar levels paired with those timestamps. Non-finite levels are discarded. | |
start_s | float | None |
Inclusive run bounds on that clock. Set start to run start plus lead-in; samples outside these bounds never contribute, including to lag estimation. Defaults to the common recorded interval. | None |
end_s | float | None |
Inclusive run bounds on that clock. Set start to run start plus lead-in; samples outside these bounds never contribute, including to lag estimation. Defaults to the common recorded interval. | None |
max_lag_s | float |
Non-negative search radius for normalised cross-correlation. | 1.0 |
step_s | float |
Positive interpolation step in seconds, also the lag resolution. | 0.01 |
Returns
| Name | Type | Description | Default |
|---|---|---|---|
| dict |
|
FollowRun owns a dedicated recorded take and drives the operator hand on its own
clock, independent of EMG, the GUI and predict. Supply operator=, ordered
aliases=, gesture-keyed poses=, and rest= to push blended pose vectors at hz
(default 32). Every gesture must have a finite pose vector with one value per alias;
construction validates these shapes. Alternatively, supply drive(index, level) for
custom delivery. Exactly one of operator and drive is required.
level is a fraction in [0, peak]; target exposes the latest
(gesture_index, level), or None when idle. Sinusoid holds relaxed, moves up with
a half-cosine, holds at the peak, and moves down with a half-cosine, repeating after
an optional lead-in.
Give each hand its own ControlLink and map. The prediction link keeps ctx and
smoothing, and predict pushes only prediction aliases. The operator link uses
ctx=app.ctx, record_as="controls.operator" and no smoothing. Its delivered frames
and map are saved separately as controls.operator and
meta.control_spaces["controls.operator"]; prediction keeps controls and
meta.control_space. One ControlLinkConnector(link, operator) binds both.
Use binder.ensure_now() for synchronous UI binding and binder.poll() for
background attempts; binder.connected means both hands are ready.
Call follow.hold(pose) for manual gestures, or follow.hold() for rest. It returns
what the operator bus delivered, including clipping, or None while running or
unbound. Neither hold nor the driver binds a link. Each LSL outlet resends its latest
value at 32 Hz between pushes.
Construct the card once and call sync every UI frame, including hidden tabs, to
finish expired or interrupted takes and score them. The driver records
follow.target with gesture_index, level, and phase channels on the LSL clock,
using the existing PHASE_CODES. At the deadline it drives rest until sync saves
the take. stop signals and joins the driver, then pushes rest in operator mode
before on_stop, including after an external recording stop. A drive= callback
retains responsibility for its own rest push. Register stop for cleanup; keep
lifecycle calls on the UI thread and GUI code out of drive. A drive exception is
logged once per run and later steps continue.
This hardware-free example uses a local target with two independently mapped links:
from myogestic import Appfrom myogestic.controls import Capability, ControlLink, ControlLinkConnector, load_control_mapfrom myogestic.widgets import FollowRun
class Hand: def capabilities(self): return [Capability("hand.grasp", "continuous", lo=0, hi=1, rest=0)]
def bind(self, controls): pass
def send(self, values, changed): self.pose = values
def stop(self): pass
app = App("Follow example")link = ControlLink(load_control_map({"dofs": {"prediction": "hand.grasp"}}), [Hand()], ctx=app.ctx)operator = ControlLink( load_control_map({"dofs": {"control": "hand.grasp"}}), [Hand()], ctx=app.ctx, record_as="controls.operator",)binder = ControlLinkConnector(link, operator)poses = {"Fist": [1.0], "Pinch": [0.6]}follow = FollowRun( ["Fist", "Pinch"], operator=operator, aliases=("control",), poses=poses, rest=[0.0], on_record=app.start_recording, on_stop=app.stop_recording,)assert binder.ensure_now() is link.bus and binder.connectedassert follow.hold(poses["Pinch"]) == {"control": 0.6}
# predict pushes link.bus.push({"prediction": value}) when link.bus is bound.# Every GUI frame calls follow.sync(ctx), then draws follow.ui(ctx) in its Grid cell.app.cleanup_hooks.append(lambda _app: follow.stop(app.ctx))assert follow.target is Nonebinder.stop() # Teardown order: follow.stop(app.ctx), binder.stop(), transport.stop().A complete hardware-free demo is
examples/panels/follow_run.py.
The default score compares follow.target.level to the saved controls stream’s
prediction channel, so it measures delivered predictions. Both must use the same
fractional units. For a pose-vector app, project the delivered prediction onto its chosen
gesture, record that scalar using Session.append_event, and pass its stream name and
channel to FollowRun(prediction_stream=..., prediction_channel=...). No device, model,
or VHI connection is required by the widget itself. Myocontrol wraps the recording
callbacks to start and stop prediction using the existing Drive gates.
Stopping early scores only the recorded part after the lead-in. The saved take carries
extras.follow, is labelled Follow in Takes, and remains unticked for training by
default. Saving finishes before the widget reopens the take to score it. RMSE and Pearson r
are measured without a lag correction; lag maximises normalised cross-correlation within
max_lag_s (default ±1 second), at 10 ms resolution. Positive lag means prediction trails
the control target. No overlapping samples gives undefined metrics; a constant signal has
an RMSE but no correlation or lag, displayed as a dash. A periodic run can have repeated
correlation peaks, so choose a search window shorter than a cycle.