Skip to content
GitHub · 2.7.0

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

NameTypeDescriptionDefault
stream_namestr

The stable widget ID / stream to view. When selectable=True, the user may switch the active stream from the UI — each stream's channel selection is tracked separately and restored when the user switches back.

widget_idstr | None

Explicit state / ImGui id scope. Defaults to stream_name. Give each viewer its OWN id to show one stream through several panels (e.g. one per electrode grid) — otherwise they share a single state and render identically. Pair with channel_scope to give each its own channels, and prefer a stable, unique string (grid labels can repeat).

None
excludeIterable[str]

Stream names omitted from the selectable viewer, such as target feedback.

()
channel_scopeIterable[int] | None

The columns this viewer may ever show — a hard restriction, unlike initial_channels (which only seeds the opening selection). All / None / Invert, the N/total count, the [Edit…] grid and shift-click ranges are all bounded by it, so a per-electrode-grid panel stays its own array however the user clicks. None (default) is unrestricted; an explicit scope that matches no valid column renders "no channels in scope" rather than quietly widening back to the whole stream. Positional, so with selectable=True it is re-applied (clamped) to whichever stream is shown. Note it also drives the default selection: a 64-channel scope opens on its first 16 unless you pass initial_channels too.

None
titlestr | None

Panel header text. Defaults to "SIGNAL · <stream>" — set it per panel when several viewers share a stream, or every tile reads alike.

None
show_connectbool

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 StreamPanel or a DevicePicker — or the app ends up with two controls named Connect that do different things: this one attaches whatever source the stream already holds, a picker's builds a new one from its dropdown. They agree only until somebody changes the dropdown.

Left on by default: an app that is just App + Stream + a viewer has no other way to attach, and nothing attaches on its own.

True
stream_typestr | None

The LSL type ("EMG", "EEG" …) of the other streams the empty state offers next to the app's own. None (default) takes the type the scan reports for the app's stream, and offers every stream when it cannot tell. Set it when the network carries many outlets of other kinds — a Virtual Hand link publishes one per control — so stepping does not wade through them.

None
show_controlsbool

Whether the panel's chrome — toolbar, popups and footer — starts expanded (default True). The header's ⌃⌃ button toggles it at runtime and becomes ⌄⌄ to unfold it; the title and the toggle stay put either way, so a collapsed panel is still identifiable and there is always a way back. Pass False for small tiled panels that should be nearly all plot. Dropping the title itself is show_title's job.

True
show_titlebool

Whether to draw the header row at all (default True). Pass False inside a tab or a titled container that already names the panel — a panel_header under a tab label is the title twice, and the row it costs is pure padding. Orthogonal to show_controls, which folds the header controls and footer: show_title=False, show_controls=True is an untitled viewer with its full toolbar, popups and footer. Note the ⌃⌃ collapse toggle lives in that header and goes with it, so with no title the chrome is fixed at whatever show_controls was constructed with — intended for a tab, where the chrome is a layout decision rather than something the user folds away.

True
n_pixelsint | None

Optional hard cap on the points drawn per channel. None (default) means no cap — draw density tracks the plot width via the runtime "Detail" slider, which is the normal control. Set it only to force a ceiling (e.g. a slow machine with very high channel counts).

None
scale_modestr

"auto" for ImPlot fitting, "manual" for the user-set y_range.

'auto'
window_sfloat

The initial display window in seconds — the user can still drag the slider afterwards. Defaults to 5 s. The stream's buffer_ms must be at least this large.

5.0
initial_channelsIterable[int] | None

Which channels open enabled, e.g. range(16) for "the first 16" — do not pass a bare int (ambiguous with a single channel index). It seeds only the very first selection this viewer resolves; a different stream later shown through a selectable viewer falls back to the None policy. Once a selection exists (here or restored from a prior visit), the user's own toggle edits are never overwritten. None (default) falls back to resolve_initial's policy: every channel when n_channels <= 32, else the first 16.

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.

signal_viewer

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

NameTypeDescriptionDefault
stream_namestr

Stream to draw, as registered with app.streams.

sizetuple[float, float]

Plot size in UI-scaled pixels, by default (-1, 300). Nonpositive dimensions fill the available space, reserving the footer.

(-1, 300)
show_connectbool

Offer a Connect button while detached. Turn it off when a StreamPanel or DevicePicker owns connecting, to avoid duplicate Connect controls.

True
stream_typestr | None

LSL type of the other streams the empty state offers, as in SignalViewer. None takes the type of the app's own stream.

None
channel_heightfloat

Trace spacing in signal units. 0 derives spacing from the visible data. Set a common value when comparing several viewers.

0.0
widget_idstr | None

State and ImGui identity, defaulting to stream_name. Supply distinct ids for independent views of the same stream.

None
show_titlebool

Show the panel title, by default True. Window and Channels remain available when the title is hidden.

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

NameTypeDescriptionDefault
presetslist[tuple[str, float]]

Label and control-value pairs, such as [("Rest", 0.0), ("Fist", 1.0)]. The initial value is 0.0 (rest).

outletStreamOutlet | None

Control-stream outlet. If omitted, create emg_generator.control_outlet() on the first ui or set call, so construction has no LSL side effects.

None
widget_idstr

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.

SimulatorControls

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

NameTypeDescriptionDefault
streamstr

Name of the stream to attach to, as registered with app.streams.

devicesSequence[DeviceSpec]

What the dropdown offers. Defaults to [DEFAULT_DEVICES][] (the OTB family plus LSL); pass a narrower list for an app that supports one amplifier, or add your own [DeviceSpec][] entries.

DEFAULT_DEVICES
widget_idstr | 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 Grid cell is one child window. Distinct values keep panels in one cell from sharing sliders, popups and plots.

None
selectablebool

Show sorted stream chips from ctx.streams, each with a status dot. Clicking a chip changes only which stream this panel configures.

False
on_addCallable[[str], object] | None

Optional callback receiving a cleaned stream name. With selectable, adds a trailing plus chip and inline name field. Build a Stream and pass it to App.add_stream; the app owns its geometry.

None
on_removeCallable[[str], object] | None

Optional callback receiving the selected stream's name; pass App.remove_stream. The last offered stream cannot be removed. Adding and removing are disabled during a recording.

None
excludeIterable[str]

Stream names to exclude. Use for sources owned by another widget, such as a TrackingTask target or replay. Connecting another source would detach its owner and record data under the wrong stream name. This frozen set allows streams added at runtime unless named here.

()
show_headerbool

Render the standard panel_header. Turn it off when the surrounding layout already names the card; chips and the action area still carry the selected stream's state.

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

NameTypeDescriptionDefault
labelstr

Shown in the dropdown, e.g. "Quattrocento".

factoryCallable[..., Any]

Source class or functools.partial, called on Connect with the selected options as keyword arguments. Selecting a device leaves the running source unchanged and does not call the factory.

optionsSequence[DeviceOption]

The [DeviceOption][] rows to draw, in order. Their chosen values are passed to factory as keyword arguments. Each row starts on whichever choice matches the factory's own default, so leaving them all alone reproduces factory() exactly.

tuple()
scanbool

True to discover LSL or serial targets at runtime. Draws a list from discover() in place of the option rows and passes the choice to Stream.reconnect. Set this explicitly; sources with discovery can also use static options.

False
liveSequence[DeviceParam]

[DeviceParam][] sliders, shown only once this device is the connected one. Use them to tune the running source without disconnecting.

tuple()
hintstr

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.

''
stepsSequence[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

NameTypeDescriptionDefault
kwargstr

Constructor keyword the chosen value is passed as.

labelstr

Row label with the operator's unit, such as "Channels" or "Sample rate". Do not use constructor keywords such as "nch_mode" as labels. Only the device entry knows their meaning.

choicesMapping[str, Any]

{shown: value}, in the order they should appear. Shown text is drawn as a segmented control when the row is wide enough for every option at once. Keep it short; label carries the unit.

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

NameTypeDescriptionDefault
attrstr

Public attribute on the source to read and write.

labelstr

Row label, spelled out in the unit the operator thinks in.

lofloat

Slider range.

hifloat

Slider range.

fmtstr

printf format for the value shown on the slider.

'%.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

NameTypeDescriptionDefault
key_filestr or Path

Local CSV mapping IDs to names, by default "~/myogestic/participant-key.csv". Keep it outside the sessions directory so copied recordings never carry the names with them.

'~/myogestic/participant-key.csv'
widget_idstr

Stable input-state and popup identity, by default "participant". Use a different ID for each independent participant selector.

'participant'
sessions_dirstr or Path

Data root, by default "data", holding <ID>/recordings, <ID>/predictions and <ID>/models. Recorded participants are discovered once each time the dialog opens, excluding pending saves.

'data'
on_drivecallable or None

Called as on_drive(participant_id, model_path) after selecting the ID with Drive with saved model. The newest .joblib model in <ID>/models by modification time is offered. None hides that action.

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
NameTypeDescriptionDefault
ctxContext

Live app context. Only its pseudonymised participant ID is changed, and only while state == "idle".

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

NameTypeDescriptionDefault
class_nameslist[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 ctx.class_names for session metadata.

None
on_recordCallable[[], None]

Begin capture, normally app.start_recording.

on_stopCallable[[], None]

Stop and save capture, normally app.stop_recording.

on_gestureCallable[[int], None] | None

Optional side effect when a gesture tile is selected.

None
show_headerbool

Render the standard panel header.

True
take_lengthsSequence[float]

Positive durations in seconds. Empty keeps start/stop only.

()
warmupsSequence[float]

Nonnegative countdown durations in seconds; zero means Off. Must contain at least one value.

(0.0,)
timedbool

Open in Timed mode instead of Start / stop. Defaults to False. True requires nonempty take_lengths or raises ValueError.

False
take_lengthfloat or None

Initially selected entry of take_lengths. None selects the first entry when offered. A value outside the sequence raises ValueError naming the allowed values.

None
warmupfloat or None

Initially selected entry of warmups. None selects the first entry. A value outside the sequence raises ValueError naming the allowed values.

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.

recording_controls

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

NameTypeDescriptionDefault
on_recordCallable[[], None]

Called when Record is clicked (idle → recording). Pass app.start_recording.

on_stopCallable[[], None]

Called when the dialog is saved. Pass app.stop_recording.

on_discardCallable[[], None] | None

Called when the dialog is discarded. Pass app.discard_recording. Omit it and the dialog offers no Discard — appropriate for an app where deleting a take should not be one click away.

None
widget_idstr | None

ImGui id scope and state key. Defaults to "recorder". 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 Grid cell is a single child window — so two of these in one cell share every slider, popup and plot until they are told apart.

None
show_headerbool

Render the standard panel_header.

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

NameTypeDescriptionDefault
on_addCallable[[str], object]

Called with a cleaned stream name when Add is pressed. Build the Stream and hand it to App.add_stream — the app owns the geometry (window and buffer length), not this panel.

on_removeCallable[[str], object]

Called with the stream's name when its Remove is pressed. Pass App.remove_stream.

show_headerbool

Render the standard panel_header.

True
widget_idstr | None

ImGui id scope. Defaults to "streams"; give each instance its own if an app renders more than one.

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.ui
def ui(ctx):
pipeline.training_data = sessions.ui()

Parameters

NameTypeDescriptionDefault
base_pathstr

Data root, default "data". Takes are read from its recordings/ and predictions/ folders, or from base_path/<ID>/... when ui(participant=...) scopes the list to a participant, whose takes then appear automatically. Unscoped, nothing is read until you press the Rescan folder icon.

'data'
titlestr

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_nameslist[str] | None

Human-readable names for the label class indices, used to render the gesture chips (with totals across all listed takes). None falls back to whatever each session recorded in its own meta.json, then to c0, c1, …

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
NameTypeDescriptionDefault
participantstr

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 extras.pipeline. A following ui(participant=participant) preserves the ticks without scanning again.

Raises
NameTypeDescriptionDefault
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
NameTypeDescriptionDefault
participantstr | 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 or an empty ID leaves scanning manual.

None
Returns
NameTypeDescriptionDefault
TrainingData

Selected session paths and active classes for training.

selection

selection() -> SelectionSummary

Return selected-take counts and seconds for included gestures.

Returns
NameTypeDescriptionDefault
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.

session_manager

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

NameTypeDescriptionDefault
streamstr

Stream name to start on, as registered with app.streams. May be "": the panel offers every stream in ctx.streams and the choice is made at runtime.

''
channelint

Channel index within that stream carrying the force signal.

0
trapezoidTrapezoid | None

Initial target shape. Every segment is editable in the settings popover; this is only where it starts. Defaults to Trapezoid's own defaults.

None
targetTargetSource | None

Optional myogestic.sources.target.TargetSource to drive, so the trajectory is recorded beside the EMG instead of being reconstructed afterwards from a start time and a copy of these settings. The app owns it — register it as a Stream and pass it here; the task never builds one. Start, Stop and every shape edit are forwarded, so what is drawn and what is recorded cannot diverge.

None
tail_msfloat

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_sfloat

How long the MVC action watches for a peak after it is pressed.

3.0
widget_idstr | 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 Grid cell is a single child window, so two of these in one cell share every slider and both plots until they are told apart.

None
look_ahead_sfloat

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_heightfloat

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

NameTypeDescriptionDefault
rest_sfloat

Baseline seconds before the ramp begins.

3.0
ramp_up_sfloat

Seconds spent rising linearly from baseline to level_pct.

5.0
hold_sfloat

Seconds at level_pct.

10.0
ramp_down_sfloat

Seconds spent falling linearly back to baseline.

5.0
recover_sfloat

Baseline seconds after the ramp, before the next repetition.

5.0
level_pctfloat

Plateau height as a percentage of MVC.

30.0
repsint

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.duration
10.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
NameTypeDescriptionDefault
tfloat

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
NameTypeDescriptionDefault
tfloat

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. reps above 1 repeats the same path deliberately, to make repetitions comparable, and every rep after the first is therefore learnable: raise hops rather than reps to 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

NameTypeDescriptionDefault
rest_sfloat

Baseline seconds before the wander begins.

5.0
hop_sfloat

Seconds per waypoint-to-waypoint segment. The difficulty knob: halving it doubles every rate without changing the levels visited.

2.0
hopsint

How many segments one repetition is made of. Fewer than about 16 and the coverage starts to clump.

24
recover_sfloat

Baseline seconds after the wander, before the next repetition.

5.0
repsint

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.duration
8.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
NameTypeDescriptionDefault
tfloat

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
NameTypeDescriptionDefault
tfloat

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

NameTypeDescriptionDefault
zerofloat

The resting reading, in the force channel's own signal units.

mvcfloat

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
NameTypeDescriptionDefault
xfloat

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

NameTypeDescriptionDefault
ball_speedfloat

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_sizefloat

Subject's paddle height in court y units; the court is 2.0 tall, so 0.36 covers 18% and 0.6 covers 30%. Clamped to [0.02, 2.0]. Bigger is easier.

0.36
opponent_paddle_sizefloat | None

Opponent's paddle height in the same units and with the same bounds as paddle_size, or None to use paddle_size for both paddles. Set it separately to enlarge the subject's paddle without enlarging the opponent's.

None
controlstr

What the command does to the paddle. Neither mode is the right one in general.

"velocity", the default, integrates it: +1 drives the paddle up at full speed, -1 down, 0 holds. That makes a coarse decoder into a complete controller — three distinct outputs become up / hold / down, which reach every height in the court, where by position three outputs are three places and nothing in between. What it buys is paid for in drift: an integrator accumulates a decoder's resting bias as faithfully as its intent. _DEAD_ZONE cuts that down and is not optional, but read what it says — it slows the drift and cannot stop it, because a noisy biased command still rectifies to something positive. Expect a paddle that wanders onto a wall while the subject holds still, and expect the subject to be the one correcting it.

"position" maps the command onto the paddle's travel, +1 at the top — the full command range across the full travel, so no band at either end is unreachable and none of it is two commands deep. It cannot drift and needs no dead zone, which makes it the honest mode to debug a model against and the better one whenever the command is already continuous — a force channel, a slider, a regressor fit on densely covered levels. Its ceiling is that the paddle is exactly as smooth, and reaches exactly as many places, as the command does.

'velocity'
opponentfloat | None

Speed factor of a paddle playing back from the far wall, or None for the plain wall to rally against. Its top tracking speed is opponent * ball_speed in court y per second, so a slower ball also slows the opponent. With equal paddles, ~0.6 is a fair rally, 1.0 and above is hard. Must be positive.

None
court_heightfloat

Court height in pixels at UI scale 1.0, or 0 or less to take the height the cell has left over after the header — the contract SignalViewer's plot height already uses. Either way it is floored at 80 px, below which the ball is smaller than the paddle is thick. The width is always whatever the cell gives.

260.0
widget_idstr

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 Grid cell is a single child window, so two of these in one cell would otherwise share every control.

'pong'
win_scoreint | None

First to this many points wins. Pass None for an endless game.

11
opponent_namestr | None

Optional name beside CPU, such as "Fair". A plain wall is labelled WALL.

None
on_harderCallable[[], 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
NameTypeDescriptionDefault
commandfloat

The control signal, in [-1, +1]. Under control="velocity" it is the paddle's speed as a fraction of full; under control="position" it is the paddle's height, +1 at the top of the court. Either way values outside the range saturate and a non-finite one is ignored.

targetfloat | None

The command the subject is being asked to produce, in the same [-1, +1] as command and typically myogestic.tracking.Pursuit.value_at — drawn as a ghost paddle wherever a paddle obeying it would sit, which is the same mapping control="position" uses. So it is the number the block recorded, not a court coordinate, and a subject sitting on the ghost has produced exactly what the recording says they were asked for. None, the default, draws nothing and leaves the court exactly as it was. The ghost does not play the ball and is not a second player. Its dashed trail shows the last three seconds of observed positions, never future ones; passing None clears that history when the block ends.

None
effortfloat | None

How hard the subject is contracting now, on 0..1, drawn as a magnitude gauge at the left of the court with a tick at abs(target). For the training block, where there is no model yet and so no honest way to move the paddle. Deliberately unsigned: amplitude is knowable without a decoder and direction is not, so a gauge taking its sign from target would show the subject their own instruction. None draws nothing.

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

NameTypeDescriptionDefault
processeslist[Process]

The launchable processes, as (name, argv) tuples.

widget_idstr

ImGui id scope for this launcher. A unique instance ID is generated when empty; an explicit ID can preserve state across reconstruction.

''
log_heightfloat

Height in pixels of an optional inline log. <= 0 (the default) draws no inline log at all: state and elapsed time stay visible and output is one click away in the ↗ popout window, which can be moved, resized and left open while the dropdown moves to another process. Pass a positive height to get a strip under the controls instead.

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
NameTypeDescriptionDefault
namestr

The process name from the configured (name, argv) tuples.

Raises
NameTypeDescriptionDefault
ValueError

If name is not configured for this launcher.

stop

stop(name: str) -> None

Stop a process started by this launcher.

Parameters
NameTypeDescriptionDefault
namestr

The process name from the configured (name, argv) tuples.

Raises
NameTypeDescriptionDefault
ValueError

If name is not configured for this launcher.

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
NameTypeDescriptionDefault
namestr

The process name, as given in the (name, argv) tuple.

process_launcher

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

NameTypeDescriptionDefault
targetsSequence[_Launchable]

Anything shaped like myogestic.remote.InterfaceSpec: a name and a launcher() returning [(name, argv)], or raising FileNotFoundError when it cannot be launched here (not installed, or a build this MyoGestic refuses). It is asked again on every press, so an install made meanwhile is picked up.

connectorsMapping[str, ControlLinkConnector] | None

A myogestic.controls.ControlLinkConnector per target name, for the targets the app binds controls to. The app keeps it and reads link.bus as before.

None
titlestr

The card's panel_header.

'Targets'
iconstr

The card's panel_header.

'Targets'
widget_idstr

Scope for this card's processes and popouts. Defaults to title.

''

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
NameTypeDescriptionDefault
ValueError

If no target is called name.

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
NameTypeDescriptionDefault
detailsMapping[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

TargetPanel

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

NameTypeDescriptionDefault
labelstr

Plot label shown above the scatter.

sizetuple[float, float]

Plot size in UI-scaled pixels, by default (-1, 300). Nonpositive dimensions fill the available space, reserving the legend.

(-1, 300)
marker_sizefloat

Marker radius in UI-scaled pixels, by default 3.0.

3.0
widget_idstr | None

Explicit ImGui id scope, defaulting to label. Supply distinct ids for instances with the same visible label.

None
show_titlebool

Show the panel header, by default True. The plot itself has no title.

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
NameTypeDescriptionDefault
pointsnp.ndarray

Point coordinates of shape (n_points, 2).

labelsnp.ndarray | None

Per-point integer class labels for coloring. If omitted, all points share a single series.

None
class_nameslist[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

NameTypeDescriptionDefault
labelstr

Plot label shown above the scatter.

sizetuple[float, float]

Plot size in UI-scaled pixels, by default (-1, 400). Nonpositive dimensions fill the available space, reserving the legend.

(-1, 400)
axis_namestuple[str, str, str]

Names for the X, Y and Z axes, by default ("X", "Y", "Z").

('X', 'Y', 'Z')
widget_idstr | None

Explicit ImGui id scope, defaulting to label. Supply distinct ids for instances with the same visible label.

None
show_titlebool

Show the panel header, by default True. The plot itself has no title.

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
NameTypeDescriptionDefault
pointsnp.ndarray

Point coordinates of shape (n_points, 3).

labelsnp.ndarray | None

Per-point integer class labels for coloring. If omitted, all points share a single series.

None
class_nameslist[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

NameTypeDescriptionDefault
labelstr

Plot label shown above the heatmap.

sizetuple[float, float]

Plot size in UI-scaled pixels, by default (-1, 300). Nonpositive dimensions fill the available space.

(-1, 300)
label_fmtstr

Printf-style format for the per-cell value labels, by default "%.1f".

'%.1f'
colormapint | None

An implot.Colormap_ value. None (default) uses viridis — a perceptually-uniform map suited to continuous values (ImPlot's own default, "Deep", is categorical and misleads on a heatmap). Pass e.g. implot.Colormap_.rd_bu for signed / diverging data.

None
widget_idstr | None

Explicit ImGui id scope, defaulting to label. Supply distinct ids for instances with the same visible label.

None
show_titlebool

Show the panel header, by default True. The plot itself has no title.

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
NameTypeDescriptionDefault
datanp.ndarray

2D array of values to render, row-major (row 0 is drawn at the top).

x_tick_labelslist[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_labelslist[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
vrangetuple[float, float]

Explicit (min, max) for the colour mapping. None (default) maps this frame's own data.min()/.max(). Pass a shared range whenever several heatmaps are meant to be compared — with per-instance autoscaling a quiet grid and a loud one render identically — or a fixed one to stop colours drifting frame to frame.

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

NameTypeDescriptionDefault
labelstr

Plot label shown above the lines.

sizetuple[float, float]

Plot size in UI-scaled pixels, by default (-1, 200). Nonpositive dimensions fill the available space, reserving the legend.

(-1, 200)
widget_idstr | None

Explicit ImGui id scope, defaulting to label. Supply distinct ids for instances with the same visible label.

None
show_titlebool

Show the panel header, by default True. The plot itself has no title.

True
y_rangetuple[float, float] | None

Shared amplitude limits for comparisons. When supplied, start in Shared mode and offer an Auto / Shared control beside the header. None keeps automatic scaling. Limits must be finite and increasing.

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
NameTypeDescriptionDefault
datanp.ndarray

Samples of shape (n_samples,) or (n_samples, n_channels).

channel_nameslist[str] | None

Per-channel legend names. Falls back to ch{i} when omitted.

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

NameTypeDescriptionDefault
hzfloat

Sample rate forwarded to filters that need it (e.g. one_euro). Set it to the rate your predictions actually arrive at, or the smoothing is tuned for the wrong timebase.

50.0
widget_idstr

ImGui id scope — give each instance a unique value if you render more than one.

'output_filter'
compactbool

True (the default) shows Smoothing, the filter, mono latency and a settings popover for parameters and Reset. In narrow cells the combo takes its own row. False shows the full POST-PROCESSING panel.

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.

FilterControl

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

NameTypeDescriptionDefault
filtersSequence[FilterSpec]

Ordered palette of [FilterSpec][]. Defaults to the three built-ins (BUILTIN_FILTERS).

BUILTIN_FILTERS
hzfloat

Sample rate forwarded to filters that need it (e.g. one_euro).

50.0
defaultstr | None

key of the filter selected on start. None selects the first.

None
titlestr

Panel header text.

'FILTER'
widget_idstr

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

NameTypeDescriptionDefault
keystr

Stable identifier (e.g. "one_euro") — used for default= selection and ImGui id scoping. Distinct from the display name.

namestr

Button label shown in the panel (e.g. "One Euro").

buildCallable[..., VectorFilter]

Factory build(*, hz, **params) -> VectorFilter — constructs the filter from the current parameter values.

paramstuple[FilterParam, ...]

Tunable sliders. Empty for a fixed filter (e.g. identity).

()
descriptionstr

Muted description shown above the parameter controls.

''
reconfigureCallable[..., VectorFilter] | None

Optional in-place update reconfigure(current, *, hz, params) -> VectorFilter. When set, live tuning mutates the existing filter (preserving its smoothing history) instead of rebuilding it. Return the same object (or a replacement). None -> rebuild via build.

None
delayCallable[[float, Mapping[str, Any]], float] | None

Optional delay(hz, params) -> float returning the filter's latency estimate in milliseconds — shown live in monospace. None (e.g. a passthrough) displays zero delay.

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

NameTypeDescriptionDefault
keystr

Keyword name passed to the spec's build / reconfigure.

labelstr

Slider label shown in the panel.

minfloat

Slider bounds and initial value. min <= default <= max.

maxfloat

Slider bounds and initial value. min <= default <= max.

defaultfloat

Slider bounds and initial value. min <= default <= max.

kindLiteral['int', 'float']

"int" (uses an integer slider) or "float".

'float'
fmtstr

ImGui display format; a sensible default is used per kind.

''
logbool

Logarithmic slider (float only) — handy for wide ranges like beta.

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

NameTypeDescriptionDefault
featuresdict[str, FeatureFn]

Ordered map of feature name → callable. Each callable takes an EMG window (n_channels, n_samples) and returns an array - typically (n_channels, n_features_out) for time-preserving features like sliding RMS, but any consistent shape works as long as every active feature returns the same shape (they're concatenated along axis 0 by __call__).

defaultIterable[str] | None

Optional iterable of feature names to start active. None (default) activates every feature; an empty list activates none.

None
show_headerbool

Render the standard panel header.

True

Raises

NameTypeDescriptionDefault
ValueError

if a name in default isn't in features.

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.

FeatureSelector

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

NameTypeDescriptionDefault
widget_idstr

Stable identity string. Two inspectors with the same widget_id share selection and gesture-filter state; different widget_ids are independent.

titlestr

Header text shown above the table.

'Templates'
heightfloat

Table height at UI scale 1.0, scaled with the rest of the interface.

240.0
label_colorsdict[str, tuple[float, float, float, float]] | None

Optional {label_text: (r, g, b, a)} identity colours for gesture dots and tag tints. Unmapped labels use PALETTE in sorted label order. Tag text always follows the active theme, including with caller colours.

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

NameTypeDescriptionDefault
keystr

Stable identity (e.g. "<session>#<trial_idx>"). The widget uses this for selection and for ImGui id disambiguation.

labelstr

Short class/category badge (e.g. "OPEN" / "CLOSED").

acceptedbool

Mutable. True = include in training. Toggled in place by the kept/out chip, or the All / None buttons.

True
info_textstr | None

Optional secondary text shown in the table (e.g. session name, source path). May be None.

None
energyfloat | 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 hides the bar.

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

NameTypeDescriptionDefault
widget_idstr

Stable identity string for ImPlot (combined into plot ids so two TrialPreview instances in the same frame don't collide).

data_layoutLiteral['channels_first', 'samples_first']

"channels_first" (default) treats data as (n_channels, n_samples); "samples_first" as (n_samples, n_channels).

'channels_first'
titlestr | None

Header above the plot; None uses "Trial preview". Pass an empty string to hide the inline header.

None
sizetuple[float, float]

ImPlot size as (width, height) at UI scale 1.0. Positive dimensions scale with the UI; -1 width fills the available region.

(-1.0, 240.0)
channel_nameslist[str] | None

Optional per-channel labels. When omitted, channels are shown as ch0..chN-1.

None
bandtuple[float, float] | None

Optional (t_start_s, t_end_s) shaded band drawn behind the traces — useful for marking an extracted template, highlighting a labeled segment, etc.

None
band_colortuple[float, float, float, float] | None

RGBA in [0,1]. Defaults to the shared TRIAL_BAND token.

None
gainfloat

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_filterLiteral['none', 'rectify', 'dc_removal', 'rms_env']

Visual-only transform applied to a copy of data before plotting. Same vocabulary as signal_viewer's display dropdown.

'none'
scale_modeLiteral['auto', 'manual']

"auto" (default) computes the per-lane height from the signal's global min/max with 20% padding; "manual" uses y_range directly.

'auto'
y_rangetuple[float, float]

(y_min, y_max) used in manual scale mode.

(-1.0, 1.0)
as_windowbool

When True, the widget wraps itself in a free-floating ImGui window with title title. When False (default), it draws inline at the current cursor position.

False

ui

ui(data: np.ndarray, fs: float) -> None

Render stacked multi-channel waveform with optional band overlay.

Parameters
NameTypeDescriptionDefault
datanp.ndarray

Multi-channel signal. Shape (n_channels, n_samples) if data_layout == "channels_first" (default) or (n_samples, n_channels) if "samples_first".

fsfloat

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

NameTypeDescriptionDefault
titlestr

Window title — also used as the ImGui id and as the dedup key for repeated calls.

gui_fnCallable[[], None]

Zero-arg callable invoked by ImGui every frame. Treat it like the body of a with imgui.begin(...): — call imgui/ implot from inside.

default_openbool

Initial visibility of the window on first launch. Subsequent launches restore from .imgui_state.

True
can_be_closedbool

Whether the user can close the window with the X button. Closed windows reappear via the "View" menu.

True
remember_is_visiblebool | 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

NameTypeDescriptionDefault
streamstr

Acquisition stream to describe, by default "emg".

'emg'
sessions_dirstr or Path

Root of the participant folders, by default "data".

'data'
pipelinePipeline or None

Read model and last_saved_model for a right-aligned model readout. Without a pipeline, no model text is drawn.

None
widget_idstr

Stable ImGui identity, by default "status_bar".

'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
NameTypeDescriptionDefault
ctxContext

Acquisition state and the participant whose folder is displayed.

StatusBar

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

NameTypeDescriptionDefault
selectablebool

Connect opens a popover of discovered outlets when the source supports discover(). Otherwise it reconnects the configured source directly.

True
show_headerbool

Render the standard Streams header, state dot and rescan action.

True
widget_idstr | 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

NameTypeDescriptionDefault
heightfloat

Panel height in pixels. Pass a value <= 0 (default) to fill the remaining vertical space of the parent cell — matches the ImGui convention where -1 means "fill available".

-1.0
titlestr

Header label (only shown when show_header=True).

'Log'
show_headerbool

Render the button-style panel_header above the log.

True
widget_idstr | None

Optional per-instance ImGui id scope. Defaults to title.

None

ui

ui(ctx: Context) -> None

Render the app log.

Parameters
NameTypeDescriptionDefault
ctxContext

App context; reads from ctx.logs.

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

NameTypeDescriptionDefault
titlestr

Muted application title. Without steps, long titles ellipsize and show their full text on hover; with steps, the title yields to navigation.

stepsStepBar or None

Workflow navigation, by default absent.

None
participantParticipantPanel or None

Participant selector, by default absent. Its chip yields to the state.

None
show_statebool

Show the context's state at the right edge, by default True.

True
widget_idstr

Stable ImGui and instance-local measurement identity, by default "app_header". Use distinct IDs for headers in the same window.

'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
NameTypeDescriptionDefault
ctxContext

Live participant and application state.

donelist[bool] or None

One completion flag per step. None marks all steps incomplete. Ignored when no StepBar was supplied.

None
Returns
NameTypeDescriptionDefault
int or None

The active step, including a click made this frame, or None.

AppHeader

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

NameTypeDescriptionDefault
assetstr

Path to the image, relative to MyoGestic's registered assets folder (resolved via HelloImGui's asset system).

max_sizefloat | None

Optional cap on the rendered width in pixels. None (default) lets the image grow to fill the cell.

None
paddingfloat

Margin in pixels reserved on every side. Default 12 px.

12.0
missing_labelstr | None

Text shown (muted) when the asset can't be found. Defaults to "(image asset missing: <asset>)".

None
widget_idstr | None

Optional per-instance ImGui id scope. Defaults to asset.

None

ui

ui() -> None

Render the image asset fit-to-cell, aspect-preserving, centred.

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

NameTypeDescriptionDefault
variantLiteral['stacked', 'line']

"stacked" (default) for the full logo, or "line" for the one-line wordmark.

'stacked'
heightfloat | 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 max_size and padding. Pass ui_px(26) from myogestic.widgets.common for a scaled header. None (default) keeps the fit-to-cell behaviour.

None
max_sizefloat | None

Optional cap on the wordmark's width in pixels. None (default) lets it grow to fill the cell — appropriate for a dedicated branding cell. Pass a value when the cell can be much larger than the wordmark should ever appear (e.g. a full-screen splash).

None
paddingfloat

Margin in pixels reserved on every side. Default 12 px gives the wordmark breathing room against the panel border.

12.0
widget_idstr | None

Optional per-instance ImGui id scope.

None

ui

ui() -> None

Draw the chosen logo, or the display text wordmark if it is missing.

app_logo

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

NameTypeDescriptionDefault
pipelinePipeline

The Pipeline whose predictions to read. Untrained or first-frame state (predictions == {}) renders as a muted "—".

class_namesSequence[str]

Class names indexed the same way as the model — class_names[i] is the name for class index i.

class_keystr

Dict key in predictions holding the class index. Default "class" matches the convention in the bundled examples.

'class'
probability_keystr

Dict key holding the per-class probability vector, consumed only when show_probability is on.

'proba'
titlestr

Card identity and tooltip text.

'Prediction'
show_probabilitybool

When True, render one thin categorical bar and mono percentage for every class below the name.

False
font_scalefloat

Multiplier applied to the class name's text size. Defaults to 2× the panel font.

2.0
widget_idstr | None

Optional per-instance ImGui id scope. Defaults to title.

None

ui

ui() -> None

Render the prediction or idle reason.

Probability bars share a fixed 0–1 range.

prediction_label

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

NameTypeDescriptionDefault
clientRecordingClient

The myogestic.remote.RecordingClient used to fetch control-hand state (available movements, the current one, whether a recording trajectory is running).

on_movementCallable[[str], None]

Click handler for a movement button — required. Wire it to a discrete DOF, e.g. lambda s: bus.select("gesture", s) — the states come from the target's manifest, so pass one of those names through. There is deliberately no default: dispatching straight at the target would bypass the DOF's debounce, which is the only thing protecting a classifier-driven session from state chatter.

min_interval_sfloat

Minimum seconds between background state refreshes. Default 1 s.

1.0
titlestr

Panel header text rendered above the wrapping movement chips.

'Hand movements'
widget_idstr | 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.

VhiMovementPanel

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

NameTypeDescriptionDefault
gesturesSequence[str]

Non-empty gesture names. The exposed index addresses this exact sequence.

on_recordCallable[[], None]

Start and stop callbacks, usually app.start_recording and app.stop_recording. The app may wrap these to start/stop prediction.

on_stopCallable[[], None]

Start and stop callbacks, usually app.start_recording and app.stop_recording. The app may wrap these to start/stop prediction.

driveCallable[[int, float], Any] | None

Called with (gesture_index, level) on a dedicated daemon thread. Push the operator hand's bus here; keep it separate from prediction's bus. Exceptions are logged once per run and subsequent steps keep running. Supply exactly one of drive and operator.

None
operatorControlLink | 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
aliasesSequence[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.

()
posesSequence[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.

()
restSequence[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.

()
hzfloat

Finite, positive drive rate in Hz; defaults to 32.

32.0
trajectorySinusoid | None

Initial editable shape; defaults to Sinusoid.

None
prediction_streamstr

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 prediction alias. Apps with pose vectors should record a projected scalar level as an event stream and select its channel here.

'controls'
prediction_channelstr

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 prediction alias. Apps with pose vectors should record a projected scalar level as an event stream and select its channel here.

'controls'
max_lag_sfloat

Finite, non-negative correlation search radius.

1.0
widget_idstr

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

NameTypeDescriptionDefault
move_sfloat

Positive seconds for each smooth movement.

2.0
hold_high_sfloat

Non-negative seconds at the peak and relaxed endpoints.

2.0
hold_low_sfloat

Non-negative seconds at the peak and relaxed endpoints.

2.0
peakfloat

Fraction of the gesture, between zero and one.

1.0
repsint

Positive integer number of cycles.

5
lead_sfloat

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

NameTypeDescriptionDefault
relaxedArrayLike

One-dimensional pose vectors in the app's own control units.

gestureArrayLike

One-dimensional pose vectors in the app's own control units.

levelfloat

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

NameTypeDescriptionDefault
t_targetArrayLike

Strictly increasing finite timestamps in the same clock domain.

t_predArrayLike

Strictly increasing finite timestamps in the same clock domain.

targetArrayLike

Scalar levels paired with those timestamps. Non-finite levels are discarded.

predArrayLike

Scalar levels paired with those timestamps. Non-finite levels are discarded.

start_sfloat | 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_sfloat | 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_sfloat

Non-negative search radius for normalised cross-correlation.

1.0
step_sfloat

Positive interpolation step in seconds, also the lag resolution.

0.01

Returns

NameTypeDescriptionDefault
dict

rmse and Pearson r at zero lag, plus lag_s at the largest normalised cross-correlation (positive means prediction follows target). A lag needs at least three samples and half the common interval in overlap; ties prefer the smallest absolute lag. Undefined metrics are None. Constant signals can have an RMSE but no correlation or lag.

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:

Python
from myogestic import App
from myogestic.controls import Capability, ControlLink, ControlLinkConnector, load_control_map
from 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.connected
assert 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 None
binder.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.