Linear fit
Fit a straight line to your measurements, read its parameters, and inspect the residuals with mespy.lin_fit().
What does lin_fit do?
lin_fit() fits the model
It estimates the slope \(m\), the intercept \(q\), and their standard uncertainties.
By default, the calculation treats x as exact. Pass measurement uncertainties on y through sigma_y. To propagate uncertainties on x, supply sigma_x and explicitly choose x_error_method="iterate", as shown below.
Basic linear fit
Save linear.csv in your project’s data/ folder. It contains example position measurements at different times:
CSV
x,y,sigma_y
1.0,2.85,0.25
2.0,4.90,0.25
3.0,6.88,0.25
4.0,9.18,0.25
5.0,11.08,0.25
6.0,13.42,0.25
7.0,15.35,0.25
8.0,17.63,0.25
9.0,19.55,0.25
10.0,21.92,0.25
x: time in seconds, the independent variable.y: measured position in metres.sigma_y: the standard uncertainty of each position, in metres. Values must be positive.
Run the code from your project folder:
import pandas as pd
from mespy import lin_fit
df = pd.read_csv("data/linear.csv")
result = lin_fit(
df["x"],
df["y"],
sigma_y=df["sigma_y"],
output="results/linear_fit",
)
Output
Top: position measurements, fitted line, and uncertainty band. Bottom: residuals in metres, with measurement uncertainty bars.
This is weighted least squares (WLS): points with smaller uncertainties receive more weight. The function returns a LinearFitResult object, stored as result.
output sets the destination and base filename, without an extension. MesPy creates missing folders. With plotting enabled, as it is by default, it writes:
Saved files
results/
├── linear_fit.pdf
└── linear_fit.toml
The PDF contains the fit figure. The TOML is a text file containing the inputs, fit parameters, available diagnostics, and physical residuals.
Understanding the results
The figure
The upper panel shows the measurements, their standard uncertainty bars, and the fitted line. The shaded band spans one standard uncertainty of the predicted mean on either side. It describes uncertainty in the line, rather than a range expected to contain future measurements.
The lower panel shows residuals:
A residual is the vertical distance from a measurement to the line. Positive values lie above it; negative values lie below it. Look for scatter around zero. A curved pattern, for example, can suggest that a straight line misses a trend.
Residuals are not normalized by default: they keep the units of y. Read them as result.residuals; access the Matplotlib figure as result.figure.
The numerical results
Read the main attributes:
print(f"Slope: {result.slope:.3f} +/- {result.slope_std:.3f}")
print(f"Intercept: {result.intercept:.3f} +/- {result.intercept_std:.3f}")
print(f"Chi-squared: {result.chi2:.3f}")
print(f"Reduced chi-squared: {result.reduced_chi2:.3f}")
print(f"p-value: {result.p_value:.3f}")
print(f"Degrees of freedom: {result.dof}")
print("Fit method:", result.fit_method)
print("x uncertainty treatment:", result.x_error_method)
Output
Slope: 2.114 +/- 0.028
Intercept: 0.650 +/- 0.171
Chi-squared: 1.598
Reduced chi-squared: 0.200
p-value: 0.991
Degrees of freedom: 8
Fit method: wls
x uncertainty treatment: none
Attribute |
Meaning |
|---|---|
|
Slope \(m\) and its standard uncertainty; here both have units of m/s. |
|
Position \(q\) at \(x=0\) and its standard uncertainty, in metres. |
|
Sum of squared residuals divided by their respective variances. |
|
|
|
Under the model and error assumptions, the probability of chi-squared at least as large as observed. |
|
Number of measurements minus the two fitted parameters. |
|
|
|
|
Parameter uncertainties differ from measurement uncertainties. slope_std and intercept_std describe how precisely the line is determined. sigma_y describes individual measurements. WLS uses the supplied absolute uncertainties without rescaling parameter uncertainties by reduced chi-squared.
Interpreting chi-squared and p-value assumes independent Gaussian measurement errors, reliable uncertainties, and an appropriate model. Reduced chi-squared near one is consistent with the assumed scatter. Large values can suggest a poor model or underestimated uncertainties; very small values can suggest overestimated uncertainties. A p-value is not the probability that the model is correct. Inspect the residuals too.
With only two weighted points, dof=0: chi2 is available, but residual_std, reduced_chi2, and p_value are None.
result.residual_std describes residual scatter in the units of y, using dof in the denominator of the variance. In WLS it is descriptive, and result.estimated_sigma is None.
Uncertainties on x
Suppose each time measurement also has a standard uncertainty of 0.05 seconds. sigma_x accepts this single value or one value per measurement. Values must be finite and non-negative; zero means no horizontal uncertainty.
|
Effect of supplying |
|---|---|
|
Draw horizontal bars; keep the existing OLS/WLS calculation. |
|
Propagate horizontal uncertainties through iterative reweighting; requires both |
Display horizontal bars
Choose "none" to display the uncertainties without including them in the calculation:
bars_only = lin_fit(
df["x"],
df["y"],
sigma_y=df["sigma_y"],
sigma_x=0.05,
x_error_method="none",
output="results/horizontal_bars",
)
The horizontal bars appear in both panels. The fitted parameters, their uncertainties, and diagnostics remain the same as in the basic example.
Propagate horizontal uncertainties
Select "iterate" to include sigma_x in the calculation:
result_with_x = lin_fit(
df["x"],
df["y"],
sigma_y=df["sigma_y"],
sigma_x=0.05,
x_error_method="iterate",
output="results/linear_fit_x",
)
Here every point has the same sigma_y and the same sigma_x. Propagation therefore leaves the slope and intercept unchanged, but increases their standard uncertainties. Compare the slope uncertainty:
print(f"Without propagation: {bars_only.slope_std:.3f} m/s")
print(f"With propagation: {result_with_x.slope_std:.3f} m/s")
Output
Without propagation: 0.028 m/s
With propagation: 0.030 m/s
MesPy starts with the y-only fit, then repeatedly updates the effective variances:
It refits using these variances until the relative slope change is at most 1e-10. If it does not converge within 100 iterations, it raises RuntimeError before creating figures or files.
This is an approximate iterative method. Its parameter covariance, uncertainty band, and chi-square p-value have an approximate interpretation. Convergence does not guarantee a minimum of the effective criterion.
result_with_x.fit_method is still "wls"; result_with_x.x_error_method is "iterate". The files are linear_fit_x.pdf and linear_fit_x.toml.
Whenever sigma_x is supplied, TOML uses schema 3 and retains its original values and the selected x_error_method, including "none". Calls without sigma_x retain schema 2.
What if sigma_y is not provided?
unweighted_result = lin_fit(
df["x"],
df["y"],
output="results/unweighted_fit",
)
MesPy performs ordinary least squares (OLS): all observations receive equal weight. It emits a UserWarning and estimates a common vertical dispersion from the residuals.
unweighted_result.fit_methodis"ols".fit_methodis a result attribute, not a function argument.unweighted_result.estimated_sigmaequalsunweighted_result.residual_std. This estimate supplies the parameter uncertainties. OLS needs at least three measurements.Slope, intercept, their uncertainties, residuals, and
dofremain available.chi2,reduced_chi2, andp_valueareNoneand are omitted from TOML.
Without sigma_x, the figure has no measurement uncertainty bars. You may supply sigma_x for horizontal bars with x_error_method="none"; propagation with "iterate" requires sigma_y too.
Omitting sigma_y is not equivalent to setting sigma_y=1. The latter declares a known standard uncertainty of one y unit per measurement. It gives equal weights but uses WLS parameter uncertainties and diagnostics, even when the fitted line is the same.
Supply measurement uncertainties when they are available and scientifically justified.
Normalized residuals
The default is normalize_residuals=False. Request normalization explicitly:
normalized_result = lin_fit(
df["x"],
df["y"],
sigma_y=df["sigma_y"],
normalize_residuals=True,
output="results/normalized_fit",
)
For this y-only weighted fit, the lower panel displays
These dimensionless values express deviations in units of each measurement’s standard uncertainty, making measurements with different uncertainties easier to compare.
The denominator depends on the selected fit:
Fit |
Divide physical residuals by |
|---|---|
WLS with |
The supplied |
WLS with |
The final effective uncertainty |
OLS |
The common dispersion |
To normalize the iterative fit, also include sigma_x=0.05 and x_error_method="iterate" in the call above. In either WLS mode, the displayed vertical uncertainty bars then have a half-length of one. Horizontal bars keep their original x units.
OLS normalization does not provide known measurement uncertainties or chi-squared diagnostics. Zero OLS dispersion cannot be normalized for plotting and raises ValueError.
Normalization changes only the residual visualization. It does not change fitted parameters, their uncertainties, or the method. normalized_result.residuals and residuals saved in TOML always remain physical.