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:

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 DataSeries or a CSV path is passed, y and the error columns are read from it.

  • y (array-like, optional) – y-values (ignored if x is a DataSeries or CSV path).

  • model (str or callable, default "linear") – Built-in model name ("gaussian", "exponential", …) or a custom callable f(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 like predict(x) and residuals.

Return type:

FitResult

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:

FitResult

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) – If True, 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:

Plotter

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 DataSeries per 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:

Plotter

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:

Plotter

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

labfit.models.constant(x, level)[source]

Horizontal line at a fixed y-value.

Equation

\[y = k\]

Variables

  • x: input x-values.

  • k: constant output level.

linear

labfit.models.linear(x, slope, intercept)[source]

Straight line with constant gradient.

Equation

\[y = m x + c\]

Variables

  • x: input x-values.

  • m: linear gradient.

  • c: vertical offset.

quadratic

labfit.models.quadratic(x, a, b, c)[source]

Second-degree polynomial (parabola).

Equation

\[y = a x^2 + b x + c\]

Variables

  • x: input x-values.

  • a: quadratic coefficient.

  • b: linear coefficient.

  • c: constant term.

cubic

labfit.models.cubic(x, a, b, c, d)[source]

Third-degree polynomial.

Equation

\[y = a x^3 + b x^2 + c x + d\]

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

\[y = A\, e^{-\frac{1}{2}\bigl((x-\mu)/\sigma\bigr)^2}\]

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

\[y = A\, \frac{\gamma^{2}}{(x - x_0)^2 + \gamma^{2}}\]

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 amplitude at x = 0.

Equation

\[y = A\,e^{-\lambda x}\]

Variables

  • x: input x-values.

  • A: starting scale at x = 0.

  • \lambda: exponential decay constant.

power_law

labfit.models.power_law(x, amplitude, exponent)[source]

Power-law scaling with a variable exponent.

Equation

\[y = A\,x^{n}\]

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 baseline to baseline + amplitude centred at x0. Used for population growth, dose-response curves, and phase transitions with a continuous order parameter.

Equation

\[y = b + \frac{A}{1 + e^{-k(x - x_0)}}\]

Variables

  • x: input x-values.

  • A: curve height above the baseline.

  • x_0: midpoint / inflection location.

  • k: steepness parameter.

  • b: low-end offset, default 0.0.

sine

labfit.models.sine(x, amplitude, frequency, phase, offset=0.0)[source]

Sinusoidal oscillation with tunable frequency and phase.

Equation

\[y = o + A \sin(2\pi f x + \phi)\]

Variables

  • x: input x-values.

  • A: oscillation amplitude.

  • f: cycles per unit of x.

  • \phi: phase shift in radians.

  • o: vertical offset, default 0.0.

cosine

labfit.models.cosine(x, amplitude, frequency, phase, offset=0.0)[source]

Cosinusoidal oscillation with tunable frequency and phase.

Equation

\[y = o + A \cos(2\pi f x + \phi)\]

Variables

  • x: input x-values.

  • A: oscillation amplitude.

  • f: cycles per unit of x.

  • \phi: phase shift in radians.

  • o: vertical offset, default 0.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

\[y = A\,e^{-\gamma x}\cos(2\pi f x + \phi)\]

Variables

  • x: input x-values.

  • A: initial oscillation amplitude.

  • \gamma: exponential damping constant.

  • f: cycles per unit of x.

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

\[y = o + A\,e^{-\gamma x}\sin(2\pi f x + \phi)\]

Variables

  • x: input x-values.

  • A: initial oscillation amplitude.

  • \gamma: exponential damping constant.

  • f: cycles per unit of x.

  • \phi: phase shift in radians.

  • o: vertical offset, default 0.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 center and the characteristic width. Arises in diffraction patterns, signal processing (ideal low-pass filter response), and Fourier optics.

Equation

\[y = A\, \frac{\sin(u)}{u}, \quad u = \frac{\pi (x - x_0)}{w}\]

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 offset and rises exponentially toward offset + amplitude with time constant tau. Describes charging capacitors, thermal equilibration, and approach to steady state in first-order systems.

Equation

\[y = A\bigl(1 - e^{-x/\tau}\bigr) + o\]

Variables

  • x: input x-values.

  • A: asymptotic amplitude.

  • \tau: time constant.

  • o: vertical offset, default 0.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

\[y = A_1 e^{-x/\tau_1} + A_2 e^{-x/\tau_2}\]

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 (beta controls the tail weight). Widely used in astronomy for point-spread functions and in X-ray diffraction profile analysis.

Equation

\[y = A\, \Bigl[1 + \Bigl(\frac{x - x_0}{\alpha}\Bigr)^2\Bigr]^{-\beta}\]

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

\[y = A\, e^{-\frac{1}{2}\bigl((x-\mu)/\sigma\bigr)^2} + m x + b\]

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

\[y = A_1\, e^{-\frac{1}{2}\bigl((x-\mu_1)/\sigma_1\bigr)^2} +\; A_2\, e^{-\frac{1}{2}\bigl((x-\mu_2)/\sigma_2\bigr)^2}\]

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

\[y = A\, V(x - x_0, \sigma, \gamma)\]

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. When alpha = 0 the 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

\[y = A\, f(x; \alpha, \mu, \sigma)\]

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

\[y = A\, e^{-\frac{1}{2}\bigl((x-\mu)/\sigma\bigr)^2}, \qquad \sigma = \frac{\text{FWHM}}{2\sqrt{2\ln 2}}\]

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

\[y = A\, \frac{(\text{FWHM}/2)^2}{(x - x_0)^2 + (\text{FWHM}/2)^2}\]

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

\[y = A\, \frac{1}{2\tau} \exp\!\Bigl(\frac{\sigma^2}{2\tau^2} - \frac{x - \mu}{\tau}\Bigr) \operatorname{erfc}\!\Bigl( -\frac{x - \mu}{\sqrt{2}\,\sigma} + \frac{\sigma}{\sqrt{2}\,\tau} \Bigr)\]

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. When beta = 1 it reduces to a simple exponential; values of beta between zero and one produce a slower, stretched decay. Commonly used to model relaxation in disordered systems such as polymers, glasses, and biological tissues.

Equation

\[y = o + A\, \exp\!\Bigl[-\Bigl(\frac{x}{\tau}\Bigr)^\beta\Bigr]\]

Variables

  • x: input x-values.

  • A: amplitude at x = 0.

  • \tau: decay constant.

  • \beta: stretching exponent (\(\beta = 1\) recovers a simple exponential).

  • o: vertical offset, default 0.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 center with transition width width. Appears in models of magnetic phase transitions, adsorption isotherms, and switching phenomena where the transition has a well-defined midpoint.

Equation

\[y = o + A\, \tanh\!\Bigl(\frac{x - x_0}{w}\Bigr)\]

Variables

  • x: input x-values.

  • A: step height (half the total amplitude).

  • x_0: inflection point.

  • w: transition width.

  • o: vertical offset, default 0.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

\[y = o + A\, \arctan\!\Bigl(\frac{x - x_0}{w}\Bigr)\]

Variables

  • x: input x-values.

  • A: step amplitude scale.

  • x_0: inflection point.

  • w: transition width.

  • o: vertical offset, default 0.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

\[y = o + \frac{A}{2}\, \bigl[\cos(2\pi f_1 x + \phi) + \cos(2\pi f_2 x + \phi)\bigr]\]

Variables

  • x: input x-values.

  • A: overall amplitude.

  • f_1: cycles per unit x (first frequency).

  • f_2: cycles per unit x (second frequency).

  • \phi: phase shift in radians.

  • o: vertical offset, default 0.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

\[y = \frac{A}{x - x_0}\]

Variables

  • x: input x-values.

  • A: amplitude scale.

  • x_0: pole location.

quartic

labfit.models.quartic(x, a, b, c, d, e)[source]

Fourth-degree polynomial.

Equation

\[y = a x^4 + b x^3 + c x^2 + d x + e\]

Variables

  • x: input x-values.

  • a: quartic coefficient.

  • b: cubic coefficient.

  • c: quadratic coefficient.

  • d: linear coefficient.

  • e: constant term.

quintic

labfit.models.quintic(x, a, b, c, d, e, f)[source]

Fifth-degree polynomial.

Equation

\[y = a x^5 + b x^4 + c x^3 + d x^2 + e x + f\]

Variables

  • x: input x-values.

  • a: quintic coefficient.

  • b: quartic coefficient.

  • c: cubic coefficient.

  • d: quadratic coefficient.

  • e: linear coefficient.

  • f: constant term.