Skip to content

Fit container

FitResultContainer

Source code in itfit/utils/fit_container.py
class FitResultContainer:
    def __init__(self, data: DataSelection, fit_manager: FunctionContainer|GenericFitter, scipy_result: dict):
        """_summary_

        Parameters:
            data (itfit.data.DataSelection):
                Data fitted.
            fit_manager (FunctionContainer|GenericFitter):
                Fit function used
            scipy_result (dict):
                Dictionary of `scipy.optimize.curve_fit` output.
        """
        self.data = data
        self.function = fit_manager.function
        self.gradient = fit_manager.gradient
        self.fit_manager = fit_manager
        self.scipy_output = {
            "popt" : scipy_result[0],
            "pcov" : scipy_result[1],
            "fvec" : scipy_result[2]["fvec"],
            "nfev" : scipy_result[2]["nfev"],
            "fjac" : scipy_result[2]["fjac"],
            "ipvt" : scipy_result[2]["ipvt"],
            "qtf"  : scipy_result[2]["qtf"],
            "mesg" : scipy_result[3],
            "ier"  : scipy_result[4] 
        }

    def get_parameters(self):
        """Gets the optimal fitting parameters found.

        Returns:
            (tuple[float]):
                tuple of parameters.
        """
        return self.scipy_output["popt"]

    def get_parameters_covariance(self):
        """Gets the parameters covariance matrix.

        Returns:
            (Ndarray(NxN)[float]):
                Parameters covariance matrix.
        """
        return self.scipy_output["pcov"]

    def get_parameters_errors(self):
        """Gets the square root of diagonal elements of the covariance matrix.

        Returns:
            (tuple[float]):
                Optimal fitting parameters standard error.
        """
        return np.sqrt(np.diag(self.get_parameters_covariance()))

    def get_xdata(self):
        """Gets the x component of all the data.

        Returns:
            (tuple[float]):
                X component of all the data.
        """
        return self.data.xdata

    def get_xdata_errors(self):
        """Gets the x component error in all the data.

        Returns:
            (tuple[float]):
                X component error of all the data.
        """
        return self.data.get_errors()[0]

    def get_ydata(self):
        """Gets the y component of all the data.

        Returns:
            (tuple[float]):
                Y component of all data.
        """
        return self.data.ydata

    def get_ydata_errors(self):
        """Gets the y component error in all the data.

        Returns:
            (tuple[float]):
                Y component error of all the data.
        """
        return self.data.get_errors()[1]

    def get_xdata_selected(self):
        """Gets the x component of the data used.

        Returns:
            (tuple[float]):
                X component of data used.
        """
        return self.data.get_selected()[0]

    def get_xdata_errors_selected(self):
        """Gets the x component error in data used.

        Returns:
            (tuple[float]):
                X component error of data used.
        """
        return self.data.get_selected_errors()[0]

    def get_ydata_selected(self):
        """Gets the y component of the data used.

        Returns:
            (tuple[float]):
                Y component of data used.
        """
        return self.data.get_selected()[1]

    def get_ydata_errors_selected(self):
        """Gets the y component error in data used.

        Returns:
            (tuple[float]):
                Y component error of data used.
        """
        return self.data.get_selected_errors()[1]

    def get_data(self):
        """Gets the all data.

        Returns:
            (tuple[tuple[float], tuple[float]]):
                All data.
        """
        return self.data.get_data()

    def get_data_selected(self):
        """Gets the data used.

        Returns:
            (tuple[tuple[float], tuple[float]]):
                Data used.
        """
        return np.array(self.data.get_selected()).T

    def prop_errors(self):
        """ Return the error of the fit, given a gradient of a function.

        Returns:
            (Tuple[float]):
                errors of the fit
        """
        try:
            x_array = self.get_fit_xdata()
            errors = np.zeros((len(x_array)))
            cov = self.get_parameters_covariance()

            for i,x in enumerate(x_array):
                grad = self.gradient(x, *self.get_parameters())
                errors[i] = np.sqrt( float(grad.T @ cov @ grad))
        except AttributeError:
            return None
        return errors


    def get_fit_xdata(self):
        """Gets the x component of the fit curve. Equal to get_xdata output.

        Returns:
            (tuple[float]):
                X component of fit curve. Equal to get_xdata output.
        """
        return self.get_xdata()

    def get_fit_ydata(self):
        """Gets the y coomponent of the fit curve.

        Returns:
            (tuple[float]):
                Y component of fit curve.
        """
        return self.function(self.get_xdata(), *self.get_parameters())

    def get_fit_xdata_selected(self):
        """Gets the x component of the fit curve for selected data interval. Equal to get_xdata_selected output.

        Returns:
            (tuple[float]):
                X component of fit curve. Equal to get_xdata output.
        """
        return self.get_xdata_selected()

    def get_fit_ydata_selected(self):
        """Gets the y coomponent of the fit curve for selected data interval.

        Returns:
            (tuple[float]):
                Y component of fit curve.
        """
        return self.function(self.get_xdata_selected(), *self.get_parameters())

    def get_fit_data(self):
        """Gets the fit curve data for all data.

        Returns:
            (tuple[tuple[float], tuple[float]]):
                Fit curve data.
        """
        return np.array((self.get_fit_xdata(), self.get_fit_ydata())).T

    def get_fit_data_selected(self):
        """Gets the fit curve data for selected data.

        Returns:
            (tuple[tuple[float], tuple[float]]):
                Fit curve data.
        """
        return np.array((self.get_fit_xdata_selected(), self.get_fit_ydata_selected())).T

    def get_message(self):
        """Gets scipy output `mesg` output.

        Returns:
            (str):
                Scipy output message.
        """
        return self.scipy_output["mesg"]

    def evaluate(self, x):
        """Evaluates the given `x` in the fitting function with the optimal parameters.

        Parameters:
            x (float): 
                Independent variable.

        Returns:
            y (float): 
                Dependent variable.
        """
        return self.function(x, *self.get_parameters())

    def error_verts(self, only_selected: bool=True):
        """Returns a tuple of two lists of points representing the error of the optimization. 
        Each lists size is Nx2 or None if errors in the function are not supported.

        Parameters:
            only_selected (bool):
                Only get errors points for selected data. Defaults to True.

        Returns:
            (tuple[list]|tuple[None]): Positive and negative error points.
        """
        xdata, _  = self.data.get_selected() if only_selected else self.data.get_data().T
        error_fit = self.prop_errors()
        if error_fit is not None:
            iy_pos = self.evaluate(xdata)+error_fit
            verts_positive = [(xdata[0],self.evaluate(xdata[0])), *zip(xdata,iy_pos), (xdata[len(xdata)-1],self.evaluate(xdata[len(xdata)-1]))]

            iy_neg = self.evaluate(xdata)-error_fit
            verts_negative = [(xdata[0],self.evaluate(xdata[0])), *zip(xdata,iy_neg), (xdata[len(xdata)-1],self.evaluate(xdata[len(xdata)-1]))]
            return verts_positive, verts_negative
        return (None, None)


    def __str__(self):
        TAB = "\t"
        NEX = "\n"

        return f"""ItFit FitResultContainer
Using fit function: {self.fit_manager.name}
Scipy result message: {self.get_message()}

Optimal parameters: 
{TAB}values: {self.get_parameters()}
{TAB}errors: {self.get_parameters_errors()}
{TAB}covariance:
{TAB}{TAB}[{(NEX + TAB*2 +" ").join([str(l) for l in self.get_parameters_covariance()])}]
"""

    def save(self, filename): # TODO:
        ...

    @classmethod    
    def load(cls, filename): # TODO:
        ...

__init__(data, fit_manager, scipy_result)

summary

Parameters:

Name Type Description Default
data itfit.data.DataSelection

Data fitted.

required
fit_manager FunctionContainer | GenericFitter

Fit function used

required
scipy_result dict

Dictionary of scipy.optimize.curve_fit output.

required
Source code in itfit/utils/fit_container.py
def __init__(self, data: DataSelection, fit_manager: FunctionContainer|GenericFitter, scipy_result: dict):
    """_summary_

    Parameters:
        data (itfit.data.DataSelection):
            Data fitted.
        fit_manager (FunctionContainer|GenericFitter):
            Fit function used
        scipy_result (dict):
            Dictionary of `scipy.optimize.curve_fit` output.
    """
    self.data = data
    self.function = fit_manager.function
    self.gradient = fit_manager.gradient
    self.fit_manager = fit_manager
    self.scipy_output = {
        "popt" : scipy_result[0],
        "pcov" : scipy_result[1],
        "fvec" : scipy_result[2]["fvec"],
        "nfev" : scipy_result[2]["nfev"],
        "fjac" : scipy_result[2]["fjac"],
        "ipvt" : scipy_result[2]["ipvt"],
        "qtf"  : scipy_result[2]["qtf"],
        "mesg" : scipy_result[3],
        "ier"  : scipy_result[4] 
    }

error_verts(only_selected=True)

Returns a tuple of two lists of points representing the error of the optimization. Each lists size is Nx2 or None if errors in the function are not supported.

Parameters:

Name Type Description Default
only_selected bool

Only get errors points for selected data. Defaults to True.

True

Returns:

Type Description
tuple[list] | tuple[None]

Positive and negative error points.

Source code in itfit/utils/fit_container.py
def error_verts(self, only_selected: bool=True):
    """Returns a tuple of two lists of points representing the error of the optimization. 
    Each lists size is Nx2 or None if errors in the function are not supported.

    Parameters:
        only_selected (bool):
            Only get errors points for selected data. Defaults to True.

    Returns:
        (tuple[list]|tuple[None]): Positive and negative error points.
    """
    xdata, _  = self.data.get_selected() if only_selected else self.data.get_data().T
    error_fit = self.prop_errors()
    if error_fit is not None:
        iy_pos = self.evaluate(xdata)+error_fit
        verts_positive = [(xdata[0],self.evaluate(xdata[0])), *zip(xdata,iy_pos), (xdata[len(xdata)-1],self.evaluate(xdata[len(xdata)-1]))]

        iy_neg = self.evaluate(xdata)-error_fit
        verts_negative = [(xdata[0],self.evaluate(xdata[0])), *zip(xdata,iy_neg), (xdata[len(xdata)-1],self.evaluate(xdata[len(xdata)-1]))]
        return verts_positive, verts_negative
    return (None, None)

evaluate(x)

Evaluates the given x in the fitting function with the optimal parameters.

Parameters:

Name Type Description Default
x float

Independent variable.

required

Returns:

Name Type Description
y float

Dependent variable.

Source code in itfit/utils/fit_container.py
def evaluate(self, x):
    """Evaluates the given `x` in the fitting function with the optimal parameters.

    Parameters:
        x (float): 
            Independent variable.

    Returns:
        y (float): 
            Dependent variable.
    """
    return self.function(x, *self.get_parameters())

get_data()

Gets the all data.

Returns:

Type Description
tuple[tuple[float], tuple[float]]

All data.

Source code in itfit/utils/fit_container.py
def get_data(self):
    """Gets the all data.

    Returns:
        (tuple[tuple[float], tuple[float]]):
            All data.
    """
    return self.data.get_data()

get_data_selected()

Gets the data used.

Returns:

Type Description
tuple[tuple[float], tuple[float]]

Data used.

Source code in itfit/utils/fit_container.py
def get_data_selected(self):
    """Gets the data used.

    Returns:
        (tuple[tuple[float], tuple[float]]):
            Data used.
    """
    return np.array(self.data.get_selected()).T

get_fit_data()

Gets the fit curve data for all data.

Returns:

Type Description
tuple[tuple[float], tuple[float]]

Fit curve data.

Source code in itfit/utils/fit_container.py
def get_fit_data(self):
    """Gets the fit curve data for all data.

    Returns:
        (tuple[tuple[float], tuple[float]]):
            Fit curve data.
    """
    return np.array((self.get_fit_xdata(), self.get_fit_ydata())).T

get_fit_data_selected()

Gets the fit curve data for selected data.

Returns:

Type Description
tuple[tuple[float], tuple[float]]

Fit curve data.

Source code in itfit/utils/fit_container.py
def get_fit_data_selected(self):
    """Gets the fit curve data for selected data.

    Returns:
        (tuple[tuple[float], tuple[float]]):
            Fit curve data.
    """
    return np.array((self.get_fit_xdata_selected(), self.get_fit_ydata_selected())).T

get_fit_xdata()

Gets the x component of the fit curve. Equal to get_xdata output.

Returns:

Type Description
tuple[float]

X component of fit curve. Equal to get_xdata output.

Source code in itfit/utils/fit_container.py
def get_fit_xdata(self):
    """Gets the x component of the fit curve. Equal to get_xdata output.

    Returns:
        (tuple[float]):
            X component of fit curve. Equal to get_xdata output.
    """
    return self.get_xdata()

get_fit_xdata_selected()

Gets the x component of the fit curve for selected data interval. Equal to get_xdata_selected output.

Returns:

Type Description
tuple[float]

X component of fit curve. Equal to get_xdata output.

Source code in itfit/utils/fit_container.py
def get_fit_xdata_selected(self):
    """Gets the x component of the fit curve for selected data interval. Equal to get_xdata_selected output.

    Returns:
        (tuple[float]):
            X component of fit curve. Equal to get_xdata output.
    """
    return self.get_xdata_selected()

get_fit_ydata()

Gets the y coomponent of the fit curve.

Returns:

Type Description
tuple[float]

Y component of fit curve.

Source code in itfit/utils/fit_container.py
def get_fit_ydata(self):
    """Gets the y coomponent of the fit curve.

    Returns:
        (tuple[float]):
            Y component of fit curve.
    """
    return self.function(self.get_xdata(), *self.get_parameters())

get_fit_ydata_selected()

Gets the y coomponent of the fit curve for selected data interval.

Returns:

Type Description
tuple[float]

Y component of fit curve.

Source code in itfit/utils/fit_container.py
def get_fit_ydata_selected(self):
    """Gets the y coomponent of the fit curve for selected data interval.

    Returns:
        (tuple[float]):
            Y component of fit curve.
    """
    return self.function(self.get_xdata_selected(), *self.get_parameters())

get_message()

Gets scipy output mesg output.

Returns:

Type Description
str

Scipy output message.

Source code in itfit/utils/fit_container.py
def get_message(self):
    """Gets scipy output `mesg` output.

    Returns:
        (str):
            Scipy output message.
    """
    return self.scipy_output["mesg"]

get_parameters()

Gets the optimal fitting parameters found.

Returns:

Type Description
tuple[float]

tuple of parameters.

Source code in itfit/utils/fit_container.py
def get_parameters(self):
    """Gets the optimal fitting parameters found.

    Returns:
        (tuple[float]):
            tuple of parameters.
    """
    return self.scipy_output["popt"]

get_parameters_covariance()

Gets the parameters covariance matrix.

Returns:

Type Description
Ndarray(NxN)[float]

Parameters covariance matrix.

Source code in itfit/utils/fit_container.py
def get_parameters_covariance(self):
    """Gets the parameters covariance matrix.

    Returns:
        (Ndarray(NxN)[float]):
            Parameters covariance matrix.
    """
    return self.scipy_output["pcov"]

get_parameters_errors()

Gets the square root of diagonal elements of the covariance matrix.

Returns:

Type Description
tuple[float]

Optimal fitting parameters standard error.

Source code in itfit/utils/fit_container.py
def get_parameters_errors(self):
    """Gets the square root of diagonal elements of the covariance matrix.

    Returns:
        (tuple[float]):
            Optimal fitting parameters standard error.
    """
    return np.sqrt(np.diag(self.get_parameters_covariance()))

get_xdata()

Gets the x component of all the data.

Returns:

Type Description
tuple[float]

X component of all the data.

Source code in itfit/utils/fit_container.py
def get_xdata(self):
    """Gets the x component of all the data.

    Returns:
        (tuple[float]):
            X component of all the data.
    """
    return self.data.xdata

get_xdata_errors()

Gets the x component error in all the data.

Returns:

Type Description
tuple[float]

X component error of all the data.

Source code in itfit/utils/fit_container.py
def get_xdata_errors(self):
    """Gets the x component error in all the data.

    Returns:
        (tuple[float]):
            X component error of all the data.
    """
    return self.data.get_errors()[0]

get_xdata_errors_selected()

Gets the x component error in data used.

Returns:

Type Description
tuple[float]

X component error of data used.

Source code in itfit/utils/fit_container.py
def get_xdata_errors_selected(self):
    """Gets the x component error in data used.

    Returns:
        (tuple[float]):
            X component error of data used.
    """
    return self.data.get_selected_errors()[0]

get_xdata_selected()

Gets the x component of the data used.

Returns:

Type Description
tuple[float]

X component of data used.

Source code in itfit/utils/fit_container.py
def get_xdata_selected(self):
    """Gets the x component of the data used.

    Returns:
        (tuple[float]):
            X component of data used.
    """
    return self.data.get_selected()[0]

get_ydata()

Gets the y component of all the data.

Returns:

Type Description
tuple[float]

Y component of all data.

Source code in itfit/utils/fit_container.py
def get_ydata(self):
    """Gets the y component of all the data.

    Returns:
        (tuple[float]):
            Y component of all data.
    """
    return self.data.ydata

get_ydata_errors()

Gets the y component error in all the data.

Returns:

Type Description
tuple[float]

Y component error of all the data.

Source code in itfit/utils/fit_container.py
def get_ydata_errors(self):
    """Gets the y component error in all the data.

    Returns:
        (tuple[float]):
            Y component error of all the data.
    """
    return self.data.get_errors()[1]

get_ydata_errors_selected()

Gets the y component error in data used.

Returns:

Type Description
tuple[float]

Y component error of data used.

Source code in itfit/utils/fit_container.py
def get_ydata_errors_selected(self):
    """Gets the y component error in data used.

    Returns:
        (tuple[float]):
            Y component error of data used.
    """
    return self.data.get_selected_errors()[1]

get_ydata_selected()

Gets the y component of the data used.

Returns:

Type Description
tuple[float]

Y component of data used.

Source code in itfit/utils/fit_container.py
def get_ydata_selected(self):
    """Gets the y component of the data used.

    Returns:
        (tuple[float]):
            Y component of data used.
    """
    return self.data.get_selected()[1]

prop_errors()

Return the error of the fit, given a gradient of a function.

Returns:

Type Description
Tuple[float]

errors of the fit

Source code in itfit/utils/fit_container.py
def prop_errors(self):
    """ Return the error of the fit, given a gradient of a function.

    Returns:
        (Tuple[float]):
            errors of the fit
    """
    try:
        x_array = self.get_fit_xdata()
        errors = np.zeros((len(x_array)))
        cov = self.get_parameters_covariance()

        for i,x in enumerate(x_array):
            grad = self.gradient(x, *self.get_parameters())
            errors[i] = np.sqrt( float(grad.T @ cov @ grad))
    except AttributeError:
        return None
    return errors