Skip to content

Custom Function

curve_fit

Fit a curve with curve_fit method.

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

Parameters:

Name Type Description Default
fit_func

Function to fit.

required
x _NDARRAY

x data.

required
data _NDARRAY

data to fit.

required
p0 Optional[List[Any]]

Initial guess for the parameters.

None
bounds Optional[Union[List[Tuple[Any, Any]], Tuple[Any, Any]]]

Bounds for the parameters.

(-inf, inf)
**kwargs

Additional keyword arguments to curve_fit.

{}

Returns:

Name Type Description
FitResult FitResult

Fit result.

Source code in ffit/front.py
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def curve_fit(
    func: _t.Callable,
    x: _NDARRAY,
    data: _NDARRAY,
    p0: _t.Optional[_t.List[_t.Any]] = None,
    *,
    bounds: _t.Optional[
        _t.Union[_t.List[_t.Tuple[_t.Any, _t.Any]], _t.Tuple[_t.Any, _t.Any]]
    ] = (
        -np.inf,
        np.inf,
    ),
    method: _t.Literal["leastsq", "curve_fit"] = "curve_fit",
    **kwargs,
) -> FitResult:
    """Fit a curve with curve_fit method.

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

    Args:
        fit_func: Function to fit.
        x: x data.
        data: data to fit.
        p0: Initial guess for the parameters.
        bounds: Bounds for the parameters.
        **kwargs: Additional keyword arguments to curve_fit.

    Returns:
        FitResult: Fit result.
    """

    res = _curve_fit(func, x, data, p0=p0, bounds=bounds, method=method, **kwargs)
    args_ordered = tuple(key for key, _ in get_function_args_ordered(func)[1:])
    return FitResult(
        np.asarray(res),
        lambda x: func(x, *res),
        x=x,
        data=data,
        keys=args_ordered,
    )