Fitting functions
LabFit exposes a small set of entry points for fitting and plotting, plus a collection of built-in model functions for common textbook curves.
The public fitting helpers are intentionally small:
labfit.fit()— the main least-squares entry point.labfit.fit_curve()— a convenience wrapper that takesy_errexplicitly.labfit.fit_multi()— fit a whole sequence oflabfit.Seriesobjects.labfit.plot_fit()— plot one fit and, by default, its residuals.labfit.plot_multi_fit()— compare multiple fits in a grid.labfit.plot_residuals()— explicit residual-focused wrapper.
Entry points
- labfit.fit(x, y=None, *, model='linear', p0=None, bounds=None, sigma=None, weights=None, sigma_low=None, sigma_high=None, sigma_cov=None, label='', **kwargs)[source]
Fit a model to data and return parameter estimates with uncertainties.
This is the main entry point. The first argument can be arrays, a
DataSeries, or a path to a CSV file — the function adapts automatically.- Parameters:
x (array-like or DataSeries or Path or str) – x-values for the data. If a
DataSeriesor a CSV path is passed,yand the error columns are read from it.y (array-like, optional) – y-values (ignored if
xis a DataSeries or CSV path).model (str or callable, default
"linear") – Built-in model name ("gaussian","exponential", …) or a custom callablef(x, *params).p0 (dict or array-like, optional) – Initial parameter guesses. Dict keys must match the parameter names (e.g.
{"amplitude": 1.0, "mean": 0.0}).bounds (dict or tuple of arrays, optional) – Parameter bounds. Either a dict
{"name": (lo, hi)}or a(lower, upper)tuple of arrays.sigma (array-like or AsymmetricError, optional) – 1-σ uncertainties for each y-value.
weights (array-like, optional) – Inverse-variance weights (alternative to
sigma).sigma_low (array-like, optional) – Asymmetric lower and upper uncertainties.
sigma_high (array-like, optional) – Asymmetric lower and upper uncertainties.
sigma_cov (array-like, optional) – Full covariance matrix for correlated measurement errors.
label (str, optional) – Label for the data series (used in plot legends).
- Returns:
Container with
params,uncertainties,reduced_chi2,p_value, and convenience methods likepredict(x)andresiduals.- Return type:
- labfit.fit_curve(model, x, y, y_err, *, p0=None, bounds=None, label='', **kwargs)[source]
Fit a model to data with explicit 1-sigma y uncertainties.
A convenience wrapper around
fit()that keeps the error specification as a dedicated positional argument for clarity.- Parameters:
model (str or callable) – Built-in model name or custom callable.
x (array-like) – x-values.
y (array-like) – y-values.
y_err (array-like) – 1-sigma uncertainties for each y-value.
p0 (dict or array-like, optional) – Initial parameter guesses.
bounds (dict or tuple of arrays, optional) – Parameter bounds.
label (str, optional) – Label for legends.
- Return type:
- labfit.fit_multi(dataset: Iterable[DataSeries] | Dataset, *, model='linear', p0=None, bounds=None, **kwargs)[source]
Fit the same model to every series in a collection.
- Parameters:
dataset (Dataset or iterable of DataSeries) – The data series to fit. Each series can carry its own label and error specification.
model (str or callable, default
"linear") – Model name or custom callable.p0 (dict or array-like, optional) – Shared initial parameter guesses for all series.
bounds (dict or tuple of arrays, optional) – Shared parameter bounds for all series.
- Returns:
One result per input series.
- Return type:
list of FitResult
- labfit.plot_fit(result=None, *, data_series=None, ax=None, show_residuals: bool = True, show_ci: bool = False, ci_level: float = 0.68, prediction: bool = False, **kwargs) Plotter[source]
Plot a single fit result with its data and residuals.
The simplest way to visualise a fitted curve. Data points with error bars, the best-fit line, and (by default) a residual panel underneath are all generated automatically.
- Parameters:
result (FitResult) – The fit result to plot.
data_series (DataSeries, optional) – The data to show. Falls back to
result.series.ax (matplotlib Axes, optional) – Existing axes to plot into.
show_residuals (bool, default
True) – Include a residual sub-panel.show_ci (bool, default
False) – Draw a confidence band around the fit line.ci_level (float, default
0.68) – Confidence level for the band (e.g. 0.68 for 1σ, 0.95 for 95%).prediction (bool, default
False) – IfTrue, draw a prediction band (includes data scatter) instead of a confidence band for the mean.title (str, optional) – Plot title.
xlabel (str) – Axis labels.
ylabel (str) – Axis labels.
- Return type:
- labfit.plot_multi_fit(results, series_list, layout: str = 'grid', *, figsize=(5.0, 4.0), title: str | None = None, xlabel: str = 'x', ylabel: str = 'y') Plotter[source]
Compare multiple fits in a side-by-side grid.
Each fit gets its own column with data and fit line in the top panel and residuals below. Requires exactly one
DataSeriesper fit result.- Parameters:
results (list of FitResult) – The fits to display.
series_list (list of DataSeries) – The corresponding measured data (one per fit).
layout (str, default
"grid") – Layout style (currently only"grid"is supported).figsize (tuple, default
(5, 4)) – Dimensions per panel in inches.title (str, optional) – Overall figure title.
xlabel (str) – Axis labels shared by all panels.
ylabel (str) – Axis labels shared by all panels.
- Return type:
- labfit.plot_residuals(result=None, *, data_series=None, ax=None, **kwargs) Plotter[source]
Plot a fit emphasising the residuals.
Equivalent to
plot_fit(…, show_residuals=True).- Parameters:
result (FitResult) – The fit result to plot.
data_series (DataSeries, optional) – The data to show.
ax (matplotlib Axes, optional) – Existing axes to plot into.
- Return type:
Built-in model functions
The built-in models live in labfit.models. They can be passed either by
name or as a callable to labfit.fit() and labfit.Fitter.
The sections below show each function signature, then the equation, then the variable definitions used in the formula.
constant
Equation
Variables
x: input x-values.k: constant output level.
linear
Equation
Variables
x: input x-values.m: linear gradient.c: vertical offset.
quadratic
Equation
Variables
x: input x-values.a: quadratic coefficient.b: linear coefficient.c: constant term.
cubic
Equation
Variables
x: input x-values.a: cubic coefficient.b: quadratic coefficient.c: linear coefficient.d: constant term.
gaussian
- labfit.models.gaussian(x, amplitude, mean, sigma)[source]
Symmetric bell-shaped peak (normal distribution).
Equation
Variables
x: input x-values.A: peak height scale.\mu: center position.\sigma: Gaussian width parameter.
lorentzian
- labfit.models.lorentzian(x, amplitude, center, gamma)[source]
Peak with a narrower core and heavier tails than a Gaussian.
Also known as the Cauchy or Breit-Wigner distribution. Common in spectroscopy for natural line shapes and in particle physics for resonance profiles.
Equation
Variables
x: input x-values.A: peak height scale.x_0: line center.\gamma: half-width parameter.
exponential
- labfit.models.exponential(x, amplitude, decay)[source]
Exponential decay starting from
amplitudeatx = 0.
Equation
Variables
x: input x-values.A: starting scale atx = 0.\lambda: exponential decay constant.
power_law
- labfit.models.power_law(x, amplitude, exponent)[source]
Power-law scaling with a variable exponent.
Equation
Variables
x: input x-values.A: scale factor.n: power-law exponent.
logistic
- labfit.models.logistic(x, amplitude, x0, k, baseline=0.0)[source]
Sigmoidal curve with a tunable steepness.
Transitions smoothly from
baselinetobaseline + amplitudecentred atx0. Used for population growth, dose-response curves, and phase transitions with a continuous order parameter.
Equation
Variables
x: input x-values.A: curve height above the baseline.x_0: midpoint / inflection location.k: steepness parameter.b: low-end offset, default0.0.
sine
- labfit.models.sine(x, amplitude, frequency, phase, offset=0.0)[source]
Sinusoidal oscillation with tunable frequency and phase.
Equation
Variables
x: input x-values.A: oscillation amplitude.f: cycles per unit ofx.\phi: phase shift in radians.o: vertical offset, default0.0.
cosine
- labfit.models.cosine(x, amplitude, frequency, phase, offset=0.0)[source]
Cosinusoidal oscillation with tunable frequency and phase.
Equation
Variables
x: input x-values.A: oscillation amplitude.f: cycles per unit ofx.\phi: phase shift in radians.o: vertical offset, default0.0.
damped_oscillator
- labfit.models.damped_oscillator(x, amplitude, damping, frequency, phase)[source]
Oscillation that decays exponentially (cosine form).
Represents a harmonic oscillator with friction, such as a swinging pendulum subject to air resistance or an RLC circuit with resistance.
Equation
Variables
x: input x-values.A: initial oscillation amplitude.\gamma: exponential damping constant.f: cycles per unit ofx.\phi: phase shift in radians.
damped_sine
- labfit.models.damped_sine(x, amplitude, damping, frequency, phase, offset=0.0)[source]
Oscillation that decays exponentially (sine form).
Identical in form to the damped oscillator but uses sine instead of cosine. Suitable when the signal starts at the equilibrium point.
Equation
Variables
x: input x-values.A: initial oscillation amplitude.\gamma: exponential damping constant.f: cycles per unit ofx.\phi: phase shift in radians.o: vertical offset, default0.0.
sinc
- labfit.models.sinc(x, amplitude, center, width)[source]
Central peak with oscillating sidelobes.
Defined as sin(u)/u where u depends on the distance from
centerand the characteristicwidth. Arises in diffraction patterns, signal processing (ideal low-pass filter response), and Fourier optics.
Equation
Variables
x: input x-values.A: peak amplitude.x_0: center position.w: characteristic width.
exponential_rise
- labfit.models.exponential_rise(x, amplitude, tau, offset=0.0)[source]
Saturation curve approaching an asymptotic value.
Starts at
offsetand rises exponentially towardoffset + amplitudewith time constanttau. Describes charging capacitors, thermal equilibration, and approach to steady state in first-order systems.
Equation
Variables
x: input x-values.A: asymptotic amplitude.\tau: time constant.o: vertical offset, default0.0.
double_exponential
- labfit.models.double_exponential(x, amplitude1, tau1, amplitude2, tau2)[source]
Sum of two exponential decays with distinct time constants.
Useful when a process has both a fast and a slow relaxation channel, such as biexponential fluorescence decay, two-component nuclear magnetic resonance relaxation, or mixed kinetics.
Equation
Variables
x: input x-values.A_1: amplitude of the fast component.\tau_1: decay constant of the fast component.A_2: amplitude of the slow component.\tau_2: decay constant of the slow component.
moffat
- labfit.models.moffat(x, amplitude, x0, alpha, beta)[source]
Peak with power-law tails controlled by an exponent.
Similar to a Lorentzian near the centre but with a variable power-law fall-off (
betacontrols the tail weight). Widely used in astronomy for point-spread functions and in X-ray diffraction profile analysis.
Equation
Variables
x: input x-values.A: peak amplitude.x_0: center position.\alpha: width parameter.\beta: power-law exponent controlling the tail weight.
gaussian_baseline
- labfit.models.gaussian_baseline(x, amplitude, mean, sigma, m, b)[source]
Gaussian peak superimposed on a linear background.
Equation
Variables
x: input x-values.A: peak height scale.\mu: center position.\sigma: Gaussian width parameter.m: linear baseline slope.b: linear baseline intercept.
bimodal_gaussian
- labfit.models.bimodal_gaussian(x, amplitude1, mean1, sigma1, amplitude2, mean2, sigma2)[source]
Sum of two independent Gaussian peaks.
Models data with two resolved components — for example, emission lines from closely spaced energy levels, overlapping diffraction peaks, or multi-species velocity distributions.
Equation
Variables
x: input x-values.A_1: amplitude of the first peak.\mu_1: center of the first peak.\sigma_1: width of the first peak.A_2: amplitude of the second peak.\mu_2: center of the second peak.\sigma_2: width of the second peak.
voigt
- labfit.models.voigt(x, amplitude, center, sigma, gamma)[source]
Symmetric peak shape with a Gaussian core and Lorentzian wings.
The Voigt profile is the convolution of a Gaussian and a Lorentzian of equal widths. It arises naturally in spectroscopy when Doppler (Gaussian) and natural/pressure (Lorentzian) broadening act together.
Equation
where \(V\) is the Voigt profile (convolution of a Gaussian and Lorentzian).
Variables
x: input x-values.A: peak amplitude scale.x_0: center position.\sigma: Gaussian width parameter.\gamma: Lorentzian half-width parameter.
skew_normal
- labfit.models.skew_normal(x, amplitude, location, scale, alpha)[source]
Asymmetric bell-shaped curve with a shape parameter.
Generalises the normal distribution by adding a skewness parameter
alpha. Whenalpha = 0the curve is a symmetric Gaussian; positive values tilt the peak leftwards and negative values tilt it rightwards. Useful for modelling peaks that are not symmetric about their centre.
Equation
where \(f\) is the skew-normal probability density function.
Variables
x: input x-values.A: amplitude scale factor.\mu: location (center) parameter.\sigma: scale (width) parameter.\alpha: shape parameter (\(\alpha=0\) recovers a symmetric Gaussian).
gaussian_fwhm
- labfit.models.gaussian_fwhm(x, amplitude, center, fwhm)[source]
Gaussian peak parameterised by its full width at half maximum.
Identical to the standard Gaussian model but accepts the peak width as the directly measurable FWHM instead of the standard deviation. The conversion between FWHM and sigma is handled internally.
Equation
Variables
x: input x-values.A: peak amplitude.\mu: center position.\text{FWHM}: full width at half maximum.
lorentzian_fwhm
- labfit.models.lorentzian_fwhm(x, amplitude, center, fwhm)[source]
Lorentzian peak parameterised by its full width at half maximum.
Identical to the standard Lorentzian model but accepts the peak width as the directly measurable FWHM instead of the half-width at half maximum. The conversion is handled internally.
Equation
Variables
x: input x-values.A: peak amplitude.x_0: center position.\text{FWHM}: full width at half maximum.
exgaussian
- labfit.models.exgaussian(x, amplitude, mu, sigma, tau)[source]
Asymmetric peak with a Gaussian rise and exponential tail.
The exponentially modified Gaussian (ExGaussian) is the convolution of a normal distribution with an exponential decay. It produces a peak that rises symmetrically but decays with a long tail, matching the characteristic shape of chromatographic signals, reaction-time data, and detector pulses.
Equation
Variables
x: input x-values.A: amplitude scale.\mu: Gaussian center.\sigma: Gaussian width.\tau: exponential decay constant (tailing).
stretched_exponential
- labfit.models.stretched_exponential(x, amplitude, tau, beta, offset=0.0)[source]
Decay function with a variable stretching exponent.
A generalisation of the exponential decay where the time constant is raised to a power
beta. Whenbeta = 1it reduces to a simple exponential; values ofbetabetween zero and one produce a slower, stretched decay. Commonly used to model relaxation in disordered systems such as polymers, glasses, and biological tissues.
Equation
Variables
x: input x-values.A: amplitude atx = 0.\tau: decay constant.\beta: stretching exponent (\(\beta = 1\) recovers a simple exponential).o: vertical offset, default0.0.
tanh
- labfit.models.tanh(x, amplitude, center, width, offset=0.0)[source]
Smooth sigmoidal step with a hyperbolic-tangent shape.
Produces a monotonic transition from one level to another, centred at
centerwith transition widthwidth. Appears in models of magnetic phase transitions, adsorption isotherms, and switching phenomena where the transition has a well-defined midpoint.
Equation
Variables
x: input x-values.A: step height (half the total amplitude).x_0: inflection point.w: transition width.o: vertical offset, default0.0.
arctan
- labfit.models.arctan(x, amplitude, center, width, offset=0.0)[source]
Smooth step with broad polynomial tails.
Similar to a hyperbolic-tangent step but approaches the asymptotic levels as inverse-power tails rather than exponentially, giving a broader transition zone. Useful for resistivity jumps, specific-heat anomalies, and other phase-transition signatures with wide tails.
Equation
Variables
x: input x-values.A: step amplitude scale.x_0: inflection point.w: transition width.o: vertical offset, default0.0.
beat
- labfit.models.beat(x, amplitude, frequency1, frequency2, phase, offset=0.0)[source]
Superposition of two cosine waves of nearby frequencies.
Models the acoustic or electronic beat phenomenon where two oscillations of similar frequency interfere, producing an amplitude modulation (envelope) at the difference frequency. The output is the average of the two cosines, scaled by the amplitude.
Equation
Variables
x: input x-values.A: overall amplitude.f_1: cycles per unitx(first frequency).f_2: cycles per unitx(second frequency).\phi: phase shift in radians.o: vertical offset, default0.0.
rational
- labfit.models.rational(x, amplitude, x0)[source]
First-order rational function with a single pole.
Produces a simple resonance lineshape with a singularity at
x0. The magnitude diverges as the independent variable approaches the pole, making this suitable for modelling resonant behaviour in driven systems and susceptibility measurements away from the singular point.
Equation
Variables
x: input x-values.A: amplitude scale.x_0: pole location.
quartic
Equation
Variables
x: input x-values.a: quartic coefficient.b: cubic coefficient.c: quadratic coefficient.d: linear coefficient.e: constant term.
quintic
Equation
Variables
x: input x-values.a: quintic coefficient.b: quartic coefficient.c: cubic coefficient.d: quadratic coefficient.e: linear coefficient.f: constant term.