Skip to content

Exp

Simples example

>>> from ffit.funcs.exp import Exp

# Call the fit method with x and y data.
>>> fit_result = Exp().fit(x, y)

# The result is a FitResult object that can be unpacked.
>>> res, res_func = fit_result

# One can combine multiple calls in one line.
>>> res = Exp().fit(x, y, guess=[1, 2, 3, 4]).plot(ax).res

Exp function.

Function

\[ f(x) = A \exp(Γ⋅x) + A_{\text{offset}} \]
f(x) = amplitude * np.exp(rate * x) + offset

Final parameters

The final parameters are given by ExpParam dataclass.

Source code in ffit/funcs/exp.py
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
class Exp(FitLogic[ExpParam]):  # type: ignore
    r"""Exp function.


    Function
    ---------

    $$
        f(x) = A \exp(Γ⋅x) + A_{\text{offset}}
    $$

        f(x) = amplitude * np.exp(rate * x) + offset


    Final parameters
    -----------------
    The final parameters are given by [`ExpParam`](../exp_param/) dataclass.

    """

    param: _t.Type[ExpParam] = ExpParam

    func = staticmethod(exp_func)
    func_std = staticmethod(exp_error)
    _guess = staticmethod(exp_guess)

    _example_param = (-3, -0.5, 3)
    _example_x_min = 0
    _example_x_max = 10

fit

fit(x, data, mask=None, guess=None, method='leastsq', maxfev=10000, **kwargs)

Fit the data using the specified fitting function.

This function returns FitResult see the documentation for more information what is possible with it.

Parameters:

Name Type Description Default
x _ARRAY

The independent variable.

required
data _ARRAY

The dependent variable.

required
mask Optional[Union[_ARRAY, float]]

The mask array or threshold for data filtering (optional).

None
guess Optional[Union[_T, tuple, list]]

The initial guess for fit parameters (optional).

None
method Literal['least_squares', 'leastsq', 'curve_fit']

The fitting method to use. Valid options are "least_squares", "leastsq", and "curve_fit" (default: "leastsq").

'leastsq'
**kwargs

Additional keyword arguments.

{}

Returns:

Name Type Description
FitResult FitWithErrorResult[_T]

The result of the fit, including the fitted parameters and the fitted function.

Raises:

Type Description
ValueError

If an invalid fitting method is provided.

Source code in ffit/fit_logic.py
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
def fit(
    self,
    x: _ARRAY,
    data: _ARRAY,
    mask: _t.Optional[_t.Union[_ARRAY, float]] = None,
    guess: _t.Optional[_t.Union[_T, tuple, list]] = None,
    method: _t.Literal["least_squares", "leastsq", "curve_fit"] = "leastsq",
    maxfev: int = 10000,
    **kwargs,
) -> FitWithErrorResult[_T]:  # Tuple[_T, _t.Callable, _NDARRAY]:
    """
    Fit the data using the specified fitting function.

    This function returns [FitResult][ffit.fit_results.FitResult] see
    the documentation for more information what is possible with it.


    Args:
        x: The independent variable.
        data: The dependent variable.
        mask: The mask array or threshold for data filtering (optional).
        guess: The initial guess for fit parameters (optional).
        method: The fitting method to use. Valid options are "least_squares", "leastsq",
            and "curve_fit" (default: "leastsq").
        **kwargs: Additional keyword arguments.

    Returns:
        FitResult: The result of the fit, including the fitted parameters and the fitted function.

    Raises:
        ValueError: If an invalid fitting method is provided.

    """
    # Convert x and data to numpy arrays
    x, data = np.asarray(x), np.asarray(data)

    # Mask the data and check that length of masked data is greater than lens of params
    x_masked, data_masked = get_masked_data(x, data, mask, param_len(self.param))
    if len(x_masked) == 0 or len(data_masked) == 0:
        return FitWithErrorResult()

    # Get a guess if not provided
    if guess is None:
        guess = self._guess(x_masked, data_masked, **kwargs)

    guess = tuple(guess)  # type: ignore
    # Fit the data
    res, cov = self._fit(x_masked, data_masked, guess, method, maxfev=maxfev)

    # Normalize the result if necessary. Like some periodicity that should not be important
    if self.normalize_res is not None:  # type: ignore
        res = self.normalize_res(res)  # type: ignore

    # Convert the result to a parameter object (NamedTuple)
    # print(cov)
    if cov is not None:
        stds = np.diag(cov)
        if self.normalize_res is not None:  # type: ignore
            stds = self.normalize_res(stds)  # type: ignore
        param_std = self.param(*stds)
    else:
        param_std = None
    param = self.param(*res, std=param_std)

    full_func = getattr(self, "full_func", self.__class__().func)

    # print(res)
    return FitWithErrorResult(
        param,
        lambda x: full_func(x, *res),
        x=x,
        data=data,
        cov=cov,
        stderr=param_std,
        stdfunc=lambda x: self.get_func_std()(x, *res, *stds),
    )

async_fit async

async_fit(x, data, mask=None, guess=None, **kwargs)

Asynchronously fits the model to the provided data.

Parameters:

Name Type Description Default
x _ARRAY

The independent variable data.

required
data _ARRAY

The dependent variable data to fit.

required
mask Optional[Union[_ARRAY, float]]

An optional mask to apply to the data. Defaults to None.

None
guess Optional[_T]

An optional initial guess for the fitting parameters. Defaults to None.

None
**kwargs

Additional keyword arguments to pass to the fitting function.

{}

Returns:

Type Description
FitWithErrorResult[_T]

FitWithErrorResult[_T]: The result of the fitting process, including the fitted parameters and associated errors.

Source code in ffit/fit_logic.py
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
async def async_fit(
    self,
    x: _ARRAY,
    data: _ARRAY,
    mask: _t.Optional[_t.Union[_ARRAY, float]] = None,
    guess: _t.Optional[_T] = None,
    **kwargs,
) -> FitWithErrorResult[_T]:
    """
    Asynchronously fits the model to the provided data.

    Args:
        x (_ARRAY): The independent variable data.
        data (_ARRAY): The dependent variable data to fit.
        mask (Optional[Union[_ARRAY, float]], optional): An optional mask to apply to the data. Defaults to None.
        guess (Optional[_T], optional): An optional initial guess for the fitting parameters. Defaults to None.
        **kwargs: Additional keyword arguments to pass to the fitting function.

    Returns:
        FitWithErrorResult[_T]:
            The result of the fitting process, including the fitted parameters and associated errors.
    """
    return self.fit(x, data, mask, guess, **kwargs)

guess classmethod

guess(x, data, mask=None, guess=None, **kwargs)

Guess the initial fit parameters.

This function returns an object of the class FitResult. See its documentation for more information on what is possible with it.

Parameters:

Name Type Description Default
x

The independent variable.

required
data

The dependent variable.

required
mask Optional[Union[_ARRAY, float]]

The mask array or threshold for data filtering (optional).

None
guess Optional[_T]

The initial guess for the fit parameters (optional).

None
**kwargs

Additional keyword arguments.

{}

Returns:

Name Type Description
FitResult FitResult[_T]

The guess, including the guess parameters and the function based on the guess.

Examples:

>>> x = [1, 2, 3, 4, 5]
>>> data = [2, 4, 6, 8, 10]
>>> fit_guess = FitLogic.guess(x, data)
>>> fit_guess.plot()
Source code in ffit/fit_logic.py
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
@classmethod
def guess(
    cls,
    x,
    data,
    mask: _t.Optional[_t.Union[_ARRAY, float]] = None,
    guess: _t.Optional[_T] = None,
    **kwargs,
) -> FitResult[_T]:
    """Guess the initial fit parameters.

    This function returns an object of the class `FitResult`.
    See its documentation for more information on what is possible with it.

    Args:
        x: The independent variable.
        data: The dependent variable.
        mask: The mask array or threshold for data filtering (optional).
        guess: The initial guess for the fit parameters (optional).
        **kwargs: Additional keyword arguments.

    Returns:
        FitResult: The guess, including the guess parameters and the function based on the guess.


    Examples:
        >>> x = [1, 2, 3, 4, 5]
        >>> data = [2, 4, 6, 8, 10]
        >>> fit_guess = FitLogic.guess(x, data)
        >>> fit_guess.plot()
    """
    if guess is not None:
        return FitResult(
            cls.param(*guess), lambda x: cls.func(x, *guess), x=x, data=data
        )
    x_masked, data_masked = get_masked_data(x, data, mask, mask_min_len=1)
    guess_param = cls._guess(x_masked, data_masked, **kwargs)
    return FitResult(
        cls.param(*guess_param), lambda x: cls.func(x, *guess_param), x=x, data=data
    )

bootstrapping

bootstrapping(x, data, mask=None, guess=None, method='leastsq', sampling_len=None, sampling_portion=0.75, **kwargs)

Fit the data using the specified fitting function.

This function returns FitResult see the documentation for more information what is possible with it.

Parameters:

Name Type Description Default
x _ARRAY

The independent variable.

required
data _ARRAY

The dependent variable.

required
mask Optional[Union[_ARRAY, float]]

The mask array or threshold for data filtering (optional).

None
guess Optional[Union[_T, tuple, list]]

The initial guess for fit parameters (optional).

None
method Literal['least_squares', 'leastsq', 'curve_fit']

The fitting method to use. Valid options are "least_squares", "leastsq", and "curve_fit" (default: "leastsq").

'leastsq'
**kwargs

Additional keyword arguments.

{}

Returns:

Name Type Description
FitResult FitWithErrorResult[_T]

The result of the fit, including the fitted parameters and the fitted function.

Raises:

Type Description
ValueError

If an invalid fitting method is provided.

Source code in ffit/fit_logic.py
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
def bootstrapping(
    self,
    x: _ARRAY,
    data: _ARRAY,
    mask: _t.Optional[_t.Union[_ARRAY, float]] = None,
    guess: _t.Optional[_t.Union[_T, tuple, list]] = None,
    method: _t.Literal["least_squares", "leastsq", "curve_fit"] = "leastsq",
    sampling_len: _t.Optional[int] = None,
    sampling_portion: float = 0.75,
    **kwargs,
) -> FitWithErrorResult[_T]:  # Tuple[_T, _t.Callable, _NDARRAY]:
    """
    Fit the data using the specified fitting function.

    This function returns [FitResult][ffit.fit_results.FitResult] see
    the documentation for more information what is possible with it.


    Args:
        x: The independent variable.
        data: The dependent variable.
        mask: The mask array or threshold for data filtering (optional).
        guess: The initial guess for fit parameters (optional).
        method: The fitting method to use. Valid options are "least_squares", "leastsq",
            and "curve_fit" (default: "leastsq").
        **kwargs: Additional keyword arguments.

    Returns:
        FitResult: The result of the fit, including the fitted parameters and the fitted function.

    Raises:
        ValueError: If an invalid fitting method is provided.

    """
    # Convert x and data to numpy arrays
    x, data = np.asarray(x), np.asarray(data)

    mask = get_mask(mask, x)

    # Mask the data and check that length of masked data is greater than lens of params
    x_masked, data_masked = get_masked_data(x, data, mask, param_len(self.param))
    if len(x_masked) == 0 or len(data_masked) == 0:
        return FitWithErrorResult()

    # Get a guess if not provided
    if guess is None:
        guess = self._guess(x_masked, data_masked, **kwargs)

    # Fit ones to get the best initial guess
    guess, cov = self._fit(x_masked, data_masked, guess, method)

    # Set sampling length if not provided
    sampling_len = (
        int(min(max(len(x_masked) / 10, 1000), 10_000))
        if sampling_len is None
        else sampling_len
    )

    # Run fit on random subarrays
    all_res = []
    for xx, yy in get_random_subarrays(
        x_masked, data_masked, sampling_len, sampling_portion
    ):
        res, _ = self._fit(xx, yy, guess, method)
        if self.normalize_res is not None:  # type: ignore
            res = self.normalize_res(res)  # type: ignore
        all_res.append(res)

    res_means = np.mean(all_res, axis=0)
    bootstrap_std = np.std(all_res, axis=0)
    # print(cov)
    # total_std = np.sqrt(np.diag(cov) + bootstrap_std**2)
    total_std = bootstrap_std
    # print(res_means, total_std)

    # Convert the result to a parameter object (NamedTuple)
    param_std = self.param(*total_std)
    param = self.param(*res_means, std=param_std)

    full_func = getattr(self, "full_func", self.__class__().func)

    return FitWithErrorResult(
        param,
        lambda x: full_func(x, *res),
        x=x,
        data=data,
        cov=cov,
        stderr=param_std,
        stdfunc=lambda x: self.get_func_std()(x, *res_means, *total_std),
    )