stoner_measurement.plugins.transform.curve_fit.CurveFitPlugin

class stoner_measurement.plugins.transform.curve_fit.CurveFitPlugin(parent=None)[source]

Bases: TransformPlugin

Fit a user-defined model function to a selected trace.

Use this transform when you want to extract model parameters from measured data. It takes a selected trace, fits a function that you provide, and reports the fitted parameter values and uncertainties as outputs that can be plotted, saved, or reused elsewhere in the sequence.

The configuration UI is organised into three main tabs:

  • Data — contains the instance-name editor at the top, followed by data-selection controls. In simple mode choose a trace and optionally a specific y-column. In advanced mode provide expressions for x, y, and optional y-uncertainty data.

  • Fit Function — write the fitting function as Python source code or load a reusable module from the bundled Standard functions or per-user User functions library. The function must be named fit. An optional p0(x, y) function can generate initial parameter guesses. The complete editor source is executed, so imports and helper functions are available to both callables.

  • Parameters — a table with one column per detected parameter. Each parameter column lets you set optional minimum, initial, and maximum values plus the SI unit propagated with its scalar outputs. Optional outputs can also be enabled:

    • reporting the initial parameter values used by the fit

    • generating an initial fit trace

    • generating a best fit trace

This plugin executes user-supplied Python fit code. Only use trusted fit definitions in normal workflows.

Library discovery accepts modules containing only imports, function definitions, and an optional module docstring at top level. A module must define fit with at least two positional parameters; when present, p0 must take exactly (x, y). Load copies the complete module source into the editor. Save… writes the editor source beneath the per-user user_functions package and creates any missing package directories and __init__.py files. Double-clicking a module is equivalent to selecting it and pressing Load.

After a fit has run, each fitted parameter can be read directly by its function-signature name. For example, curve_fit.a returns the same value as curve_fit.data["a"]. Uncertainties and reported initial values remain available through data. Normal plugin attributes take precedence over dynamic fitted parameters; retrieve a clashing parameter name from data instead.

Variables:
  • trace_key (str) – Key in the _traces catalogue used in simple mode.

  • column_key (str) – Selected y-data column within trace_key. An empty string uses the source trace’s default y column.

  • advanced_mode (bool) – When True, x_expr, y_expr, and y_error_expr are used to select data instead of trace_key.

  • x_expr (str) – Python expression for the x data array (advanced mode).

  • y_expr (str) – Python expression for the y data array (advanced mode).

  • y_error_expr (str) – Python expression for the y-uncertainty array (advanced mode). When non-empty the array is passed as sigma with absolute_sigma=True.

  • fit_code (str) – Python source code defining the fit(x, …) function and optionally a p0(x, y) function.

  • fit_module_name (str) – Qualified library-module name last loaded or saved. It supplies package context for relative imports; fit_code remains the authoritative, serialised source executed by the transform.

  • param_names (list[str]) – Parameter names extracted from the fit function signature. Updated automatically whenever fit_code changes.

  • param_settings (dict[str, dict[str, float | str | None]]) – Per-parameter bounds, initial value, and SI unit. Each entry maps a parameter name to {"min": …, "initial": …, "max": …, "units": …}; None means unconstrained / auto for numeric settings.

  • show_initial_trace (bool) – When True, the transform stores an "initial_fit" trace in data containing the fitting function evaluated at the x data with the initial parameter estimates.

  • show_best_fit_trace (bool) – When True, the transform stores a "best_fit" trace in data containing the fitting function evaluated at the x data with the optimal parameters.

  • report_initial_values (bool) – When True, the initial parameter values actually used for the fit are also reported as scalar outputs in the values catalogue.

  • fit_code_syntax_error_line (int | None) – Line containing the latest detected syntax error in fit_code, or None when the code parses successfully.

  • fit_code_syntax_error_message (str) – Message for the latest detected fit-code syntax error, or an empty string when the code parses successfully.

  • fit (Callable[..., Any]) – Dynamically compiled fit function from fit_code. This callable is available from the Script tab or QtConsole without running a fit first.

  • p0 (Callable[..., Any]) – Dynamically compiled initial-estimate function from fit_code. This attribute is absent when the source does not define p0.

  • data (dict[str, Any]) – Inherited result mapping from the latest run(). It contains fitted values, "{parameter}_err" uncertainties, optional "{parameter}_initial" values, and any enabled fit traces.

  • instance_name (str) – Inherited sequence-instance name used to access this plugin in generated scripts and the QtConsole.

  • sequence_engine (SequenceEngine | None) – Inherited reference to the sequence engine and its live namespace.

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

Keyword Parameters:

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

Examples

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

curve_fit.param_names
curve_fit.fit_code = (
    "def fit(x, amplitude, offset):\n"
    "    return amplitude * x + offset\n\n"
    "def p0(x, y):\n"
    "    return (1.0, y.mean())\n"
)
curve_fit.data
config_tabs(parent: QWidget | None = None) → list[tuple[str, QWidget]][source]

Return the configuration tabs for this plugin.

Produces a Data tab (with the instance-name editor at the top, followed by trace / expression selection controls), a Fit Function tab containing a Python code editor, a Parameters tab with the per-parameter bounds table, and an optional About tab. The separate General tab is intentionally omitted — its controls are embedded at the top of the Data tab.

Keyword Parameters:

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

Returns:

List of (tab_title, widget) pairs.

Return type:

(list[tuple[str, QWidget]])

Examples

>>> from qtpy.QtWidgets import QApplication
>>> _ = QApplication.instance() or QApplication([])
>>> p = CurveFitPlugin()
>>> tabs = p.config_tabs()
>>> [t for t, _ in tabs[:3]]
['Data', 'Fit Function', 'Parameters']
>>> 'General' not in [t for t, _ in tabs]
True
declared_outputs() → PluginOutputs[source]

Declare fitted parameters, uncertainties and enabled fit traces.

property name: str

Unique identifier for this plugin.

Returns:

"Curve Fit".

Return type:

(str)

Examples

>>> from qtpy.QtWidgets import QApplication
>>> _ = QApplication.instance() or QApplication([])
>>> CurveFitPlugin().name
'Curve Fit'
property required_inputs: list[str]

Required input keys.

The plugin retrieves its own data from the engine namespace using the configured expressions, so no external inputs are required.

Returns:

Always an empty list.

Return type:

(list[str])

Examples

>>> from qtpy.QtWidgets import QApplication
>>> _ = QApplication.instance() or QApplication([])
>>> CurveFitPlugin().required_inputs
[]
to_json() → dict[str, Any][source]

Serialise the curve-fit configuration to a JSON-compatible dict.

Returns:

Base dict extended with "trace_key", "column_key", "advanced_mode", "x_expr", "y_expr", "y_error_expr", "fit_code", "fit_module_name", "param_names", "param_settings", "report_initial_values", "show_initial_trace", and "show_best_fit_trace".

Return type:

(dict[str, Any])

Examples

>>> from qtpy.QtWidgets import QApplication
>>> _ = QApplication.instance() or QApplication([])
>>> p = CurveFitPlugin()
>>> d = p.to_json()
>>> d["type"]
'transform'
>>> "fit_code" in d and "param_settings" in d
True
>>> "show_initial_trace" in d and "show_best_fit_trace" in d
True
transform(data: dict[str, Any]) → dict[str, Any][source]

Fit the selected data and return optimal parameters and uncertainties.

Retrieves x/y (and optional y-uncertainty) data from the engine namespace, compiles the user-supplied fit function, and calls scipy.optimize.curve_fit. Returns a dict whose keys are the parameter names and their _err counterparts.

If preparation, curve fitting or result construction fails, the method logs an error and returns a dict of NaN values so that downstream code can still run.

Parameters:

data (dict[str, Any]) – Ignored; the plugin retrieves its own data from the engine namespace.

Returns:

Mapping of parameter name → optimal value and "{name}_err" → 1-sigma uncertainty.

Return type:

(dict[str, Any])

Examples

>>> from qtpy.QtWidgets import QApplication
>>> _ = QApplication.instance() or QApplication([])
>>> from stoner_measurement.core.sequence_engine import SequenceEngine
>>> import numpy as np
>>> engine = SequenceEngine()
>>> plugin = CurveFitPlugin()
>>> engine.add_plugin("curve_fit", plugin)
>>> engine._namespace["_xdata"] = np.linspace(0, 1, 20)
>>> engine._namespace["_ydata"] = 2.0 * np.linspace(0, 1, 20) + 0.5
>>> plugin.advanced_mode = True
>>> plugin.x_expr = "_xdata"
>>> plugin.y_expr = "_ydata"
>>> plugin.fit_code = "def fit(x, a, b): return a * x + b"
>>> plugin.param_names = ["a", "b"]
>>> result = plugin.transform({})
>>> abs(result["a"] - 2.0) < 1e-6
True
>>> abs(result["b"] - 0.5) < 1e-6
True
>>> engine.shutdown()