stoner_measurement.plugins.base_plugin.BasePlugin¶
- class stoner_measurement.plugins.base_plugin.BasePlugin[source]¶
Bases:
ABCAbstract root class shared by all measurement plugins.
Subclasses must implement
name. Subclasses may optionally overrideconfig_widget(),config_tabs(), andmonitor_widget()to provide richer UI integration.Implement
declared_outputs()to publish trace expressions, configured schemas and scalar units together. Legacy publication hooks remain supported and are compatibility views for migrated plugins.Rather than subclassing
BasePlugindirectly, prefer one of the six specialised sub-types:TracePlugin— collects (x, y) traces from instruments.StateControlPlugin— controls experimental state (field, temperature, etc.).MonitorPlugin— passively records auxiliary quantities.TransformPlugin— performs pure-computation transforms on collected data.SequencePlugin— acts as a branch node in the sequence tree, containing nested sub-steps.CommandPlugin— executes a single action in the sequence without instrument lifecycle steps.
- Variables:
plugin_type (str) – Short tag identifying the sub-type. Overridden by each specialised base class.
has_lifecycle (bool) –
Truefor plugins that participate in the connect/configure/ disconnect lifecycle emitted by the sequence engine. ReturnsFalseforCommandPluginsubclasses, which only contribute an action call.instance_name (str) – Per-instance variable name used in the sequence engine namespace. Defaults to a sanitised form of
name(lowercase, spaces and hyphens replaced with underscores). Must be a valid Python identifier. Setting this attribute emitsinstance_name_changed(old_name, new_name)in QObject sub-types.sequence_engine (SequenceEngine | None) – Reference to the
SequenceEnginethat owns this plugin, orNoneif the plugin is not currently loaded into an engine. Set automatically byadd_plugin()and cleared byremove_plugin(). Plugin lifecycle methods (connect,configure,measure, etc.) can read values set by other parts of the measurement sequence viaengine_namespace.comment (str) – Optional short note shown in the sequence list after the plugin label when non-empty.
- config_tabs(parent: QWidget | None = None) list[tuple[str, QWidget]][source]¶
Return a list of
(tab_title, widget)pairs for the config panel.Each pair contributes one tab to the right-hand configuration panel. The default implementation wraps
config_widget()in a Settings tab, appends a General tab containing the instance-name editor, and optionally appends an About tab whose HTML content is provided by_about_html().Override this method when a plugin needs to contribute more than one tab, or when a custom tab title is desired.
- Keyword Parameters:
parent (QWidget | None) – Optional Qt parent widget passed to each tab widget.
- Returns:
List of
(tab_title, widget)pairs.- Return type:
Examples
>>> from qtpy.QtWidgets import QApplication >>> _ = QApplication.instance() or QApplication([]) >>> from stoner_measurement.plugins.base_plugin import BasePlugin >>> class _Minimal(BasePlugin): ... @property ... def name(self): return "Minimal" >>> plugin = _Minimal() >>> tabs = plugin.config_tabs() >>> len(tabs) 2 >>> tabs[0][0] 'Settings' >>> tabs[1][0] 'General'
- config_widget(parent: QWidget | None = None) QWidget[source]¶
Return a
QWidgetfor configuring this plugin.The default implementation returns a simple label. Override this method to provide a richer configuration interface. This method is called by the default
config_tabs()implementation to supply the single tab widget.- Keyword Parameters:
parent (QWidget | None) – Optional Qt parent widget.
- Returns:
The configuration widget for this plugin.
- Return type:
(QWidget)
Examples
>>> from qtpy.QtWidgets import QApplication >>> _ = QApplication.instance() or QApplication([]) >>> from stoner_measurement.plugins.trace import DummyPlugin >>> plugin = DummyPlugin() >>> widget = plugin.config_widget() >>> widget is not None True
- configured_trace_data() dict[str, TraceData][source]¶
Return the compatibility view of configured trace schemas.
Return empty tables with columns, roles, names and units, keyed exactly as in
reported_traces(). Omit outputs whose schema is unknown. New plugins supply schemas throughdeclared_outputs(); existing overrides remain supported. Schema construction must not access hardware, evaluate runtime expressions or modify acquired results. Refresh the engine’s catalogues after configuration changes.
- connect() None[source]¶
Open owned resources; repeated calls must first release existing ones.
The shared lifecycle wrapper calls
disconnect()before retrying a previous connection attempt, including a partially failed attempt. Resource-owning plugins must implement idempotentdisconnect()that also closes partially opened resources and clears their references. The default is a no-op for plugins without hardware resources.
- property controller_features: frozenset[str]¶
Return controller feature flags required by this plugin.
- declared_outputs() PluginOutputs | None[source]¶
Declare configured trace and scalar outputs in one place.
Return ordered, fully qualified catalogue identifiers with typed expressions, units and optional empty schemas. Declarations must not access hardware or evaluate runtime expressions. None selects legacy adaptation; an empty PluginOutputs explicitly declares no outputs.
For mapping-backed outputs, set each descriptor’s
result_keyto its local data key, independently of the catalogue identifier. Defer schemas that depend on scalar catalogues withschema_factory. Keep the legacy publication hooks as inherited compatibility views; extend a migrated parent’ssuper().declared_outputs()instead.- Returns:
Unified declarations or legacy adaptation.
- Return type:
(PluginOutputs | None)
- delay_configuration: bool = False¶
Derived by the sequence’s Reconfigure selections; no direct UI control.
- property engine_namespace: dict¶
Live view of the sequence engine’s interpreter namespace.
Returns the live
globalsdict used by the sequence engine so that plugin lifecycle methods (connect,configure,measure, etc.) can read or write variables that were set by other parts of the measurement sequence.Because this is the live dict (not a copy), reads always reflect the current state of the namespace even during a running script. Writes are also immediately visible to the executing script.
When the plugin is not attached to an engine (i.e.
sequence_engineisNone) an empty dict is returned so that callers do not need to guard againstNone.- Returns:
The live interpreter namespace dict, or
{}when detached.- Return type:
(dict)
Examples
>>> from stoner_measurement.plugins.trace import DummyPlugin >>> plugin = DummyPlugin() >>> plugin.engine_namespace # detached — returns empty dict {} >>> from qtpy.QtWidgets import QApplication >>> _ = QApplication.instance() or QApplication([]) >>> from stoner_measurement.core.sequence_engine import SequenceEngine >>> engine = SequenceEngine() >>> engine.add_plugin("dummy", plugin) >>> engine._namespace["sweep_start"] = 0.5 >>> plugin.engine_namespace["sweep_start"] 0.5 >>> engine.shutdown()
- eval(expr: str) Any[source]¶
Evaluate a Python expression using the sequence engine namespace.
The expression is evaluated via
asteval.Interpreter— a safe, restricted evaluator that supports the full mathematical subset of Python syntax. The live engine namespace (including all numpy functions seeded at startup and any variables set by earlier sequence steps) is used as the interpreter symbol table, so expressions like"sqrt(x)"or"linspace(0, field_max, 100)"work without any additional imports.Plain and raw string literals containing replacement fields are promoted to f-strings immediately before evaluation. For example,
'Run {index}'interpolates without an explicitfprefix while leaving the stored expression unchanged. If the initial text is not syntactically valid Python, it is retried as a quoted string and the same template promotion is applied. Errors from syntactically valid expressions are not converted into strings.This method must only be called while the plugin is attached to a sequence engine (i.e.
sequence_engineis notNone).- Parameters:
expr (str) – A single Python expression to evaluate.
- Returns:
The value produced by evaluating expr.
- Return type:
(Any)
- Raises:
RuntimeError – If the plugin is not currently attached to a sequence engine.
Exception – Any runtime error raised by a valid expression, or an error raised while evaluating the quoted-string fallback.
Examples
>>> from qtpy.QtWidgets import QApplication >>> _ = QApplication.instance() or QApplication([]) >>> from stoner_measurement.plugins.trace import DummyPlugin >>> from stoner_measurement.core.sequence_engine import SequenceEngine >>> engine = SequenceEngine() >>> plugin = DummyPlugin() >>> engine.add_plugin("dummy", plugin) >>> plugin.eval("1 + 1") 2 >>> plugin.eval("sqrt(9.0)") 3.0 >>> engine.shutdown()
- eval_float(expr: str | float | int) float[source]¶
Resolve a numeric literal or expression to a floating-point value.
When attached to a sequence engine, string values are evaluated in the live engine namespace via
eval(). Numeric values are converted directly, so callers can use one path for settings loaded from either older numeric JSON or newer expression strings.- Parameters:
expr (str | float | int) – Numeric value or Python expression producing one.
- Returns:
The resolved floating-point value.
- Return type:
(float)
- Raises:
RuntimeError – If the plugin is not attached to a sequence engine.
Exception – Any expression-evaluation or conversion error raised while attached to an engine.
- classmethod from_json(data: dict[str, Any], parent: QObject | None = None) BasePlugin[source]¶
Reconstruct a plugin from a serialised dict produced by
to_json().Uses the
"class"field to import the concrete plugin class, creates a new instance, restoresinstance_name, and calls_restore_from_json()so that subclasses can restore additional state such as the active scan generator.- Parameters:
data (dict[str, Any]) – Serialised plugin dict as produced by
to_json().- Keyword Parameters:
parent (QObject | None) – Optional Qt parent for QObject-based plugin subclasses.
- Returns:
A fully configured plugin instance of the correct concrete type.
- Return type:
- Raises:
KeyError – If
datadoes not contain a"class"key.ImportError – If the module specified in
"class"cannot be imported.AttributeError – If the class name specified in
"class"is not found in the module.
Examples
>>> from qtpy.QtWidgets import QApplication >>> _ = QApplication.instance() or QApplication([]) >>> from stoner_measurement.plugins.trace import DummyPlugin >>> original = DummyPlugin() >>> original.instance_name = "my_dummy" >>> restored = BasePlugin.from_json(original.to_json()) >>> restored.instance_name 'my_dummy' >>> type(restored).__name__ 'DummyPlugin'
- full_refresh() None[source]¶
Recursively refresh this plugin and all member plugins.
The default implementation performs a local
refresh()and then callsfull_refresh()on every plugin returned bymember_plugins().
- generate_action_code(indent: int, sub_steps: list, render_sub_step: Callable) list[str][source]¶
Return the action code lines for this plugin at the given indentation level.
The sequence engine calls this method when building the action body of the generated script. The default implementation emits a comment indicating an unknown plugin type. Specialised sub-types (
TracePlugin,StateControlPlugin, etc.) override this method to produce the appropriate code.- Parameters:
indent (int) – Number of four-space indentation levels for the emitted lines.
sub_steps (list) – Raw sub-step descriptors from the sequence tree (strings or
(plugin_or_name, [sub-steps…])tuples). Leaf plugins (e.g.TracePlugin) can ignore this; container plugins should call render_sub_step for each entry.render_sub_step (Callable) – Callback with signature
(step, indent) -> list[str]provided by the sequence engine. Container plugins call this to render each nested step at the appropriate indentation level.
- Returns:
Lines of Python source code (without trailing newlines) that implement this plugin’s action phase.
- Return type:
Examples
>>> from stoner_measurement.plugins.trace import DummyPlugin >>> plugin = DummyPlugin() >>> lines = plugin.generate_action_code(1, [], lambda s, i: []) >>> "dummy.measure" in "\n".join(lines) True
- generate_finally_code(indent: int) list[str][source]¶
Return optional lines to run before lifecycle disconnects in
finally.
- generate_instantiation_code() list[str][source]¶
Return Python code lines that conditionally instantiate this plugin from its config.
The generated code checks whether the plugin’s
instance_namevariable already exists inglobals()(i.e. was injected into the namespace by the sequence engine) and, only if it does not, recreates the plugin from its serialised configuration usingfrom_json().This ensures that a saved script is self-contained: when run outside the app (e.g. loaded from a file into a fresh Python session), the plugin is reconstructed from the configuration that was current at the time the script was generated. When the script is run by the app with the plugin already registered in the engine namespace, the existing instance is kept unchanged so that live engine state (such as the
sequence_engineback-reference) is preserved.The caller (
generate_sequence_code()) is responsible for emitting the following one-time import before calling this method for any plugin:from stoner_measurement.plugins.base_plugin import BasePlugin as _BasePlugin
Examples
>>> from qtpy.QtWidgets import QApplication >>> _ = QApplication.instance() or QApplication([]) >>> from stoner_measurement.plugins.trace import DummyPlugin >>> plugin = DummyPlugin() >>> lines = plugin.generate_instantiation_code() >>> lines[0] 'if "dummy" not in globals():' >>> '_BasePlugin.from_json' in lines[1] True >>> '_json.loads' in lines[1] False
- property has_lifecycle: bool¶
Whether this plugin participates in the connect/configure/disconnect lifecycle.
The sequence engine checks this flag when generating code so that
CommandPluginsubclasses (which execute a single action without hardware lifecycle steps) are omitted from the connect, configure, and disconnect phases.- Returns:
Truefor all plugin types exceptCommandPlugin, which overrides this to returnFalse.- Return type:
(bool)
Examples
>>> from stoner_measurement.plugins.trace import DummyPlugin >>> DummyPlugin().has_lifecycle True
- property instance_name: str¶
Variable name for this instance in the sequence engine namespace.
Defaults to a sanitised form of
name(lowercase, spaces and hyphens replaced with underscores). May be changed at runtime to support multiple instances of the same plugin type.Use a class attribute _DEFAULT_INSTANCE followed by fallback to the class’s name attribute.
- Returns:
A valid Python identifier.
- Return type:
(str)
Examples
>>> from stoner_measurement.plugins.trace import DummyPlugin >>> plugin = DummyPlugin() >>> plugin.instance_name 'dummy'
- property is_loop_container: bool¶
Return whether nested steps execute inside a generated Python loop.
The default is
False. Sequence container plugins that generate a loop override this marker so placement-sensitive commands can validate their position without depending on particular scan implementations.
- property log: Logger¶
Logger for this plugin.
When the plugin is attached to a sequence engine, returns the shared
loglogging.Loggerfrom the engine namespace so that all plugin code and user scripts share a single logger whose records are routed through the engine’s Qt log handler.When the plugin is not attached (i.e.
sequence_engineisNone), returns a module-level logger named after the plugin’s class so that standalone plugin code still has a functional logger.- Returns:
A
logging.Loggerinstance.- Return type:
Examples
>>> from stoner_measurement.plugins.trace import DummyPlugin >>> plugin = DummyPlugin() >>> import logging >>> isinstance(plugin.log, logging.Logger) True >>> from qtpy.QtWidgets import QApplication >>> _ = QApplication.instance() or QApplication([]) >>> from stoner_measurement.core.sequence_engine import SequenceEngine >>> engine = SequenceEngine() >>> engine.add_plugin("dummy", plugin) >>> plugin.log is engine._namespace["log"] True >>> engine.shutdown()
- member_plugins() list[BasePlugin][source]¶
Return any
BasePlugininstances owned directly by this plugin.This hook is used by
sequence_plugins()to discover plugins nested inside container plugins. The engine calls this method recursively so that deeply nested plugin hierarchies are fully enumerated.The default implementation returns an empty list. Plugins that own other plugin instances as attributes (e.g. a combined plugin that wraps a
TracePluginand aMonitorPlugin) should override this method to expose those instances.- Returns:
Ordered list of directly owned plugin instances. Must not include
self.- Return type:
(list[BasePlugin])
Examples
>>> from stoner_measurement.plugins.base_plugin import BasePlugin >>> class _Minimal(BasePlugin): ... @property ... def name(self): return "Minimal" >>> _Minimal().member_plugins() []
- monitor_widget(parent: QWidget | None = None) QWidget | None[source]¶
Return an optional live-status widget for the left dock panel.
The widget will be displayed in the monitoring section of the
DockPanelwhile the plugin is registered. The default implementation returnsNone, meaning the plugin contributes no monitoring widget.- Keyword Parameters:
parent (QWidget | None) – Optional Qt parent widget.
- Returns:
A monitoring widget, or
Noneif the plugin provides none.- Return type:
(QWidget | None)
Examples
>>> from stoner_measurement.plugins.trace import DummyPlugin >>> plugin = DummyPlugin() >>> plugin.monitor_widget() is None True
- property plugin_type: str¶
Short tag identifying the plugin sub-type.
- Returns:
"base"for directBasePluginsubclasses. Overridden to"trace","state","monitor","transform", or"command"by the respective specialised sub-types.- Return type:
(str)
- reconfigure() None[source]¶
Reconnect safely, then apply this instance’s settings at the current step.
- refresh() None[source]¶
Refresh this plugin and any cached configuration widgets.
This method is intended for programmatic use (for example from the console) after mutating plugin attributes directly. It refreshes this plugin’s derived state, the active scan generator (when present), the attached engine’s output catalogues, and cached configuration widgets that expose a
refresh()method. It does not connect to or configure instruments.
- remap_trace_reference(old_key: str, new_key: str, old_expression: str, new_expression: str) None[source]¶
Update common configuration references after a trace output is renamed.
- reported_traces() dict[str, str][source]¶
Return trace access expressions from resolved output declarations.
- Returns:
- Catalogue identifiers mapped to expressions that
retrieve acquired TraceData tables from the live namespace.
- Return type:
Notes
This is a compatibility view. New publication implementations use
declared_outputs(); declaration does not acquire data.
- reported_value_units() dict[str, str][source]¶
Return scalar units from resolved output declarations.
- Returns:
- Physical units keyed by scalar catalogue identity,
matching
reported_values(). Empty units mean unspecified or dimensionless. New plugins set units on ScalarOutput.
- Return type:
- reported_values() dict[str, str][source]¶
Return scalar access expressions from resolved output declarations.
- require_ready() None[source]¶
Reject execution until every meaningful lifecycle phase has succeeded.
- property scan¶
Alias for a plugin’s
scan_generatorattribute.This convenience property exists primarily for interactive console use, allowing
plugin.scaninstead ofplugin.scan_generator.- Raises:
AttributeError – If the plugin does not define a
scan_generatorattribute.
- sequence_engine: SequenceEngine | None = None¶
Reference to the owning SequenceEngine; set by add_plugin / remove_plugin.
- to_json() dict[str, Any][source]¶
Serialise this plugin’s configuration to a JSON-compatible dict.
The returned dict contains at minimum:
"type"— the plugin sub-type tag (e.g."trace","state")."class"— the fully qualified class path"module:ClassName"used byfrom_json()to reconstruct the exact subclass."instance_name"— the currentinstance_name.
Subclasses should call
super().to_json()and then add their own configuration keys to the returned dict.- Returns:
A JSON-serialisable dictionary representing this plugin’s current configuration.
- Return type:
Examples
>>> from qtpy.QtWidgets import QApplication >>> _ = QApplication.instance() or QApplication([]) >>> from stoner_measurement.plugins.trace import DummyPlugin >>> plugin = DummyPlugin() >>> d = plugin.to_json() >>> d["type"] 'trace' >>> d["instance_name"] 'dummy' >>> "class" in d True
- tooltip() str[source]¶
Return a short tooltip description for this plugin.
The default implementation extracts the first non-empty line of the class docstring and returns it (stripped of leading/trailing whitespace). Subclasses may override this to provide alternative tooltip text.
- Returns:
A one-line description of the plugin, or an empty string if no docstring is available.
- Return type:
(str)
Examples
>>> from stoner_measurement.plugins.trace import DummyPlugin >>> plugin = DummyPlugin() >>> tooltip = plugin.tooltip() >>> isinstance(tooltip, str) True >>> len(tooltip) > 0 True
- validate() bool[source]¶
Check configuration before connection without evaluating expressions.
Override to check literal settings and expression syntax. Do not access hardware, evaluate runtime expressions or modify configuration.
- Returns:
True when configuration passes preflight checks.
- Return type:
(bool)
- Raises:
ValidationError – If configuration is invalid.
- validate_sequence_position(sequence_steps: list) None[source]¶
Validate this plugin’s position in sequence_steps.
The base implementation accepts every position. Plugins with placement constraints may inspect the complete nested step list and raise an exception with a user-facing message. The sequence editor calls this hook before inserting or moving a step, and code generation repeats the validation as a final safeguard.