sigima 0.0.1.dev0__py3-none-any.whl → 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sigima/__init__.py +142 -2
- sigima/client/__init__.py +105 -0
- sigima/client/base.py +780 -0
- sigima/client/remote.py +469 -0
- sigima/client/stub.py +814 -0
- sigima/client/utils.py +90 -0
- sigima/config.py +444 -0
- sigima/data/logo/Sigima.svg +135 -0
- sigima/data/tests/annotations.json +798 -0
- sigima/data/tests/curve_fitting/exponential_fit.txt +511 -0
- sigima/data/tests/curve_fitting/gaussian_fit.txt +100 -0
- sigima/data/tests/curve_fitting/piecewiseexponential_fit.txt +1022 -0
- sigima/data/tests/curve_fitting/polynomial_fit.txt +100 -0
- sigima/data/tests/curve_fitting/twohalfgaussian_fit.txt +1000 -0
- sigima/data/tests/curve_formats/bandwidth.txt +201 -0
- sigima/data/tests/curve_formats/boxcar.npy +0 -0
- sigima/data/tests/curve_formats/datetime.txt +1001 -0
- sigima/data/tests/curve_formats/dynamic_parameters.txt +4000 -0
- sigima/data/tests/curve_formats/fw1e2.txt +301 -0
- sigima/data/tests/curve_formats/fwhm.txt +319 -0
- sigima/data/tests/curve_formats/multiple_curves.csv +29 -0
- sigima/data/tests/curve_formats/noised_saw.mat +0 -0
- sigima/data/tests/curve_formats/oscilloscope.csv +111 -0
- sigima/data/tests/curve_formats/other/other2/recursive2.txt +5 -0
- sigima/data/tests/curve_formats/other/recursive1.txt +5 -0
- sigima/data/tests/curve_formats/paracetamol.npy +0 -0
- sigima/data/tests/curve_formats/paracetamol.txt +1010 -0
- sigima/data/tests/curve_formats/paracetamol_dx_dy.csv +1000 -0
- sigima/data/tests/curve_formats/paracetamol_dy.csv +1001 -0
- sigima/data/tests/curve_formats/pulse1.npy +0 -0
- sigima/data/tests/curve_formats/pulse2.npy +0 -0
- sigima/data/tests/curve_formats/simple.txt +5 -0
- sigima/data/tests/curve_formats/spectrum.mca +2139 -0
- sigima/data/tests/curve_formats/square2.npy +0 -0
- sigima/data/tests/curve_formats/step.npy +0 -0
- sigima/data/tests/fabry-perot1.jpg +0 -0
- sigima/data/tests/fabry-perot2.jpg +0 -0
- sigima/data/tests/flower.npy +0 -0
- sigima/data/tests/image_formats/NF 180338201.scor-data +11003 -0
- sigima/data/tests/image_formats/binary_image.npy +0 -0
- sigima/data/tests/image_formats/binary_image.png +0 -0
- sigima/data/tests/image_formats/centroid_test.npy +0 -0
- sigima/data/tests/image_formats/coordinated_text/complex_image.txt +10011 -0
- sigima/data/tests/image_formats/coordinated_text/complex_ref_image.txt +10010 -0
- sigima/data/tests/image_formats/coordinated_text/image.txt +15 -0
- sigima/data/tests/image_formats/coordinated_text/image2.txt +14 -0
- sigima/data/tests/image_formats/coordinated_text/image_no_unit_no_label.txt +14 -0
- sigima/data/tests/image_formats/coordinated_text/image_with_nan.txt +15 -0
- sigima/data/tests/image_formats/coordinated_text/image_with_unit.txt +14 -0
- sigima/data/tests/image_formats/fiber.csv +480 -0
- sigima/data/tests/image_formats/fiber.jpg +0 -0
- sigima/data/tests/image_formats/fiber.png +0 -0
- sigima/data/tests/image_formats/fiber.txt +480 -0
- sigima/data/tests/image_formats/gaussian_spot_with_noise.npy +0 -0
- sigima/data/tests/image_formats/mr-brain.dcm +0 -0
- sigima/data/tests/image_formats/noised_gaussian.mat +0 -0
- sigima/data/tests/image_formats/sif_reader/nd_lum_image_no_glue.sif +0 -0
- sigima/data/tests/image_formats/sif_reader/raman1.sif +0 -0
- sigima/data/tests/image_formats/tiling.txt +10 -0
- sigima/data/tests/image_formats/uint16.tiff +0 -0
- sigima/data/tests/image_formats/uint8.tiff +0 -0
- sigima/data/tests/laser_beam/TEM00_z_13.jpg +0 -0
- sigima/data/tests/laser_beam/TEM00_z_18.jpg +0 -0
- sigima/data/tests/laser_beam/TEM00_z_23.jpg +0 -0
- sigima/data/tests/laser_beam/TEM00_z_30.jpg +0 -0
- sigima/data/tests/laser_beam/TEM00_z_35.jpg +0 -0
- sigima/data/tests/laser_beam/TEM00_z_40.jpg +0 -0
- sigima/data/tests/laser_beam/TEM00_z_45.jpg +0 -0
- sigima/data/tests/laser_beam/TEM00_z_50.jpg +0 -0
- sigima/data/tests/laser_beam/TEM00_z_55.jpg +0 -0
- sigima/data/tests/laser_beam/TEM00_z_60.jpg +0 -0
- sigima/data/tests/laser_beam/TEM00_z_65.jpg +0 -0
- sigima/data/tests/laser_beam/TEM00_z_70.jpg +0 -0
- sigima/data/tests/laser_beam/TEM00_z_75.jpg +0 -0
- sigima/data/tests/laser_beam/TEM00_z_80.jpg +0 -0
- sigima/enums.py +195 -0
- sigima/io/__init__.py +123 -0
- sigima/io/base.py +311 -0
- sigima/io/common/__init__.py +5 -0
- sigima/io/common/basename.py +164 -0
- sigima/io/common/converters.py +189 -0
- sigima/io/common/objmeta.py +181 -0
- sigima/io/common/textreader.py +58 -0
- sigima/io/convenience.py +157 -0
- sigima/io/enums.py +17 -0
- sigima/io/ftlab.py +395 -0
- sigima/io/image/__init__.py +9 -0
- sigima/io/image/base.py +177 -0
- sigima/io/image/formats.py +1016 -0
- sigima/io/image/funcs.py +414 -0
- sigima/io/signal/__init__.py +9 -0
- sigima/io/signal/base.py +129 -0
- sigima/io/signal/formats.py +290 -0
- sigima/io/signal/funcs.py +723 -0
- sigima/objects/__init__.py +260 -0
- sigima/objects/base.py +937 -0
- sigima/objects/image/__init__.py +88 -0
- sigima/objects/image/creation.py +556 -0
- sigima/objects/image/object.py +524 -0
- sigima/objects/image/roi.py +904 -0
- sigima/objects/scalar/__init__.py +57 -0
- sigima/objects/scalar/common.py +215 -0
- sigima/objects/scalar/geometry.py +502 -0
- sigima/objects/scalar/table.py +784 -0
- sigima/objects/shape.py +290 -0
- sigima/objects/signal/__init__.py +133 -0
- sigima/objects/signal/constants.py +27 -0
- sigima/objects/signal/creation.py +1428 -0
- sigima/objects/signal/object.py +444 -0
- sigima/objects/signal/roi.py +274 -0
- sigima/params.py +405 -0
- sigima/proc/__init__.py +96 -0
- sigima/proc/base.py +381 -0
- sigima/proc/decorator.py +330 -0
- sigima/proc/image/__init__.py +513 -0
- sigima/proc/image/arithmetic.py +335 -0
- sigima/proc/image/base.py +260 -0
- sigima/proc/image/detection.py +519 -0
- sigima/proc/image/edges.py +329 -0
- sigima/proc/image/exposure.py +406 -0
- sigima/proc/image/extraction.py +458 -0
- sigima/proc/image/filtering.py +219 -0
- sigima/proc/image/fourier.py +147 -0
- sigima/proc/image/geometry.py +661 -0
- sigima/proc/image/mathops.py +340 -0
- sigima/proc/image/measurement.py +195 -0
- sigima/proc/image/morphology.py +155 -0
- sigima/proc/image/noise.py +107 -0
- sigima/proc/image/preprocessing.py +182 -0
- sigima/proc/image/restoration.py +235 -0
- sigima/proc/image/threshold.py +217 -0
- sigima/proc/image/transformations.py +393 -0
- sigima/proc/signal/__init__.py +376 -0
- sigima/proc/signal/analysis.py +206 -0
- sigima/proc/signal/arithmetic.py +551 -0
- sigima/proc/signal/base.py +262 -0
- sigima/proc/signal/extraction.py +60 -0
- sigima/proc/signal/features.py +310 -0
- sigima/proc/signal/filtering.py +484 -0
- sigima/proc/signal/fitting.py +276 -0
- sigima/proc/signal/fourier.py +259 -0
- sigima/proc/signal/mathops.py +420 -0
- sigima/proc/signal/processing.py +580 -0
- sigima/proc/signal/stability.py +175 -0
- sigima/proc/title_formatting.py +227 -0
- sigima/proc/validation.py +272 -0
- sigima/tests/__init__.py +7 -0
- sigima/tests/common/__init__.py +0 -0
- sigima/tests/common/arithmeticparam_unit_test.py +26 -0
- sigima/tests/common/basename_unit_test.py +126 -0
- sigima/tests/common/client_unit_test.py +412 -0
- sigima/tests/common/converters_unit_test.py +77 -0
- sigima/tests/common/decorator_unit_test.py +176 -0
- sigima/tests/common/examples_unit_test.py +104 -0
- sigima/tests/common/kernel_normalization_unit_test.py +242 -0
- sigima/tests/common/roi_basic_unit_test.py +73 -0
- sigima/tests/common/roi_geometry_unit_test.py +171 -0
- sigima/tests/common/scalar_builder_unit_test.py +142 -0
- sigima/tests/common/scalar_unit_test.py +991 -0
- sigima/tests/common/shape_unit_test.py +183 -0
- sigima/tests/common/stat_unit_test.py +138 -0
- sigima/tests/common/title_formatting_unit_test.py +338 -0
- sigima/tests/common/tools_coordinates_unit_test.py +60 -0
- sigima/tests/common/transformations_unit_test.py +178 -0
- sigima/tests/common/validation_unit_test.py +205 -0
- sigima/tests/conftest.py +129 -0
- sigima/tests/data.py +998 -0
- sigima/tests/env.py +280 -0
- sigima/tests/guiutils.py +163 -0
- sigima/tests/helpers.py +532 -0
- sigima/tests/image/__init__.py +28 -0
- sigima/tests/image/binning_unit_test.py +128 -0
- sigima/tests/image/blob_detection_unit_test.py +312 -0
- sigima/tests/image/centroid_unit_test.py +170 -0
- sigima/tests/image/check_2d_array_unit_test.py +63 -0
- sigima/tests/image/contour_unit_test.py +172 -0
- sigima/tests/image/convolution_unit_test.py +178 -0
- sigima/tests/image/datatype_unit_test.py +67 -0
- sigima/tests/image/edges_unit_test.py +155 -0
- sigima/tests/image/enclosingcircle_unit_test.py +88 -0
- sigima/tests/image/exposure_unit_test.py +223 -0
- sigima/tests/image/fft2d_unit_test.py +189 -0
- sigima/tests/image/filtering_unit_test.py +166 -0
- sigima/tests/image/geometry_unit_test.py +654 -0
- sigima/tests/image/hough_circle_unit_test.py +147 -0
- sigima/tests/image/imageobj_unit_test.py +737 -0
- sigima/tests/image/morphology_unit_test.py +71 -0
- sigima/tests/image/noise_unit_test.py +57 -0
- sigima/tests/image/offset_correction_unit_test.py +72 -0
- sigima/tests/image/operation_unit_test.py +518 -0
- sigima/tests/image/peak2d_limits_unit_test.py +41 -0
- sigima/tests/image/peak2d_unit_test.py +133 -0
- sigima/tests/image/profile_unit_test.py +159 -0
- sigima/tests/image/projections_unit_test.py +121 -0
- sigima/tests/image/restoration_unit_test.py +141 -0
- sigima/tests/image/roi2dparam_unit_test.py +53 -0
- sigima/tests/image/roi_advanced_unit_test.py +588 -0
- sigima/tests/image/roi_grid_unit_test.py +279 -0
- sigima/tests/image/spectrum2d_unit_test.py +40 -0
- sigima/tests/image/threshold_unit_test.py +91 -0
- sigima/tests/io/__init__.py +0 -0
- sigima/tests/io/addnewformat_unit_test.py +125 -0
- sigima/tests/io/convenience_funcs_unit_test.py +470 -0
- sigima/tests/io/coordinated_text_format_unit_test.py +495 -0
- sigima/tests/io/datetime_csv_unit_test.py +198 -0
- sigima/tests/io/imageio_formats_test.py +41 -0
- sigima/tests/io/ioregistry_unit_test.py +69 -0
- sigima/tests/io/objmeta_unit_test.py +87 -0
- sigima/tests/io/readobj_unit_test.py +130 -0
- sigima/tests/io/readwriteobj_unit_test.py +67 -0
- sigima/tests/signal/__init__.py +0 -0
- sigima/tests/signal/analysis_unit_test.py +135 -0
- sigima/tests/signal/check_1d_arrays_unit_test.py +169 -0
- sigima/tests/signal/convolution_unit_test.py +404 -0
- sigima/tests/signal/datetime_unit_test.py +176 -0
- sigima/tests/signal/fft1d_unit_test.py +303 -0
- sigima/tests/signal/filters_unit_test.py +403 -0
- sigima/tests/signal/fitting_unit_test.py +929 -0
- sigima/tests/signal/fwhm_unit_test.py +111 -0
- sigima/tests/signal/noise_unit_test.py +128 -0
- sigima/tests/signal/offset_correction_unit_test.py +34 -0
- sigima/tests/signal/operation_unit_test.py +489 -0
- sigima/tests/signal/peakdetection_unit_test.py +145 -0
- sigima/tests/signal/processing_unit_test.py +657 -0
- sigima/tests/signal/pulse/__init__.py +112 -0
- sigima/tests/signal/pulse/crossing_times_unit_test.py +123 -0
- sigima/tests/signal/pulse/plateau_detection_unit_test.py +102 -0
- sigima/tests/signal/pulse/pulse_unit_test.py +1824 -0
- sigima/tests/signal/roi_advanced_unit_test.py +392 -0
- sigima/tests/signal/signalobj_unit_test.py +603 -0
- sigima/tests/signal/stability_unit_test.py +431 -0
- sigima/tests/signal/uncertainty_unit_test.py +611 -0
- sigima/tests/vistools.py +1030 -0
- sigima/tools/__init__.py +59 -0
- sigima/tools/checks.py +290 -0
- sigima/tools/coordinates.py +308 -0
- sigima/tools/datatypes.py +26 -0
- sigima/tools/image/__init__.py +97 -0
- sigima/tools/image/detection.py +451 -0
- sigima/tools/image/exposure.py +77 -0
- sigima/tools/image/extraction.py +48 -0
- sigima/tools/image/fourier.py +260 -0
- sigima/tools/image/geometry.py +190 -0
- sigima/tools/image/preprocessing.py +165 -0
- sigima/tools/signal/__init__.py +86 -0
- sigima/tools/signal/dynamic.py +254 -0
- sigima/tools/signal/features.py +135 -0
- sigima/tools/signal/filtering.py +171 -0
- sigima/tools/signal/fitting.py +1171 -0
- sigima/tools/signal/fourier.py +466 -0
- sigima/tools/signal/interpolation.py +70 -0
- sigima/tools/signal/peakdetection.py +126 -0
- sigima/tools/signal/pulse.py +1626 -0
- sigima/tools/signal/scaling.py +50 -0
- sigima/tools/signal/stability.py +258 -0
- sigima/tools/signal/windowing.py +90 -0
- sigima/worker.py +79 -0
- sigima-1.0.0.dist-info/METADATA +233 -0
- sigima-1.0.0.dist-info/RECORD +262 -0
- {sigima-0.0.1.dev0.dist-info → sigima-1.0.0.dist-info}/licenses/LICENSE +29 -29
- sigima-0.0.1.dev0.dist-info/METADATA +0 -60
- sigima-0.0.1.dev0.dist-info/RECORD +0 -6
- {sigima-0.0.1.dev0.dist-info → sigima-1.0.0.dist-info}/WHEEL +0 -0
- {sigima-0.0.1.dev0.dist-info → sigima-1.0.0.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,1171 @@
|
|
|
1
|
+
# Copyright (c) DataLab Platform Developers, BSD 3-Clause license, see LICENSE file.
|
|
2
|
+
|
|
3
|
+
"""
|
|
4
|
+
Curve Fitting Algorithms
|
|
5
|
+
=========================
|
|
6
|
+
|
|
7
|
+
This module provides curve fitting functions without GUI dependencies.
|
|
8
|
+
The functions take x,y data and return fitted curves and parameters.
|
|
9
|
+
|
|
10
|
+
These functions are designed to be used programmatically and in tests,
|
|
11
|
+
providing the core fitting algorithms without PlotPy GUI components.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import string
|
|
17
|
+
import warnings
|
|
18
|
+
from typing import Type
|
|
19
|
+
|
|
20
|
+
import numpy as np
|
|
21
|
+
import scipy.optimize
|
|
22
|
+
import scipy.special
|
|
23
|
+
|
|
24
|
+
from sigima.tools.signal import peakdetection, pulse
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class FitComputer:
|
|
28
|
+
"""Base class for fit computers"""
|
|
29
|
+
|
|
30
|
+
PARAMS_NAMES: tuple[str] = () # To be defined by subclasses
|
|
31
|
+
|
|
32
|
+
def __init__(self, x: np.ndarray, y: np.ndarray) -> None:
|
|
33
|
+
self.x = x
|
|
34
|
+
self.y = y
|
|
35
|
+
|
|
36
|
+
def get_params_names(self) -> tuple[str]:
|
|
37
|
+
"""Return the names of the parameters used in this fit."""
|
|
38
|
+
return self.PARAMS_NAMES
|
|
39
|
+
|
|
40
|
+
def check_params(self, **params) -> None:
|
|
41
|
+
"""Check that all required parameters are provided."""
|
|
42
|
+
missing = [p for p in self.get_params_names() if p not in params]
|
|
43
|
+
if missing:
|
|
44
|
+
raise ValueError(f"Missing required parameters: {missing}")
|
|
45
|
+
|
|
46
|
+
@classmethod
|
|
47
|
+
def args_kwargs_to_list(cls, *args, **kwargs) -> list[float]:
|
|
48
|
+
"""Convert args and kwargs to a parameter list."""
|
|
49
|
+
if kwargs and args:
|
|
50
|
+
raise ValueError("Cannot mix positional and keyword arguments")
|
|
51
|
+
if cls.PARAMS_NAMES:
|
|
52
|
+
param_names = cls.PARAMS_NAMES
|
|
53
|
+
else:
|
|
54
|
+
if not kwargs:
|
|
55
|
+
raise ValueError("No parameter names available and no kwargs provided")
|
|
56
|
+
param_names = cls.infer_param_names_from_kwargs(kwargs)
|
|
57
|
+
if len(args) > len(param_names):
|
|
58
|
+
raise ValueError("Too many positional arguments")
|
|
59
|
+
if args:
|
|
60
|
+
params = list(args)
|
|
61
|
+
else:
|
|
62
|
+
params = []
|
|
63
|
+
for name in param_names:
|
|
64
|
+
if name in kwargs:
|
|
65
|
+
params.append(kwargs[name])
|
|
66
|
+
else:
|
|
67
|
+
raise ValueError(f"Missing required parameter: {name}")
|
|
68
|
+
return params
|
|
69
|
+
|
|
70
|
+
@classmethod
|
|
71
|
+
def infer_param_names_from_kwargs(cls, kwargs: dict) -> tuple[str, ...]:
|
|
72
|
+
"""Infer parameter names from kwargs. Override in subclasses if needed."""
|
|
73
|
+
return tuple(kwargs.keys())
|
|
74
|
+
|
|
75
|
+
@classmethod
|
|
76
|
+
def evaluate(cls, x: np.ndarray, *args, **kwargs) -> np.ndarray:
|
|
77
|
+
"""Evaluate the fit function at given x values."""
|
|
78
|
+
raise NotImplementedError("Subclasses must implement evaluate method")
|
|
79
|
+
|
|
80
|
+
def compute_initial_params(self) -> dict[str, float]:
|
|
81
|
+
"""Compute initial parameters for fitting. To be implemented by subclasses."""
|
|
82
|
+
raise NotImplementedError(
|
|
83
|
+
"Subclasses must implement compute_initial_params method"
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
# pylint: disable=unused-argument
|
|
87
|
+
def compute_bounds(self, **initial_params) -> list[tuple[float, float]] | None:
|
|
88
|
+
"""Compute parameter bounds for fitting."""
|
|
89
|
+
return None
|
|
90
|
+
|
|
91
|
+
def create_params(self, y_fitted: np.ndarray, **params) -> dict[str, float]:
|
|
92
|
+
"""Create a fit parameters dictionary from given parameters."""
|
|
93
|
+
self.check_params(**params)
|
|
94
|
+
params["fit_type"] = self.__class__.__name__.replace("FitComputer", "").lower()
|
|
95
|
+
params["residual_rms"] = np.sqrt(np.mean((self.y - y_fitted) ** 2))
|
|
96
|
+
return params
|
|
97
|
+
|
|
98
|
+
def fit(self) -> tuple[np.ndarray, dict[str, float]]:
|
|
99
|
+
"""Fit the model to the data."""
|
|
100
|
+
# Default implementation uses scipy curve_fit
|
|
101
|
+
return self.optimize_fit_with_scipy()
|
|
102
|
+
|
|
103
|
+
def optimize_fit_with_scipy(self) -> tuple[np.ndarray, np.ndarray]:
|
|
104
|
+
"""Generic fitting function using `scipy.optimize.curve_fit`
|
|
105
|
+
|
|
106
|
+
Returns:
|
|
107
|
+
tuple: (fitted_y_values, fitted_parameters)
|
|
108
|
+
"""
|
|
109
|
+
initial_params = self.compute_initial_params()
|
|
110
|
+
bounds = self.compute_bounds(**initial_params) # pylint: disable=E1128
|
|
111
|
+
if bounds is not None:
|
|
112
|
+
# Convert bounds to scipy format
|
|
113
|
+
lower_bounds = [b[0] for b in bounds]
|
|
114
|
+
upper_bounds = [b[1] for b in bounds]
|
|
115
|
+
bounds_scipy = (lower_bounds, upper_bounds)
|
|
116
|
+
else:
|
|
117
|
+
bounds_scipy = (-np.inf, np.inf)
|
|
118
|
+
|
|
119
|
+
# Create a wrapper function that unpacks parameters correctly
|
|
120
|
+
def objective_func(x, *params):
|
|
121
|
+
"""Wrapper function for scipy curve_fit."""
|
|
122
|
+
param_dict = dict(zip(self.get_params_names(), params))
|
|
123
|
+
try:
|
|
124
|
+
# Try as classmethod first
|
|
125
|
+
return self.__class__.evaluate(x, **param_dict)
|
|
126
|
+
except TypeError:
|
|
127
|
+
# Fall back to instance method
|
|
128
|
+
return self.evaluate(x, **param_dict)
|
|
129
|
+
|
|
130
|
+
try:
|
|
131
|
+
with warnings.catch_warnings():
|
|
132
|
+
warnings.filterwarnings(
|
|
133
|
+
"ignore", category=scipy.optimize.OptimizeWarning
|
|
134
|
+
)
|
|
135
|
+
popt, _ = scipy.optimize.curve_fit(
|
|
136
|
+
objective_func,
|
|
137
|
+
self.x,
|
|
138
|
+
self.y,
|
|
139
|
+
p0=list(initial_params.values()),
|
|
140
|
+
bounds=bounds_scipy,
|
|
141
|
+
maxfev=5000,
|
|
142
|
+
)
|
|
143
|
+
except (RuntimeError, ValueError, TypeError) as err:
|
|
144
|
+
# Fallback to initial parameters if optimization fails
|
|
145
|
+
warnings.warn(f"Optimization failed: {err}. Using initial parameters.")
|
|
146
|
+
try:
|
|
147
|
+
# Try as classmethod first
|
|
148
|
+
fitted_y = self.__class__.evaluate(self.x, **initial_params)
|
|
149
|
+
except TypeError:
|
|
150
|
+
# Fall back to instance method
|
|
151
|
+
fitted_y = self.evaluate(self.x, **initial_params)
|
|
152
|
+
result_params = self.create_params(fitted_y, **initial_params)
|
|
153
|
+
return fitted_y, result_params
|
|
154
|
+
|
|
155
|
+
names = self.get_params_names()
|
|
156
|
+
assert len(popt) == len(names), "Unexpected number of parameters"
|
|
157
|
+
param_dict = dict(zip(names, popt))
|
|
158
|
+
try:
|
|
159
|
+
# Try as classmethod first
|
|
160
|
+
fitted_y = self.__class__.evaluate(self.x, **param_dict)
|
|
161
|
+
except TypeError:
|
|
162
|
+
# Fall back to instance method
|
|
163
|
+
fitted_y = self.evaluate(self.x, **param_dict)
|
|
164
|
+
params = self.create_params(fitted_y, **param_dict)
|
|
165
|
+
return fitted_y, params
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
class LinearFitComputer(FitComputer):
|
|
169
|
+
"""Linear fit computer"""
|
|
170
|
+
|
|
171
|
+
PARAMS_NAMES = ("a", "b") # slope and intercept
|
|
172
|
+
|
|
173
|
+
@classmethod
|
|
174
|
+
def evaluate(cls, x: np.ndarray, *args, **kwargs) -> np.ndarray:
|
|
175
|
+
"""Evaluate linear function at given x values."""
|
|
176
|
+
# pylint: disable=unbalanced-tuple-unpacking
|
|
177
|
+
a, b = cls.args_kwargs_to_list(*args, **kwargs)
|
|
178
|
+
return a * x + b
|
|
179
|
+
|
|
180
|
+
def compute_initial_params(self) -> dict[str, float]:
|
|
181
|
+
"""Compute initial parameters for linear fitting using numpy polyfit."""
|
|
182
|
+
coeffs = np.polyfit(self.x, self.y, 1)
|
|
183
|
+
a, b = coeffs
|
|
184
|
+
return {"a": a, "b": b}
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
class PolynomialFitComputer(FitComputer):
|
|
188
|
+
"""Polynomial fit computer of given degree"""
|
|
189
|
+
|
|
190
|
+
def __init__(self, x: np.ndarray, y: np.ndarray, degree: int = 2) -> None:
|
|
191
|
+
super().__init__(x, y)
|
|
192
|
+
if degree < 1:
|
|
193
|
+
raise ValueError("Degree must be at least 1")
|
|
194
|
+
self.degree = degree
|
|
195
|
+
|
|
196
|
+
def get_params_names(self) -> tuple[str]:
|
|
197
|
+
"""Return the names of the parameters used in this fit."""
|
|
198
|
+
return tuple(string.ascii_lowercase[: self.degree + 1])
|
|
199
|
+
|
|
200
|
+
@classmethod
|
|
201
|
+
def infer_param_names_from_kwargs(cls, kwargs: dict) -> tuple[str, ...]:
|
|
202
|
+
"""Infer parameter names for polynomial from kwargs."""
|
|
203
|
+
# Parameters are named 'a', 'b', 'c', ... in order
|
|
204
|
+
param_keys = [k for k in kwargs.keys() if k in string.ascii_lowercase]
|
|
205
|
+
if not param_keys:
|
|
206
|
+
raise ValueError("No valid polynomial parameters found")
|
|
207
|
+
# Sort to ensure correct order (a, b, c, ...)
|
|
208
|
+
return tuple(sorted(param_keys))
|
|
209
|
+
|
|
210
|
+
@classmethod
|
|
211
|
+
def evaluate(cls, x: np.ndarray, *args, **kwargs) -> np.ndarray:
|
|
212
|
+
"""Evaluate polynomial function at given x values."""
|
|
213
|
+
# pylint: disable=unbalanced-tuple-unpacking
|
|
214
|
+
coeffs = cls.args_kwargs_to_list(*args, **kwargs)
|
|
215
|
+
return np.polyval(coeffs, x)
|
|
216
|
+
|
|
217
|
+
def compute_initial_params(self) -> dict[str, float]:
|
|
218
|
+
"""Compute initial parameters for polynomial fitting using numpy polyfit."""
|
|
219
|
+
coeffs = np.polyfit(self.x, self.y, self.degree)
|
|
220
|
+
param_names = self.get_params_names()
|
|
221
|
+
|
|
222
|
+
# Map numpy polyfit coefficients (highest to lowest degree) to parameter names
|
|
223
|
+
return dict(zip(param_names, coeffs))
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
class GaussianFitComputer(FitComputer):
|
|
227
|
+
"""Gaussian fit computer"""
|
|
228
|
+
|
|
229
|
+
PARAMS_NAMES = ("amp", "sigma", "x0", "y0")
|
|
230
|
+
|
|
231
|
+
@classmethod
|
|
232
|
+
def evaluate(cls, x: np.ndarray, *args, **kwargs) -> np.ndarray:
|
|
233
|
+
"""Evaluate Gaussian function at given x values."""
|
|
234
|
+
# pylint: disable=unbalanced-tuple-unpacking
|
|
235
|
+
amp, sigma, x0, y0 = cls.args_kwargs_to_list(*args, **kwargs)
|
|
236
|
+
return pulse.GaussianModel.func(x, amp, sigma, x0, y0)
|
|
237
|
+
|
|
238
|
+
def compute_initial_params(self) -> dict[str, float]:
|
|
239
|
+
"""Compute initial parameters for Gaussian fitting."""
|
|
240
|
+
dx = np.max(self.x) - np.min(self.x)
|
|
241
|
+
dy = np.max(self.y) - np.min(self.y)
|
|
242
|
+
y_min = np.min(self.y)
|
|
243
|
+
|
|
244
|
+
sigma = dx * 0.1
|
|
245
|
+
amp = pulse.GaussianModel.get_amp_from_amplitude(dy, sigma)
|
|
246
|
+
x0 = peakdetection.xpeak(self.x, self.y)
|
|
247
|
+
y0 = y_min
|
|
248
|
+
|
|
249
|
+
return {"amp": amp, "sigma": sigma, "x0": x0, "y0": y0}
|
|
250
|
+
|
|
251
|
+
def compute_bounds(self, **initial_params) -> list[tuple[float, float]] | None:
|
|
252
|
+
"""Compute parameter bounds for Gaussian fitting."""
|
|
253
|
+
dy = np.max(self.y) - np.min(self.y)
|
|
254
|
+
y_min = np.min(self.y)
|
|
255
|
+
|
|
256
|
+
return [
|
|
257
|
+
(0.0, initial_params["amp"] * 2), # amp
|
|
258
|
+
(initial_params["sigma"] * 0.1, initial_params["sigma"] * 10), # sigma
|
|
259
|
+
(np.min(self.x), np.max(self.x)), # x0
|
|
260
|
+
(y_min - 0.2 * dy, y_min + 0.2 * dy), # y0
|
|
261
|
+
]
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
class LorentzianFitComputer(FitComputer):
|
|
265
|
+
"""Lorentzian fit computer"""
|
|
266
|
+
|
|
267
|
+
PARAMS_NAMES = ("amp", "sigma", "x0", "y0")
|
|
268
|
+
|
|
269
|
+
@classmethod
|
|
270
|
+
def evaluate(cls, x: np.ndarray, *args, **kwargs) -> np.ndarray:
|
|
271
|
+
"""Evaluate Lorentzian function at given x values."""
|
|
272
|
+
# pylint: disable=unbalanced-tuple-unpacking
|
|
273
|
+
amp, sigma, x0, y0 = cls.args_kwargs_to_list(*args, **kwargs)
|
|
274
|
+
return pulse.LorentzianModel.func(x, amp, sigma, x0, y0)
|
|
275
|
+
|
|
276
|
+
def compute_initial_params(self) -> dict[str, float]:
|
|
277
|
+
"""Compute initial parameters for Lorentzian fitting."""
|
|
278
|
+
dx = np.max(self.x) - np.min(self.x)
|
|
279
|
+
dy = np.max(self.y) - np.min(self.y)
|
|
280
|
+
y_min = np.min(self.y)
|
|
281
|
+
|
|
282
|
+
sigma = dx * 0.1
|
|
283
|
+
amp = pulse.LorentzianModel.get_amp_from_amplitude(dy, sigma)
|
|
284
|
+
x0 = peakdetection.xpeak(self.x, self.y)
|
|
285
|
+
y0 = y_min
|
|
286
|
+
|
|
287
|
+
return {"amp": amp, "sigma": sigma, "x0": x0, "y0": y0}
|
|
288
|
+
|
|
289
|
+
def compute_bounds(self, **initial_params) -> list[tuple[float, float]] | None:
|
|
290
|
+
"""Compute parameter bounds for Lorentzian fitting."""
|
|
291
|
+
dy = np.max(self.y) - np.min(self.y)
|
|
292
|
+
y_min = np.min(self.y)
|
|
293
|
+
|
|
294
|
+
return [
|
|
295
|
+
(0.0, initial_params["amp"] * 2), # amp
|
|
296
|
+
(initial_params["sigma"] * 0.1, initial_params["sigma"] * 10), # sigma
|
|
297
|
+
(np.min(self.x), np.max(self.x)), # x0
|
|
298
|
+
(y_min - 0.2 * dy, y_min + 0.2 * dy), # y0
|
|
299
|
+
]
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
class VoigtFitComputer(FitComputer):
|
|
303
|
+
"""Voigt fit computer"""
|
|
304
|
+
|
|
305
|
+
PARAMS_NAMES = ("amp", "sigma", "x0", "y0")
|
|
306
|
+
|
|
307
|
+
@classmethod
|
|
308
|
+
def evaluate(cls, x: np.ndarray, *args, **kwargs) -> np.ndarray:
|
|
309
|
+
"""Evaluate Voigt function at given x values."""
|
|
310
|
+
# pylint: disable=unbalanced-tuple-unpacking
|
|
311
|
+
amp, sigma, x0, y0 = cls.args_kwargs_to_list(*args, **kwargs)
|
|
312
|
+
return pulse.VoigtModel.func(x, amp, sigma, x0, y0)
|
|
313
|
+
|
|
314
|
+
def compute_initial_params(self) -> dict[str, float]:
|
|
315
|
+
"""Compute initial parameters for Voigt fitting."""
|
|
316
|
+
dx = np.max(self.x) - np.min(self.x)
|
|
317
|
+
dy = np.max(self.y) - np.min(self.y)
|
|
318
|
+
y_min = np.min(self.y)
|
|
319
|
+
|
|
320
|
+
sigma = dx * 0.1
|
|
321
|
+
amp = pulse.VoigtModel.get_amp_from_amplitude(dy, sigma)
|
|
322
|
+
x0 = peakdetection.xpeak(self.x, self.y)
|
|
323
|
+
y0 = y_min
|
|
324
|
+
|
|
325
|
+
return {"amp": amp, "sigma": sigma, "x0": x0, "y0": y0}
|
|
326
|
+
|
|
327
|
+
def compute_bounds(self, **initial_params) -> list[tuple[float, float]] | None:
|
|
328
|
+
"""Compute parameter bounds for Voigt fitting."""
|
|
329
|
+
sigma = initial_params["sigma"]
|
|
330
|
+
amp = initial_params["amp"]
|
|
331
|
+
return [
|
|
332
|
+
(0.0, 10 * amp), # amp
|
|
333
|
+
(sigma * 0.01, sigma * 10), # sigma
|
|
334
|
+
(np.min(self.x), np.max(self.x)), # x0
|
|
335
|
+
(initial_params["y0"] - amp, initial_params["y0"] + amp), # y0
|
|
336
|
+
]
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
class ExponentialFitComputer(FitComputer):
|
|
340
|
+
"""Exponential fit computer: y = a * exp(b * x) + y0"""
|
|
341
|
+
|
|
342
|
+
PARAMS_NAMES = ("a", "b", "y0")
|
|
343
|
+
|
|
344
|
+
@classmethod
|
|
345
|
+
def evaluate(cls, x: np.ndarray, *args, **kwargs) -> np.ndarray:
|
|
346
|
+
"""Evaluate exponential function at given x values."""
|
|
347
|
+
# pylint: disable=unbalanced-tuple-unpacking
|
|
348
|
+
a, b, y0 = cls.args_kwargs_to_list(*args, **kwargs)
|
|
349
|
+
# Clip b to prevent overflow
|
|
350
|
+
b_clipped = np.clip(b, -50, 50)
|
|
351
|
+
return a * np.exp(b_clipped * x) + y0
|
|
352
|
+
|
|
353
|
+
def compute_initial_params(self) -> dict[str, float]:
|
|
354
|
+
"""Compute initial parameters for exponential fitting."""
|
|
355
|
+
y_range = np.max(self.y) - np.min(self.y)
|
|
356
|
+
y_min = np.min(self.y)
|
|
357
|
+
|
|
358
|
+
# Estimate from data
|
|
359
|
+
if len(self.y) > 1:
|
|
360
|
+
# Try to determine if it's growth or decay
|
|
361
|
+
if self.y[0] > self.y[-1]:
|
|
362
|
+
# Decay
|
|
363
|
+
a = y_range
|
|
364
|
+
b = -1.0 / (np.max(self.x) - np.min(self.x))
|
|
365
|
+
else:
|
|
366
|
+
# Growth
|
|
367
|
+
a = y_range * 0.1
|
|
368
|
+
b = 1.0 / (np.max(self.x) - np.min(self.x))
|
|
369
|
+
else:
|
|
370
|
+
a = y_range
|
|
371
|
+
b = -1.0
|
|
372
|
+
|
|
373
|
+
y0 = y_min
|
|
374
|
+
|
|
375
|
+
return {"a": a, "b": b, "y0": y0}
|
|
376
|
+
|
|
377
|
+
def compute_bounds(self, **initial_params) -> list[tuple[float, float]] | None:
|
|
378
|
+
"""Compute parameter bounds for exponential fitting."""
|
|
379
|
+
y_range = np.max(self.y) - np.min(self.y)
|
|
380
|
+
y_min = np.min(self.y)
|
|
381
|
+
|
|
382
|
+
return [
|
|
383
|
+
(-y_range * 1000, y_range * 1000), # a
|
|
384
|
+
(-10, 10), # b (reasonable range to prevent overflow)
|
|
385
|
+
(y_min - 0.5 * y_range, y_min + 0.5 * y_range), # y0
|
|
386
|
+
]
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
class PlanckianFitComputer(FitComputer):
|
|
390
|
+
"""Planckian fit computer"""
|
|
391
|
+
|
|
392
|
+
PARAMS_NAMES = ("amp", "x0", "sigma", "y0")
|
|
393
|
+
|
|
394
|
+
@classmethod
|
|
395
|
+
def evaluate(cls, x: np.ndarray, *args, **kwargs) -> np.ndarray:
|
|
396
|
+
"""Return Planckian fitting function
|
|
397
|
+
|
|
398
|
+
Args:
|
|
399
|
+
x: wavelength values (in nm or other units)
|
|
400
|
+
amp: amplitude scaling factor
|
|
401
|
+
x0: peak wavelength (Wien's displacement law)
|
|
402
|
+
sigma: width parameter (larger sigma = wider peak)
|
|
403
|
+
y0: baseline offset
|
|
404
|
+
"""
|
|
405
|
+
# pylint: disable=unbalanced-tuple-unpacking
|
|
406
|
+
amp, x0, sigma, y0 = cls.args_kwargs_to_list(*args, **kwargs)
|
|
407
|
+
|
|
408
|
+
# Planck-like function with Wien's displacement law behavior
|
|
409
|
+
# The function peaks at approximately x0 when properly parameterized
|
|
410
|
+
|
|
411
|
+
x = np.asarray(x, dtype=float)
|
|
412
|
+
y = np.full_like(x, y0, dtype=float)
|
|
413
|
+
|
|
414
|
+
# Only compute for positive wavelengths
|
|
415
|
+
valid_mask = x > 0
|
|
416
|
+
if not np.any(valid_mask):
|
|
417
|
+
return y
|
|
418
|
+
|
|
419
|
+
x_valid = x[valid_mask]
|
|
420
|
+
|
|
421
|
+
try:
|
|
422
|
+
# Wien's displacement law: λ_max * T = constant
|
|
423
|
+
# For a proper Planckian curve, we need:
|
|
424
|
+
# d/dx [x^(-5) / (exp(c/x) - 1)] = 0 at x = x0
|
|
425
|
+
# This gives us c = 5*x0 for the peak condition
|
|
426
|
+
|
|
427
|
+
# The exponential argument that produces peak at x0
|
|
428
|
+
wien_constant = 5.0
|
|
429
|
+
|
|
430
|
+
# Use sigma to control the effective temperature/width
|
|
431
|
+
# sigma=1.0 gives the canonical Planck curve
|
|
432
|
+
# sigma>1.0 gives broader curves (cooler)
|
|
433
|
+
# sigma<1.0 gives sharper curves (hotter)
|
|
434
|
+
temperature_factor = sigma
|
|
435
|
+
|
|
436
|
+
exp_argument = wien_constant * x0 / (x_valid * temperature_factor)
|
|
437
|
+
|
|
438
|
+
# Clip to prevent overflow
|
|
439
|
+
exp_argument = np.clip(exp_argument, 0, 50)
|
|
440
|
+
|
|
441
|
+
# Planck function components:
|
|
442
|
+
# 1. The wavelength dependence: x^(-5)
|
|
443
|
+
wavelength_factor = (x_valid / x0) ** (-5)
|
|
444
|
+
|
|
445
|
+
# 2. The exponential term: 1/(exp(arg) - 1)
|
|
446
|
+
exp_denominator = np.expm1(exp_argument) # exp(x) - 1
|
|
447
|
+
|
|
448
|
+
# Avoid division by very small numbers
|
|
449
|
+
exp_denominator = np.where(
|
|
450
|
+
np.abs(exp_denominator) < 1e-12, 1e-12, exp_denominator
|
|
451
|
+
)
|
|
452
|
+
|
|
453
|
+
# Combine the Planckian terms
|
|
454
|
+
planck_curve = wavelength_factor / exp_denominator
|
|
455
|
+
|
|
456
|
+
# Apply amplitude and add to baseline
|
|
457
|
+
y[valid_mask] += amp * planck_curve
|
|
458
|
+
|
|
459
|
+
except (OverflowError, ZeroDivisionError, RuntimeWarning):
|
|
460
|
+
# If computation fails, return baseline only
|
|
461
|
+
pass
|
|
462
|
+
|
|
463
|
+
return y
|
|
464
|
+
|
|
465
|
+
def compute_initial_params(self) -> dict[str, float]:
|
|
466
|
+
"""Compute initial parameters for Planckian fitting."""
|
|
467
|
+
dy = np.max(self.y) - np.min(self.y)
|
|
468
|
+
x_peak = self.x[np.argmax(self.y)]
|
|
469
|
+
y_min = np.min(self.y)
|
|
470
|
+
return {"amp": dy, "x0": x_peak, "sigma": 1.0, "y0": y_min}
|
|
471
|
+
|
|
472
|
+
def compute_bounds(self, **initial_params) -> list[tuple[float, float]] | None:
|
|
473
|
+
"""Compute parameter bounds for Planckian fitting."""
|
|
474
|
+
return [
|
|
475
|
+
(initial_params["amp"] * 0.01, initial_params["amp"] * 100), # amp
|
|
476
|
+
(np.min(self.x), np.max(self.x)), # x0
|
|
477
|
+
(0.1, 5.0), # sigma
|
|
478
|
+
(
|
|
479
|
+
initial_params["y0"] - 0.2 * initial_params["amp"],
|
|
480
|
+
initial_params["y0"] + 0.2 * initial_params["amp"],
|
|
481
|
+
), # y0
|
|
482
|
+
]
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
class TwoHalfGaussianFitComputer(FitComputer):
|
|
486
|
+
"""Two Half-Gaussian fit computer"""
|
|
487
|
+
|
|
488
|
+
PARAMS_NAMES = (
|
|
489
|
+
"amp_left",
|
|
490
|
+
"amp_right",
|
|
491
|
+
"sigma_left",
|
|
492
|
+
"sigma_right",
|
|
493
|
+
"x0",
|
|
494
|
+
"y0_left",
|
|
495
|
+
"y0_right",
|
|
496
|
+
)
|
|
497
|
+
|
|
498
|
+
@classmethod
|
|
499
|
+
def evaluate(cls, x: np.ndarray, *args, **kwargs) -> np.ndarray:
|
|
500
|
+
"""Return two half-Gaussian with separate left/right amplitudes
|
|
501
|
+
|
|
502
|
+
Args:
|
|
503
|
+
x: x values
|
|
504
|
+
amp_left: amplitude for left side (x < x0)
|
|
505
|
+
amp_right: amplitude for right side (x >= x0)
|
|
506
|
+
sigma_left: standard deviation for x < x0
|
|
507
|
+
sigma_right: standard deviation for x > x0
|
|
508
|
+
x0: center position
|
|
509
|
+
y0_left: baseline offset for x < x0
|
|
510
|
+
y0_right: baseline offset for x >= x0
|
|
511
|
+
"""
|
|
512
|
+
# pylint: disable=unbalanced-tuple-unpacking
|
|
513
|
+
amp_left, amp_right, sigma_left, sigma_right, x0, y0_left, y0_right = (
|
|
514
|
+
cls.args_kwargs_to_list(*args, **kwargs)
|
|
515
|
+
)
|
|
516
|
+
|
|
517
|
+
y = np.zeros_like(x)
|
|
518
|
+
|
|
519
|
+
# Left side (x < x0): use amp_left, sigma_left and y0_left
|
|
520
|
+
left_mask = x < x0
|
|
521
|
+
if np.any(left_mask):
|
|
522
|
+
exp_left = np.exp(-0.5 * ((x[left_mask] - x0) / sigma_left) ** 2)
|
|
523
|
+
y[left_mask] = y0_left + amp_left * exp_left
|
|
524
|
+
|
|
525
|
+
# Right side (x >= x0): use amp_right, sigma_right and y0_right
|
|
526
|
+
right_mask = x >= x0
|
|
527
|
+
if np.any(right_mask):
|
|
528
|
+
exp_right = np.exp(-0.5 * ((x[right_mask] - x0) / sigma_right) ** 2)
|
|
529
|
+
y[right_mask] = y0_right + amp_right * exp_right
|
|
530
|
+
|
|
531
|
+
return y
|
|
532
|
+
|
|
533
|
+
def compute_initial_params(self) -> dict[str, float]:
|
|
534
|
+
"""Compute initial parameters for Two Half-Gaussian fitting."""
|
|
535
|
+
# Parameter estimation with separate baseline analysis
|
|
536
|
+
dx = np.max(self.x) - np.min(self.x)
|
|
537
|
+
dy = np.max(self.y) - np.min(self.y)
|
|
538
|
+
x_peak = self.x[np.argmax(self.y)]
|
|
539
|
+
|
|
540
|
+
# Estimate separate baselines for left and right sides
|
|
541
|
+
left_mask = self.x < x_peak
|
|
542
|
+
right_mask = self.x >= x_peak
|
|
543
|
+
|
|
544
|
+
# Use the lower quartile of each side for robust baseline estimation
|
|
545
|
+
if np.any(left_mask):
|
|
546
|
+
y0_left = np.percentile(self.y[left_mask], 25)
|
|
547
|
+
else:
|
|
548
|
+
y0_left = np.min(self.y)
|
|
549
|
+
if np.any(right_mask):
|
|
550
|
+
y0_right = np.percentile(self.y[right_mask], 25)
|
|
551
|
+
else:
|
|
552
|
+
y0_right = np.min(self.y)
|
|
553
|
+
|
|
554
|
+
# Peak amplitude estimation (above average baseline)
|
|
555
|
+
avg_baseline = (y0_left + y0_right) / 2
|
|
556
|
+
amp_guess = np.max(self.y) - avg_baseline
|
|
557
|
+
half_max = avg_baseline + amp_guess * 0.5
|
|
558
|
+
|
|
559
|
+
# Find points at half maximum
|
|
560
|
+
left_points = np.where((self.x < x_peak) & (self.y >= half_max))[0]
|
|
561
|
+
right_points = np.where((self.x > x_peak) & (self.y >= half_max))[0]
|
|
562
|
+
|
|
563
|
+
# Estimate sigma values from half-width measurements
|
|
564
|
+
if len(left_points) > 0:
|
|
565
|
+
left_hw = x_peak - self.x[left_points[0]]
|
|
566
|
+
sigma_left = left_hw / np.sqrt(2 * np.log(2))
|
|
567
|
+
else:
|
|
568
|
+
sigma_left = dx * 0.05
|
|
569
|
+
|
|
570
|
+
if len(right_points) > 0:
|
|
571
|
+
right_hw = self.x[right_points[-1]] - x_peak
|
|
572
|
+
sigma_right = right_hw / np.sqrt(2 * np.log(2))
|
|
573
|
+
else:
|
|
574
|
+
sigma_right = dx * 0.05
|
|
575
|
+
|
|
576
|
+
x0 = x_peak
|
|
577
|
+
|
|
578
|
+
if np.any(left_mask):
|
|
579
|
+
left_peak_val = np.max(self.y[left_mask])
|
|
580
|
+
amp_left = left_peak_val - y0_left
|
|
581
|
+
else:
|
|
582
|
+
amp_left = dy * 0.5
|
|
583
|
+
|
|
584
|
+
if np.any(right_mask):
|
|
585
|
+
right_peak_val = np.max(self.y[right_mask])
|
|
586
|
+
amp_right = right_peak_val - y0_right
|
|
587
|
+
else:
|
|
588
|
+
amp_right = dy * 0.5
|
|
589
|
+
|
|
590
|
+
return {
|
|
591
|
+
"amp_left": amp_left,
|
|
592
|
+
"amp_right": amp_right,
|
|
593
|
+
"sigma_left": sigma_left,
|
|
594
|
+
"sigma_right": sigma_right,
|
|
595
|
+
"x0": x0,
|
|
596
|
+
"y0_left": y0_left,
|
|
597
|
+
"y0_right": y0_right,
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
|
|
601
|
+
class DoubleExponentialFitComputer(FitComputer):
|
|
602
|
+
"""Piecewise exponential (raise-decay) fit computer."""
|
|
603
|
+
|
|
604
|
+
PARAMS_NAMES = ("x_center", "a_left", "b_left", "a_right", "b_right", "y0")
|
|
605
|
+
|
|
606
|
+
@classmethod
|
|
607
|
+
def evaluate(cls, x: np.ndarray, *args, **kwargs) -> np.ndarray:
|
|
608
|
+
"""Return piecewise exponential (raise-decay) fitting function
|
|
609
|
+
|
|
610
|
+
Args:
|
|
611
|
+
x: time values
|
|
612
|
+
x_center: center position (boundary between left and right components)
|
|
613
|
+
a_left: left component amplitude coefficient
|
|
614
|
+
b_left: left component time constant coefficient
|
|
615
|
+
a_right: right component amplitude coefficient
|
|
616
|
+
b_right: right component time constant coefficient
|
|
617
|
+
y0: baseline offset
|
|
618
|
+
"""
|
|
619
|
+
# pylint: disable=unbalanced-tuple-unpacking
|
|
620
|
+
x_center, a_left, b_left, a_right, b_right, y0 = cls.args_kwargs_to_list(
|
|
621
|
+
*args, **kwargs
|
|
622
|
+
)
|
|
623
|
+
y = np.zeros_like(x)
|
|
624
|
+
y[x < x_center] = a_left * np.exp(b_left * x[x < x_center]) + y0
|
|
625
|
+
y[x >= x_center] = a_right * np.exp(b_right * x[x >= x_center]) + y0
|
|
626
|
+
return y
|
|
627
|
+
|
|
628
|
+
def compute_initial_params(self) -> dict[str, float]:
|
|
629
|
+
"""Compute initial parameters for piecewise exponential (raise-decay)
|
|
630
|
+
fitting."""
|
|
631
|
+
y_range = np.max(self.y) - np.min(self.y)
|
|
632
|
+
x_range = np.max(self.x) - np.min(self.x)
|
|
633
|
+
y_max = np.max(self.y)
|
|
634
|
+
|
|
635
|
+
# Baseline is rarely different from zero:
|
|
636
|
+
y0 = 0.0
|
|
637
|
+
|
|
638
|
+
# Analyze signal characteristics for better initial guesses
|
|
639
|
+
peak_idx = np.argmax(self.y)
|
|
640
|
+
|
|
641
|
+
# Estimate x_center as the peak position
|
|
642
|
+
x_center = self.x[peak_idx]
|
|
643
|
+
|
|
644
|
+
# Estimate parameters (a_left, b_left, a_right, b_right) by decomposing
|
|
645
|
+
# the signal into growth and decay components based on peak position, and
|
|
646
|
+
# fitting each curve with exponential functions using exponential_fit().
|
|
647
|
+
# X center estimation is very rough here, so we need to remove say 10% of
|
|
648
|
+
# the x range on each side to avoid fitting artifacts.
|
|
649
|
+
x_range = np.max(self.x) - np.min(self.x)
|
|
650
|
+
x_left_mask = self.x < (x_center - 0.1 * x_range)
|
|
651
|
+
x_right_mask = self.x >= (x_center + 0.1 * x_range)
|
|
652
|
+
|
|
653
|
+
x_left, y_left = self.x[x_left_mask], self.y[x_left_mask]
|
|
654
|
+
x_right, y_right = self.x[x_right_mask], self.y[x_right_mask]
|
|
655
|
+
|
|
656
|
+
left_params = {"a": 0.0, "b": 0.1, "y0": 0.0}
|
|
657
|
+
right_params = {"a": 0.0, "b": 0.1, "y0": 0.0}
|
|
658
|
+
if np.any(x_left_mask):
|
|
659
|
+
_y_fitted, left_params = ExponentialFitComputer(x_left, y_left).fit()
|
|
660
|
+
if np.any(x_right_mask):
|
|
661
|
+
_y_fitted, right_params = ExponentialFitComputer(x_right, y_right).fit()
|
|
662
|
+
|
|
663
|
+
a_left = left_params["a"]
|
|
664
|
+
b_left = left_params["b"]
|
|
665
|
+
a_right = right_params["a"]
|
|
666
|
+
b_right = right_params["b"]
|
|
667
|
+
y0 = (left_params["y0"] + right_params["y0"]) / 2
|
|
668
|
+
|
|
669
|
+
# Set bounds for parameters - b can be positive or negative
|
|
670
|
+
amp_bound = max(abs(y_max - y0), y_range) * 2
|
|
671
|
+
rate_bound = 5.0 / max(x_range, 1e-6) # Avoid division by zero
|
|
672
|
+
|
|
673
|
+
# Ensure initial parameters are within bounds
|
|
674
|
+
b_left = np.clip(b_left, -rate_bound, rate_bound)
|
|
675
|
+
b_right = np.clip(b_right, -rate_bound, rate_bound)
|
|
676
|
+
a_left = np.clip(a_left, -amp_bound, amp_bound)
|
|
677
|
+
a_right = np.clip(a_right, -amp_bound, amp_bound)
|
|
678
|
+
|
|
679
|
+
return {
|
|
680
|
+
"x_center": x_center,
|
|
681
|
+
"a_left": a_left,
|
|
682
|
+
"b_left": b_left,
|
|
683
|
+
"a_right": a_right,
|
|
684
|
+
"b_right": b_right,
|
|
685
|
+
"y0": y0,
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
|
|
689
|
+
class BaseMultiPeakFitComputer(FitComputer):
|
|
690
|
+
"""Base class for multi-peak fit computers"""
|
|
691
|
+
|
|
692
|
+
PULSE_MODEL: Type[pulse.PulseFitModel] # To be defined by subclasses
|
|
693
|
+
|
|
694
|
+
def __init__(
|
|
695
|
+
self, x: np.ndarray, y: np.ndarray, peak_indices: list[int] | None = None
|
|
696
|
+
) -> None:
|
|
697
|
+
super().__init__(x, y)
|
|
698
|
+
self.peak_indices = peak_indices
|
|
699
|
+
|
|
700
|
+
def get_params_names(self) -> tuple[str]:
|
|
701
|
+
"""Return the names of the parameters used in this fit."""
|
|
702
|
+
n_peaks = len(self.peak_indices)
|
|
703
|
+
names = []
|
|
704
|
+
for i in range(n_peaks):
|
|
705
|
+
names.extend([f"amp_{i + 1}", f"sigma_{i + 1}", f"x0_{i + 1}"])
|
|
706
|
+
names.append("y0")
|
|
707
|
+
return tuple(names)
|
|
708
|
+
|
|
709
|
+
@classmethod
|
|
710
|
+
def infer_param_names_from_kwargs(cls, kwargs: dict) -> tuple[str, ...]:
|
|
711
|
+
"""Infer parameter names for multi-gaussian from kwargs."""
|
|
712
|
+
# Find all amp_X parameters to count peaks
|
|
713
|
+
amp_params = [k for k in kwargs.keys() if k.startswith("amp_")]
|
|
714
|
+
n_peaks = len(amp_params)
|
|
715
|
+
if n_peaks == 0:
|
|
716
|
+
raise ValueError("No amp parameters found")
|
|
717
|
+
|
|
718
|
+
names = []
|
|
719
|
+
for i in range(1, n_peaks + 1):
|
|
720
|
+
names.extend([f"amp_{i}", f"sigma_{i}", f"x0_{i}"])
|
|
721
|
+
names.append("y0")
|
|
722
|
+
return tuple(names)
|
|
723
|
+
|
|
724
|
+
@classmethod
|
|
725
|
+
def evaluate(cls, x: np.ndarray, *args, **kwargs) -> np.ndarray:
|
|
726
|
+
"""Evaluate the fit function at given x values."""
|
|
727
|
+
# pylint: disable=unbalanced-tuple-unpacking
|
|
728
|
+
paramlist = cls.args_kwargs_to_list(*args, **kwargs)
|
|
729
|
+
# Determine number of peaks from parameter count
|
|
730
|
+
n_peaks = (
|
|
731
|
+
len(paramlist) - 1
|
|
732
|
+
) // 3 # -1 for y0, then divide by 3 params per peak
|
|
733
|
+
y_result = np.zeros_like(x) + paramlist[-1]
|
|
734
|
+
for i in range(n_peaks):
|
|
735
|
+
amp, sigma, x0 = paramlist[3 * i : 3 * i + 3]
|
|
736
|
+
y_result += cls.PULSE_MODEL.func(x, amp, sigma, x0, 0.0)
|
|
737
|
+
return y_result
|
|
738
|
+
|
|
739
|
+
def compute_initial_params(self) -> dict[str, float]:
|
|
740
|
+
"""Compute initial parameters for Multi Gaussian fitting."""
|
|
741
|
+
params = {}
|
|
742
|
+
for i, peak_idx in enumerate(self.peak_indices):
|
|
743
|
+
if i > 0:
|
|
744
|
+
istart = (self.peak_indices[i - 1] + peak_idx) // 2
|
|
745
|
+
else:
|
|
746
|
+
istart = 0
|
|
747
|
+
if i < len(self.peak_indices) - 1:
|
|
748
|
+
iend = (self.peak_indices[i + 1] + peak_idx) // 2
|
|
749
|
+
else:
|
|
750
|
+
iend = len(self.x) - 1
|
|
751
|
+
local_dx = 0.5 * (self.x[iend] - self.x[istart])
|
|
752
|
+
local_dy = np.max(self.y[istart:iend]) - np.min(self.y[istart:iend])
|
|
753
|
+
amp = self.PULSE_MODEL.get_amp_from_amplitude(local_dy, local_dx * 0.1)
|
|
754
|
+
sigma = local_dx * 0.1
|
|
755
|
+
x0 = self.x[peak_idx]
|
|
756
|
+
|
|
757
|
+
params[f"amp_{i + 1}"] = amp
|
|
758
|
+
params[f"sigma_{i + 1}"] = sigma
|
|
759
|
+
params[f"x0_{i + 1}"] = x0
|
|
760
|
+
|
|
761
|
+
params["y0"] = np.min(self.y)
|
|
762
|
+
return params
|
|
763
|
+
|
|
764
|
+
def compute_bounds(self, **initial_params) -> list[tuple[float, float]] | None:
|
|
765
|
+
"""Compute parameter bounds for Multi Lorentzian fitting."""
|
|
766
|
+
bounds = []
|
|
767
|
+
for i, peak_idx in enumerate(self.peak_indices):
|
|
768
|
+
if i > 0:
|
|
769
|
+
istart = (self.peak_indices[i - 1] + peak_idx) // 2
|
|
770
|
+
else:
|
|
771
|
+
istart = 0
|
|
772
|
+
if i < len(self.peak_indices) - 1:
|
|
773
|
+
iend = (self.peak_indices[i + 1] + peak_idx) // 2
|
|
774
|
+
else:
|
|
775
|
+
iend = len(self.x) - 1
|
|
776
|
+
local_dx = 0.5 * (self.x[iend] - self.x[istart])
|
|
777
|
+
bounds.extend(
|
|
778
|
+
[
|
|
779
|
+
(0.0, initial_params[f"amp_{i + 1}"] * 10.0), # amp
|
|
780
|
+
(local_dx * 0.001, local_dx * 10.0), # sigma
|
|
781
|
+
(self.x[istart], self.x[iend]), # x0
|
|
782
|
+
]
|
|
783
|
+
)
|
|
784
|
+
y0 = initial_params["y0"]
|
|
785
|
+
dy = np.max(self.y) - np.min(self.y)
|
|
786
|
+
bounds.append((y0 - dy, y0 + dy))
|
|
787
|
+
return bounds
|
|
788
|
+
|
|
789
|
+
def create_params(self, y_fitted: np.ndarray, **params) -> dict[str, float]:
|
|
790
|
+
"""Create a flat fit parameters dictionary."""
|
|
791
|
+
self.check_params(**params)
|
|
792
|
+
params["fit_type"] = self.__class__.__name__.replace("FitComputer", "").lower()
|
|
793
|
+
params["residual_rms"] = np.sqrt(np.mean((self.y - y_fitted) ** 2))
|
|
794
|
+
return params
|
|
795
|
+
|
|
796
|
+
|
|
797
|
+
class MultiGaussianFitComputer(BaseMultiPeakFitComputer):
|
|
798
|
+
"""Multi Gaussian fit computer"""
|
|
799
|
+
|
|
800
|
+
PULSE_MODEL = pulse.GaussianModel
|
|
801
|
+
|
|
802
|
+
|
|
803
|
+
class MultiLorentzianFitComputer(BaseMultiPeakFitComputer):
|
|
804
|
+
"""Multi Lorentzian fit computer"""
|
|
805
|
+
|
|
806
|
+
PULSE_MODEL = pulse.LorentzianModel
|
|
807
|
+
|
|
808
|
+
|
|
809
|
+
class SinusoidalFitComputer(FitComputer):
|
|
810
|
+
"""Sinusoidal fit computer."""
|
|
811
|
+
|
|
812
|
+
PARAMS_NAMES = ("amplitude", "frequency", "phase", "offset")
|
|
813
|
+
|
|
814
|
+
@classmethod
|
|
815
|
+
def evaluate(cls, x: np.ndarray, *args, **kwargs) -> np.ndarray:
|
|
816
|
+
"""Evaluate sinusoidal function at given x values."""
|
|
817
|
+
# pylint: disable=unbalanced-tuple-unpacking
|
|
818
|
+
amplitude, frequency, phase, offset = cls.args_kwargs_to_list(*args, **kwargs)
|
|
819
|
+
return amplitude * np.sin(2 * np.pi * frequency * x + phase) + offset
|
|
820
|
+
|
|
821
|
+
def compute_initial_params(self) -> dict[str, float]:
|
|
822
|
+
"""Compute initial parameters for sinusoidal fitting."""
|
|
823
|
+
# Parameter estimation using FFT for frequency
|
|
824
|
+
dy = np.max(self.y) - np.min(self.y)
|
|
825
|
+
amplitude = dy / 2
|
|
826
|
+
offset = np.mean(self.y)
|
|
827
|
+
phase = 0.0
|
|
828
|
+
|
|
829
|
+
# Estimate frequency using FFT
|
|
830
|
+
if len(self.x) > 2:
|
|
831
|
+
dt = self.x[1] - self.x[0] # Assuming evenly spaced
|
|
832
|
+
fft_y = np.fft.fft(self.y - offset)
|
|
833
|
+
freqs = np.fft.fftfreq(len(self.y), dt)
|
|
834
|
+
# Find dominant frequency (excluding DC component)
|
|
835
|
+
dominant_idx = np.argmax(np.abs(fft_y[1 : len(fft_y) // 2])) + 1
|
|
836
|
+
frequency = np.abs(freqs[dominant_idx])
|
|
837
|
+
else:
|
|
838
|
+
frequency = 1.0 / (np.max(self.x) - np.min(self.x))
|
|
839
|
+
|
|
840
|
+
return {
|
|
841
|
+
"amplitude": amplitude,
|
|
842
|
+
"frequency": frequency,
|
|
843
|
+
"phase": phase,
|
|
844
|
+
"offset": offset,
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
def compute_bounds(self, **initial_params) -> list[tuple[float, float]] | None:
|
|
848
|
+
"""Compute parameter bounds for sinusoidal fitting."""
|
|
849
|
+
dy = initial_params["amplitude"] * 2
|
|
850
|
+
y0 = initial_params["offset"]
|
|
851
|
+
return [
|
|
852
|
+
(0.0, dy), # amplitude
|
|
853
|
+
(0.0, 2.0 * initial_params["frequency"]), # frequency
|
|
854
|
+
(-2 * np.pi, 2 * np.pi), # phase
|
|
855
|
+
(y0 - dy, y0 + dy), # offset
|
|
856
|
+
]
|
|
857
|
+
|
|
858
|
+
|
|
859
|
+
class CDFFitComputer(FitComputer):
|
|
860
|
+
"""Cumulative Distribution Function (CDF) fit computer"""
|
|
861
|
+
|
|
862
|
+
PARAMS_NAMES = ("amplitude", "mu", "sigma", "baseline")
|
|
863
|
+
|
|
864
|
+
@classmethod
|
|
865
|
+
def evaluate(cls, x: np.ndarray, *args, **kwargs) -> np.ndarray:
|
|
866
|
+
"""Evaluate CDF function at given x values."""
|
|
867
|
+
# pylint: disable=unbalanced-tuple-unpacking
|
|
868
|
+
amplitude, mu, sigma, baseline = cls.args_kwargs_to_list(*args, **kwargs)
|
|
869
|
+
erf = scipy.special.erf # pylint: disable=no-member
|
|
870
|
+
return amplitude * erf((x - mu) / (sigma * np.sqrt(2))) + baseline
|
|
871
|
+
|
|
872
|
+
def compute_initial_params(self) -> dict[str, float]:
|
|
873
|
+
"""Compute initial parameters for CDF fitting."""
|
|
874
|
+
# Parameter estimation
|
|
875
|
+
y_min, y_max = np.min(self.y), np.max(self.y)
|
|
876
|
+
dy = y_max - y_min
|
|
877
|
+
x_min, x_max = np.min(self.x), np.max(self.x)
|
|
878
|
+
dx = x_max - x_min
|
|
879
|
+
return {
|
|
880
|
+
"amplitude": dy,
|
|
881
|
+
"mu": (x_max + np.abs(x_min)) / 2,
|
|
882
|
+
"sigma": dx / 10,
|
|
883
|
+
"baseline": dy / 2,
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
def compute_bounds(self, **initial_params) -> list[tuple[float, float]] | None:
|
|
887
|
+
"""Compute parameter bounds for CDF fitting."""
|
|
888
|
+
y_min, y_max = np.min(self.y), np.max(self.y)
|
|
889
|
+
dy = initial_params["amplitude"]
|
|
890
|
+
x_min, x_max = np.min(self.x), np.max(self.x)
|
|
891
|
+
dx = x_max - x_min
|
|
892
|
+
return [
|
|
893
|
+
(0.0, dy * 2), # amplitude
|
|
894
|
+
(x_min, x_max), # mu
|
|
895
|
+
(dx * 0.001, dx), # sigma
|
|
896
|
+
(y_min - dy, y_max + dy), # baseline
|
|
897
|
+
]
|
|
898
|
+
|
|
899
|
+
|
|
900
|
+
class SigmoidFitComputer(FitComputer):
|
|
901
|
+
"""Sigmoid fit computer."""
|
|
902
|
+
|
|
903
|
+
PARAMS_NAMES = ("amplitude", "k", "x0", "offset")
|
|
904
|
+
|
|
905
|
+
@classmethod
|
|
906
|
+
def evaluate(cls, x: np.ndarray, *args, **kwargs) -> np.ndarray:
|
|
907
|
+
"""Evaluate Sigmoid function at given x values."""
|
|
908
|
+
# pylint: disable=unbalanced-tuple-unpacking
|
|
909
|
+
amplitude, k, x0, offset = cls.args_kwargs_to_list(*args, **kwargs)
|
|
910
|
+
return amplitude / (1 + np.exp(-k * (x - x0))) + offset
|
|
911
|
+
|
|
912
|
+
def compute_initial_params(self) -> dict[str, float]:
|
|
913
|
+
"""Compute initial parameters for Sigmoid fitting."""
|
|
914
|
+
y_min, y_max = np.min(self.y), np.max(self.y)
|
|
915
|
+
dy = y_max - y_min
|
|
916
|
+
x_min, x_max = np.min(self.x), np.max(self.x)
|
|
917
|
+
dx = x_max - x_min
|
|
918
|
+
return {
|
|
919
|
+
"amplitude": dy,
|
|
920
|
+
"k": 4.0 / dx,
|
|
921
|
+
"x0": (x_max + np.abs(x_min)) / 2,
|
|
922
|
+
"offset": y_min,
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
def compute_bounds(self, **initial_params) -> list[tuple[float, float]] | None:
|
|
926
|
+
"""Compute parameter bounds for Sigmoid fitting."""
|
|
927
|
+
y_min, y_max = np.min(self.y), np.max(self.y)
|
|
928
|
+
dy = initial_params["amplitude"]
|
|
929
|
+
x_min, x_max = np.min(self.x), np.max(self.x)
|
|
930
|
+
dx = x_max - x_min
|
|
931
|
+
return [
|
|
932
|
+
(0.0, 10 * dy), # amplitude
|
|
933
|
+
(0.1 / dx, 100.0 / dx), # k
|
|
934
|
+
(x_min, x_max), # x0
|
|
935
|
+
(y_min - dy, y_max + dy), # offset
|
|
936
|
+
]
|
|
937
|
+
|
|
938
|
+
|
|
939
|
+
def linear_fit(x: np.ndarray, y: np.ndarray) -> tuple[np.ndarray, dict[str, float]]:
|
|
940
|
+
"""Compute linear fit: y = a*x + b.
|
|
941
|
+
|
|
942
|
+
Args:
|
|
943
|
+
x: x data array
|
|
944
|
+
y: y data array
|
|
945
|
+
|
|
946
|
+
Returns:
|
|
947
|
+
A tuple containing the fitted y values and a dictionary of fit parameters.
|
|
948
|
+
"""
|
|
949
|
+
return LinearFitComputer(x, y).fit()
|
|
950
|
+
|
|
951
|
+
|
|
952
|
+
def polynomial_fit(
|
|
953
|
+
x: np.ndarray, y: np.ndarray, degree: int = 2
|
|
954
|
+
) -> tuple[np.ndarray, dict[str, float]]:
|
|
955
|
+
"""Compute polynomial fit.
|
|
956
|
+
|
|
957
|
+
Args:
|
|
958
|
+
x: x data array
|
|
959
|
+
y: y data array
|
|
960
|
+
degree: polynomial degree
|
|
961
|
+
|
|
962
|
+
Returns:
|
|
963
|
+
A tuple containing the fitted y values and a dictionary of fit parameters.
|
|
964
|
+
"""
|
|
965
|
+
return PolynomialFitComputer(x, y, degree).fit()
|
|
966
|
+
|
|
967
|
+
|
|
968
|
+
def gaussian_fit(x: np.ndarray, y: np.ndarray) -> tuple[np.ndarray, dict[str, float]]:
|
|
969
|
+
"""Compute Gaussian fit.
|
|
970
|
+
|
|
971
|
+
Args:
|
|
972
|
+
x: x data array
|
|
973
|
+
y: y data array
|
|
974
|
+
|
|
975
|
+
Returns:
|
|
976
|
+
A tuple containing the fitted y values and a dictionary of fit parameters.
|
|
977
|
+
"""
|
|
978
|
+
return GaussianFitComputer(x, y).fit()
|
|
979
|
+
|
|
980
|
+
|
|
981
|
+
def lorentzian_fit(x: np.ndarray, y: np.ndarray) -> tuple[np.ndarray, dict]:
|
|
982
|
+
"""Compute Lorentzian fit.
|
|
983
|
+
|
|
984
|
+
Args:
|
|
985
|
+
x: x data array
|
|
986
|
+
y: y data array
|
|
987
|
+
|
|
988
|
+
Returns:
|
|
989
|
+
A tuple containing the fitted y values and a dictionary of fit parameters.
|
|
990
|
+
"""
|
|
991
|
+
return LorentzianFitComputer(x, y).fit()
|
|
992
|
+
|
|
993
|
+
|
|
994
|
+
def exponential_fit(
|
|
995
|
+
x: np.ndarray, y: np.ndarray
|
|
996
|
+
) -> tuple[np.ndarray, dict[str, float]]:
|
|
997
|
+
"""Compute exponential fit: y = a * exp(b * x) + y0.
|
|
998
|
+
|
|
999
|
+
Args:
|
|
1000
|
+
x: x data array
|
|
1001
|
+
y: y data array
|
|
1002
|
+
|
|
1003
|
+
Returns:
|
|
1004
|
+
A tuple containing the fitted y values and a dictionary of fit parameters.
|
|
1005
|
+
"""
|
|
1006
|
+
return ExponentialFitComputer(x, y).fit()
|
|
1007
|
+
|
|
1008
|
+
|
|
1009
|
+
def planckian_fit(x: np.ndarray, y: np.ndarray) -> tuple[np.ndarray, dict[str, float]]:
|
|
1010
|
+
"""Compute Planckian (blackbody radiation) fit.
|
|
1011
|
+
|
|
1012
|
+
Args:
|
|
1013
|
+
x: wavelength data array
|
|
1014
|
+
y: intensity data array
|
|
1015
|
+
|
|
1016
|
+
Returns:
|
|
1017
|
+
A tuple containing the fitted y values and a dictionary of fit parameters.
|
|
1018
|
+
"""
|
|
1019
|
+
return PlanckianFitComputer(x, y).fit()
|
|
1020
|
+
|
|
1021
|
+
|
|
1022
|
+
def twohalfgaussian_fit(
|
|
1023
|
+
x: np.ndarray, y: np.ndarray
|
|
1024
|
+
) -> tuple[np.ndarray, dict[str, float]]:
|
|
1025
|
+
"""Compute two half-Gaussian fit for asymmetric peaks with separate baselines.
|
|
1026
|
+
|
|
1027
|
+
Now supports separate amplitudes for even better asymmetric peak fitting.
|
|
1028
|
+
|
|
1029
|
+
Args:
|
|
1030
|
+
x: x data array
|
|
1031
|
+
y: y data array
|
|
1032
|
+
|
|
1033
|
+
Returns:
|
|
1034
|
+
A tuple containing the fitted y values and a dictionary of fit parameters.
|
|
1035
|
+
"""
|
|
1036
|
+
return TwoHalfGaussianFitComputer(x, y).fit()
|
|
1037
|
+
|
|
1038
|
+
|
|
1039
|
+
def piecewiseexponential_fit(
|
|
1040
|
+
x: np.ndarray, y: np.ndarray
|
|
1041
|
+
) -> tuple[np.ndarray, dict[str, float]]:
|
|
1042
|
+
"""Compute piecewise exponential fit (raise-decay).
|
|
1043
|
+
|
|
1044
|
+
Args:
|
|
1045
|
+
x: time data array
|
|
1046
|
+
y: intensity data array
|
|
1047
|
+
|
|
1048
|
+
Returns:
|
|
1049
|
+
A tuple containing the fitted y values and a dictionary of fit parameters.
|
|
1050
|
+
"""
|
|
1051
|
+
return DoubleExponentialFitComputer(x, y).fit()
|
|
1052
|
+
|
|
1053
|
+
|
|
1054
|
+
def multilorentzian_fit(
|
|
1055
|
+
x: np.ndarray, y: np.ndarray, peak_indices: list[int]
|
|
1056
|
+
) -> tuple[np.ndarray, dict[str, float]]:
|
|
1057
|
+
"""Compute multi-Lorentzian fit for multiple peaks.
|
|
1058
|
+
|
|
1059
|
+
Args:
|
|
1060
|
+
x: x data array
|
|
1061
|
+
y: y data array
|
|
1062
|
+
peak_indices: list of peak indices
|
|
1063
|
+
|
|
1064
|
+
Returns:
|
|
1065
|
+
A tuple containing the fitted y values and a dictionary of fit parameters.
|
|
1066
|
+
"""
|
|
1067
|
+
return MultiLorentzianFitComputer(x, y, peak_indices).fit()
|
|
1068
|
+
|
|
1069
|
+
|
|
1070
|
+
def multigaussian_fit(
|
|
1071
|
+
x: np.ndarray, y: np.ndarray, peak_indices: list[int]
|
|
1072
|
+
) -> tuple[np.ndarray, dict[str, float]]:
|
|
1073
|
+
"""Compute multi-Gaussian fit for multiple peaks.
|
|
1074
|
+
|
|
1075
|
+
Args:
|
|
1076
|
+
x: x data array
|
|
1077
|
+
y: y data array
|
|
1078
|
+
peak_indices: list of peak indices
|
|
1079
|
+
|
|
1080
|
+
Returns:
|
|
1081
|
+
A tuple containing the fitted y values and a dictionary of fit parameters.
|
|
1082
|
+
"""
|
|
1083
|
+
return MultiGaussianFitComputer(x, y, peak_indices).fit()
|
|
1084
|
+
|
|
1085
|
+
|
|
1086
|
+
def sinusoidal_fit(x: np.ndarray, y: np.ndarray) -> tuple[np.ndarray, dict[str, float]]:
|
|
1087
|
+
"""Compute sinusoidal fit.
|
|
1088
|
+
|
|
1089
|
+
Args:
|
|
1090
|
+
x: x data array
|
|
1091
|
+
y: y data array
|
|
1092
|
+
|
|
1093
|
+
Returns:
|
|
1094
|
+
A tuple containing the fitted y values and a dictionary of fit parameters.
|
|
1095
|
+
"""
|
|
1096
|
+
return SinusoidalFitComputer(x, y).fit()
|
|
1097
|
+
|
|
1098
|
+
|
|
1099
|
+
def voigt_fit(x: np.ndarray, y: np.ndarray) -> tuple[np.ndarray, dict[str, float]]:
|
|
1100
|
+
"""Compute Voigt fit.
|
|
1101
|
+
|
|
1102
|
+
Args:
|
|
1103
|
+
x: x data array
|
|
1104
|
+
y: y data array
|
|
1105
|
+
|
|
1106
|
+
Returns:
|
|
1107
|
+
A tuple containing the fitted y values and a dictionary of fit parameters.
|
|
1108
|
+
"""
|
|
1109
|
+
return VoigtFitComputer(x, y).fit()
|
|
1110
|
+
|
|
1111
|
+
|
|
1112
|
+
def cdf_fit(x: np.ndarray, y: np.ndarray) -> tuple[np.ndarray, dict[str, float]]:
|
|
1113
|
+
"""Compute Cumulative Distribution Function (CDF) fit.
|
|
1114
|
+
|
|
1115
|
+
Args:
|
|
1116
|
+
x: x data array
|
|
1117
|
+
y: y data array
|
|
1118
|
+
|
|
1119
|
+
Returns:
|
|
1120
|
+
A tuple containing the fitted y values and a dictionary of fit parameters.
|
|
1121
|
+
"""
|
|
1122
|
+
return CDFFitComputer(x, y).fit()
|
|
1123
|
+
|
|
1124
|
+
|
|
1125
|
+
def sigmoid_fit(x: np.ndarray, y: np.ndarray) -> tuple[np.ndarray, dict[str, float]]:
|
|
1126
|
+
"""Compute Sigmoid (Logistic) fit.
|
|
1127
|
+
|
|
1128
|
+
Args:
|
|
1129
|
+
x: x data array
|
|
1130
|
+
y: y data array
|
|
1131
|
+
|
|
1132
|
+
Returns:
|
|
1133
|
+
A tuple containing the fitted y values and a dictionary of fit parameters.
|
|
1134
|
+
"""
|
|
1135
|
+
return SigmoidFitComputer(x, y).fit()
|
|
1136
|
+
|
|
1137
|
+
|
|
1138
|
+
FIT_TYPE_MAPPING = {
|
|
1139
|
+
"linear": LinearFitComputer,
|
|
1140
|
+
"polynomial": PolynomialFitComputer,
|
|
1141
|
+
"gaussian": GaussianFitComputer,
|
|
1142
|
+
"lorentzian": LorentzianFitComputer,
|
|
1143
|
+
"exponential": ExponentialFitComputer,
|
|
1144
|
+
"planckian": PlanckianFitComputer,
|
|
1145
|
+
"twohalfgaussian": TwoHalfGaussianFitComputer,
|
|
1146
|
+
"doubleexponential": DoubleExponentialFitComputer,
|
|
1147
|
+
"multilorentzian": MultiLorentzianFitComputer,
|
|
1148
|
+
"multigaussian": MultiGaussianFitComputer,
|
|
1149
|
+
"sinusoidal": SinusoidalFitComputer,
|
|
1150
|
+
"voigt": VoigtFitComputer,
|
|
1151
|
+
"cdf": CDFFitComputer,
|
|
1152
|
+
"sigmoid": SigmoidFitComputer,
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
|
|
1156
|
+
def evaluate_fit(x: np.ndarray, **fit_params) -> np.ndarray:
|
|
1157
|
+
"""Evaluate fit function with given parameters at x values.
|
|
1158
|
+
|
|
1159
|
+
Args:
|
|
1160
|
+
x: X values to evaluate at
|
|
1161
|
+
**fit_params: Fit parameters (any of the ``*Params`` dataclasses)
|
|
1162
|
+
|
|
1163
|
+
Returns:
|
|
1164
|
+
Y values computed from the fit function
|
|
1165
|
+
"""
|
|
1166
|
+
params = fit_params.copy()
|
|
1167
|
+
params.pop("residual_rms", None)
|
|
1168
|
+
fcclass: Type[FitComputer] = FIT_TYPE_MAPPING.get(params.pop("fit_type", None))
|
|
1169
|
+
if fcclass is None:
|
|
1170
|
+
raise ValueError(f"Unsupported fit type: {fit_params.get('fit_type')}")
|
|
1171
|
+
return fcclass.evaluate(x, **params)
|