Linear fit

This notebook shows two typical uses of mp.lin_fit with a placeholder dataset included in the examples folder.

Imports

import mespy as mp


df = mp.load_csv(
    "data/test_linear_fit.csv",
    required_columns=[
        "tempo_s",
        "spazio_m",
        "sigma_spazio_m",
        "sigma_tempo_s",
    ],
    missing="error",
)

tempo = df["tempo_s"]
spazio = df["spazio_m"]
sigma_spazio = df["sigma_spazio_m"]
sigma_tempo = df["sigma_tempo_s"]

Linear fit with uncertainties on y only

The first example uses the same dataset but considers only the uncertainties on y, ignoring the sigma_tempo_s column.

fit_base = mp.lin_fit(
    tempo,
    spazio,
    sigma_spazio,
    xlabel="tempo [s]",
    ylabel="spazio [m]",
    title="Fit lineare con sole incertezze su y",
    show_fit_params=True,
)

{
    "slope": round(fit_base.slope, 3),
    "intercept": round(fit_base.intercept, 3),
    "reduced_chi2": round(fit_base.reduced_chi2, 3),
}
{'slope': 2.114, 'intercept': 0.65, 'reduced_chi2': 0.2}
../_images/e773811a4ec7dac69421bd1ae67a7db4fc7fae8a56a958ddaf9f5b5bfeaefab9.png

Example with sigma_x

If you also provide the uncertainty on x, lin_fit uses the effective variance and updates the fit weights iteratively.

fit_sigma_x = mp.lin_fit(
    tempo,
    spazio,
    sigma_spazio,
    sigma_x=sigma_tempo,
    xlabel="tempo [s]",
    ylabel="spazio [m]",
    title="Fit lineare con sigma_x e sigma_y",
    show_fit_params=True,
)

{
    "slope": round(fit_sigma_x.slope, 3),
    "slope_std": round(fit_sigma_x.slope_std, 3),
    "intercept": round(fit_sigma_x.intercept, 3),
    "iterations": fit_sigma_x.iterations,
    "converged": fit_sigma_x.converged,
}
{'slope': 2.112,
 'slope_std': 0.034,
 'intercept': 0.66,
 'iterations': 4,
 'converged': True}
../_images/d304a7b22f817830740cd658d78a7cd313a5f2395b3ba30521923eba64200403.png

Related pages