stoner_measurement.plugins.base_plugin.BasePlugin

class stoner_measurement.plugins.base_plugin.BasePlugin[source]

Bases: ABC

Abstract root class shared by all measurement plugins.

Subclasses must implement name. Subclasses may optionally override config_widget(), config_tabs(), and monitor_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 BasePlugin directly, 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) – True for plugins that participate in the connect/configure/ disconnect lifecycle emitted by the sequence engine. Returns False for CommandPlugin subclasses, 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 emits instance_name_changed(old_name, new_name) in QObject sub-types.

  • sequence_engine (SequenceEngine | None) – Reference to the SequenceEngine that owns this plugin, or None if the plugin is not currently loaded into an engine. Set automatically by add_plugin() and cleared by remove_plugin(). Plugin lifecycle methods (connect, configure, measure, etc.) can read values set by other parts of the measurement sequence via engine_namespace.

  • comment (str) – Optional short note shown in the sequence list after the plugin label when non-empty.

property comment: str

Optional short note associated with this plugin instance.

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:

(list[tuple[str, QWidget]])

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 QWidget for 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
configure() → None[source]

Default configuration phase for plugins without setup work.

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 through declared_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.

Returns:

Independent empty schemas keyed by catalogue identifier. Outputs with unknown schemas are omitted.

Return type:

(dict[str, TraceData])

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 idempotent disconnect() 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_key to its local data key, independently of the catalogue identifier. Defer schemas that depend on scalar catalogues with schema_factory. Keep the legacy publication hooks as inherited compatibility views; extend a migrated parent’s super().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.

disabled: bool = False

When True this plugin is disabled and will not contribute generated code.

disconnect() → None[source]

Default cleanup phase for plugins without hardware resources.

property engine_namespace: dict

Live view of the sequence engine’s interpreter namespace.

Returns the live globals dict 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_engine is None) an empty dict is returned so that callers do not need to guard against None.

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 explicit f prefix 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_engine is not None).

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, restores instance_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:

(BasePlugin)

Raises:
  • KeyError – If data does 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 calls full_refresh() on every plugin returned by member_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:

(list[str])

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_name variable already exists in globals() (i.e. was injected into the namespace by the sequence engine) and, only if it does not, recreates the plugin from its serialised configuration using from_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_engine back-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
Returns:

Lines of Python source code (without trailing newlines).

Return type:

(list[str])

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 CommandPlugin subclasses (which execute a single action without hardware lifecycle steps) are omitted from the connect, configure, and disconnect phases.

Returns:

True for all plugin types except CommandPlugin, which overrides this to return False.

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 log logging.Logger from 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_engine is None), returns a module-level logger named after the plugin’s class so that standalone plugin code still has a functional logger.

Returns:

A logging.Logger instance.

Return type:

(logging.Logger)

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 BasePlugin instances 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 TracePlugin and a MonitorPlugin) 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 DockPanel while the plugin is registered. The default implementation returns None, meaning the plugin contributes no monitoring widget.

Keyword Parameters:

parent (QWidget | None) – Optional Qt parent widget.

Returns:

A monitoring widget, or None if the plugin provides none.

Return type:

(QWidget | None)

Examples

>>> from stoner_measurement.plugins.trace import DummyPlugin
>>> plugin = DummyPlugin()
>>> plugin.monitor_widget() is None
True
abstract property name: str

Unique human-readable name for this plugin.

property plugin_type: str

Short tag identifying the plugin sub-type.

Returns:

"base" for direct BasePlugin subclasses. 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:

(dict[str, str])

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:

(dict[str, str])

reported_values() → dict[str, str][source]

Return scalar access expressions from resolved output declarations.

Returns:

Scalar catalogue identifiers mapped to runtime

expressions. Presence does not imply a result is available.

Return type:

(dict[str, str])

require_ready() → None[source]

Reject execution until every meaningful lifecycle phase has succeeded.

property scan

Alias for a plugin’s scan_generator attribute.

This convenience property exists primarily for interactive console use, allowing plugin.scan instead of plugin.scan_generator.

Raises:

AttributeError – If the plugin does not define a scan_generator attribute.

sequence_engine: SequenceEngine | None = None

Reference to the owning SequenceEngine; set by add_plugin / remove_plugin.

start() → None[source]

Reset per-run lifecycle state before a generated sequence starts.

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 by from_json() to reconstruct the exact subclass.

  • "instance_name" — the current instance_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:

(dict[str, Any])

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.

Parameters:

sequence_steps (list) – Nested sequence descriptors containing the proposed plugin position.

Raises:

Exception – Subclasses may raise when the proposed position is invalid.