Reference
Core API
App lifecycle
App
App(
name: str,
theme: bool = True,
docking: bool = False,
ui_scale: float | None = None,
require_participant: bool = False,
)
Top-level application object.
Owns the GUI loop, the Context, the run-loop lifecycle hooks, and
the recording state machine.
Construct one per process. Register streams via app.streams(...),
register your UI via @app.ui, then call app.run(). Optional
extensions like Pipeline(app) register themselves via
app.before_run_hooks / app.cleanup_hooks. User code rarely needs to
modify those lists directly.
On desktop, ImGui multi-viewport is on by default. Floating windows, including
the signal viewer's channel-grid Edit… window, use native OS windows with
square corners and opaque backgrounds. Browser mode skips multi-viewport
because it has no backend for extra OS windows.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
name | str |
Window title. Also used for the persisted ImGui state
file ( | |
theme | bool |
Apply MyoGestic's built-in ImGui theme. Set | True |
docking | bool |
Enable experimental ImGui docking in a full-screen dockspace so panels
registered via | False |
ui_scale | float | None |
Fixed UI zoom factor for fonts, imgui style metrics including padding,
spacing and rounding, and every | None |
require_participant | bool |
Require | False |
Examples
>>> from myogestic import App>>> app = App("EMG demo")>>> @app.ui... def ui(ctx):... pass>>> app.run()streams
streams(*streams: Stream) -> None
Register one or more streams with the app.
Each stream is keyed by its name into ctx.streams.
Acquisition threads start when app.run() is called, not at
registration time. Calling this with the same name overwrites
the previous registration - typically you call it once at setup.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
*streams | Stream |
One or more [ | () |
add_stream
add_stream(stream: Stream) -> bool
Register a stream, and start it if the app is already running.
Pairs with remove_stream for runtime
device changes. Before run, behaves like streams with a return value.
While running, also calls Stream.start; run starts registered streams
once during startup.
Refused while recording, and refused for a name already taken. A session
sizes one Zarr array per stream at start_recording, so a stream that
appears afterwards has nowhere to write; and overwriting a live name
would strand the running acquire thread of whatever it replaced.
Returns
| Name | Type | Description | Default |
|---|---|---|---|
| bool |
|
remove_stream
remove_stream(name: str) -> bool
Stop a stream and unregister it.
Stops the acquire thread and disconnects the source, then drops the name
from ctx.streams. Widgets look it up by name each frame and report
it missing without failing.
Refused while recording: stop_recording walks ctx.streams to detach
the session, so a stream removed mid-take would keep the session
attached and never be finalized.
Returns
| Name | Type | Description | Default |
|---|---|---|---|
| bool |
|
bridges
bridges(*bridges: Any) -> None
Register one or more Bridge subprocesses with the app.
Bridges run webcam, ultrasound or depth-camera acquisition in separate
processes and publish LSL clock streams that the app subscribes to.
Registration does not start them. Call bridge.start() yourself,
unlike [streams][]. Each bridge is stored in
ctx.bridges by .name; the same name overwrites.
Bridges have no automatic UI. Use bridge.status and bridge.alive
to display their state.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
*bridges | Any |
One or more bridge instances - each must expose a
| () |
ui
ui(fn: Callable[[Context], None]) -> Callable[[Context], None]
Decorator. Register the render callback.
@app.ui def my_ui(ctx): imgui.text(f"State: {ctx.state}")
popout
popout(
title: str,
gui_fn: Callable[[], None],
*,
default_open: bool = True,
can_be_closed: bool = True,
remember_is_visible: bool | None = None,
) -> None
Register a dockable window before run().
Prefer this over popout_panel(...) inside @app.ui. It gives Hello
ImGui the complete DockableWindow list before launch.
Calls to popout_panel(...) inside @app.ui register on the first frame.
start_recording
start_recording(base_path: str = 'data') -> None
Begin recording all connected streams to a new session.
Creates base_path/<ID>/recordings/<ID>_<timestamp>/, or
.../predictions/... when the take starts while a model is
predicting, writes initial metadata marked finished=False, and starts appending each
stream's data + timestamps to per-stream Zarr arrays. Streams
whose info is still None (disconnected) are skipped -
they won't be retroactively captured if they connect later in
the recording. Refuses to start while a take is already open or
when ctx.state is not in RECORDABLE_STATES; updates
ctx.status_message with the result.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
base_path | str |
Data root holding one folder per participant. Defaults to
| 'data' |
stop_recording
stop_recording(*, wait: bool = False) -> None
Stop the active recording and pack the session to a .mg.zip.
Detaches every stream and freezes the session on the calling thread, then on a
daemon thread runs finalize_hooks, updates meta.json with finished=True
and writes labels.json,
packs the folder into <ID>_<YYYYMMDD-HHMM>_<what>.mg.zip (the folder is kept
until the pack succeeds) and registers the archive with the session browser.
wait=True runs this inline for tests or shutdown, where a daemon could
exit before packing finishes. Refuses if no recording is open.
discard_recording
discard_recording() -> None
Stop the active recording and delete it, unsaved and unpacked.
The counterpart to stop_recording for a
take the operator discards, such as a false start or bad trial. Detaches every
stream, removes the session folder, and returns the state to "idle" when
the take was started from idle (a take under "predicting" leaves the state
alone). Removes the take's arrays and initial metadata without producing an
archive, so a discarded recording leaves no trace to clean up later.
Refuses if no recording is open.
run
run(
mode: str = 'gui',
window_size: tuple[int, int] = (1280, 800),
fullscreen: bool = False,
) -> None
Blocking entry point.
On macOS, GUI startup waits for an active display before starting streams or hooks. Unlock or wake the screen to continue; Ctrl+C cancels the wait without starting app resources. Headless mode does not need a display.
Call tree (top → bottom = runtime order):
App.run()├─ 1. Stream.start() per stream → daemon acquire thread├─ 2. before_run_hooks(app) extensions register here│ └─ e.g. myogestic.ml.attach_pipeline → starts predict thread├─ 3. self._gui_loop() ← main thread, BLOCKS│ └─ immapp.run → per frame: self._ui_fn(self.ctx) (your @app.ui)└─ 4. [finally] cleanup - always runs, even on startup failure ├─ cleanup_hooks(app) each wrapped in try/except ├─ stop_recording(wait=True) if a take is open ├─ wait for pending saves (up to 30 seconds) ├─ Stream.stop() per stream ├─ Bridge.stop() per bridge └─ process_launcher._cleanup_all()Core has only idle ↔ recording. myogestic.ml.attach_pipeline(app) adds
training/predicting states + their transition methods.
AppState
Bases: StrEnum
Core app-state values. myogestic.ml.PipelineState adds ML states.
Context.state is a bare str so extensions can introduce their own states
without subclassing. Each module validates transitions within its own
namespace only.
Examples
>>> from myogestic import AppState>>> AppState.RECORDING.value'recording'Context
Context(
streams: dict[str, Stream] = dict(),
bridges: dict[str, Any] = dict(),
state: str = AppState.IDLE,
session: Session | None = None,
recording: bool = False,
pending_saves: set[Path] = set(),
class_names: list[str] = list(),
class_codes: dict[str, str] = dict(),
control_space: Any = None,
control_spaces: dict[str, Any] = dict(),
current_label: int = -1,
status_message: str = '',
logs: list[str] = list(),
notifications: list[Notification] = list(),
participant: str = '',
require_participant: bool = False,
finalize_hooks: list[Callable[[Session], None]] = list(),
) -> None
Shared state all threads read/write.
Extensions may add own fields dynamically on the owning App, but
Context itself is core-only.
Attributes
| Name | Type | Description | Default |
|---|---|---|---|
streams | dict[str, Stream] |
Registered | |
bridges | dict[str, Any] |
Registered remote-target bridges keyed by name. Start them explicitly;
see | |
state | str |
The recording state machine: | |
session | Session | None |
The | |
recording | bool |
| |
pending_saves | set[Path] |
Source folders still being finalized. Nonempty until every pending pack has registered its saved take or reported failure. | |
finalize_hooks | list[Callable[[Session], None]] |
The owning | |
participant | str |
Pseudonymized ID used to label new recordings; empty when none is set. | |
require_participant | bool |
Refuse recording until a participant ID is set. Recording widgets mirror this opt-in gate with a disabled Record button. | |
class_names | list[str] |
Names for the label class indices, mirrored here by the recording
widgets so | |
class_codes | dict[str, str] |
Codes this app fixes for some classes in its file names, by class name
( | |
control_space | Any |
Optional | |
control_spaces | dict[str, Any] |
Additional control maps keyed by recording stream name, populated by
| |
current_label | int |
Class index a label click would record right now; | |
status_message | str |
One line of transient status, written by the recording lifecycle. | |
logs | list[str] |
The app-event lines | |
notifications | list[Notification] |
Corner toasts drawn by the |
Examples
>>> from myogestic import Context>>> ctx = Context()>>> ctx.status_message = "Ready">>> ctx.status_message'Ready'notify
notify(title: str, detail: str = '', kind: str = 'info') -> None
Show a corner toast and mirror it to the app log, from any thread.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
title | str |
Short description of the event. | |
detail | str |
Optional supporting text, such as a saved archive's name. | '' |
kind | str |
| 'info' |
Raises
| Name | Type | Description | Default |
|---|---|---|---|
| ValueError |
If |
log
log(message: str, max_lines: int = 500) -> None
Append a one-line app event for the log_panel widget.
Bounded to max_lines, dropping the oldest entry. Use for lifecycle
events such as recording saves, training start/done and model loads. Do not
log per-frame messages. Safe from any thread because list.append/pop
are GIL-atomic.
Stream
Stream(
name: str,
source: Source,
window_ms: float,
buffer_ms: float = 10000,
notch_hz: int = 0,
)
A named ring-buffered live stream backed by a [Source][].
Pair a name ("emg") with a source (LSLSource("TestEMG1")) and a
window duration, register it with app.streams(...), and the rest of
the framework addresses it by stream name.
- Nothing attaches on its own. Call
reconnect— or press the button in aStreamPanel— and the source is opened once. The acquire loop never opens one for you, on the first tick or after a source goes away, so a stream left running by an earlier process is never picked up behind you. - One daemon acquisition thread is started per Stream when
App.run()begins. Once attached it loopssource.read(), appends to the ring buffer and, if a recording session is active, appends to the session's Zarr store. Display and prediction consumers copy only the bounded tail they request. Until attached it waits. - [
get_window][] and [get_display][] are then readable concurrently from other threads. - The ring buffer holds the last
buffer_msof samples so transient consumers (slow extract, momentary GUI hitches) don't lose data.
Examples
>>> from myogestic import App, Stream>>> from myogestic.sources import LSLSource>>> app = App("hello")>>> app.streams(... Stream("emg", source=LSLSource("TestEMG1"),... window_ms=1000, buffer_ms=10000),... )See Streams concept for the buffer + decimation model in depth, and Add a custom source for the matching source-side contract.
Live ring-buffered stream with display decimation.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
name | str |
Stream label (also used as the recorded zarr stream key). | |
source | Source |
Anything implementing the [ | |
window_ms | float |
Duration in milliseconds of the window returned
by [ | |
buffer_ms | float |
Ring-buffer depth in milliseconds. Defaults to 10000 (10 s). | 10000 |
notch_hz | int |
Mains frequency to notch out of the acquired signal — This conditions the samples themselves, so it reaches the model's windows and the recording, which is the point: train and predict then cannot see different preprocessing. It is not the signal viewer's Notch, which changes only what is drawn. A recording made with this on holds filtered samples and the raw is not recoverable, so a session's setting is worth storing beside it — training on a mix of filtered and unfiltered takes is a silent inconsistency. | 0 |
reconnect
reconnect(target: str | None = None) -> bool
Reconnect source. Optionally switch to a different target.
Uses the source's own reconnect() if it has one (preserving
source-specific logic like LSL resolve or serial port open), else
disconnect + connect. Either way the source is connected ONCE, then
buffers are (re)allocated from the returned StreamInfo.
One attempt at a time. A second caller while one is in flight is refused rather than queued: an app can offer more than one way to connect a stream (a device picker, a viewer's own button), and two attempts racing used to interleave — the queued one would wake up inside the lock and re-run against whatever source the first had since swapped in, reconnecting a live source out from under the buffers.
The source is connected outside self._lock. That lock is taken by
the acquire loop and by every render-side read, while an OTB
accept() blocks for accept_timeout — 30 s by default. Holding it
across the attempt froze the whole GUI for as long as a device took to
answer, or to not answer. It is now taken twice and briefly: once to
mark the stream detached, once to publish the new buffers.
disconnect
disconnect() -> None
Detach the source, leaving the acquire loop running and idle.
The counterpart to [reconnect][]. Not stop: that ends the
acquire thread, which App.run starts once and owns — a stream stopped
that way could not be brought back from the UI.
info is cleared along with the connection. A stream that was
deliberately detached has no geometry, and leaving the old one behind
makes a viewer report the connection as lost rather than as closed on
purpose.
start
start() -> None
Start the acquisition loop (a daemon thread, or a per-frame task in the browser).
stop
stop() -> None
Stop the acquisition loop and disconnect the source (errors suppressed).
attach_session
attach_session(session: Session) -> None
Begin recording this stream into session.
Called by [App.start_recording][]. Set under _session_lock
so the acquire loop sees a fully-attached session atomically.
detach_session
detach_session() -> None
Stop recording this stream (called by App.stop_recording).
Waits for any append in flight on the acquire thread and blocks further ones, so once this returns the caller may finalise/clear the session's Zarr stores without racing the acquire loop.
get_window
get_window() -> tuple[np.ndarray, np.ndarray]
Return the most recent window_ms as (data, ts).
data is channels-first (n_channels, n_samples) and
always float32, whatever dtype the stream buffers in. ts is a
view into a reusable per-stream buffer; for a float32 stream data
is a view too, otherwise a fresh float32 copy. Copy explicitly to
retain either past the next call.
get_display
get_display(n_pixels: int = 800) -> tuple[np.ndarray, np.ndarray] | None
M4-decimated display snapshot, computed on demand on the render thread.
Recomputed per call from the current display buffer; the acquire thread must not precompute it (it starves the socket read at high channel counts).
get_raw_snapshot
get_raw_snapshot() -> tuple[np.ndarray, np.ndarray] | None
Return an on-demand full, contiguous ring snapshot.
Prefer :meth:get_raw_snapshot_stable with duration_s for live
widgets; this compatibility API necessarily copies the whole buffer.
get_raw_snapshot_stable
get_raw_snapshot_stable(
duration_s: float | None = None,
) -> tuple[int, int, float, np.ndarray, np.ndarray] | None
Locked copy of the (tail of the) display snapshot, tagged with buffer identity.
Like [get_raw_snapshot][] but returns arrays the acquire thread cannot
overwrite, for render-side consumers carrying state across frames (the
incremental display notch): the copy so a concurrent buffer refresh cannot
tear the samples being filtered (a torn read poisons the IIR state
permanently), (epoch, end_seq) to tell new samples from seen ones and
detect a reallocation, and fs so the rate matches the copied samples —
reading stream.info.fs separately can race a reconnect.
duration_s copies only the newest duration_s seconds instead of the
whole buffer (a 60 s buffer at 10 kHz is ~40 MB per frame). The trim uses the
locked fs. end_seq stays absolute, so the returned data[i] has
sequence end_seq - len(data) + i.
Returns (epoch, end_seq, fs, ts, data) or None if fewer than 2 samples
are buffered (or the stream is not connected).
last_timestamp
last_timestamp() -> float | None
Most recent sample timestamp, or None if no samples yet.
Reads the ring tail under _lock, so a concurrent reconnect or append
cannot strand the read on a torn buffer.
StreamInfo
StreamInfo(
n_channels: int,
fs: float,
dtype: np.dtype = np.dtype(np.float32),
channel_names: list[str] | None = None,
channel_grids: list[ChannelGrid] | None = None,
) -> None
Describes the shape and dtype of a [Source][]'s data.
Returned by [Source.connect][]; sizes the ring buffer and lays out
the signal viewer.
Attributes
| Name | Type | Description | Default |
|---|---|---|---|
n_channels | int |
Channel count. Fixed for the life of the source. | |
fs | float |
Sample rate in Hz. Used to convert | |
dtype | np.dtype |
NumPy dtype of each sample, one of | |
channel_names | list[str] | None |
Optional per-channel labels for the signal viewer
legend. | |
channel_grids | list[ChannelGrid] | None |
Optional list of |
Examples
>>> from myogestic import StreamInfo>>> info = StreamInfo(8, 2048.0, dtype="int16")>>> (info.n_channels, info.fs, info.dtype.name)(8, 2048.0, 'int16')TrainingData
TrainingData(
paths: list[str] = list(),
class_names: list[str] = list(),
classes: set[int] = set(),
) -> None
Inputs delivered to the user's @pipeline.train callback.
Built by session_manager() and assigned by the user to
pipeline.training_data from inside @app.ui::
@app.uidef ui(ctx): pipeline.training_data = session_manager(...)Attributes
| Name | Type | Description | Default |
|---|---|---|---|
paths | list[str] |
Session locations (folders or | |
class_names | list[str] |
Human-readable labels — same list passed to
| |
classes | set[int] |
Active class indices to include. Pass as the |
Examples
>>> from myogestic import TrainingData>>> data = TrainingData(... paths=["sessions/demo.mg.zip"],... class_names=["Rest"],... classes={0},... )>>> data.is_emptyFalseis_empty
is_empty: bool
True when no session paths have been assigned yet.
Layout
Grid
Grid(
rows: int,
cols: int,
row_height: list[Track] | None = None,
col_width: list[Track] | None = None,
)
Grid layout manager. Index with [row, col] or [row, col_start:col_end].
Both axes accept the same Px/Fr track specs. See module docstring for examples.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
rows | int |
Number of rows. | |
cols | int |
Number of columns. | |
row_height | list[Track] | None |
Per-row track specs (length must equal | None |
col_width | list[Track] | None |
Per-column track specs (length must equal | None |
Raises
| Name | Type | Description | Default |
|---|---|---|---|
| ValueError |
if a list length doesn't match | |
| TypeError |
if a track entry isn't Px, Fr, or a number. |
Examples
>>> from myogestic import Fr, Grid, Px>>> grid = Grid(2, 3, row_height=[Px(120), Fr(1)])>>> (grid.rows, grid.cols)(2, 3)areas
areas(
template: str,
*,
row_height: list[Track] | None = None,
col_width: list[Track] | None = None,
bare: Iterable[str] = (),
) -> Grid
Create named cells from a text template; place panels with area.
One line per row, one word per cell. A name repeated across a rectangle
spans it; . leaves a cell empty; a | b | c puts tabbed panels in
one cell. Names let Layout move panels without changing widget identity.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
template | str |
The arrangement, one line per row. | |
row_height | list[Track] | None |
Per-row track specs; default all | None |
col_width | list[Track] | None |
Per-column track specs; default all | None |
bare | Iterable[str] |
Area names to draw without a border or background. Their child windows retain content clipping; short standalone rows reduce vertical padding enough to fit a control and its trailing spacing. | () |
Raises
| Name | Type | Description | Default |
|---|---|---|---|
| ValueError |
if rows differ in length, a name does not cover a rectangle, a panel
is placed twice, a track list has the wrong length, or |
Examples
>>> from myogestic import Fr, Grid, Px>>> grid = Grid.areas('''... logo signal... record signal... sessions | train signal... ''', col_width=[Px(260), Fr(1)])>>> (grid.rows, grid.cols)(3, 2)>>> sorted(grid.panel_names)['logo', 'record', 'sessions', 'signal', 'train']panel_names
panel_names: frozenset[str]
Every panel name placed by Grid.areas, tabbed ones included.
area
area(name: str) -> _AreaCell
The cell for the panel called name — use as with grid.area("record"):.
Layout
Layout(*, wide: Grid, narrow: Grid, breakpoint: Px)
Two arrangements of the same named panels, picked by window width.
Use wide at or above breakpoint and narrow below it. The breakpoint
follows the UI scale. Panels are placed by name in either arrangement.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
wide | Grid |
Arrangement for windows at least | |
narrow | Grid |
Arrangement for narrower windows (from | |
breakpoint | Px |
Window width, at scale 1.0, where the two swap. |
Raises
| Name | Type | Description | Default |
|---|---|---|---|
| ValueError |
if either grid has no named areas, or they do not place the same panels. |
Examples
>>> from myogestic import Fr, Grid, Layout, Px>>> layout = Layout(... wide=Grid.areas('''... record signal... train signal... ''', col_width=[Px(260), Fr(1)]),... narrow=Grid.areas('''... signal... record | train... '''),... breakpoint=Px(1100),... )>>> sorted(layout.panel_names)['record', 'signal', 'train']panel_names
panel_names: frozenset[str]
Every panel the layout places.
Px
Px(value: float) -> None
Fixed size. Px(300) means "300 px at UI scale 1.0".
Tracks follow the live UI scale (see App(ui_scale=...)).
Examples
>>> from myogestic import Px>>> Px(300)Px(300)Fr
Fr(value: float) -> None
Fractional unit (CSS-grid fr).
Fr(1) means "1 share of the space remaining after [Px][]
tracks are subtracted". Multiple Fr entries split the remainder
proportionally to their values, so [Fr(1), Fr(2)] splits leftover
space 1:2.
Examples
>>> from myogestic import Fr>>> Fr(2)Fr(2)Track
Track = Px | Fr
A single grid track size: either a fixed [Px][] or a fractional [Fr][].
Examples
>>> from myogestic.grid import Px, Track>>> track: Track = Px(300)Event helpers
EdgeTrigger
EdgeTrigger(callback: Callable[[T], None], *, n_stable_ticks: int = 1) -> None
Calls callback(value) only when value differs from the last fire.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
callback | Callable[[T], None] |
Invoked with the new value when an edge fires. | |
n_stable_ticks | int |
Debounce: the new value must hold for this many consecutive
[ | 1 |
Notes
Thread-safety: the typical pattern is "one writer (predict thread) +
occasional rebase() from the UI thread". The whole (last, candidate, count) state is held in one tuple replaced in a single assignment, so under
CPython's GIL no lock is needed; a race between the two callers can at worst
cost one extra suppressed-or-fired callback — harmless for the intended uses
(RPC dedup, audio-cue gating, robot-movement commands).
Examples
>>> from myogestic import EdgeTrigger>>> fired = []>>> trigger = EdgeTrigger(fired.append)>>> [trigger.fire_if_changed(v) for v in ("Rest", "Rest", "Fist")][True, False, True]>>> fired['Rest', 'Fist']fire_if_changed
fire_if_changed(value: T) -> bool
Fire the callback when value becomes a new, stable value.
Fires iff value differs from the last fired value and (when
n_stable_ticks > 1) has held for n_stable_ticks
consecutive calls. Returns True when the callback ran,
False when suppressed.
rebase
rebase(value: T) -> None
Set the "last fired" value without firing.
Discards any pending debounce candidate. Use when another code
path already performed the equivalent action; the
next different value must then earn the full n_stable_ticks count, so
a flicker candidate in progress can't complete on top of the manual one.
last
last: T | None
The most recently fired (or rebased) value; None before first fire.
Built-in features
features
Classic time-domain EMG features — the starter set every example used to copy-paste.
Use as-is, mix with your own, or replace entirely::
from myogestic.recipes.features import rms, mav, wlfrom myogestic.widgets import FeatureSelector
feats = FeatureSelector( {"RMS": rms, "MAV": mav, "WL": wl, "MyCustom": my_custom_fn}, default=["RMS", "MAV"],)All take an EMG window of shape (n_channels, n_samples) and return a
per-channel scalar vector (n_channels,) of dtype float32.
rms
rms(emg: np.ndarray) -> np.ndarray
Root mean square per channel.
Examples
>>> import numpy as np>>> from myogestic.recipes.features import rms>>> emg = np.array([[1, -1], [2, -2]], dtype=np.float32)>>> rms(emg).tolist()[1.0, 2.0]mav
mav(emg: np.ndarray) -> np.ndarray
Mean absolute value per channel.
Examples
>>> import numpy as np>>> from myogestic.recipes.features import mav>>> emg = np.array([[1, -1], [2, -2]], dtype=np.float32)>>> mav(emg).tolist()[1.0, 2.0]wl
wl(emg: np.ndarray) -> np.ndarray
Waveform length per channel — sum of absolute first differences.
Examples
>>> import numpy as np>>> from myogestic.recipes.features import wl>>> emg = np.array([[1, -1], [2, -2]], dtype=np.float32)>>> wl(emg).tolist()[2.0, 4.0]var
var(emg: np.ndarray) -> np.ndarray
Variance per channel.
Examples
>>> import numpy as np>>> from myogestic.recipes.features import var>>> emg = np.array([[1, -1], [2, -2]], dtype=np.float32)>>> var(emg).tolist()[1.0, 4.0]zc
zc(emg: np.ndarray) -> np.ndarray
Zero-crossing count per channel.
Examples
>>> import numpy as np>>> from myogestic.recipes.features import zc>>> emg = np.array([[1, -1], [2, -2]], dtype=np.float32)>>> zc(emg).tolist()[1.0, 1.0]External interfaces
virtual_hand
virtual_hand(
godot_bin: str | None = None,
vhi_path: str | None = None,
grpc_host: str | None = None,
grpc_port: int | None = None,
launch_mode: str | None = None,
) -> InterfaceSpec
The MyoGestic Virtual Hand Interface (VHI).
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
godot_bin | str | None |
Path to the Godot binary, for source-mode launch. Falls
back to | None |
vhi_path | str | None |
Directory containing VHI (binary install OR Godot project).
Falls back to | None |
grpc_host | str | None |
VHI gRPC host. Falls back to | None |
grpc_port | int | None |
VHI gRPC port. Falls back to | None |
launch_mode | str | None |
Launch mode — | None |
Returns
| Name | Type | Description | Default |
|---|---|---|---|
| A `myogestic.remote.InterfaceSpec` with the resolved argv, ready to wire into | ||
| ``process_launcher()``. |
Examples
>>> from myogestic.vhi import virtual_hand>>> vhi = virtual_hand()>>> vhi.n_output_channels9InterfaceSpec
InterfaceSpec(
name: str,
process: list[str],
n_output_channels: int,
output_hz: float,
control_stream_name: str | None = None,
n_control_channels: int | None = None,
grpc_host: str = '127.0.0.1',
grpc_port: int = 50051,
install_root: Path | None = None,
install_hint: str = '',
version_gate: Callable[[], None] | None = None,
min_target_version: str | None = None,
) -> None
Description of a remote target — a separate process MyoGestic drives.
Attributes
| Name | Type | Description | Default |
|---|---|---|---|
name | str |
Human label, used as the process_launcher row title. | |
process | list[str] |
argv to spawn the target (passed to | |
n_output_channels | int |
Number of channels in the target's full pose vector — the width of the whole-pose read-back a recording consumes, not of a control's own stream. | |
output_hz | float |
Outlet send rate. | |
control_stream_name | str | None |
LSL inlet name the target publishes when the user drives it manually (used for regression targets). May be None. | |
n_control_channels | int | None |
Channel count of the control stream, if known. | |
grpc_host | str |
Host the target's gRPC control server listens on. | |
grpc_port | int |
Port the target's gRPC control server listens on. | |
install_root | Path | None |
The directory | |
install_hint | str |
Appended to that error. How this target is installed is the target's own business — an installer command, an environment variable — and a generic spec has nothing useful to say about it. | |
version_gate | Callable[[], None] | None |
Called by | |
min_target_version | str | None |
Oldest build of this target known to behave, checked against the
|
Examples
>>> from myogestic.remote import InterfaceSpec>>> spec = InterfaceSpec(... name="Hand",... process=["vhi"],... n_output_channels=9,... output_hz=32.0,... )>>> spec.launcher()[('Hand', ['vhi'])]stream_outlet
stream_outlet(name: str, *, n_channels: int | None = None) -> LSLOutlet
Construct an LSLOutlet publishing the target's stream called name.
The name is the target's, not this spec's. Which controls exist is in the
manifest a running target answers with, and a streamed control's stream is
named for that control's own address — so a stream is named where that answer is
read (myogestic.remote.RemoteTarget, which calls this once per address it
drives, after negotiation has settled), never guessed here.
Carries a stable source_id so a consumer can re-resolve this stream after a
restart. Without one, LSL cannot tell a restarted outlet from a new stream and a
consumer that resolved the old one keeps a dead inlet.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
name | str |
The stream's name, as the target's manifest reports it. | |
n_channels | int | None |
Width. | None |
Raises
| Name | Type | Description | Default |
|---|---|---|---|
| ValueError |
If |
control_client
control_client() -> RemoteClient
Construct a client for this target's control service.
Hand it to myogestic.remote.RemoteTarget and it asks the remote target which
named DOFs it drives, refusing a configuration it cannot place. Required:
without one there is nothing to negotiate the control space against.
Imported lazily — a plain install has no [grpc] extra, and
stream_outlet / launcher must keep working without it.
Examples
>>> from myogestic.controls import ControlBus, Continuous, ControlSet>>> from myogestic.remote import RemoteTarget>>> from myogestic.vhi import virtual_hand>>>>>> vhi = virtual_hand()>>> controls = ControlSet(dofs={"my_index": Continuous("my_index")})>>> target = RemoteTarget(client=vhi.control_client(), interface=vhi)>>> bus = ControlBus(controls, targets=[target])>>> target.negotiated # True once the remote end has answered, False until thenFalserecording_client
recording_client() -> RecordingClient
Construct a client for this target's recording session gate.
Not a control plane, and nothing it does is a control DOF. It carries the two things a recording session needs: the gate that stops the target's own local input competing as a movement source, and trajectories that cycle its control rig so the recorded kinematics sweep a continuous range.
Imported lazily, like the other gRPC client, so a plain install without the
[grpc] extra can still use stream_outlet / launcher.
Examples
>>> from myogestic.vhi import virtual_hand>>> aid = virtual_hand().recording_client()>>> aid.set_recording_session(True) # False when the target is unreachableFalselauncher
launcher() -> list[tuple[str, list[str]]]
Return the (name, argv) tuple list expected by process_launcher.
Raises FileNotFoundError, quoting install_hint, when nothing can be
launched from the resolved location. version_gate runs last, so an install
this MyoGestic cannot drive is refused before the process starts rather than
by every target at bind.
launchable
launchable() -> list[tuple[str, list[str]]]
Like launcher, but empty instead of raising when nothing can be launched.
For a myogestic.widgets.ProcessLauncher in an application's own UI, where an
in-app Launch button is a convenience: launcher raising there takes the whole
app down at import, even when a target is already running. This returns no rows
and logs why instead. launcher stays strict for a caller whose entire job is to
start the thing (tools/launch_vhi.py).
Examples
>>> from myogestic.vhi import virtual_hand>>> processes = virtual_hand().launchable() # [] rather than an exceptionTools
control_outlet
control_outlet(name: str = DEFAULT_CONTROL_STREAM) -> StreamOutlet
LSL outlet for steering the EMG generator from another script.
The generator listens on a stream named name for a single float
(channel = 1) that selects the next gesture amplitude — typically
0.0 (rest) … 1.0 (full). Push samples like::
from myogestic.tools.emg_generator import control_outletout = control_outlet()out.push_sample(np.array([0.0], dtype=np.float32)) # restout.push_sample(np.array([1.0], dtype=np.float32)) # fistMatches the protocol the --control flag on
python -m myogestic.tools.emg_generator listens for.
Examples
>>> import numpy as np>>> from myogestic.tools.emg_generator import control_outlet>>> outlet = control_outlet()>>> outlet.push_sample(np.array([1.0], dtype=np.float32))myogestic.tools.install_vhi
Install the Virtual Hand Interface release binary for this platform.
VHI ships pre-built artefacts on every release at
https://github.com/NsquaredLab/MyoGestic-VHI/releases. This CLI picks the
right asset for the host OS/arch, downloads it, unpacks it into the location
virtual_hand() looks at, and drops a vhi-version.txt marker so a
later install knows what's already there.
MyoGestic drives VHI over its control service, asking it what it exports. A
release older than MIN_VHI_TAG has no control manifest to answer with, so this refuses
to install one because it would fail at every launch.
Usage: python -m myogestic.tools.install_vhi # latest, default dest python -m myogestic.tools.install_vhi --tag v2.0.0 # pinned version python -m myogestic.tools.install_vhi --dest /custom/path python -m myogestic.tools.install_vhi --force # reinstall over existing
Or after pip install myogestic:
myogestic-install-vhi
Pin --tag in production for reproducible installs. latest may resolve
to a different VHI version on a later rebuild.
main
main() -> None
Console-script entry point (myogestic-install-vhi).