stoner_measurement.plugins.command.save.SaveCommand

class stoner_measurement.plugins.command.save.SaveCommand(parent=None)[source]

Bases: CommandPlugin

Save traces or collected table data to a TDI or NeXus file.

Use this command when you want to write the current measurement results to disk from inside a sequence. It can save either:

  • one or more trace datasets from the trace catalogue, including collected state-scan and state-sweep tables.

In the configuration panel you select which trace tables to save and provide a path expression. The path can be a fixed filename or a Python expression that builds a filename from current sequence variables, for example:

"f'data/run_{run_index:03d}.txt'"

By default, existing files are not overwritten. Instead, if the chosen filename already exists, a numeric suffix is added automatically.

The format selector offers TDI text or NeXus/HDF5 (requiring h5py). The default TDI Format 2.0 text file is structured as follows:

  • The top-left cell (row 0, column 0) contains "TDI Format 2.0".

  • The remaining cells of row 0 are trace column headers with the form "{channel_name}:{axis_label} ({axis_units})".

  • The remaining cells of column 0 (rows 1 onwards) hold a flattened metadata snapshot. sequence is the depth-first list of dotted instance paths; each path’s final component names a top-level serialised configuration item, alongside evaluated outputs scalar readings. Nested dicts are flattened using . separators; list items use [{index}] notation.

  • The remaining cells (rows 1 onwards, columns 1 onwards) contain the numerical data from each column.

If a parent directory does not exist it is created automatically. When no_overwrite is True (the default) and the resolved path already exists, a numeric suffix (_001, _002, …) is inserted before the file extension until a free filename is found.

Variables:
  • path_expr (str) – Python expression string that evaluates to the filename or path. Plain or raw string literals containing { are automatically evaluated as f-strings, so an explicit f prefix is optional. Defaults to "'data/output.txt'". A relative value is first joined to the default data directory configured in the application settings, then the complete path is evaluated for replacement fields. This allows placeholders in either the preference-sourced directory or this command’s filename. If no default data directory is set the path is relative to the current working directory.

  • trace_selection (dict[str, bool]) – Per-trace enable flags for trace mode. Keys are trace catalogue keys ("{instance_name}:{channel_name}"). A key mapping to True (or absent from the dict) means the trace is saved; mapping to False means it is excluded. An empty dict (the default) saves all available traces.

  • no_overwrite (bool) – When True (the default) an existing file is never overwritten; instead a numeric suffix is appended to the stem until a free filename is found.

  • save_format (str) – Registered writer identifier for the output file format. Defaults to "tdi". "nexus" writes a NeXus/HDF5 file when h5py is available.

  • instance_name (str) – Inherited Python identifier for this instance in the Script tab and QtConsole.

  • comment (str) – Inherited optional note displayed beside this step.

  • sequence_engine (SequenceEngine | None) – Inherited owning engine and its live namespace; None while detached.

Keyword Parameters:

parent (QObject | None) – Optional Qt parent object.

Examples

With an instance named save in the sequence, use the QtConsole to inspect or edit it before running. Substitute your instance name if different; result data reflects completed steps:

save.path_expr = "'sample/run.txt'"
save.no_overwrite = True
save.save_format = "tdi"
build_payload(*, trace_keys: set[str] | None = None) → SavePayload[source]

Take an independent snapshot of selected data ready for writing.

The returned arrays are copies, so a caller may pass the payload to a background writer without retaining a live view of data that the sequence engine may continue to update.

Keyword Arguments:

trace_keys (set[str] | None) – Trace catalogue keys to include. None applies the command’s configured trace_selection mapping.

Returns:

Metadata and numeric columns detached from the live namespace.

Return type:

(SavePayload)

config_widget(parent: QWidget | None = None) → QWidget[source]

Return a settings widget for the save command.

Displays controls for the output path expression, output file format, incremental and no-overwrite flags, and a scrollable list of per-trace checkboxes built from the _traces catalogue in the sequence engine namespace (or an empty list when the plugin is detached).

Keyword Parameters:

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

Returns:

The settings widget for the Settings tab.

Return type:

(QWidget)

Examples

>>> from qtpy.QtWidgets import QApplication
>>> _ = QApplication.instance() or QApplication([])
>>> from stoner_measurement.plugins.command import SaveCommand
>>> from qtpy.QtWidgets import QWidget
>>> isinstance(SaveCommand().config_widget(), QWidget)
True
configure() → None[source]

No-op lifecycle hook; Save has no hardware to configure.

connect() → None[source]

Start a new save session, forgetting incremental files from earlier runs.

disconnect() → None[source]

No-op lifecycle hook; Save has no hardware to disconnect.

execute(*, trace: str | list[str] | None = None, no_overwrite: bool | None = None) → None[source]

Evaluate path_expr and write data to disc.

Evaluates path_expr in the sequence engine namespace to obtain the output file path, creates any required parent directories, and writes a TDI Format 2.0 tab-delimited text file.

The keyword parameters allow per-call overrides of the configured settings without permanently modifying the plugin:

  • trace optionally selects one or more trace catalogue keys.

  • no_overwrite overrides no_overwrite for this call only.

When the effective no-overwrite flag is True and the resolved path already exists, a numeric suffix (_001, _002, …) is appended before the file extension until a free filename is found.

The x axis and every DataFrame column of each selected trace contributes one output column. Without the trace kwarg the selection is driven by trace_selection (absent key → enabled). When trace is supplied it must be a trace catalogue key or a list of trace catalogue keys; only those traces are saved. Column headers have the form "{channel_name}:{axis_label} ({axis_units})".

The file layout is:

  • Row 0 — "TDI Format 2.0" followed by one column header per data column.

  • Column 0 (rows 1+) — flattened metadata entries of the form "{key}{typename}={repr(value)}" collected from the to_json() state of each plugin instance in the current sequence. sequence stores depth-first dotted instance paths so nested steps retain their structure; each final path component maps to its serialised configuration at the metadata root, and outputs maps catalogue keys to evaluated current scalar readings.

  • Remaining cells — numerical data from each data column.

Keyword Parameters:
  • trace (str | list[str] | None) – One or more trace catalogue keys ("{instance_name}:{channel_name}" format) to save. When supplied, only the listed traces are saved regardless of trace_selection. Defaults to None (use configured trace_selection).

  • no_overwrite (bool | None) – When True, prevent overwriting an existing file (see no_overwrite). None (default) uses the configured no_overwrite attribute.

Raises:
  • RuntimeError – If the plugin is not attached to a sequence engine.

  • TypeError – If path_expr does not evaluate to a string.

  • OSError – If the file cannot be written (e.g. due to permissions).

Examples

>>> from qtpy.QtWidgets import QApplication
>>> _ = QApplication.instance() or QApplication([])
>>> import tempfile, os
>>> from stoner_measurement.plugins.command import SaveCommand
>>> from stoner_measurement.core.sequence_engine import SequenceEngine
>>> engine = SequenceEngine()
>>> cmd = SaveCommand()
>>> engine.add_plugin("save", cmd)
>>> with tempfile.TemporaryDirectory() as tmp:
...     path = os.path.join(tmp, "out.txt")
...     cmd.path_expr = repr(path)
...     cmd.execute()
...     first_line = open(path).readline().rstrip("\n")
>>> first_line.startswith("TDI Format 2.0")
True
>>> engine.shutdown()
property has_lifecycle: bool

Participate in lifecycle setup so each script starts a new save session.

incremental_save: bool
property name: str

Unique identifier for the save command.

Returns:

"Save".

Return type:

(str)

Examples

>>> from qtpy.QtWidgets import QApplication
>>> _ = QApplication.instance() or QApplication([])
>>> from stoner_measurement.plugins.command import SaveCommand
>>> SaveCommand().name
'Save'
no_overwrite: bool
path_expr: str
save_format: str
to_json() → dict[str, Any][source]

Serialise the save command configuration to a JSON-compatible dict.

Returns:

Base dict from to_json() extended with "path_expr", "trace_selection", "no_overwrite", "incremental_save", and "save_format".

Return type:

(dict[str, Any])

Examples

>>> from qtpy.QtWidgets import QApplication
>>> _ = QApplication.instance() or QApplication([])
>>> from stoner_measurement.plugins.command import SaveCommand
>>> d = SaveCommand().to_json()
>>> d["type"]
'command'
>>> "path_expr" in d
True
>>> "trace_selection" in d
True
>>> "no_overwrite" in d
True
trace_selection: dict[str, bool]