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
 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
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
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)
    res = np.asarray(res)

    # Get ordered parameter names
    args_default = get_function_args_ordered(func)[1:]
    args_ordered = tuple(key for key, _ in args_default)
    values_ordered = tuple(val for _, val in args_default)

    if len(res) != len(values_ordered):
        res = np.concatenate([res, values_ordered[len(res) :]])

    return FitResult(
        res,
        lambda x: func(x, *res),
        x=x,
        data=data,
        keys=args_ordered,
    )