stoner_measurement.plugins.command.save.SaveCommand¶
- class stoner_measurement.plugins.command.save.SaveCommand(parent=None)[source]¶
Bases:
CommandPluginSave 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.
sequenceis the depth-first list of dotted instance paths; each path’s final component names a top-level serialised configuration item, alongside evaluatedoutputsscalar 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_overwriteisTrue(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 explicitfprefix 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 toTrue(or absent from the dict) means the trace is saved; mapping toFalsemeans 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 whenh5pyis 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
savein 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.
Noneapplies the command’s configuredtrace_selectionmapping.- Returns:
Metadata and numeric columns detached from the live namespace.
- Return type:
- 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
_tracescatalogue 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
- execute(*, trace: str | list[str] | None = None, no_overwrite: bool | None = None) None[source]¶
Evaluate
path_exprand write data to disc.Evaluates
path_exprin 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:
traceoptionally selects one or more trace catalogue keys.no_overwriteoverridesno_overwritefor this call only.
When the effective no-overwrite flag is
Trueand 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
tracekwarg the selection is driven bytrace_selection(absent key → enabled). Whentraceis 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 theto_json()state of each plugin instance in the current sequence.sequencestores depth-first dotted instance paths so nested steps retain their structure; each final path component maps to its serialised configuration at the metadata root, andoutputsmaps 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 oftrace_selection. Defaults toNone(use configuredtrace_selection).no_overwrite (bool | None) – When
True, prevent overwriting an existing file (seeno_overwrite).None(default) uses the configuredno_overwriteattribute.
- Raises:
RuntimeError – If the plugin is not attached to a sequence engine.
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.
- 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'
- 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:
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