stoner_measurement.plugins.transform.curve_fit.CurveFitPlugin¶
- class stoner_measurement.plugins.transform.curve_fit.CurveFitPlugin(parent=None)[source]¶
Bases:
TransformPluginFit 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 optionalp0(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
fitwith at least two positional parameters; when present,p0must take exactly(x, y). Load copies the complete module source into the editor. Save… writes the editor source beneath the per-useruser_functionspackage and creates any missing package directories and__init__.pyfiles. 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.areturns the same value ascurve_fit.data["a"]. Uncertainties and reported initial values remain available throughdata. Normal plugin attributes take precedence over dynamic fitted parameters; retrieve a clashing parameter name fromdatainstead.- Variables:
trace_key (str) – Key in the
_tracescatalogue 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, andy_error_exprare used to select data instead oftrace_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
sigmawithabsolute_sigma=True.fit_code (str) – Python source code defining the
fit(x, …)function and optionally ap0(x, y)function.fit_module_name (str) – Qualified library-module name last loaded or saved. It supplies package context for relative imports;
fit_coderemains the authoritative, serialised source executed by the transform.param_names (list[str]) – Parameter names extracted from the
fitfunction signature. Updated automatically wheneverfit_codechanges.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": …};Nonemeans unconstrained / auto for numeric settings.show_initial_trace (bool) – When
True, the transform stores an"initial_fit"trace indatacontaining 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 indatacontaining 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, orNonewhen 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
fitfunction fromfit_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 definep0.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_fitin 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:
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.
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:
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_errcounterparts.If preparation, curve fitting or result construction fails, the method logs an error and returns a dict of
NaNvalues 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:
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()