Skip to content

Fit result

ffit.fit_results.FitResult

Bases: Tuple[Optional[_R], Callable]

This class represents the result of a fit operation.

Examples

>>> import ffit as ff
>>> result = ff.Cos().fit(x, y)
>>> result.res.amplitude # to get the amplitude
>>> result.res # to get whole result as a NamedTuple
>>> y0 = result.res_func(x0) # to get the fitted values
>>> result.plot() # to plot the fit results

All in one:
>>> amp = ff.Cos().fit(x, y).plot().res.amplitude

Unpack the FitResult

The FitResult is based on a tuple with two elements to have right type hints. You can unpack the FitResult like this:

>>> res, res_func = ff.Cos().fit(x, y)

You can also unpack it after using some methods:

>>> res, res_func = ff.Cos().fit(x, y).plot(ax, x=x, label="Cosine fit")

Remember: fit method always returns FitResult that can be unpacked. In case the fit fails, the FitResult will have res=None, res_func=lambda x: [np.nan] * len(x).

Remember: The FitResult is immutable as based on the tuple, so you cannot change the values.

Methods:

Name Description
plot

Plot the fit results on the given axes.

Source code in ffit/fit_results.py
 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
106
107
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
class FitResult(_t.Tuple[_t.Optional[_R], _t.Callable]):
    """This class represents the result of a fit operation.

    Examples
    --------
        >>> import ffit as ff
        >>> result = ff.Cos().fit(x, y)
        >>> result.res.amplitude # to get the amplitude
        >>> result.res # to get whole result as a NamedTuple
        >>> y0 = result.res_func(x0) # to get the fitted values
        >>> result.plot() # to plot the fit results

        All in one:
        >>> amp = ff.Cos().fit(x, y).plot().res.amplitude

    Unpack the FitResult
    ----------------------
    The FitResult is based on a tuple with two elements to have right type hints.
    You can unpack the FitResult like this:

        >>> res, res_func = ff.Cos().fit(x, y)

    You can also unpack it after using some methods:

        >>> res, res_func = ff.Cos().fit(x, y).plot(ax, x=x, label="Cosine fit")

    Remember: fit method always returns FitResult that can be unpacked.
    In case the fit fails, the FitResult will have `res=None, res_func=lambda x: [np.nan] * len(x)`.


    Remember: The FitResult is immutable as based on the tuple, so you cannot change the values.
    """

    res: _t.Optional[_R]
    res_func: _t.Callable[[_NDARRAY], _NDARRAY]
    x: _t.Optional[_NDARRAY]
    data: _t.Optional[_NDARRAY]
    cov: _t.Optional[_NDARRAY]

    def __init__(
        self,
        res: _t.Optional[_R] = None,
        res_func: _t.Optional[_t.Callable] = None,
        x: _t.Optional[_NDARRAY] = None,
        data: _t.Optional[_NDARRAY] = None,
        cov: _t.Optional[_NDARRAY] = None,
        **kwargs,
    ):
        """
        Initialize the FitResult class.
        ---------------------------

        Args:
            res: Result value as NamedTuple.
            res_func: Optional callable function for result.
            x: Original x values used to fitted.
            data: Original data that was fitted.
            **kwargs: Additional keyword arguments that will be ignored.

        Example to create yourself.
        -----------------------------
            >>> result = ff.FitResult(res=(1, 2, 3), res_func=lambda x: x ** 2)

        """
        del kwargs
        self.res = res
        self.res_func = (
            res_func if res_func is not None else (lambda x: np.ones_like(x) * np.nan)
        )
        self.x = x
        self.data = data
        self.cov = cov

    def __new__(
        cls,
        res: _t.Optional[_R] = None,
        res_func: _t.Optional[_t.Callable] = None,
        x: _t.Optional[_NDARRAY] = None,
        **kwargs,
    ):
        if res_func is None:
            res_func = lambda _: None  # noqa: E731

        new = super().__new__(cls, (res, res_func))
        return new

    def plot(
        self,
        ax: _t.Optional["Axes"] = None,
        *,
        x: _t.Optional[_t.Union[_NDARRAY, int]] = None,
        label: _t.Optional[str] = DEFAULT_FIT_LABEL,
        color: _t.Optional[_t.Union[str, int]] = None,
        title: _t.Optional[str] = None,
        post_func_x: _t.Optional[_t.Callable[[_NDARRAY], _NDARRAY]] = None,
        post_func_y: _t.Optional[_t.Callable[[_NDARRAY], _NDARRAY]] = None,
        **kwargs,
    ):
        """Plot the fit results on the given axes.

        Args:
            ax (Optional[Axes]): The axes on which to plot the fit results. If None, a new axes will be created.
            label (str): The label for the plot. Defaults to ffit.config.DEFAULT_FIT_LABEL.
            color (Optional[Union[str, int]]): The color of the plot. If None, a default color will be used.
            title (Optional[str]): The title for the plot. If provided, it will be appended to the existing title.
            **kwargs: Additional keyword arguments to be passed to the plot function.

        Returns:
            FitResults: The FitResults object itself.

        Example:
            ```
            >>> result = ff.Cos().fit(x, y)
            >>> result.plot() # ax will be get from plt.gca()
            >>> result.plot(ax, x=x, label="Cosine fit")
            >>> result.plot(ax, x=x, label="Cosine fit", color="r")
            ```
        Worth to mention: title will be appended to the existing title with a new line.


        """
        ax = get_ax_from_gca(ax)
        x_fit = get_right_x(x, ax, self.x)

        y_fit = self.res_func(x_fit)
        if label is not None:
            label = format_str_with_params(self.res, label)
            kwargs.update({"label": label})

        color = get_right_color(color)
        kwargs.update({"color": color})

        if post_func_x:
            x_fit = post_func_x(x_fit)
        if post_func_y:
            y_fit = post_func_y(y_fit)
        ax.plot(x_fit, y_fit, **kwargs)

        if title:
            title = format_str_with_params(self.res, title)
            current_title = ax.get_title()
            if current_title:
                title = f"{current_title}\n{title}"
            ax.set_title(title)

        if label != DEFAULT_FIT_LABEL and label is not None:
            ax.legend()

        return self

plot

plot(ax=None, *, x=None, label=DEFAULT_FIT_LABEL, color=None, title=None, post_func_x=None, post_func_y=None, **kwargs)

Plot the fit results on the given axes.

Parameters:

Name Type Description Default
ax Optional[Axes]

The axes on which to plot the fit results. If None, a new axes will be created.

None
label str

The label for the plot. Defaults to ffit.config.DEFAULT_FIT_LABEL.

DEFAULT_FIT_LABEL
color Optional[Union[str, int]]

The color of the plot. If None, a default color will be used.

None
title Optional[str]

The title for the plot. If provided, it will be appended to the existing title.

None
**kwargs

Additional keyword arguments to be passed to the plot function.

{}

Returns:

Name Type Description
FitResults

The FitResults object itself.

Example
>>> result = ff.Cos().fit(x, y)
>>> result.plot() # ax will be get from plt.gca()
>>> result.plot(ax, x=x, label="Cosine fit")
>>> result.plot(ax, x=x, label="Cosine fit", color="r")

Worth to mention: title will be appended to the existing title with a new line.

Source code in ffit/fit_results.py
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
def plot(
    self,
    ax: _t.Optional["Axes"] = None,
    *,
    x: _t.Optional[_t.Union[_NDARRAY, int]] = None,
    label: _t.Optional[str] = DEFAULT_FIT_LABEL,
    color: _t.Optional[_t.Union[str, int]] = None,
    title: _t.Optional[str] = None,
    post_func_x: _t.Optional[_t.Callable[[_NDARRAY], _NDARRAY]] = None,
    post_func_y: _t.Optional[_t.Callable[[_NDARRAY], _NDARRAY]] = None,
    **kwargs,
):
    """Plot the fit results on the given axes.

    Args:
        ax (Optional[Axes]): The axes on which to plot the fit results. If None, a new axes will be created.
        label (str): The label for the plot. Defaults to ffit.config.DEFAULT_FIT_LABEL.
        color (Optional[Union[str, int]]): The color of the plot. If None, a default color will be used.
        title (Optional[str]): The title for the plot. If provided, it will be appended to the existing title.
        **kwargs: Additional keyword arguments to be passed to the plot function.

    Returns:
        FitResults: The FitResults object itself.

    Example:
        ```
        >>> result = ff.Cos().fit(x, y)
        >>> result.plot() # ax will be get from plt.gca()
        >>> result.plot(ax, x=x, label="Cosine fit")
        >>> result.plot(ax, x=x, label="Cosine fit", color="r")
        ```
    Worth to mention: title will be appended to the existing title with a new line.


    """
    ax = get_ax_from_gca(ax)
    x_fit = get_right_x(x, ax, self.x)

    y_fit = self.res_func(x_fit)
    if label is not None:
        label = format_str_with_params(self.res, label)
        kwargs.update({"label": label})

    color = get_right_color(color)
    kwargs.update({"color": color})

    if post_func_x:
        x_fit = post_func_x(x_fit)
    if post_func_y:
        y_fit = post_func_y(y_fit)
    ax.plot(x_fit, y_fit, **kwargs)

    if title:
        title = format_str_with_params(self.res, title)
        current_title = ax.get_title()
        if current_title:
            title = f"{current_title}\n{title}"
        ax.set_title(title)

    if label != DEFAULT_FIT_LABEL and label is not None:
        ax.legend()

    return self

ffit.fit_results.FitArrayResult

Bases: Tuple[List[Optional[_R]], Callable]

Source code in ffit/fit_results.py
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
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
class FitArrayResult(_t.Tuple[_t.List[_t.Optional[_R]], _t.Callable]):
    res: _t.Optional[_t.List[FitResult[_R]]]
    res_func: _t.Callable[[_NDARRAY], _NDARRAY]
    x: _t.Optional[_NDARRAY]
    extracted_data: _t.Dict[str, _NDARRAY]

    def __init__(
        self,
        res: _t.Optional[_t.List[FitResult[_R]]] = None,
        res_func: _t.Optional[_t.Callable] = None,
        x: _t.Optional[_NDARRAY] = None,
        **kwargs,
    ):
        """
        Initialize the Main class.

        Args:
            res: Optional result value.
            res_func: Optional callable function for result.
            **kwargs: Additional keyword arguments.
        """
        del kwargs
        self.res = res
        self.res_func = (
            res_func if res_func is not None else (lambda x: np.ones_like(x) * np.nan)
        )
        self.x = x
        self.extracted_data = {}

    def __new__(
        cls,
        res: _t.Optional[_t.List[FitResult[_R]]] = None,
        res_func: _t.Optional[_t.Callable] = None,
        x: _t.Optional[_NDARRAY] = None,
        **kwargs,
    ):

        if res_func is None:
            res_func = lambda x: np.ones_like(x) * np.nan  # noqa: E731

        new = super().__new__(cls, (res, res_func))  # type: ignore
        return new

    def __getitem__(self, key):
        if isinstance(key, int):
            return super().__getitem__(key)

        if self.extracted_data is None:
            raise KeyError("No functions have been set.")
        if key not in self.extracted_data:
            raise KeyError(f"Function with key {key} not found.")
        return self.extracted_data[key]

    # def extract(self, parameter: _t.Union[str, int], data_name: _t.Optional[str] = None):
    #     if data_name is None:
    #         data_name = str(parameter)

    #     self.extracted_data[data_name] = self.get(parameter)
    #     return self

    def get(self, parameter: _t.Union[str, int]) -> _NDARRAY:
        if self.res is None:
            raise ValueError("No results have been set.")

        def get_key(res: FitResult[_R]):
            if res.res is None:
                return np.nan
            if isinstance(parameter, int):
                return res.res[parameter]  # type: ignore
            return getattr(res.res, parameter)

        return np.array([get_key(f) for f in self.res])

    def plot(
        self,
        ax: _t.Optional["Axes"] = None,
        *,
        x: _t.Optional[_NDARRAY] = None,
        data: _t.Optional[_t.Union[str, int]] = None,
        label: str = DEFAULT_FIT_LABEL,
        color: _t.Optional[_t.Union[str, int]] = None,
        title: _t.Optional[str] = None,
        **kwargs,
    ):
        if ax is None:
            ax = get_ax_from_gca()
        if data is None:
            raise ValueError("Data must be provided.")
        y_fit = self.get(data)

        if x is None:
            x = get_x_from_ax(ax, len(y_fit))

        if label != DEFAULT_FIT_LABEL or kwargs.get("legend", False):
            ax.legend()
        if label == DEFAULT_FIT_LABEL:
            if isinstance(data, int):
                try:
                    data = self.res[0].res._fields[data]  # type: ignore
                except AttributeError:
                    data = str(data)
            label = f"Fit of {data}"

        color = get_right_color(color)

        ax.plot(x, y_fit, label=label, color=color, **kwargs)

        if title:
            current_title = ax.get_title()
            if current_title:
                title = f"{current_title}\n{title}"
            ax.set_title(title)

        return self