Get started
Anatomy of a MyoGestic app
Read this page first to see how the parts fit together in the order you write them. Open the script in your editor and read it alongside the descriptions below. The concept pages cover Streams, Pipeline, Recording and Widgets in detail.
from myogestic import App, Stream, TrainingDatafrom myogestic.ml import Pipeline, save_pickle, load_picklefrom myogestic.ml.widgets import PipelinePanelfrom myogestic.session import iter_labeled_windowsfrom myogestic.sources import LSLSourcefrom myogestic.widgets import RecordingControls, SessionManager, SignalViewerfrom sklearn.linear_model import LogisticRegressionimport numpy as np
app = App("EMG Demo")app.streams(Stream("emg", source=LSLSource("EMG"), window_ms=200))
pipeline = Pipeline(app, predict_hz=20)pipeline.save_model = save_picklepipeline.load_model = load_pickle
@pipeline.extractdef extract(windows): return windows["emg"].mean(axis=1)
@pipeline.traindef train(data: TrainingData): X, y = [], [] for window, _ts, c in iter_labeled_windows(data.paths, "emg", 200, 100, classes=data.classes): X.append(extract({"emg": window})) y.append(c) return LogisticRegression().fit(np.array(X), np.array(y))
@pipeline.predictdef predict(model, features): return {"class": int(model.predict(features.reshape(1, -1))[0])}
emg_viewer = SignalViewer("emg")rec_controls = RecordingControls( ["Rest", "Fist"], on_record=app.start_recording, on_stop=app.stop_recording)sessions = SessionManager("data", class_names=["Rest", "Fist"])ml_panel = PipelinePanel(pipeline)
@app.uidef ui(ctx): emg_viewer.ui(ctx) rec_controls.ui(ctx) pipeline.training_data = sessions.ui() ml_panel.ui()
app.run()The shape
A MyoGestic app has one App object, streams, an optional Pipeline for ML, and a @app.ui callback that draws widgets every frame. app.run() starts threads and blocks on the GUI loop.
Imports, in three layers
from myogestic import App, Stream, TrainingData # the orchestrator + data primitivesfrom myogestic.ml import Pipeline, save_pickle, load_pickle # ML lifecycle layer (opt-in)from myogestic.session import iter_labeled_windows # session reading helpersfrom myogestic.sources import LSLSource # one of the built-in sourcesfrom myogestic.widgets import ( RecordingControls, SessionManager, SignalViewer,) # ImGui widget classesfrom sklearn.linear_model import LogisticRegression # YOUR ML libraryThree layers, from framework-owned to user-owned:
- Compose framework primitives from
App,Stream,PipelineandTrainingData. The framework owns these. - Add built-in capabilities from
sources,widgets,mlandsession. - Bring your own domain code with sklearn, MyoVerse, scipy or PyTorch. You own this layer.
DSP, ML models and feature extraction are user concerns. myogestic.recipes supplies optional feature functions and estimator constructors as starting points. See Design principles.
App - the orchestrator
app = App("EMG Demo")One per process. App owns the GUI loop, the shared Context, the run-loop lifecycle hooks, and the recording state machine. Construct it, attach streams and widgets with an optional pipeline, then call app.run().
Do not subclass App or define class MyApp(App):. Compose an App by attaching objects.
→ Deep dive: Architecture, Design principles.
Stream - the data plumbing
app.streams(Stream("emg", source=LSLSource("EMG"), window_ms=200))A Stream wraps a Source plus a fixed-memory ring buffer. Each stream owns one daemon acquisition thread that polls the source, appends to the buffer, and writes to a Zarr array while app.start_recording() is active. Plotting and prediction copy only their requested recent tail, so acquisition work does not grow as the history fills.
Two reads come out the other side:
stream.get_window()returns(data, timestamps), with the most recentwindow_msof data channels-first(n_channels, n_samples). This is what feature extractors and ML models consume.stream.get_raw_snapshot_stable(duration_s)returns a stable recent tail for rendering.SignalViewerrequests only its visible duration and decimates it to the live plot width.
app.streams(*streams) registers one or more. Each registered Stream wraps any Source implementation, so swapping LSLSource for offline replay with ReplaySource or your own custom source changes one line.
The stream starts detached. Start the upstream outlet and press Connect in the viewer, or call stream.reconnect() before headless acquisition.
→ Deep dive: Streams.
Pipeline - the optional ML lifecycle
pipeline = Pipeline(app, predict_hz=20)pipeline.save_model = save_picklepipeline.load_model = load_picklePipeline(app) adds:
- A predict thread that fires every
1/predict_hzseconds. - Two states,
trainingandpredicting. A take may also stay open while predicting, tracked separately byctx.recording. - Three function-decorator slots (
extract,train,predict) for your code.
Attach a Pipeline for ML. Recording and visualization work without it.
save_model / load_model are plain attribute slots. They enable the separate SaveModelButton / LoadModelButton widgets when those are added to the UI. PipelinePanel itself contains Train and Predict controls. The default save_pickle / load_pickle round-trip anything pickleable.
→ Deep dive: Pipeline.
@pipeline.extract - feature extraction
@pipeline.extractdef extract(windows): return windows["emg"].mean(axis=1)Receives a dict keyed by stream name. Each value is channels-first (n_channels, n_samples). Return the input your model needs, such as a feature vector, tuple or raw window. It becomes the features argument to predict().
The same function runs from inside train() over recorded windows, and on the predict thread over live windows.
@pipeline.train - training
@pipeline.traindef train(data: TrainingData): X, y = [], [] for window, _ts, c in iter_labeled_windows(data.paths, "emg", 200, 100, classes=data.classes): X.append(extract({"emg": window})) y.append(c) return LogisticRegression().fit(np.array(X), np.array(y))Runs on a one-shot training thread when the user clicks Train. Receives TrainingData with paths, class_names and classes populated by SessionManager. Return any object to store on pipeline.model. It remains there for later prediction calls.
iter_labeled_windows opens session folders or .mg.zip archives, reads the label track, and slices trials into overlapping windows. Write your feature extraction for these windows.
→ Deep dive: Pipeline, Recording.
@pipeline.predict - live prediction
@pipeline.predictdef predict(model, features): return {"class": int(model.predict(features.reshape(1, -1))[0])}Fires at predict_hz while the user is in Predict mode and at least one input stream has data. Return a dict[str, Any]; the result is stored in pipeline.predictions for widgets to read.
Publish to an outlet or push a ControlBus from predict() before returning. A paced outlet sends its latest value at its own rate; a target may instead deliver commands directly.
@app.ui - the rendering surface
emg_viewer = SignalViewer("emg")rec_controls = RecordingControls( ["Rest", "Fist"], on_record=app.start_recording, on_stop=app.stop_recording)sessions = SessionManager("data", class_names=["Rest", "Fist"])ml_panel = PipelinePanel(pipeline)
@app.uidef ui(ctx): emg_viewer.ui(ctx) rec_controls.ui(ctx) pipeline.training_data = sessions.ui() ml_panel.ui()The @app.ui callback runs on the main thread every frame. Its body is a flat sequence of widget calls. Call each widget’s .ui() method to draw ImGui commands from its live inputs. Its instance or identity-keyed state persists between frames.
Widget roles include
- Display widgets such as
SignalViewerrenderctx.streamsdata. - Control widgets such as
RecordingControlsandPipelinePanelcall recording, training and prediction callbacks. - Bridge widgets such as
SessionManagerreturnTrainingDataforpipeline.training_data, passing UI selection to training.
For grid layouts use Grid and with grid[r, c]:. For pop-out windows use App(docking=True) + app.popout(...).
→ Deep dive: Widgets.
app.run() - the blocking event loop
app.run()Last line of every script. In order:
- Starts each
Stream’s acquisition thread. - Fires
before_run_hooks, includingPipeline’s predict-thread startup. - Hands control to the blocking GUI event loop on the main thread.
- On window close, runs
cleanup_hooks, saves any open take inline, waits up to 30 seconds for pending saves, then stops streams, bridges and adopted subprocesses.
app.run(mode="gui") is the default. Use mode="headless" for unattended recording with threads only.
→ Deep dive: Architecture, Threading.
Driving a device
The skeleton above predicts a class index and moves no device.
Drive a prosthesis on a serial port, a motor controller, a cursor or the Virtual Hand
through a Target. It has three methods and a TOML control map
that pairs model outputs with controls.
examples/synthetic/my_device.py is a complete one with three lines left for you, and it runs
without hardware:
uv run python examples/synthetic/my_device.py→ Drive your own device. To publish predictions for another
program, push an LSLOutlet from predict(). This publishes data without driving a device. See
Publish a data stream.
Extending the skeleton
- Recording lifecycle. The controls above start and stop takes. Streams flow whether you record or not. Recording starts when
app.start_recording()is called, typically by theRecordingControlswidget’s Record button. See Recording. - Multi-stream. A second
Stream("imu", ...)and yourextract()seeswindows["imu"]too. Match theiter_aligned_windowspattern intrain()for paired primary/target streams. See Recording. - Bridges. Heavy-data sources such as webcams and ultrasound run as subprocesses via
app.bridges(...). See Threading.
Where to read next
The concept pages describe each component in more detail:
- Streams - ring buffer geometry, the channels-first contract,
get_displaydecimation. - Pipeline - state machine, decorator semantics, stale-tick guards.
- Recording - sessions, label tracks, the
.mg.ziparchive. - Widgets - the construct-once
.ui()pattern,Gridlayout, pop-out windows. - Architecture - thread roles and the data flow diagram.
- Threading - GIL release, GPU contention rule, bridge subprocesses.
- Design principles - the eight rules the framework keeps to.
Or jump straight into a hands-on walkthrough: the EMG classification tutorial builds on this skeleton with real features, real data, and a real model.