Core modules¶
Configuration-time output declarations and legacy plugin adapters.
- class stoner_measurement.core.plugin_outputs.PluginOutputs(traces: dict[str, ~stoner_measurement.core.plugin_outputs.TraceOutput]=<factory>, values: dict[str, ~stoner_measurement.core.plugin_outputs.ScalarOutput]=<factory>, result_order: tuple[str, ...] | None=None)[source]¶
Bases:
objectOrdered trace and scalar declarations keyed by existing catalogue identity.
result_orderoptionally preserves interleaved transform result names. Expressions and schemas are derived configuration, never persisted results.- Parameters:
traces (dict[str, TraceOutput]) – Ordered trace declarations by catalogue identifier. Defaults to an independent empty mapping.
values (dict[str, ScalarOutput]) – Ordered scalar declarations by catalogue identifier. Defaults to an independent empty mapping.
result_order (tuple[str, ...] | None) – Optional local-result order. Listed known keys come first, followed by remaining declared keys.
Notes
Without explicit ordering, combined result names put scalar result keys before trace result keys. Projections without a result_key are excluded. The trace and scalar mappings may share a catalogue key. Descriptor records are frozen; the mappings can be extended when implementing super().declared_outputs() in a subclass.
Examples
>>> outputs = PluginOutputs(values={ ... "source:Resistance": ScalarOutput("source.resistance", "Ω") ... }) >>> outputs.values["source:Resistance"].units 'Ω'
- class stoner_measurement.core.plugin_outputs.ScalarOutput(expression: str, units: str = '', result_key: str | None = None)[source]¶
Bases:
objectA scalar access expression with units and an optional stored-result key.
- class stoner_measurement.core.plugin_outputs.TraceOutput(expression: str, result_key: str | None = None, schema: TraceData | None = None, schema_factory: Callable[[], TraceData | None] | None = None)[source]¶
Bases:
objectA trace expression with an optional empty schema or deferred factory.
- Parameters:
expression (str) – Runtime expression returning the acquired TraceData.
result_key (str | None) – Local key for mapping-backed trace results.
schema (TraceData | None) – Complete empty configured table, if known.
schema_factory (Callable | None) – Configuration-only zero-argument builder. Called after scalar catalogues are available. Supply either this or schema; neither is needed for unknown schemas.
- configured_data() TraceData | None[source]¶
Materialise the configured schema without evaluating the expression.
- Returns:
Independent empty schema, or unknown schema.
- Return type:
(TraceData | None)
- Raises:
ValueError – If both schema forms are supplied, the builder returns a non-TraceData object, or a schema contains acquired rows.
- stoner_measurement.core.plugin_outputs.resolve_outputs(plugin: Any, *, adapt_legacy: bool = True) PluginOutputs[source]¶
Resolve one plugin’s declarations and more-specific legacy overrides.
Active declarations back
super().reported_*()calls during legacy adaptation, preventing recursion and duplicate declaration evaluation. An explicit empty PluginOutputs is authoritative; None selects adaptation.- Parameters:
plugin (BasePlugin) – Plugin whose current outputs are requested.
- Keyword Parameters:
adapt_legacy (bool) – Apply more-specific legacy overrides. The direct legacy-call wrapper disables this to construct its super baseline.
- Returns:
Fresh declaration mappings with compatibility applied.
- Return type:
- Raises:
TypeError – If a plugin returns invalid declaration types.
Sequence engine — runs Python scripts in an isolated namespace with plugin instances.
The engine maintains a persistent background QThread that processes
both REPL commands (from the console widget) and full Python scripts (from the
sequence editor). Plugin instances registered with the
PluginManager are injected
into the namespace automatically, so scripts can reference them directly by a
sanitised variable name derived from each plugin’s name property.
Namespace access¶
The shared interpreter namespace is a plain Python dict that persists for
the lifetime of the engine. It is the globals() environment in which all
scripts and REPL commands execute.
Scripts read and write namespace variables in the normal Python way — any assignment (
x = 1) or import creates a new key; subsequent scripts or REPL commands see the same variable.Plugin lifecycle methods (
connect,configure,measure, etc.) can access the same namespace viaengine_namespace. When a plugin is registered with the engine itssequence_engineattribute is set to the owningSequenceEngineinstance, which gives the plugin a direct reference to the live_namespacedict. For example:class MyPlugin(TracePlugin): def connect(self) -> None: # Read a parameter set by an earlier script step sweep_start = self.engine_namespace.get("sweep_start", 0.0) self._instrument.set_start(sweep_start)
The
namespaceproperty onSequenceEngine(see below) returns a snapshot copy and is intended for external inspection (e.g. by the UI); plugin code should useengine_namespaceinstead so that mutations are immediately visible to running scripts.
- stoner_measurement.core.sequence_engine.ROOT_LOGGER_NAME = 'stoner_measurement'¶
Root logger name for the entire stoner_measurement package. The Qt log handler is attached here so that every
stoner_measurement.*child logger (instruments, temperature/magnet engines, plugins, etc.) is visible in the application log window.
- stoner_measurement.core.sequence_engine.SEQUENCE_LOGGER_NAME = 'stoner_measurement.sequence'¶
Logger name used for sequence-engine and plugin log messages. Also used as the name of the
logobject injected into the sequence namespace.
- class stoner_measurement.core.sequence_engine.SequenceEngine(parent: QObject | None = None)[source]¶
Bases:
QObjectPython interpreter for sequence execution and interactive REPL.
The engine maintains a persistent
QThreadthat processes commands from an internal queue. Plugin instances are injected into the interpreter namespace so that sequence scripts can reference them directly by a sanitised variable name.Two execution modes are supported:
REPL mode — single Python expressions or statements submitted via
execute_command(). Results and errors are emitted as signals.Script mode — a complete Python script submitted via
run_script(). The script is compiled and executed withsys.settraceinstalled so thatpause()andstop()work at Python line boundaries.
All scripts and REPL commands share the same persistent namespace (a plain Python
dictused asglobals()). Variables assigned in one script are visible in all subsequent scripts and REPL commands.Plugin code can read and write the same namespace via
engine_namespace— see the module-level documentation for details and an example.Signals¶
- output(str):
Text written to
sys.stdoutduring execution.- error_output(str):
Text written to
sys.stderror unhandled exception tracebacks.- status_changed(str):
Execution status:
"Idle","Running","Paused","Stopped", or"Error".- traces_catalog_changed(dict):
Snapshot of the rebuilt trace catalogue after sequence steps change.
- values_catalog_changed(dict):
Snapshot of the rebuilt scalar-value catalogue after sequence steps change.
- namespace_updated():
Emitted after a general mutation of the shared execution namespace.
- measurement_details_changed(str, str, str):
Validated user, project and sample from an executed Details command.
- script_finished():
Emitted when a script runs to completion without raising an exception.
- param parent:
Optional Qt parent.
- type parent:
QObject | None
Examples
>>> from qtpy.QtWidgets import QApplication >>> _ = QApplication.instance() or QApplication([]) >>> engine = SequenceEngine() >>> engine.is_running False >>> engine.shutdown()
- add_plugin(ep_name: str, plugin: BasePlugin) None[source]¶
Add plugin to the interpreter namespace.
The variable name is taken from
plugin.instance_name(a valid Python identifier, defaulting to a sanitised form ofplugin.name). If the entry-point name ep_name produces a different identifier it is also added as an alias.The plugin’s
sequence_engineattribute is set to this engine so that lifecycle methods (connect,configure,measure, etc.) can access the shared namespace viaengine_namespace.- Parameters:
ep_name (str) – Entry-point name used to register the plugin.
plugin (BasePlugin) – Plugin instance to expose in the namespace.
Examples
>>> from qtpy.QtWidgets import QApplication >>> _ = QApplication.instance() or QApplication([]) >>> from stoner_measurement.plugins.trace import DummyPlugin >>> engine = SequenceEngine() >>> plugin = DummyPlugin() >>> engine.add_plugin("dummy", plugin) >>> "dummy" in engine.namespace True >>> plugin.sequence_engine is engine True >>> engine.shutdown()
- adopt_namespace(ns: dict) None[source]¶
Merge the current interpreter namespace into ns and use ns as the live namespace.
The engine’s existing namespace contents (numpy helpers, plugins, catalogues, and any previously script-defined names) are merged into ns so that all of them remain accessible. Python interpreter internals (
__builtins__,__name__,__doc__, etc.) already present in ns are preserved so that ns retains the identity of its original environment.After this call the engine and its worker thread execute scripts and commands directly against ns, so any variable created or mutated during execution — regardless of whether the script completes successfully, raises an exception, or is stopped — is immediately visible through ns without a separate synchronisation step.
This is intended for use when the console widget shares an in-process IPython kernel with the engine. Passing
kernel.shell.user_nsmakes the kernel’s namespace the single live dictionary for both the engine and the IPython REPL, eliminating the need for post-execution syncing.- Parameters:
ns (dict) – External namespace dict to adopt. Typically
kernel_manager.kernel.shell.user_nsfrom an in-process IPython kernel.- Raises:
RuntimeError – If a script is currently running. Callers must ensure the engine is idle before adopting a new namespace.
Examples
>>> from qtpy.QtWidgets import QApplication >>> _ = QApplication.instance() or QApplication([]) >>> engine = SequenceEngine() >>> shared = {} >>> engine.adopt_namespace(shared) >>> "np" in shared True >>> engine.shutdown()
- all_plugins() list[BasePlugin][source]¶
Return all plugin instances known to this engine.
Combines the base plugins registered via
add_plugin()with the step plugins registered viaupdate_step_plugin_catalog(). Each plugin instance appears at most once (identity-based deduplication).This is intended for use by consumers that need the full set of plugin instances regardless of their role (e.g. for capturing configuration snapshots in file metadata). The
_traces/_valuescatalogs are built from step plugins only; seeupdate_step_plugin_catalog().- Returns:
Ordered list of
BasePlugininstances — base plugins first, then step plugins.- Return type:
(list[BasePlugin])
Examples
>>> from qtpy.QtWidgets import QApplication >>> _ = QApplication.instance() or QApplication([]) >>> from stoner_measurement.plugins.trace import DummyPlugin >>> engine = SequenceEngine() >>> base = DummyPlugin() >>> step = DummyPlugin() >>> engine.add_plugin("dummy", base) >>> engine.update_step_plugin_catalog([step]) >>> plugins = engine.all_plugins() >>> base in plugins True >>> step in plugins True >>> engine.shutdown()
- append_chart_sample(trace: ChartTrace, timestamp: float, samples: dict[tuple[str, str], float]) None[source]¶
Append one chart row and notify trace and namespace consumers.
- chart_trace(key: str) ChartTrace | None[source]¶
Return the recorded chart behind a published catalogue key.
- error_output¶
Qt signal.
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal's arguments.
- evaluate_expression(expression: str) Any[source]¶
Evaluate expression against the live engine namespace.
- execute_command(source: str) None[source]¶
Submit a single REPL source line for execution.
The command is placed on the internal queue and processed in order after any currently pending scripts or commands.
- Parameters:
source (str) – Python expression or statement.
Examples
>>> from qtpy.QtWidgets import QApplication >>> _ = QApplication.instance() or QApplication([]) >>> engine = SequenceEngine() >>> engine.execute_command("1 + 1") >>> engine.shutdown()
- execution_progress¶
Qt signal.
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal's arguments.
- generate_sequence_code(steps: list, plugins: dict[str, BasePlugin], *, return_line_map: Literal[False] = False) str[source]¶
- generate_sequence_code(steps: list, plugins: dict[str, BasePlugin], *, return_line_map: Literal[True]) tuple[str, dict[int, BasePlugin]]
Generate executable Python code from the sequence tree.
Produces a four-phase script from steps:
Instantiate — for each unique plugin a conditional block is emitted that recreates the plugin from its current configuration (using
generate_instantiation_code()) only when the variable is not already present inglobals(). This makes the generated script self-contained: when it is saved to a file and later executed outside the app the plugins will be reconstructed from the configuration that was in force at generation time, while running the script directly in the app (where the plugins are already in the namespace) leaves the live engine instances untouched.Connect/initialise —
connect()is called for every unique plugin instance found in the tree, in depth-first order.Configure —
configure()is called for every unique plugin instance in the same order.Action — the measurement body, wrapped in a single
try/finallyblock. Each plugin’s action is generated by callinggenerate_action_code()on the plugin instance, allowing each plugin type to define its own code-generation behaviour.The
finallyblock callsdisconnect()on every plugin in reverse order so that resources are always released.
- Parameters:
steps (list) – Nested sequence step list from
sequence_steps. Each element is either a plugin instance, a plain entry-point name string (legacy), or a(plugin_or_ep_name, [sub-steps…])tuple.plugins (dict[str, BasePlugin]) – Mapping of entry-point name → plugin instance used to resolve legacy string step entries.
- Keyword Parameters:
return_line_map (bool) – When
Truethe method returns a(code, line_map)tuple instead of just the code string. line_map maps 1-based line numbers in the returned script to the plugin instance whose generated action code occupies that line. Only action lines (inside thetry:block) are mapped; infrastructure lines (instantiate/connect/configure/disconnect) are not included.- Returns:
- Executable Python script representing the sequence tree
(when return_line_map is
False).- (tuple[str, dict[int, BasePlugin]]):
(code, line_map)pair when return_line_map isTrue.
- Return type:
(str)
Examples
>>> from qtpy.QtWidgets import QApplication >>> _ = QApplication.instance() or QApplication([]) >>> from stoner_measurement.plugins.trace import DummyPlugin >>> engine = SequenceEngine() >>> plugin = DummyPlugin() >>> engine.add_plugin("dummy", plugin) >>> code = engine.generate_sequence_code(["dummy"], {"dummy": plugin}) >>> "connect" in code and "configure" in code True >>> "measure" in code True >>> "disconnect" in code True >>> "_BasePlugin.from_json" in code True >>> code2, lmap = engine.generate_sequence_code( ... ["dummy"], {"dummy": plugin}, return_line_map=True ... ) >>> code2 == code True >>> any(v is plugin for v in lmap.values()) True >>> engine.shutdown()
- property is_paused: bool¶
Truewhile execution is paused.- Returns:
Trueif the pause event is cleared (i.e., execution is suspended).- Return type:
(bool)
- property is_running: bool¶
Truewhile a script is executing.- Returns:
Trueif the worker thread is currently executing a script.- Return type:
(bool)
- property log_handler: _QtLogHandler¶
Qt log handler that forwards all
stoner_measurementlog records as a signal.The handler is attached to the
stoner_measurementroot logger so that every child logger in the package — including temperature/magnet controller engines, instrument drivers and sequence plugins — is captured.Connect
_QtLogHandler.record_emittedto a slot that accepts alogging.LogRecordin order to receive these messages.- Returns:
The handler attached to the
stoner_measurementroot logger.- Return type:
(_QtLogHandler)
Examples
>>> from qtpy.QtWidgets import QApplication >>> _ = QApplication.instance() or QApplication([]) >>> engine = SequenceEngine() >>> engine.log_handler is not None True >>> engine.shutdown()
- measurement_details_changed¶
Qt signal.
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal's arguments.
- property namespace: dict¶
Read-only snapshot of the current interpreter namespace.
Returns a copy of the interpreter
globalsdict so that callers cannot accidentally mutate the live namespace. This property is intended for external inspection (e.g. the UI displaying available variables) and for testing.Note
Plugin lifecycle methods should not use this property to read back values from the namespace, because the copy they receive would immediately become stale. Use
engine_namespaceinstead, which returns the live dict directly.- Returns:
A shallow copy of the interpreter globals.
- Return type:
(dict)
Examples
>>> from qtpy.QtWidgets import QApplication >>> _ = QApplication.instance() or QApplication([]) >>> engine = SequenceEngine() >>> isinstance(engine.namespace, dict) True >>> engine.shutdown()
- namespace_snapshot() dict[str, Any][source]¶
Return a shallow snapshot of the live engine namespace.
- namespace_updated¶
Qt signal.
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal's arguments.
- notify_namespace_updated() None[source]¶
Emit a notification that values in the live namespace may have changed.
- output¶
Qt signal.
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal's arguments.
- pause() None[source]¶
Pause script execution at the next line boundary.
Has no effect if no script is currently running.
Examples
>>> from qtpy.QtWidgets import QApplication >>> _ = QApplication.instance() or QApplication([]) >>> engine = SequenceEngine() >>> engine.pause() # no-op when idle >>> engine.shutdown()
- plot_display_host: Any¶
- property plot_widget: Any¶
Reference to the main plot widget for displaying trace data.
The application sets this attribute after startup so that
PlotTraceCommandinstances can wire theirplot_tracesignal to the widget without requiring the application to manually manage signal connections for every step plugin.- Returns:
The plot widget, or
Noneif not yet set.- Return type:
(Any)
Examples
>>> from qtpy.QtWidgets import QApplication >>> _ = QApplication.instance() or QApplication([]) >>> engine = SequenceEngine() >>> engine.plot_widget is None True >>> engine.shutdown()
- rebuild_delayed_configuration(previous_plugins=()) None[source]¶
Refresh derived setup flags and Reconfigure bindings for this sequence.
- refresh_data_catalogs() None[source]¶
Rebuild trace/value catalogues after a plugin changes reported outputs.
Sequence-tree changes call
update_step_plugin_catalog(). Plugins whose configuration changes the result ofreported_traces()orreported_values(), or theirconfigured_trace_data()schemas, can call this lighter public boundary instead.
- refresh_value_catalog() None[source]¶
Rebuild and emit the current trace and value catalogues.
This public helper allows UI components to request a catalogue refresh after sequence-editor or plugin-instance changes without depending on a private engine implementation detail.
- register_chart_trace(name: str, owner: object) ChartTrace[source]¶
Reserve a chart trace name or resume a trace owned by the same chart.
- remove_plugin(ep_name: str) None[source]¶
Remove the plugin registered under ep_name from the namespace.
The plugin’s
sequence_enginereference is also cleared so that the plugin no longer holds a reference to this engine.- Parameters:
ep_name (str) – Entry-point name passed to
add_plugin().
Examples
>>> from qtpy.QtWidgets import QApplication >>> _ = QApplication.instance() or QApplication([]) >>> from stoner_measurement.plugins.trace import DummyPlugin >>> engine = SequenceEngine() >>> engine.add_plugin("dummy", DummyPlugin()) >>> engine.remove_plugin("dummy") >>> "dummy" in engine.namespace False >>> engine.shutdown()
- rename_plugin(ep_name: str, new_var_name: str) None[source]¶
Rename the namespace variable for the plugin registered under ep_name.
Removes the old variable name and inserts the plugin under new_var_name. Does nothing if ep_name is not currently registered.
- Parameters:
ep_name (str) – Entry-point name passed to
add_plugin().new_var_name (str) – New Python identifier to use in the namespace.
- Raises:
ValueError – If new_var_name is already used by a different plugin in the namespace.
Examples
>>> from qtpy.QtWidgets import QApplication >>> _ = QApplication.instance() or QApplication([]) >>> from stoner_measurement.plugins.trace import DummyPlugin >>> engine = SequenceEngine() >>> plugin = DummyPlugin() >>> engine.add_plugin("dummy", plugin) >>> engine.rename_plugin("dummy", "my_dummy") >>> "my_dummy" in engine.namespace True >>> "dummy" in engine.namespace False >>> engine.shutdown()
- rename_trace_output(old_key: str, new_key: str, old_expression: str, new_expression: str) None[source]¶
Remap downstream references and rebuild catalogues after an output rename.
- resume() None[source]¶
Resume a paused script.
Examples
>>> from qtpy.QtWidgets import QApplication >>> _ = QApplication.instance() or QApplication([]) >>> engine = SequenceEngine() >>> engine.resume() # no-op when not paused >>> engine.shutdown()
- run_script(code_str: str, customised: bool = True, line_map: dict[int, BasePlugin] | None = None) None[source]¶
Submit code_str for execution in the background thread.
If a script is already running it is allowed to complete (or be stopped via
stop()) before the new script is executed. To cancel the current script callstop()before submitting a new one.- Parameters:
code_str (str) – Python source code to execute.
- Keyword Parameters:
customised (bool) – When
True(the default) the script has been user-edited or loaded from a file, and exceptions will be reported as a traceback filtered to the script’s own frames. WhenFalsethe script is the auto-generated version and exceptions are attributed to the responsible sequence-step plugin via line_map.line_map (dict[int, BasePlugin] | None) – Mapping of 1-based line numbers to the plugin instance responsible for that line. Obtained from
generate_sequence_code()withreturn_line_map=True. Only consulted when customised isFalse.
Examples
>>> from qtpy.QtWidgets import QApplication >>> _ = QApplication.instance() or QApplication([]) >>> engine = SequenceEngine() >>> engine.run_script("x = 1 + 1") >>> engine.shutdown()
- script_finished¶
Qt signal.
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal's arguments.
- select_display_plugin(factory_id: str) None[source]¶
Select a sequence’s required display before configuring its plugins.
Available in the script namespace as
select_display_plugin. An already selected factory is a no-op. Otherwise the host dispatches replacement to the GUI thread and clears plotted state. Missing or broken displays raise rather than falling back.
- sequence_plugins() list[BasePlugin][source]¶
Return the plugin instances that are actually part of the current sequence.
Unlike
all_plugins(), which returns every plugin registered with the engine (including step-catalog plugins that are not in the current sequence), this method returns only:The base plugins registered via
add_plugin()(always present in the measurement environment).The step plugins that were collected when
generate_sequence_code()was last called — i.e. the enabled plugins actually instantiated in the most recently built sequence.
For each plugin in the above sets, any plugins returned by
member_plugins()are also included recursively. This handles plugins that own other plugin instances internally (e.g. a combined plugin wrapping a trace plugin and a monitor plugin).Each plugin instance appears at most once (identity-based deduplication).
If
generate_sequence_code()has not yet been called (e.g. before the first sequence run), only the base plugins are returned.- Returns:
Ordered list of plugin instances that are part of the current sequence: each base plugin is expanded recursively in depth-first order (member plugins immediately follow their parent), then each in-sequence step plugin is expanded the same way.
- Return type:
(list[BasePlugin])
Examples
>>> from qtpy.QtWidgets import QApplication >>> _ = QApplication.instance() or QApplication([]) >>> from stoner_measurement.plugins.trace import DummyPlugin >>> engine = SequenceEngine() >>> base = DummyPlugin() >>> step = DummyPlugin() >>> other = DummyPlugin() >>> engine.add_plugin("base", base) >>> engine.update_step_plugin_catalog([step, other]) >>> # Before generate_sequence_code: only base plugins returned >>> plugins = engine.sequence_plugins() >>> base in plugins True >>> step in plugins False >>> # After generate_sequence_code with only 'step' in the tree: >>> _ = engine.generate_sequence_code([step], {"step": step}) >>> plugins = engine.sequence_plugins() >>> base in plugins True >>> step in plugins True >>> other in plugins False >>> engine.shutdown()
- shutdown() None[source]¶
Cleanly stop the background thread and wait for it to finish.
Should be called when the application closes. Sends a quit sentinel to the queue, then waits up to 2 seconds for the thread to exit. If it does not exit within the timeout, the thread is forcibly terminated.
Examples
>>> from qtpy.QtWidgets import QApplication >>> _ = QApplication.instance() or QApplication([]) >>> engine = SequenceEngine() >>> engine.shutdown()
- status_changed¶
Qt signal.
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal's arguments.
- step_plugins() list[BasePlugin][source]¶
Return the plugin instances currently present in the sequence tree.
Unlike
all_plugins(), this excludes plugin-manager/base instances registered viaadd_plugin(). The returned list follows sequence order and is a shallow copy, so callers cannot mutate the engine’s catalogue directly.
- stop() None[source]¶
Request the currently running script to stop.
The stop is honoured at the next Python line boundary (via
sys.settrace). Has no effect if no script is running.Examples
>>> from qtpy.QtWidgets import QApplication >>> _ = QApplication.instance() or QApplication([]) >>> engine = SequenceEngine() >>> engine.stop() # no-op when idle >>> engine.shutdown()
- property traces_catalog: dict[str, str]¶
Return the catalogue of sequence outputs and recorded chart traces.
Each name maps to a Python expression that resolves a
TraceDataobject. The live catalogue is accessible in sequence scripts as_traces.Examples
>>> from qtpy.QtWidgets import QApplication >>> _ = QApplication.instance() or QApplication([]) >>> engine = SequenceEngine() >>> chart = engine.register_chart_trace("Temperature chart", object()) >>> engine.evaluate_expression(engine.traces_catalog["Temperature chart"]) is chart True >>> engine.shutdown()
- traces_catalog_changed¶
Qt signal.
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal's arguments.
- update_step_plugin_catalog(plugins: list[BasePlugin]) None[source]¶
Update the engine’s step-plugin catalog and rebuild
_traces/_values.Called by the application layer whenever the sequence-step list changes. Stores plugins as the sole source for the trace and value catalogs, then triggers
_rebuild_data_catalogs()so that the live namespace reflects the current sequence immediately.- Parameters:
plugins (list[BasePlugin]) – Flat list of
BasePlugininstances collected from the current sequence tree. Any element that is not aBasePlugininstance is silently ignored, so mixed lists are safe to pass.
Examples
>>> from qtpy.QtWidgets import QApplication >>> _ = QApplication.instance() or QApplication([]) >>> from stoner_measurement.plugins.trace import DummyPlugin >>> engine = SequenceEngine() >>> step = DummyPlugin() >>> engine.update_step_plugin_catalog([step]) >>> "dummy:Dummy" in engine.traces_catalog True >>> engine.shutdown()
- validate_generated_sequence() bool[source]¶
Check enabled steps from the last generation without running its script.
- Returns:
True when configuration passes preflight checks.
- Return type:
(bool)
- Raises:
ValidationError – If an enabled step has invalid configuration.
- validate_script_syntax(code_str: str, *, customised: bool = True, line_map: dict[int, BasePlugin] | None = None) str | None[source]¶
Compile code_str synchronously and emit a formatted syntax error on failure.
- Parameters:
code_str (str) – Python source code to validate.
- Keyword Parameters:
customised (bool) – Whether the script has been user-edited. Auto-generated scripts use line_map to attribute syntax errors to sequence steps.
line_map (dict[int, BasePlugin] | None) – Optional generated-code line map from
generate_sequence_code().
- Returns:
Nonewhen the script is syntactically valid, otherwise the user-facing error message that was emitted viaerror_output.- Return type:
(str | None)
- property values_catalog: dict[str, str]¶
Master catalog of all scalar data values produced by registered plugins.
Returns a snapshot of the
_valuesdict in the engine namespace. Each entry maps a human-readable name ("{instance_name}:{value_name}") to a string-compatible Python expression carrying optional physical-unit metadata. The expression retrieves the corresponding scalar value from the namespace.The catalog is rebuilt automatically whenever a plugin is added, removed, or renamed. It is also available directly inside sequence scripts and plugin
eval()calls as the variable_values.Examples
>>> from qtpy.QtWidgets import QApplication >>> _ = QApplication.instance() or QApplication([]) >>> from stoner_measurement.plugins.state_control import StateControlPlugin >>> from stoner_measurement.plugins.state_control import CounterPlugin >>> engine = SequenceEngine() >>> engine.add_plugin("counter", CounterPlugin()) >>> cat = engine.values_catalog >>> any("counter" in k for k in cat) True >>> engine.shutdown()
- values_catalog_changed¶
Qt signal.
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal's arguments.
- wait_for_plot_ready(timeout: float | None = 5.0, poll_interval: float = 0.01) bool[source]¶
Block until the plot widget reports that it can accept more data.
This helper is injected into the sequence namespace as
wait_for_plot_readyand is intended for use inside generated state-control loops.- Keyword Parameters:
timeout (float | None) – Maximum time to wait in seconds. Values
<= 0perform a single non-blocking readiness check.Nonewaits indefinitely until ready or interrupted by stop.poll_interval (float) – Delay between readiness checks while waiting.
- Returns:
Truewhen the plot is ready (or no plot widget is attached);Falseif the timeout expires first.- Return type:
(bool)
Plugin manager — discovers and loads plugin classes.
Plugins are discovered via Python package entry-points under the group
stoner_measurement.plugins. Each entry-point value must be a subclass
of BasePlugin.
- class stoner_measurement.core.plugin_manager.PluginManager(parent: QObject | None = None)[source]¶
Bases:
QObjectDiscovers, loads, and provides access to measurement plugins.
Signals¶
- plugins_changed:
Emitted after the plugin registry is (re-)built.
- get(name: str) BasePlugin | None[source]¶
Return the plugin with name, or
Noneif not found.
- property plugins: dict[str, BasePlugin]¶
Mapping of plugin name → plugin instance.
- plugins_by_type(plugin_type: str) dict[str, BasePlugin][source]¶
Return a filtered mapping of plugins matching plugin_type.
- Parameters:
plugin_type (str) – The
plugin_typetag to filter by (e.g."trace","state","monitor","transform").- Returns:
Mapping of plugin name → plugin instance for all registered plugins whose
plugin_typeequals plugin_type.- Return type:
(dict[str, BasePlugin])
Examples
>>> from qtpy.QtWidgets import QApplication >>> _ = QApplication.instance() or QApplication([]) >>> from stoner_measurement.core.plugin_manager import PluginManager >>> from stoner_measurement.plugins.trace import DummyPlugin >>> pm = PluginManager() >>> pm.register("dummy", DummyPlugin()) >>> pm.plugins_by_type("trace") {'dummy': <...DummyPlugin...>} >>> pm.plugins_by_type("state") {}
- plugins_changed¶
Qt signal.
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal's arguments.
- register(name: str, plugin: BasePlugin) None[source]¶
Manually register a plugin instance (useful for testing).
- Parameters:
name – Unique identifier for the plugin.
plugin – Plugin instance to register.
Sequence serialiser — converts sequence trees to/from JSON.
Provides sequence_to_json() and sequence_from_json() for
persisting and restoring measurement sequence trees. The JSON format
embeds the application version number so that files can be identified
and forward-compatibility checks can be added in the future.
Each step in the tree is represented by a {"plugin": {...}} dict;
steps that are SequencePlugin
containers with children also carry a "sub_steps" list that follows
the same recursive structure.
- stoner_measurement.core.serializer.rename_identifier_references(data: dict[str, Any], old_name: str, new_name: str) dict[str, Any][source]¶
Return a deep-copied sequence JSON mapping with strict identifier rewrites.
Only exact identifier-token matches are replaced, so renaming
fieldtotempupdates strings such asfield.valueorfieldbut leavesfield_2,b_field, andFielduntouched.
- stoner_measurement.core.serializer.sequence_from_json(data: dict[str, Any], *, on_reserved_name_renamed: Callable[[str, str], None] | None = None) list[_SequenceStep][source]¶
Reconstruct a sequence tree from a JSON dict produced by
sequence_to_json().Rebuilds each plugin instance using
from_json()and recursively reconstructs nested sub-steps. If an older sequence uses an instance name that is now reserved, the loader chooses a valid non-conflicting replacement, updates identifier references throughout the in-memory JSON, and retries reconstruction.- Parameters:
data (dict[str, Any]) – JSON dict as produced by
sequence_to_json()and loaded from a file withjson.loads()orjson.load().- Keyword Parameters:
on_reserved_name_renamed (Callable[[str, str], None] | None) – Optional callback invoked with each old and replacement instance name when loading requires an automatic migration.
- Returns:
Sequence steps in the same nested format accepted by
load_sequence().- Return type:
(list[_SequenceStep])
- Raises:
KeyError – If any plugin entry is missing the required
"class"key.ImportError – If a plugin class specified in
"class"cannot be imported.
Examples
>>> from qtpy.QtWidgets import QApplication >>> _ = QApplication.instance() or QApplication([]) >>> from stoner_measurement.plugins.trace import DummyPlugin >>> plugin = DummyPlugin() >>> plugin.instance_name = "test_dummy" >>> data = sequence_to_json([plugin]) >>> steps = sequence_from_json(data) >>> len(steps) 1 >>> steps[0].instance_name 'test_dummy'
- stoner_measurement.core.serializer.sequence_to_json(steps: list[_SequenceStep], *, display_plugin: str = 'cartesian') dict[str, Any][source]¶
Serialise a sequence tree to a JSON-compatible dict.
The returned dict has the following structure:
{ "version": "<app version>", "display_plugin": "<display factory ID>", "steps": [ {"plugin": {...}}, {"plugin": {...}, "sub_steps": [{"plugin": {...}}, ...]}, ... ] }
Each
"plugin"value is the dict produced byto_json().- Parameters:
display_plugin (str) – Preferred display factory ID for this sequence.
steps (list[_SequenceStep]) – The sequence steps as returned by
sequence_steps. Each element is either a plugin instance or a(plugin, [sub-steps…])tuple.
- Returns:
A JSON-serialisable dictionary suitable for writing to a file with
json.dumps().- Return type:
Examples
>>> from qtpy.QtWidgets import QApplication >>> _ = QApplication.instance() or QApplication([]) >>> from stoner_measurement.plugins.trace import DummyPlugin >>> plugin = DummyPlugin() >>> data = sequence_to_json([plugin]) >>> "version" in data True >>> len(data["steps"]) 1 >>> data["steps"][0]["plugin"]["type"] 'trace'
Shared tabular measurement data structures.
- stoner_measurement.core.trace_data.COLUMN_ROLE_D: str = 'd'¶
Role tag identifying a column as x-axis uncertainty (error bar).
- stoner_measurement.core.trace_data.COLUMN_ROLE_E: str = 'e'¶
Role tag identifying a column as y-axis uncertainty (error bar).
- stoner_measurement.core.trace_data.COLUMN_ROLE_X: str = 'x'¶
Role tag identifying the independent-variable column.
- stoner_measurement.core.trace_data.COLUMN_ROLE_Y: str = 'y'¶
Role tag identifying a column as the primary dependent variable.
- stoner_measurement.core.trace_data.COLUMN_ROLE_Z: str = 'z'¶
Role tag identifying a column as a secondary dependent variable.
- class stoner_measurement.core.trace_data.TraceData(df: DataFrame | None = None, *, column_roles: dict[str, str] | None = None, names: dict[str, str] | None = None, units: dict[str, str] | None = None)[source]¶
Bases:
objectOne complete trace table with a shared independent-variable column.
The DataFrame uses a simple integer row index. Its columns store the independent variable, measured or derived data, and uncertainties on the same row grid. Column roles identify x (
x), primary data (y), auxiliary data (z), x uncertainty (d), and y uncertainty (e).namesandunitsare completed for every DataFrame column during construction. Unknown role or metadata keys are rejected so these mappings cannot silently drift away from the table.Use
from_xy()as a convenience for a conventional single-y trace.- append_row(row: dict[str, object], *, batch_size: int = 256) None[source]¶
Append one committed row, growing the backing frame in batches.
- property columns: list[str]¶
Ordered list of column names in the underlying DataFrame.
Examples
>>> import numpy as np >>> from stoner_measurement.core import TraceData >>> td = TraceData.from_xy(np.array([1.0]), np.array([2.0])) >>> td.columns ['y']
- property d: ndarray¶
First
COLUMN_ROLE_D-role column as a one-dimensional NumPy array.- Returns:
The first
"d"-role column, or an empty float64 array if no such column exists.- Return type:
(np.ndarray)
Examples
>>> import numpy as np >>> from stoner_measurement.core import TraceData >>> td = TraceData.from_xy(np.array([0.0]), np.array([1.0])) >>> len(td.d) 0
- property df: DataFrame¶
The committed DataFrame rows (integer row index, columns = channels).
- Returns:
A view containing committed rows only. Reserved append capacity is excluded.
- Return type:
(pd.DataFrame)
Examples
>>> import numpy as np, pandas as pd >>> from stoner_measurement.core import TraceData >>> td = TraceData.from_xy(np.array([1.0, 2.0]), np.array([3.0, 4.0])) >>> isinstance(td.df, pd.DataFrame) True >>> list(td.df.columns) ['x', 'y']
- property e: ndarray¶
First
COLUMN_ROLE_E-role column as a one-dimensional NumPy array.- Returns:
The first
"e"-role column, or an empty float64 array if no such column exists.- Return type:
(np.ndarray)
Examples
>>> import numpy as np >>> from stoner_measurement.core import TraceData >>> td = TraceData.from_xy(np.array([0.0]), np.array([1.0])) >>> len(td.e) 0
- property expected_column_roles: dict[str, str]¶
Return role metadata for the anticipated complete schema.
- classmethod from_xy(x: ndarray, y: ndarray, *, x_error: ndarray | None = None, y_error: ndarray | None = None, names: dict[str, str] | None = None, units: dict[str, str] | None = None) TraceData[source]¶
Build a conventional single-y trace without a second constructor path.
- get_columns_by_role(role: str) list[str][source]¶
Return the names of all columns that carry role.
- Parameters:
role (str) – One of the
COLUMN_ROLE_*constants.- Returns:
Column names (in insertion order) whose role matches role. Empty list if no columns carry that role.
- Return type:
Examples
>>> import numpy as np >>> from stoner_measurement.core import ( ... TraceData, COLUMN_ROLE_Y, COLUMN_ROLE_E, ... ) >>> td = TraceData.from_xy(np.array([1.0]), np.array([2.0])) >>> td.get_columns_by_role(COLUMN_ROLE_Y) ['y'] >>> td.get_columns_by_role(COLUMN_ROLE_E) []
- reserve_rows(capacity: int) None[source]¶
Reserve storage for at least capacity rows without exposing empty rows.
- set_expected_schema(schema: TraceData) None[source]¶
Advertise the columns and metadata expected after acquisition.
- property x: ndarray¶
Independent-variable values as a one-dimensional NumPy array.
- Returns:
The
COLUMN_ROLE_Xcolumn as a float64 array.- Return type:
(np.ndarray)
Examples
>>> import numpy as np >>> from stoner_measurement.core import TraceData >>> td = TraceData.from_xy(np.array([0.0, 1.0]), np.array([2.0, 3.0])) >>> td.x.tolist() [0.0, 1.0]
- property y: ndarray¶
First
COLUMN_ROLE_Y-role column as a one-dimensional NumPy array.- Returns:
The first
"y"-role column, or an empty float64 array if no such column exists.- Return type:
(np.ndarray)
Examples
>>> import numpy as np >>> from stoner_measurement.core import TraceData >>> td = TraceData.from_xy(np.array([0.0, 1.0]), np.array([2.0, 3.0])) >>> td.y.tolist() [2.0, 3.0]