Live Session¶
Last changes: Documentation changelog
Contract¶
fm.connect() turns a plain Python process—an interactive interpreter, a standalone script, or a
Jupyter notebook—into a live client of a running FullMag instance. Once connected, every DSL call
that modifies the scene commits an incremental transaction to the active server session, and
fm.relax(), fm.run(), and fm.run_until(...) execute as live runtime commands while Control Room
visualizes the evolving geometry, scalar time series, and field maps in real time.
When $FULLMAG_URL is exported in the environment, the first live-synced DSL call automatically
attaches once per Python context without an explicit fm.connect() call. Without a connection, the
same vocabulary retains its standard eager batch behavior, and fullmag script.py captures it
deterministically into ProblemIR. Calling fm.disconnect() closes the live session attachment and
restores ordinary eager DSL semantics in the current Python process.
Governing equations¶
This page introduces no physical equation; it defines the transport, synchronization, presence, and command execution contract for driving a live session. Continuing magnetization from one executed command to the next reuses the previous command’s final state when the spatial discretization is unchanged; it adds no PDE or energy term.
Symbols and SI units¶
until in fm.run(until) and chunk_time / max_time in fm.run_until(...) are durations in
seconds (\(\mathrm{s}\)). retry_budget_s, timeout, command_timeout, and min_interval_s are
client-side wall-clock durations in seconds (\(\mathrm{s}\)). Stopping tolerances follow
Relaxation Study, RelaxStop, and add_relax Stage Contract. Field vectors and table columns return quantities in their canonical SI
units (for example \(\mathrm{A}/\mathrm{m}\) for magnetization/fields or dimensionless normalized
\(\mathbf{m}\), \(\mathrm{J}/\mathrm{m}^3\) for energy densities, and \(\mathrm{s}\) for simulation time).
Identifiers, counts, and flags are dimensionless (\(1\)).
Assumptions and validity¶
Single shared current session per instance: One running FullMag instance (typically a Docker DEV group) owns one current session shared between Python and Control Room. Conflicting concurrent edits between Python and the browser fail with
StaleRevisionError(409) unless explicitly reconciled viafm.sync(reconcile=True).Presence heartbeats and lease:
LiveSession(fullmag.live._session) starts a background"fullmag-live-presence"thread on connect that emits client heartbeats every \(10.0\ \mathrm{s}\) toPUT /v2/sessions/current/clients/{client_id}(kind"python_live", labeled withsource_path.namewhen known or"python-live"). The server maintains active entries for a \(30\ \mathrm{s}\) presence TTL (up to 64 clients) andfm.disconnect()/close()cleanly issues aDELETEleave request.Docker accepted mode command limits: In Docker accepted mode,
fm.pause(),fm.paused(), andfm.skip()are rejected by server capability policy withUnsupportedCapabilityError; modify model parameters between commands or usefm.transaction()instead.Timestep prerequisite: Like
study.stages.add_relaxandstudy.stages.add_run, livefm.relax(...)andfm.run(...)require an explicit timestep (fm.solver(fix_dt=...),fm.relax(dt=...), or an adaptive policy providingdt_max); otherwiseValueErroris raised client-side before sending a request.Live-hook exclusions (
LiveModeError): Operations that do not map to incremental live commands— such as declarativerelax_stage/run_stagebatch builders, standalone eigenmode or frequency-response study constructors, or local file writers (save,save_response,snapshot)—raisefm.LiveModeError. Callingfm.connect()while capturing (fullmag script.py) likewise raisesfm.LiveModeError.
Python API¶
All live entry points are re-exported on top-level fullmag (import fullmag as fm), with notebook
plotting in fullmag.live.jupyter.
Python |
Type |
Default |
SI unit |
Validation |
Meaning |
Backend support |
ProblemIR |
|---|---|---|---|---|---|---|---|
|
|
|
\(1\) |
|
Origin of the DEV group frontend |
FEM/FDM CPU/GPU; runtime capability checks remain authoritative |
none (transport) |
|
|
|
\(1\) |
boolean |
Replace the current session instead of attaching |
FEM/FDM CPU/GPU |
none |
|
|
|
\(1\) |
boolean |
Start the realtime event stream |
FEM/FDM CPU/GPU |
none |
|
|
|
\(\mathrm{s}\) |
|
Retry budget for requests that provably did not apply |
FEM/FDM CPU/GPU |
none |
|
function |
— |
\(1\) |
safe when disconnected |
Leave client presence, close the WebSocket stream, and return DSL to eager mode |
FEM/FDM CPU/GPU |
none (transport) |
|
function ( |
|
\(1\) |
live session required |
Commit pending DSL changes; reconcile merges disjoint Control Room edits after conflict |
FEM/FDM CPU/GPU |
scene revision |
|
context manager |
— |
\(1\) |
live session required |
Group several DSL calls into one transaction |
FEM/FDM CPU/GPU |
scene revision |
|
context manager |
— |
\(1\) |
live session required |
Pause, apply edits, resume (interactive host only) |
Not in Docker accepted mode |
scene revision |
|
runtime commands |
|
\(\mathrm{s}\) |
explicit timestep ( |
Append a live stage and execute with |
FEM/FDM CPU/GPU |
|
|
callable, |
|
\(\mathrm{s}\) |
|
Run in chunks until the predicate holds |
FEM/FDM CPU/GPU |
|
|
runtime commands |
— |
\(1\) |
live session required |
Submit session control commands ( |
|
none (command) |
|
|
|
field SI unit |
quantity id of the session catalog |
Fetch FMVP binary field vector ( |
FEM/FDM CPU/GPU |
none (read) |
|
|
|
table column SI units |
valid table id ( |
Fetch FMTB binary rows ( |
FEM/FDM CPU/GPU |
none (read) |
|
|
|
\(1\) |
live session with |
Subscribe to WebSocket |
FEM/FDM CPU/GPU |
none (stream) |
|
function |
— |
\(1\) |
live session required |
Sync and render canonical editable Python script from the server model |
FEM/FDM CPU/GPU |
round-trip script |
|
callable, |
|
\(1\) |
distinct group URLs; equal-length lists |
Run points across several DEV groups |
FEM/FDM CPU/GPU |
one session per group |
|
helper |
|
\(1\) |
live session with event stream |
Stream scalar samples into a live notebook plot or |
FEM/FDM CPU/GPU |
none (read) |
Full signature notes¶
fm.connect(url=None, *, new_session=False, backend=None, token=None, timeout=30.0, retry_budget_s=60.0, command_timeout=None, source_path=None, events=True) -> LiveSession:backend:"fdm"or"fem"when starting or replacing a session (defaults to the local world’s configured backend or"fdm").token: optional bearer token (falls back to$FULLMAG_TOKEN).timeout/command_timeout: HTTP request timeout and command completion wait bound (when unset, long relax/run commands wait cleanly without timing out early).source_path: explicit script path whose filename is published as the presence heartbeat label.Session reuse vs. replacement: attaches to the active non-terminal session if present; replaces automatically if the session is in a terminal state (
stopping,stopped,cancelled,failed,completed,closed) or whennew_session=True.
fm.field(quantity_id, **query) -> Optional[FieldVector]: Fetches FMVP v2–v6 binary vectors (FieldVectorwith.to_numpy()shape(point_count, n_comp),.as_grid()shape(nz, ny, nx, n_comp)forfull_domain/legacy_count_onlyordering with \(x\) varying fastest,.as_complex(), and.point_count). Transparently handles HTTP202retry,204(None), and304ETag caching; whenquantity_id == "m"without extra query parameters and no plan quantity registry applies, falls back to observation-frame magnetization endpoints.fm.table(table_id, *, columns=None, **query) -> TableRows: Fetches FMTB v1 binary tabular streams with.to_numpy(),.column(name), and optional.to_pandas()(requirespandas).fm.on(event_type, callback) -> Subscription: Registerscallback(event: LiveEvent)on the background WebSocketEventStream("scalar.sample","resource.batch_changed","*"), returning aSubscriptionwhose.cancel()method detaches the callback.fm.run_until(predicate, *, chunk_time, max_time=None, max_chunks=None) -> Optional[LiveCommandResult]: Advances simulation in chunks ofchunk_timeuntilpredicate(step)returns truthy or one ofmax_time/max_chunksterminates the loop.stepexposes scalar columns (step.time,step.mx,step.my,step.mz, falling back to domain-averagedfm.field("m")if scalar rows are absent).fm.sweep(function, *, groups, points=None, new_session=False, raise_on_error=True, token=None, command_timeout=None, connect_retry_s=5.0, **parameters) -> list[SweepResult]: Assigns one thread and isolatedfm.ExecutionContext()per distinct URL ingroups, callsfm.reset()between sweep points, and returnsSweepResult(index, point, group, value, run_id, error, traceback)objects with.okstatus. Setraise_on_error=Falseto inspect partial failures instead of raisingSweepError.fullmag.live.jupyter.monitor(columns=("mx", "my", "mz"), *, x_column="time", min_interval_s=0.25) -> ScalarMonitor: Subscribes to scalar samples for live notebook visualization (requirespip install "fullmag[jupyter]"for inline IPython/matplotlib widgets, falling back cleanly to headless.samplesbuffering and text table summaries in non-notebook environments). Expose.start(),.stop(), and.samples.
The model as a stage-first study¶
Live mode programs the exact same physical model that a stage-first batch script authors. The batch
form below is executed directly by documentation verification; fullmag script.py lowers its stages
deterministically into ProblemIR:
# %% Model
import fullmag as fm
study = fm.study("live_session_basics")
study.engine("fdm")
study.device("cpu", precision="double")
study.cell(5e-9, 5e-9, 10e-9)
study.solver(fix_dt=1e-13)
layer = study.geometry(fm.Box(size=(400e-9, 100e-9, 10e-9), name="layer"), name="layer")
layer.Ms = 800e3
layer.Aex = 13e-12
layer.alpha = 0.02
layer.m = fm.texture.uniform(1, 0.1, 0)
# %% Stages: relax, then dynamics in a bias field
study.b_ext(0.02, 0.0, 0.0)
study.stages.add_relax(algorithm="llg_overdamped", dt=1e-13, tolT=1e-5, max_steps=20_000)
study.stages.add_run(1e-9)
Complete live workflow (interactive transcript)¶
In a live session, the same statements commit incrementally and each fm.relax(...), fm.run(...),
or fm.run_until(...) resumes from the final magnetization of the preceding command. Because live
transcripts require a running FullMag instance, they use pycon syntax:
>>> import fullmag as fm
>>> session = fm.connect("http://127.0.0.1:3197", new_session=True)
>>> fm.engine("fdm") # commits on each DSL call
>>> fm.device("cpu", precision="double")
>>> fm.cell(5e-9, 5e-9, 10e-9)
>>> fm.solver(fix_dt=1e-13) # explicit timestep required for live stages
>>> layer = fm.geometry(fm.Box(400e-9, 100e-9, 10e-9), name="layer")
>>> layer.Ms, layer.Aex, layer.alpha = 800e3, 13e-12, 0.02
>>> layer.m = fm.texture.uniform(1, 0.1, 0)
>>> fm.relax(dt=1e-13, tolT=1e-5, max_steps=20_000)
>>> m_vec = fm.field("m").to_numpy() # shape: (N_cells, 3)
>>> m_grid = fm.field("m").as_grid() # shape: (nz, ny, nx, 3)
>>> sub = fm.on("scalar.sample", lambda ev: print(ev.data))
>>> with fm.transaction(): # atomic multi-property delta
... fm.b_ext(0.02, 0.0, 0.0)
... layer.alpha = 0.01
>>> fm.run_until(lambda s: s.mx > 0.99, chunk_time=2e-11, max_time=5e-10)
>>> rows = fm.table("scalars", columns=("time", "mx", "my", "mz"))
>>> script_text = fm.export_script() # reproducible stage-first script
>>> sub.cancel()
>>> fm.disconnect()
Multi-instance sweeps and Control Room monitoring¶
When running parameter sweeps (fm.sweep(...)) across multiple local DEV groups, Control Room’s
multi-instance tab strip (/home -> Other instances on this computer and session tabs) lets you
monitor each port’s live session concurrently. Inside an active workspace, File -> Save canonical
copy as… exports the current session state as an editable stage-first Python script matching
fm.export_script() (experimental preview: true ribbon tabs such as Automation are stripped from
the active toolbar):
Interactive stage re-execution with Control Room¶
Because fm.relax() and fm.run() append stages cleanly into scene.study.stages and target them
by stage_index, any authored stage remains inspectable—and re-executable—from the Study and
Stage Inspector panels:
When you modify a stage draft or select an explicit initial state in Control Room and trigger stage
re-execution (executeStageAfterApply), the UI pins (scene_revision, solver_profile, domain),
verifies sessions/current/status and model/readiness, aborts safely if a live Python script
mutated the scene concurrently, and submits a targeted stage run. If Python subsequently commits
another change on top of a Control Room edit, call fm.sync(reconcile=True) to merge disjoint
updates cleanly rather than failing with a stale-revision error.
Example scripts and notebooks¶
examples/live/ ships five runnable reference scripts (# %% cells) and mirrored .ipynb notebooks
(regenerated by examples/live/sync_notebooks.py). Run any example against a running DEV group with
FULLMAG_URL=http://127.0.0.1:<port> python examples/live/<name>.py; each connects with
new_session=True:
Example |
API surface exercised |
Lane |
|---|---|---|
|
|
FDM CPU |
|
|
FEM CPU |
|
|
FDM CPU |
|
|
FDM CPU |
|
|
FDM CPU |
ProblemIR¶
Live mode does not mutate raw ProblemIR directly. Each synchronization serializes the world with the
same lowering converters used by fullmag script.py into a SceneDocument, and the server derives
validated ProblemIR from that scene before planning any command. Like study.stages.add_relax and
study.stages.add_run, live fm.relax() and fm.run() append one stage record to scene.study.stages
and submit a command targeting stage_index, so fm.export_script() reconstructs the exact authored
stage sequence cleanly.
Round-trip and failure semantics¶
Requested intent remains the Python-authored configuration serialized into SceneDocument/ProblemIR;
resolved execution records the planner’s concrete backend, device, precision, mesh/grid realization, and
capability decisions without rewriting requested intent.
The initial synchronization replaces the session scene (replace_scene); subsequent delta updates plan
minimal patch_material, assign_study_execution, or RFC 7386 merge_patch transactions. Commands
carry a scene_revision precondition (reason="python_live"). Failed or cancelled runtime commands
raise CommandFailedError; unreachable hosts raise FullmagConnectionError; concurrent browser/script
scene mutations raise StaleRevisionError (409). Validation errors report the rejected domain or
timing rule client-side (ValueError) or before execution, and unsupported combinations fail closed via
LiveModeError or UnsupportedCapabilityError rather than falling back silently.
Discrete realization¶
All numerical execution runs inside the attached session’s backend runtime (FDM CPU/GPU or FEM CPU/GPU); live mode introduces no separate solver implementation. See Runtime Selection, Backend Policy, and backend-specific physics pages for solver-lane guarantees and device qualification gates.
Implementation mapping¶
Primary owners under packages/fullmag-py/src/fullmag/:
live/__init__.py— top-level DSL entry points (connect,disconnect,sync,transaction,paused,relax,run,run_until,pause,resume,stop,skip,field,table,on,export_script,sweep) and auto-connect logic.live/_session.py—LiveSession,"fullmag-live-presence"heartbeat thread (10.0 sinterval), delta synchronization, conflict reconciliation, stage execution,run_until, binary reads, andexport_script.live/_scene.py—plan_transactions(replace_scene,patch_material,assign_study_execution,merge_patch), live stage recording (AssignmentScope), and revision conflict reconciliation.live/_hooks.py— handle/module wrappers (_LIVE_SYNCED_FUNCTIONS) forwarding live mutations cleanly.live/sweep.py&live/jupyter.py— concurrent multi-groupsweeprunner andScalarMonitor.client/— typed HTTP client, WebSocketEventStream, FMVP binary field decoder, and FMTB table decoder.
Validation¶
Contract suites packages/fullmag-py/tests/test_live_dsl_mode.py, test_live_events.py,
test_live_sweep.py, test_live_client_core.py, and test_live_client_data.py verify connection
lifecycles, presence heartbeats and leaves, transaction planning and reconciliation, WebSocket cursor
resume, FMVP/FMTB decoding, run_until, sweep, and jupyter.monitor against a stateful mock API and
real WebSocket server. Reference live scripts live under examples/live/01..05. Live transport checks
verify Python client behavior against the server API contract; physics accuracy and device parity are
governed by the dedicated suites under Validation.
Limitations¶
fm.pause(),fm.paused(), andfm.skip()are rejected in Docker accepted mode (UnsupportedCapabilityError); edit parameters between commands or start a fresh stage instead.Magnetization continuation between consecutive
fm.relax()/fm.run()commands requires keeping the discretization unchanged across those stages.Control Room exposes active Python-created sessions on Start Screen (Active simulations) and in multi-instance tabs, and the backend maintains
/v2/sessions/current/clients(30 spresence TTL, max64clients); rendering a dedicated per-client live-script badge directly fromSESSION_CLIENTS_PATHin the Control Room workspace bar is not yet wired.fullmag[jupyter]is required for inline matplotlib widgets infullmag.live.jupyter.monitor(); core live mode otherwise degrades cleanly to headless.samplesbuffering.
Scientific bibliography¶
No independent physical equation is introduced by the live session protocol. Transport and binary payload contracts reference the server API and solver documentation directly.
Control Room crosswalk¶
Status: Control Room displays every scene revision, authored stage, run telemetry trace, and field output driven by fm.connect() in real time.
Python/API surface |
Control Room path |
Status |
Transaction |
|---|---|---|---|
Scene edits & |
|
|
Python authoring transactions ( |
|
|
|
Runtime |
|
|
|
Binary |
Multi-group |
|
|
Host instance discovery ( |
Script presence ( |
|
|
Server |
See Control Room capability register for the support matrix and UI exposure rules.
Frontend source owners: apps/control-room/src/modules/start/home/ActiveSessions.tsx, apps/control-room/src/kernel/layout/InstanceTabStrip.tsx, apps/control-room/src/modules/inspector/panels/studyStageApplyAndRun.ts, apps/control-room/src/modules/inspector/panels/RuntimeExplorerInspectorPanels.tsx, and apps/control-room/src/modules/status-bar/StatusBarModule.tsx.
Source-code index¶
Claim |
Path |
Stable symbol |
Responsibility |
Evidence |
|---|---|---|---|---|
Live connection |
|
Switch the DSL to live mode |
|
|
Session, presence & IO |
|
Manage live session sync, heartbeats, commands, fields, tables, and script export |
|
|
Synchronisation |
|
Plan atomic scene transactions between the local DSL state and server revision |
|
|
Events |
|
Maintain WebSocket realtime subscriptions with cursor resume |
|
|
Sweeps |
|
Dispatch parameter sweep points concurrently across running groups |
|
|
Jupyter monitor |
|
Stream scalar telemetry for live notebook plots and headless capture |
|
|
Server presence store |
|
|
Track live client heartbeats within 30 s TTL and emit |
|
Source-map coverage¶
Claim |
Path |
Stable symbol |
Responsibility |
Evidence |
|---|---|---|---|---|
Switch the DSL to live mode. |
|
|
Switch the DSL to live mode. |
Source-map validator and live contract tests |
Manage live session sync, heartbeats, commands, fields, tables, and script export. |
|
|
Manage live session sync, heartbeats, commands, fields, tables, and script export. |
Source-map validator and live contract tests |
Plan atomic scene transactions between the local DSL state and server revision. |
|
|
Plan atomic scene transactions between the local DSL state and server revision. |
Source-map validator and live contract tests |
Maintain WebSocket realtime subscriptions with cursor resume. |
|
|
Maintain WebSocket realtime subscriptions with cursor resume. |
Source-map validator and WebSocket tests |
Dispatch parameter sweep points concurrently across running groups. |
|
|
Dispatch parameter sweep points concurrently across running groups. |
Source-map validator and sweep tests |
Stream scalar telemetry for live notebook plots and headless capture. |
|
|
Stream scalar telemetry for live notebook plots and headless capture. |
Source-map validator and live data tests |