Skip to content

ExpDecayingCos

Simples example

>>> from ffit.funcs.exp_decaying_cos import ExpDecayingCos

# Call the fit method with x and y data.
>>> fit_result = ExpDecayingCos().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 = ExpDecayingCos().fit(x, y, guess=[1, 2, 3, 4]).plot(ax)

Final parameters

Exponential Decaying Cosine parameters.

Attributes:

Name Type Description
amplitude0 float

The absolute amplitude of the decaying cosine.

frequency float

The frequency of the decaying cosine.

phi0 float

The initial phase of the decaying cosine.

offset float

The offset of the decaying cosine.

tau float

The decay constant of the decaying cosine.

std Optional[ExpDecayingCosParam]

The standard deviation of the parameters, if any.

Additional attributes

omega (float): Calculates the angular frequency based on the frequency. rate (float): Calculates the rate of decay.

Source code in ffit/funcs/exp_decaying_cos.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
class ExpDecayingCosParam(_t.Generic[_T], FuncParamClass):
    """Exponential Decaying Cosine parameters.

    Attributes:
        amplitude0 (float):
            The absolute amplitude of the decaying cosine.
        frequency (float):
            The frequency of the decaying cosine.
        phi0 (float):
            The initial phase of the decaying cosine.
        offset (float):
            The offset of the decaying cosine.
        tau (float):
            The decay constant of the decaying cosine.
        std (Optional[ExpDecayingCosParam]):
            The standard deviation of the parameters, if any.

    Additional attributes:
        omega (float):
            Calculates the angular frequency based on the frequency.
        rate (float):
            Calculates the rate of decay.
    """

    keys = ("amplitude0", "frequency", "phi0", "offset", "tau")

    amplitude0: _T
    frequency: _T
    phi0: _T
    offset: _T
    tau: _T

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

    @property
    def rate(self) -> _T:
        return -1 / self.tau  # pylint: disable=E1101  # type: ignore

Fit ExpDecayingCos function.

Function


$$ f(x) = A_0 * \cos(ω⋅x + \phi_0) * \exp(-x / τ) + A_{\text{offset}} $$

 f(x) = (
     amplitude0 * np.exp(-x / tau)
     * np.cos(2 * np.pi * x * frequency + phi0)
     + offset
 )

Final parameters

The final parameters are given by ExpDecayingCosParam dataclass.

Source code in ffit/funcs/exp_decaying_cos.py
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
class ExpDecayingCos(FitLogic[ExpDecayingCosResult]):  # type: ignore
    r"""Fit ExpDecayingCos function.


     Function
     ---------

     $$
     f(x) = A_0 * \cos(ω⋅x + \phi_0) * \exp(-x / τ) + A_{\text{offset}}
     $$

         f(x) = (
             amplitude0 * np.exp(-x / tau)
             * np.cos(2 * np.pi * x * frequency + phi0)
             + offset
         )


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

    """

    _result_class: _t.Type[ExpDecayingCosResult] = ExpDecayingCosResult

    func = staticmethod(exp_decaying_cos_func)
    # func_std = staticmethod(cos_error)

    normalize_res = staticmethod(normalize_res_list)
    _guess = staticmethod(exp_decaying_cos_guess)

    @_t.overload
    @classmethod
    def mask(  # type: ignore # pylint: disable=W0221
        cls,
        *,
        amplitude0: float = None,  # type: ignore
        frequency: float = None,  # type: ignore
        phi0: float = None,  # type: ignore
        offset: float = None,  # type: ignore
        tau: float = None,  # type: ignore
    ) -> "ExpDecayingCos": ...

    @classmethod
    def mask(cls, **kwargs) -> "ExpDecayingCos":
        return super().mask(**kwargs)

    _range_x = (0, np.inf)

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
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
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
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
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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
@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, maxfev=_DEFAULT_MAXFEV, **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, _ANY_LIST_LIKE]]

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'
num_of_permutations Optional[int]

The number of permutations to use for the bootstrapping.

None
maxfev int

The maximum number of function evaluations.

_DEFAULT_MAXFEV
**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
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
def bootstrapping(
    self,
    x: _ARRAY,
    data: _ARRAY,
    mask: _t.Optional[_t.Union[_ARRAY, float]] = None,
    guess: _t.Optional[_t.Union[_T, _ANY_LIST_LIKE]] = None,
    method: _t.Literal["least_squares", "leastsq", "curve_fit"] = "leastsq",
    num_of_permutations: _t.Optional[int] = None,
    maxfev: int = _DEFAULT_MAXFEV,
    **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").
        num_of_permutations: The number of permutations to use for the bootstrapping.
        maxfev: The maximum number of function evaluations.
        **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_means, total_std = self._bootstrapping(
        x, data, mask, guess, method, num_of_permutations, maxfev
    )

    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,
        stderr=total_std,  # type: ignore
        stdfunc=lambda x: self.get_func_std()(x, *res_means, *total_std),
        original_func=self.func,
    )

array_bootstrapping

array_bootstrapping(x, data, *, mask=None, guess=None, axis=-1, method='leastsq', maxfev=10000, num_of_permutations=None, **kwargs)

Perform array bootstrapping in parallel.

Parameters:

Name Type Description Default
x _ARRAY

The independent variable.

required
data _2DARRAY

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
axis int

The axis along which to perform the fit (default: -1).

-1
method Literal['least_squares', 'leastsq', 'curve_fit']

The fitting method to use (default: "leastsq").

'leastsq'
maxfev int

Maximum number of function evaluations (default: 10000).

10000
num_of_permutations Optional[int]

Number of bootstrap iterations.

None
**kwargs

Additional keyword arguments passed to _fit.

{}

Returns:

Name Type Description
FitResult _T

The result of the bootstrapping.

Source code in ffit/fit_logic.py
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
def array_bootstrapping(
    self,
    x: _ARRAY,
    data: _2DARRAY,
    *,
    mask: _t.Optional[_t.Union[_ARRAY, float]] = None,
    guess: _t.Optional[_t.Union[_T, tuple, list]] = None,
    axis: int = -1,
    method: _t.Literal["least_squares", "leastsq", "curve_fit"] = "leastsq",
    maxfev: int = 10000,
    num_of_permutations: _t.Optional[int] = None,
    **kwargs,
) -> _T:
    """Perform array bootstrapping in parallel.

    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).
        axis: The axis along which to perform the fit (default: -1).
        method: The fitting method to use (default: "leastsq").
        maxfev: Maximum number of function evaluations (default: 10000).
        num_of_permutations: Number of bootstrap iterations.
        **kwargs: Additional keyword arguments passed to _fit.

    Returns:
        FitResult: The result of the bootstrapping.
    """
    x, data, multi_x, data_shape, x_shape, selected_axis_len = (
        self._prepare_array_data(x, data, axis)
    )

    # Run bootstrapping on each dataset
    results = np.array(
        [
            self._bootstrapping(
                x[i] if multi_x else x,
                data[i],
                mask=mask,
                guess=guess,
                method=method,
                num_of_permutations=num_of_permutations,
                maxfev=maxfev,
                **kwargs,
            )
            for i in range(len(data))
        ]
    )

    # Split means and stds from results
    result_means = results[:, 0, :]  # First element of each result is means
    result_stds = results[:, 1, :]  # Second element is standard deviations

    # Reshape results back to original data shape
    result_means = result_means.reshape(data_shape[:-1] + (-1,))
    result_stds = result_stds.reshape(data_shape[:-1] + (-1,))

    if multi_x:
        x = x.reshape(x_shape)

    return self._result_class(
        result_means,
        self._create_array_res_func(
            result_means, multi_x, data_shape, selected_axis_len
        ),
        x=x,
        data=data,
        stderr=result_stds,
        stdfunc=lambda x: self.get_func_std()(x, *result_means, *result_stds),
        original_func=self.func,
    )

bootstrapping2D

bootstrapping2D(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 _2DARRAY

The 2D dependent variable (data, batches).

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
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
def bootstrapping2D(
    self,
    x: _ARRAY,
    data: _2DARRAY,
    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 2D dependent variable (data, batches).
        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, np.mean(data_masked, axis=-1), **kwargs)

    # Fit ones to get the best initial guess
    guess, cov = self._run_fit(
        x_masked, np.mean(data_masked, axis=-1), guess, method
    )

    # Run fit on random subarrays
    all_res = []
    total_elements = data_masked.shape[1]
    if num_of_permutations is None:
        num_of_permutations = int(min(max(total_elements / 10, 1_000), 5_000))

    for selected_index in bootstrap_generator(total_elements, num_of_permutations):
        res, _ = self._run_fit(
            x_masked,
            np.mean(data_masked[:, selected_index], axis=-1),
            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 = 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,
    )

mp_array_fit

mp_array_fit(x, data, *, mask=None, guess=None, axis=-1, method='leastsq', maxfev=10000, n_jobs=None, **kwargs)

Perform array fitting in parallel using multiprocessing.

Parameters:

Name Type Description Default
x _ARRAY

The independent variable.

required
data _2DARRAY

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
axis int

The axis along which to perform the fit (default: -1).

-1
method Literal['least_squares', 'leastsq', 'curve_fit']

The fitting method to use (default: "leastsq").

'leastsq'
maxfev int

Maximum number of function evaluations (default: 10000).

10000
n_jobs Optional[int]

Number of processes to use. If None, uses cpu_count().

None
**kwargs

Additional keyword arguments passed to _fit.

{}

Returns:

Name Type Description
FitResult _T

The result of the fit.

Source code in ffit/fit_logic.py
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
def mp_array_fit(
    self,
    x: _ARRAY,
    data: _2DARRAY,
    *,
    mask: _t.Optional[_t.Union[_ARRAY, float]] = None,
    guess: _t.Optional[_t.Union[_T, tuple, list]] = None,
    axis: int = -1,
    method: _t.Literal["least_squares", "leastsq", "curve_fit"] = "leastsq",
    maxfev: int = 10000,
    n_jobs: _t.Optional[int] = None,
    **kwargs,
) -> _T:
    """Perform array fitting in parallel using multiprocessing.

    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).
        axis: The axis along which to perform the fit (default: -1).
        method: The fitting method to use (default: "leastsq").
        maxfev: Maximum number of function evaluations (default: 10000).
        n_jobs: Number of processes to use. If None, uses cpu_count().
        **kwargs: Additional keyword arguments passed to _fit.

    Returns:
        FitResult: The result of the fit.
    """
    import multiprocessing as mp

    x, data, multi_x, data_shape, x_shape, selected_axis_len = (
        self._prepare_array_data(x, data, axis)
    )

    # Prepare arguments for parallel processing
    fit_args = [
        (x[i] if multi_x else x, data[i], mask, guess, method, maxfev, kwargs)
        for i in range(len(data))
    ]

    # Run fits in parallel using multiprocessing
    with mp.Pool(processes=n_jobs) as pool:
        results = pool.map(self._fit_worker, fit_args)

    results = np.array(results).reshape(data_shape[:-1] + (-1,))

    if multi_x:
        x = x.reshape(x_shape)

    return self._result_class(
        results,
        self._create_array_res_func(
            results, multi_x, data_shape, selected_axis_len
        ),
        x=x,
        data=data,
        original_func=self.func,
    )