Skip to content

ComplexSpiral

Simples example

>>> from ffit.funcs.complex_spiral import ComplexSpiral

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

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

# The parameters can be accessed as attributes.
>> amplitude0 = fit_result.amplitude0

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

Final parameters

Complex spiral parameters.

Attributes:

Name Type Description
amplitude0 float

The absolute amplitude of the spiral.

frequency float

The frequency of the spiral.

phi0 float

The phase of the spiral.

tau float

The time constant of the spiral.

offset_amp float

The amplitude offset of the spiral.

offset_phase float

The phase offset of the spiral.

More attributes:

  • offset (complex): Calculates the complex offset based on the amplitude and phase offsets.
  • amplitude (complex): Calculates the complex amplitude based on the initial amplitude and phase.
  • rate (float): Calculates the rate of decay of the spiral.
  • omega (float): Calculates the angular frequency of the spiral.
Source code in ffit/funcs/complex_spiral.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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
class ComplexSpiralParam(_t.Generic[_T], FuncParamClass):
    """Complex spiral parameters.

    Attributes:
        amplitude0 (float):
            The absolute amplitude of the spiral.
        frequency (float):
            The frequency of the spiral.
        phi0 (float):
            The phase of the spiral.
        tau (float):
            The time constant of the spiral.
        offset_amp (float):
            The amplitude offset of the spiral.
        offset_phase (float):
            The phase offset of the spiral.

    More attributes:

    - offset (complex):
            Calculates the complex offset based on the amplitude and phase offsets.
    - amplitude (complex):
            Calculates the complex amplitude based on the initial amplitude and phase.
    - rate (float):
            Calculates the rate of decay of the spiral.
    - omega (float):
            Calculates the angular frequency of the spiral.
    """

    keys = (
        "amplitude0",
        "frequency",
        "phi0",
        "tau",
        "offset_amp",
        "offset_phase",
    )

    amplitude0: _T
    frequency: _T
    phi0: _T
    tau: _T
    offset_amp: _T
    offset_phase: _T

    @property
    def offset(self) -> _T:
        return self.offset_amp * np.exp(1j * self.offset_phase)  # type: ignore

    @property
    def amplitude(self) -> _T:
        return self.amplitude0 * np.exp(1j * self.phi0)  # type: ignore

    @property
    def rate(self) -> _T:
        return -1.0 / self.tau  # type: ignore

    @property
    def omega(self) -> _T:
        return 2 * np.pi * self.frequency  # type: ignore

Complex Spiral function.

By default, the function has exponential decay:

\[ f(x) = Z_0 * \exp(i⋅ω⋅x) \exp(-x/τ) + Z_{\text{offset}} \]
f(x) = (
    amplitude0 * np.exp(1j * phi0)
    * np.exp(1j * 2 * np.pi * frequency * x - x / tau)
    + np.exp(1j * offset_phase) * offset_amp
)

Alternative functions

ComplexSpiral.GaussianDecay:

\[ f(x) = Z_0 \exp(i⋅ω⋅x) \exp(-x^2/τ^2) + Z_{\text{offset}} \]
f(x) = (
    amplitude0 * np.exp(1j * phi0)
    * np.exp(1j * frequency * 2 * np.pi * x - x**2 / tau**2)
    + np.exp(1j * offset_phase) * offset_amp

Final parameters

The final parameters are given by ComplexSpiralParam dataclass.

Source code in ffit/funcs/complex_spiral.py
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
210
211
212
213
214
class ComplexSpiral(ComplexSpiralExpDecay):
    r"""Complex Spiral function.
    --------
    By default, the function has exponential decay:

    $$
    f(x) = Z_0 * \exp(i⋅ω⋅x) \exp(-x/τ) + Z_{\text{offset}}
    $$

        f(x) = (
            amplitude0 * np.exp(1j * phi0)
            * np.exp(1j * 2 * np.pi * frequency * x - x / tau)
            + np.exp(1j * offset_phase) * offset_amp
        )

    Alternative functions
    ----------------------

    `ComplexSpiral.GaussianDecay`:

    $$
        f(x) = Z_0 \exp(i⋅ω⋅x) \exp(-x^2/τ^2) + Z_{\text{offset}}
    $$

        f(x) = (
            amplitude0 * np.exp(1j * phi0)
            * np.exp(1j * frequency * 2 * np.pi * x - x**2 / tau**2)
            + np.exp(1j * offset_phase) * offset_amp


    Final parameters
    -----------------
    The final parameters are given by [`ComplexSpiralParam`](../complex_spiral_param/) dataclass.
    """

    GaussianDecay = ComplexSpiralGaussianDecay
    ExpDecay = ComplexSpiralExpDecay
    _doc_ignore = False

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 _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
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
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,
) -> _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)

    res, res_std = self._fit(
        x,
        data,
        mask=mask,
        guess=guess,
        method=method,
        maxfev=maxfev,
        **kwargs,
    )

    # param = self.param(*res, std=res_std)

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

    # print(res)
    return self._result_class(
        res,
        lambda x: full_func(x, *res),
        std=res_std,
        x=x,
        data=data,
        stderr=res_std,
        stdfunc=lambda x: self.get_func_std()(x, *res, *res_std),
        original_func=self.func,
    )

async_fit async

async_fit(x, data, *, mask=None, guess=None, method='leastsq', maxfev=10000, **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
_T

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

Source code in ffit/fit_logic.py
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
async def async_fit(
    self,
    x: _ARRAY,
    data: _ARRAY,
    *,
    mask: _t.Optional[_t.Union[_ARRAY, float]] = None,
    guess: _t.Optional[_T] = None,
    method: _t.Literal["least_squares", "leastsq", "curve_fit"] = "leastsq",
    maxfev: int = 10000,
    **kwargs,
) -> _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=mask, guess=guess, method=method, maxfev=maxfev, **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 _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
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
@classmethod
def guess(
    cls,
    x,
    data,
    mask: _t.Optional[_t.Union[_ARRAY, float]] = None,
    guess: _t.Optional[_T] = None,
    **kwargs,
) -> _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 cls._result_class(
            np.asarray(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 cls._result_class(
        np.asarray(guess_param),
        lambda x: cls.func(x, *guess_param),
        x=x,
        data=data,
    )

bootstrapping

bootstrapping(x, data, mask=None, guess=None, method='leastsq', num_of_permutations=None, **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 _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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
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",
    num_of_permutations: _t.Optional[int] = None,
    **kwargs,
) -> _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, self._param_len)
    if len(x_masked) == 0 or len(data_masked) == 0:
        return self._result_class(
            np.ones(self._param_len) * np.nan,
            x=x,
            data=data,
        )

    # 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._run_fit(x_masked, data_masked, guess, method)

    # Run fit on random subarrays
    all_res = []
    for xx, yy in get_random_subarrays(x_masked, data_masked, num_of_permutations):
        res, _ = self._run_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)
    # total_std = np.sqrt(np.diag(cov) + bootstrap_std**2)
    total_std = bootstrap_std

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

    return self._result_class(
        res_means,
        lambda x: full_func(x, *res_means),
        x=x,
        data=data,
        cov=cov,  # type: ignore
        stderr=total_std,  # type: ignore
        stdfunc=lambda x: self.get_func_std()(x, *res_means, *total_std),
        original_func=self.func,
    )