Skip to content

foresight_fit ​

foresight_fit, gnuplot's fit: nonlinear least squares by the Marquardt-Levenberg method.

A translation of gnuplot 6.0's fit.c and matrix.c, so that a fit gives gnuplot's parameters, errors and iterations:

  • the parameters are prescaled by their initial values (each one starts at +-1; a zero one at 1e-30, unscaled);
  • the model derivatives are one-sided differences, the step 0.001 of each scaled parameter;
  • each step solves the least squares problem of the Jacobian over the errors, augmented by lambda times the identity, by Givens rotations; a step that does not increase chi-square is taken and lambda divided by 10, else lambda is multiplied by 10 and the step tried again; lambda starts at the root mean square of the Jacobian entries;
  • the fit stops when chi-square decreases by no more than limit times itself (plus limit_abs), after maxiter iterations if set, when lambda exceeds 1e20 or chi-square is zero;
  • the parameter errors are the square roots of the diagonal of (J^T J)^-1, scaled by sqrt(chi-square / ndf) when the data carry no errors or errorscaling holds (gnuplot's default); the correlations follow from the same matrix.

levenberg_marquardt fits any extension of fit_model (values at the data points for a parameter vector; the script fits user functions through it); fit fits a Fortran function of x; fit_report writes gnuplot's report.

Source: src/lib/foresight_fit.F90

Dependencies

Contents ​

Variables ​

NameTypeAttributesDescription
NEARLY_ZEROreal(kind=R8P)parametergnuplot's floor of a parameter and of chi-square.
DELTAreal(kind=R8P)parameterRelative step of the numerical derivatives.
MIN_LAMBDAreal(kind=R8P)parameterlambda is not decreased below.
MAX_LAMBDAreal(kind=R8P)parameterThe fit stops above.

Derived Types ​

fit_settings ​

gnuplot's set fit options.

Components

NameTypeAttributesDescription
limitreal(kind=R8P)Relative change of chi-square that stops the fit (limit, FIT_LIMIT).
limit_absreal(kind=R8P)Absolute part of the stopping change (limit_abs).
maxiterinteger(kind=I4P)Most iterations, 0 for no limit (maxiter, FIT_MAXITER).
start_lambdareal(kind=R8P)First lambda, 0 for gnuplot's estimate (start_lambda).
lambda_factorreal(kind=R8P)lambda factor up and down (lambda_factor).
prescalelogicalParameters scaled by their initial values (prescale).
errorscalinglogicalErrors scaled by the reduced chi-square (errorscaling).

fit_result ​

Outcome of a fit: gnuplot's FIT_* values, the parameters and their errors.

Components

NameTypeAttributesDescription
paramsreal(kind=R8P)allocatableFitted parameters.
errorsreal(kind=R8P)allocatableAsymptotic standard errors (a_err), 0 if not computable.
correlationreal(kind=R8P)allocatableCorrelations of the parameters, 0 if not computable.
wssrreal(kind=R8P)Weighted sum of squared residuals (FIT_WSSR).
last_wssrreal(kind=R8P)WSSR of the iteration before the last.
stdfitreal(kind=R8P)sqrt(WSSR / ndf) (FIT_STDFIT).
preal(kind=R8P)p-value of chi-square (FIT_P).
ndfinteger(kind=I4P)Degrees of freedom (FIT_NDF).
niterinteger(kind=I4P)Iterations (FIT_NITER).
convergedlogicalConverged (FIT_CONVERGED).
has_errorslogicalErrors and correlations computed.
weightedlogicalThe data carried errors.
stop_textcharacter(len=:)allocatableWhy the fit stopped, gnuplot's sentence.
progresscharacter(len=:)allocatablegnuplot's one-line progress report, iteration after iteration.
messagecharacter(len=:)allocatableFailure, empty on success.

fit_model ​

A model fitted by levenberg_marquardt: its values at the data points for a parameter vector. An object, not a procedure argument: an internal procedure passed as an argument costs gfortran an executable stack (trampoline).

Inheritance

Attributes: abstract

Type-Bound Procedures

NameAttributesDescription
valuespass(self)Values at the data points.
slopespass(self)Slopes in x at the data points (xyerrors).

function_model ​

A Fortran function of x at given abscissae, for fit.

Inheritance

Extends: fit_model

Components

NameTypeAttributesDescription
fprocedure(model_function)pointer, nopassModel.
xreal(kind=R8P)allocatableAbscissae.

Type-Bound Procedures

NameAttributesDescription
valuespass(self)Values at the abscissae.
slopespass(self)Slopes at the abscissae.

Subroutines ​

fit ​

Fit the Fortran function model(x, params) to the points (x, y), from the initial params (updated), as gnuplot fit f(x) 'data' using 1:2[:3] via ...: err the errors of y (unit weights if absent). Silent unless report is given: '-' writes gnuplot's report to the standard error, as gnuplot's terminal, a file name writes it there (gnuplot's fit.log). names name the parameters in the report (p1, p2, ... if absent). On failure result%message says why and params keep their initial values.

fortran
subroutine fit(model, x, y, params, names, err, settings, result, report)

Arguments

NameTypeIntentAttributesDescription
modelprocedure(model_function)Model.
xreal(kind=R8P)inAbscissae.
yreal(kind=R8P)inOrdinates.
paramsreal(kind=R8P)inoutParameters: initial values in, fitted out.
namescharacter(len=*)inoptionalParameter names.
errreal(kind=R8P)inoptionalErrors of y.
settingstype(fit_settings)inoptionalFit options.
resulttype(fit_result)outoptionalOutcome.
reportcharacter(len=*)inoptionalReport: '-' standard error, else a file.

Call graph

function_values ​

The model function at every abscissa.

fortran
subroutine function_values(self, p, f, ok)

Arguments

NameTypeIntentAttributesDescription
selfclass(function_model)inoutModel.
preal(kind=R8P)inParameters.
freal(kind=R8P)outValues.
oklogicaloutAll defined.

model_slopes ​

Slopes in x of the model at the data points for the parameters p (its values f there): none by default.

fortran
subroutine model_slopes(self, p, f, dfdx, ok)

Arguments

NameTypeIntentAttributesDescription
selfclass(fit_model)inoutModel.
preal(kind=R8P)inParameters.
freal(kind=R8P)inModel values.
dfdxreal(kind=R8P)outSlopes.
oklogicaloutEvery slope defined.

function_slopes ​

Slopes of the model function at the abscissae, gnuplot's calc_derivatives: one-sided, the step max(0.001 |x|, 8e-8 (|x| + 1e-8)).

fortran
subroutine function_slopes(self, p, f, dfdx, ok)

Arguments

NameTypeIntentAttributesDescription
selfclass(function_model)inoutModel.
preal(kind=R8P)inParameters.
freal(kind=R8P)inModel values.
dfdxreal(kind=R8P)outSlopes.
oklogicaloutEvery slope defined.

levenberg_marquardt ​

Fit model (values at the data points for a parameter vector) to the data z of errors err from the initial parameters a0, as gnuplot's regress (see the module notes); weighted tells the errors were given (for the error scaling and the report). With the errors xerr of the abscissae (gnuplot's xyerrors), each point's error is the effective one, sqrt(err^2 + (f' xerr)^2), the slope f' of the model at the parameters being tried (Orear's effective variance, gnuplot's effective_error).

fortran
subroutine levenberg_marquardt(model, z, err, a0, settings, result, weighted, xerr)

Arguments

NameTypeIntentAttributesDescription
modelclass(fit_model)inoutModel.
zreal(kind=R8P)inData.
errreal(kind=R8P)inErrors of the data.
a0real(kind=R8P)inInitial parameters.
settingstype(fit_settings)inOptions.
resulttype(fit_result)outOutcome.
weightedlogicalinThe data carry errors.
xerrreal(kind=R8P)inoptionalErrors of the abscissae.

Call graph

append ​

Append more to text through a temporary (no text = text//more: see foresight#3, bug 1).

Attributes: pure

fortran
subroutine append(text, more)

Arguments

NameTypeIntentAttributesDescription
textcharacter(len=:)inoutallocatableText.
morecharacter(len=*)inAppended text.

Call graph

givens ​

gnuplot's Givens: the QR decomposition of c (N x n, N >= n) by Givens rotations in place, R in its top n rows, d rotated along; with solve, x solves R x + d = 0 by back substitution. ok false on a singular matrix.

Attributes: pure

fortran
subroutine givens(c, d, solve, x, ok)

Arguments

NameTypeIntentAttributesDescription
creal(kind=R8P)inoutMatrix.
dreal(kind=R8P)inoutRight-hand side.
solvelogicalinSolve for x.
xreal(kind=R8P)outallocatableSolution.
oklogicaloutNot singular.

Call graph

invert_rtr ​

gnuplot's Invert_RtR: (R^T R)^-1 of the upper triangular r (n x n), its lower triangle in inv (the upper one mirrored). ok false on a zero diagonal.

Attributes: pure

fortran
subroutine invert_rtr(r, inv, ok)

Arguments

NameTypeIntentAttributesDescription
rreal(kind=R8P)inUpper triangular matrix.
invreal(kind=R8P)outInverse of R^T R.
oklogicaloutRegular.

Call graph

fit_report ​

Write gnuplot's fit report of result, for the parameters names: on the standard error (destination '-', gnuplot's terminal output: with progress the progress lines (gnuplot's brief), then the stop sentence and the results) or appended to the file destination (gnuplot's fit.log: a header naming the data source and the function_text, the first and last progress lines, the results).

fortran
subroutine fit_report(result, names, destination, source, function_text, progress)

Arguments

NameTypeIntentAttributesDescription
resulttype(fit_result)inOutcome.
namescharacter(len=*)inParameter names.
destinationcharacter(len=*)in'-' or a file name.
sourcecharacter(len=*)inData description.
function_textcharacter(len=*)inFitted function.
progresslogicalinTerminal: with the progress lines.

Call graph

Functions ​

sumsq ​

Sum of the squares of x, compensated (Neumaier), as gnuplot's sumsq_vec.

Attributes: pure

Returns: real(kind=R8P)

fortran
function sumsq(x) result(s)

Arguments

NameTypeIntentAttributesDescription
xreal(kind=R8P)inValues.

chisq_cdf ​

Chi-square distribution of dof degrees of freedom at chisq: the regularized lower incomplete gamma function P(dof / 2, chisq / 2) (series below a + 1, continued fraction above).

Attributes: pure

Returns: real(kind=R8P)

fortran
function chisq_cdf(dof, chisq) result(p)

Arguments

NameTypeIntentAttributesDescription
dofinteger(kind=I4P)inDegrees of freedom.
chisqreal(kind=R8P)inChi-square.

Call graph

cformat ​

v formatted by the printf format (%g, %e, %f with flags, width, precision), from its 15 significant digits (foresight_format), as C would print it.

Returns: character(len=:)

fortran
function cformat(format, v) result(text)

Arguments

NameTypeIntentAttributesDescription
formatcharacter(len=*)inFormat.
vreal(kind=R8P)inValue.

Call graph

field ​

text left-aligned in width characters, cut beyond (printf %-W.Ws).

Attributes: pure

Returns: character(len=:)

fortran
function field(text, width) result(padded)

Arguments

NameTypeIntentAttributesDescription
textcharacter(len=*)inText.
widthinteger(kind=I4P)inWidth.

Call graph

results_text ​

gnuplot's final results (show_results): sums of squares, degrees of freedom, the parameters and their errors, the correlation matrix.

Returns: character(len=:)

fortran
function results_text(result, names) result(text)

Arguments

NameTypeIntentAttributesDescription
resulttype(fit_result)inOutcome.
namescharacter(len=*)inParameter names.

Call graph

Released under the GPL v3, BSD 2-Clause, BSD 3-Clause or MIT License.