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 on y, strictly positive.

  • sigma_x: optional uncertainties on x, 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 when sigma_x is provided.

  • max_iter: maximum number of weight updates.

  • style: None usa gli rcParams correnti; i nomi degli stili inclusi nel package vengono risolti automaticamente; qualunque altra stringa viene passata a Matplotlib come nome stile.

  • show_plot, show_band, show_legend, show_fit_params, show_grid: control the plotting part.

  • xlabel, ylabel, residuals_label, title, xlim, ylim, figsize, dpi, save_path: regolano testi, assi e salvataggio della figura. figsize e dpi vengono passati alla creazione della figura solo quando esplicitati.

  • normalize_residuals: se True, il pannello inferiore mostra i residui normalizzati r_i / sigma_eff_i invece dei residui fisici. La normalizzazione riguarda solo il grafico: LinearFitResult.residuals resta sempre espresso nelle unita di y.

  • fit_label, band_label: personalizzano i testi della legenda di retta e banda. fit_label viene usato solo quando show_fit_params=False; se show_fit_params=True, la label della retta viene costruita automaticamente con m e c.

  • title_fontsize, title_pad, legend_fontsize, and legend_loc: targeted overrides for the title and legend. If left as None, the function uses the active style.

  • point_color, fit_color, band_color, res_line_color, data_alpha, band_alpha, grid_alpha: regolano colori e trasparenze di punti, retta, banda, linea di zero dei residui e griglia. res_line_color=None riusa il colore effettivo della retta di fit; gli altri colori lasciati a None vengono ricavati dal ciclo colori dello stile attivo; grid_alpha=None lascia decidere allo stile attivo.

Returns

Un LinearFitResult con parametri del fit, incertezze, residui fisici non normalizzati, diagnostiche e figura opzionale.

Errors and exceptions

  • ValueError if x, y, and sigma_y do not have the same length.

  • ValueError if there are fewer than 3 points.

  • ValueError if the inputs contain non-finite values.

  • ValueError if sigma_y or sigma_x contain non-positive values.

  • ValueError if decimals is not a valid integer between 0 and 20.

  • ValueError if tol or max_iter are invalid.

  • ValueError if x does not contain at least two distinct values.

  • ValueError if save_path is used with show_plot=False.

  • RuntimeError if the case with sigma_x does not converge within max_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,
)

Per mostrare i residui normalizzati nel pannello inferiore:

result = lin_fit(
    x,
    y,
    sigma_y,
    normalize_residuals=True,
)

In questo caso i punti del pannello dei residui sono result.residuals / sigma_y se non passi sigma_x; se passi anche sigma_x, il denominatore diventa sqrt(sigma_y**2 + result.slope**2 * sigma_x**2).

Notes

  • In the basic case the weights are 1 / sigma_y**2.

  • If sigma_x is provided, the weights are updated with the effective variance sigma_y^2 + m^2 sigma_x^2.

  • normalize_residuals=True usa la stessa varianza efficace del chi2, ma non cambia result.residuals, result.residual_std, result.chi2 o result.reduced_chi2.

  • Quando normalize_residuals=True, le barre d’errore verticali del pannello inferiore sono unitarie e l’asse dei residui diventa adimensionale. Se residuals_label resta al default, la label viene adattata automaticamente.

  • The plotting branch reuses _style_context, so the behaviour of style and the overrides is consistent with histogram.

  • The initial coefficients and intermediate updates go through _fit_coefficients.