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 uses the current rcParams, "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, and save_path: control the figure. figsize and dpi are passed to figure creation only when explicitly provided.

  • 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, data_alpha, band_alpha, and grid_alpha: control colours and transparency for points, line, band, and grid. point_color=None and grid_alpha=None leave the decision to the active style.

Returns

A LinearFitResult containing fit parameters, uncertainties, residuals, diagnostics, and an optional figure.

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,
)

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.

  • 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.