Overview
Purpose
Perform a weighted linear fit y = m x + c on experimental data with uncertainties on y and, optionally, on x as well.
Parameters
x,y: experimental data.sigma_y: uncertainties ony, strictly positive.sigma_x: optional uncertainties onx, also strictly positive.decimals: textual precision used in fit labels. It must be an integer between 0 and 20.tol: relative tolerance used in the convergence criterion whensigma_xis provided.max_iter: maximum number of weight updates.style:Noneuses the currentrcParams,"mespy"loads the package style, and any other string is passed to Matplotlib as a style name.show_plot,show_band,show_legend,show_fit_params,show_grid: control the plotting part.xlabel,ylabel,title,xlim,ylim,figsize,dpi, andsave_path: control the figure.figsizeanddpiare passed to figure creation only when explicitly provided.title_fontsize,title_pad,legend_fontsize, andlegend_loc: targeted overrides for the title and legend. If left asNone, the function uses the active style.point_color,fit_color,band_color,data_alpha,band_alpha, andgrid_alpha: control colours and transparency for points, line, band, and grid.point_color=Noneandgrid_alpha=Noneleave the decision to the active style.
Returns
A LinearFitResult containing fit parameters, uncertainties, residuals, diagnostics, and an optional figure.
Errors and exceptions
ValueErrorifx,y, andsigma_ydo not have the same length.ValueErrorif there are fewer than 3 points.ValueErrorif the inputs contain non-finite values.ValueErrorifsigma_yorsigma_xcontain non-positive values.ValueErrorifdecimalsis not a valid integer between 0 and 20.ValueErroriftolormax_iterare invalid.ValueErrorifxdoes not contain at least two distinct values.ValueErrorifsave_pathis used withshow_plot=False.RuntimeErrorif the case withsigma_xdoes not converge withinmax_iter.
Example
import numpy as np
from mespy import lin_fit
x = np.array([1.0, 2.0, 3.0, 4.0, 5.0])
y = np.array([1.8, 3.1, 4.1, 5.2, 6.1])
sigma_y = np.full_like(x, 0.2)
result = lin_fit(
x,
y,
sigma_y,
style="mespy",
xlabel="tempo [s]",
ylabel="spazio [m]",
show_plot=False,
)
Notes
In the basic case the weights are
1 / sigma_y**2.If
sigma_xis provided, the weights are updated with the effective variancesigma_y^2 + m^2 sigma_x^2.The plotting branch reuses
_style_context, so the behaviour ofstyleand the overrides is consistent withhistogram.The initial coefficients and intermediate updates go through
_fit_coefficients.