## GwyNLFitter GwyNLFitter — Marquardt-Levenberg nonlinear least square fitter |

## Functions

gdouble | (*GwyNLFitFunc) ()
void | (*GwyNLFitDerFunc) ()
gdouble | (*GwyNLFitIdxFunc) ()
void | (*GwyNLFitIdxDiffFunc) ()
GwyNLFitter * | gwy_math_nlfit_new ()
GwyNLFitter * | gwy_math_nlfit_new_idx ()
void | gwy_math_nlfit_free ()
GwyNLFitter * | gwy_math_nlfit_copy ()
gdouble | gwy_math_nlfit_fit ()
gdouble | gwy_math_nlfit_fit_full ()
gdouble | gwy_math_nlfit_fit_idx ()
gdouble | gwy_math_nlfit_fit_idx_full ()
gint | gwy_math_nlfit_get_max_iterations ()
void | gwy_math_nlfit_set_max_iterations ()
gboolean | gwy_math_nlfit_get_approx_geometric ()
void | gwy_math_nlfit_set_approx_geometric ()
gboolean | gwy_math_nlfit_succeeded ()
gdouble | gwy_math_nlfit_get_dispersion ()
gdouble | gwy_math_nlfit_get_correlations ()
gboolean | gwy_math_nlfit_get_eval ()
const gdouble * | gwy_math_nlfit_get_covar ()
gint | gwy_math_nlfit_get_nparam ()
gdouble | gwy_math_nlfit_get_sigma ()
void | gwy_math_nlfit_set_callbacks ()
void | gwy_math_nlfit_diff ()
void | gwy_math_nlfit_derive ()
void | gwy_math_nlfit_diff_idx ()
gint | gwy_math_nlfit_map_free_params ()

## Types and Values

struct | GwyNLFitter

## Includes

    #include <libgwyddion/gwyddion.h>

## Description

A new Marquardt-Levenberg nonlinear least square fitter can be created with `gwy_math_nlfit_new()`, specifying the function to fit (as GwyNLFitFunc) and its derivative (as GwyNLFitDerFunc). For functions for whose analytic derivative is not available or very impractical, `gwy_math_nlfit_derive()` (computing the derivative numerically) can be used instead.

A fitter can be then repeatedly used on different data either in `gwy_math_nlfit_fit()`, or `gwy_math_nlfit_fit_full()` when there are some fixed or linked parameters. Arbitrary additional (non-fitting) parameters can be passed to the fited function in `user_data` .

After a successfull fit additional fit information can be obtained with `gwy_math_nlfit_get_dispersion()`, `gwy_math_nlfit_get_correlations()`, `gwy_math_nlfit_get_sigma()`. Note these functions may be used only after a successfull fit. When a fitter is no longer needed, it should be freed with `gwy_math_nlfit_free()`.

Several common functions are also available as fitting presets that can be fitted with `gwy_nlfit_preset_fit()`. See GwyNLFitPreset for details.

## Functions

### GwyNLFitFunc ()

    gdouble
    (*GwyNLFitFunc) (gdouble x,
                     gint nparam,
                     const gdouble *param,
                     gpointer user_data,
                     gboolean *success);

Fitting function type for real-valued independent variables.

#### Parameters

x | The value to compute the function at. |
nparam | The number of parameters (size of `param` ). |
param | Parameters. |
user_data | User data as passed to `gwy_math_nlfit_fit()`. |
success | Set to `TRUE` if succeeds, `FALSE` on failure. |

#### Returns

The function value at `x` .

### GwyNLFitDerFunc ()

    void
    (*GwyNLFitDerFunc) (gdouble x,
                        gint nparam,
                        const gdouble *param,
                        const gboolean *fixed_param,
                        GwyNLFitFunc func,
                        gpointer user_data,
                        gdouble *der,
                        gboolean *success);

Fitting function partial derivative type for real-valued independent variables.

#### Parameters

x | x-data as passed to `gwy_math_nlfit_fit()`. |
nparam | The number of parameters (size of `param` ). |
param | Parameters. |
fixed_param | Which parameters should be treated as fixed (corresponding entries are set to `TRUE`). |
func | The fitted function. |
user_data | User data as passed to `gwy_math_nlfit_fit()`. |
der | Array where the `nparam` partial derivatives by each parameter are to be stored. Derivatives by fixed parameters are ignored so the function may set corresponding elements or not, whichever is more convenient. |
success | Set to `TRUE` if succeeds, `FALSE` on failure. |

### GwyNLFitIdxFunc ()

    gdouble
    (*GwyNLFitIdxFunc) (guint i,
                        const gdouble *param,
                        gpointer user_data,
                        gboolean *success);

Fitting function type for opaque indexed data.

Note that unlike GwyNLFitFunc which returns just the function value this function must return the difference between the function value and fitted data value (that is function minus data point). When opaque data are fitted the fitter does not know what the data values are.

The function must take care of weighting. The difference should be multiplied by the inverse of the (unsquared) estimated error of the `i` -th data point. Not multiplying by anything correspond to using the default unit weights.

#### Parameters

i | Data index from the set {0, 1, 2, ..., ndata-1}. |
param | Parameters. |
user_data | User data as passed to `gwy_math_nlfit_fit()`. |
success | Set to `TRUE` if succeeds, `FALSE` on failure. |

#### Returns

Difference between the function value and data in the `i` -th data point.

Since: 2.46

### GwyNLFitIdxDiffFunc ()

    void
    (*GwyNLFitIdxDiffFunc) (guint i,
                            const gdouble *param,
                            const gboolean *fixed_param,
                            GwyNLFitIdxFunc func,
                            gpointer user_data,
                            gdouble *der,
                            gboolean *success);

Fitting function partial derivatives type for opaque indexed data.

The function must take care of weighting. The derivatives should be multiplied by the inverse of the (unsquared) estimated error of the `i` -th data point. Not multiplying by anything correspond to using the default unit weights.

#### Parameters

i | Data index from the set {0, 1, 2, ..., ndata-1}. |
param | Parameters. |
fixed_param | Which parameters should be treated as fixed (corresponding entries are set to `TRUE`). It may be `NULL` is no parameters are fixed. The function must set derivatives by fixed parameters to zero. |
func | The fitted function. |
user_data | User data as passed to `gwy_math_nlfit_fit()`. |
der | Array where the `nparam` partial derivatives by each parameter are to be stored. Derivatives by fixed parameters are ignored so the function may set corresponding elements or not, whichever is more convenient. |
success | Set to `TRUE` if succeeds, `FALSE` on failure. |

Since: 2.46

### gwy_math_nlfit_new ()

    GwyNLFitter *
    gwy_math_nlfit_new (GwyNLFitFunc func,
                        GwyNLFitDerFunc diff);

Creates a new Marquardt-Levenberg nonlinear fitter for function with a real-valued independent variable.

See `gwy_math_nlfit_new_idx()` for more complex scenarios.

You can use `gwy_math_nlfit_diff()` computing the derivative numerically, when you do not know the derivatives explicitely. Since 2.46 passing `NULL` as `diff` has the same effect, i.e. the fitter will automatically use numerical differentiation.

#### Parameters

func | The fitted function. |
diff | The derivative of fitted function. |

#### Returns

The newly created fitter.

### gwy_math_nlfit_new_idx ()

    GwyNLFitter *
    gwy_math_nlfit_new_idx (GwyNLFitIdxFunc func,
                            GwyNLFitIdxDiffFunc diff);

Creates a new Marquardt-Levenberg nonlinear fitter for opaque indexed data.

As only the data index is passed to the functions, using this interface permits fitting more complex functions. The abscissa can be arbitrary, for instance a vector, as it is not seen by the fitter. Similarly, vector-valued functions can be emulated by mapping tuples of indices to the vector components.

You can pass `NULL` as `diff` to use automatically numerical differentiation when you do not know the derivatives explicitely. Note that this means you cannot use weighting. If you want weighting you need to pass your own `diff` function that performs the weighting (it can utilise the `gwy_math_nlfit_diff_idx()` helper).

#### Parameters

func | The fitted function. |
diff | The derivative of fitted function. |

#### Returns

The newly created fitter.

Since: 2.46

### gwy_math_nlfit_free ()

    void
    gwy_math_nlfit_free (GwyNLFitter *nlfit);

Completely frees a Marquardt-Levenberg nonlinear fitter.

#### Parameters

nlfit | A Marquardt-Levenberg nonlinear fitter. |

### gwy_math_nlfit_copy ()

    GwyNLFitter *
    gwy_math_nlfit_copy (GwyNLFitter *nlfit);

Creates a copy of a nonlinear least squares fitter.

This function is mostly usefil for language bindings.

#### Parameters

nlfit | A Marquardt-Levenberg nonlinear fitter. |

#### Returns

The newly created fitter.

Since: 2.47

### gwy_math_nlfit_fit ()

    gdouble
    gwy_math_nlfit_fit (GwyNLFitter *nlfit,
                        gint ndata,
                        const gdouble *x,
                        const gdouble *y,
                        gint nparam,
                        gdouble *param,
                        gpointer user_data);

Performs a nonlinear fit of simple function on data.

#### Parameters

nlfit | A Marquardt-Levenberg nonlinear fitter. |
ndata | The number of data points in `x` , `y` . |
x | Array of independent variable values. |
y | Array of dependent variable values. |
nparam | The nuber of parameters. |
param | Array of parameters (of size `nparam` ). Note the parameters must be initialized to reasonably near values. |
user_data | Pointer that will be passed to the function and derivative as `user_data` . |

#### Returns

The final residual sum, a negative number in the case of failure.

### gwy_math_nlfit_fit_full ()

    gdouble
    gwy_math_nlfit_fit_full (GwyNLFitter *nlfit,
                             gint ndata,
                             const gdouble *x,
                             const gdouble *y,
                             const gdouble *weight,
                             gint nparam,
                             gdouble *param,
                             const gboolean *fixed_param,
                             const gint *link_map,
                             gpointer user_data);

Performs a nonlinear fit of simple function on data, allowing some fixed parameters.

Initial values of linked (dependent) parameters are overwritten by master values, their `fixed_param` property is ignored and master's property controls whether all are fixed or all variable.

#### Parameters

nlfit | A Marquardt-Levenberg nonlinear fitter. |
ndata | The number of data points in `x` , `y` , `weight` . |
x | Array of independent variable values. |
y | Array of dependent variable values. |
weight | Array of weights associated to each data point (usually equal to inverse squares errors). Can be `NULL`, unit weight is then used for all data. |
nparam | The nuber of parameters. |
param | Array of parameters (of size `nparam` ). Note the parameters must be initialized to reasonably near values. |
fixed_param | Which parameters should be treated as fixed (set corresponding element to `TRUE` for them). May be `NULL` if all parameters are variable. |
link_map | Map of linked parameters. One of linked parameters is master, Values in this array are indices of corresponding master parameter for each parameter (for independent parameters set `link_map` [i] == i). May be `NULL` if all parameter are independent. |
user_data | Pointer that will be passed to the function and derivative |

#### Returns

The final residual sum, a negative number in the case of failure.

### gwy_math_nlfit_fit_idx ()

    gdouble
    gwy_math_nlfit_fit_idx (GwyNLFitter *nlfit,
                            guint ndata,
                            guint nparam,
                            gdouble *param,
                            gpointer user_data);

Performs a nonlinear fit of function on opaque indexed data.

#### Parameters

nlfit | A Marquardt-Levenberg nonlinear fitter. |
ndata | The number of data points in `x` , `y` , `weight` . |
nparam | The nuber of parameters. |
param | Array of parameters (of size `nparam` ). Note the parameters must be initialized to reasonably near values. |
user_data | Pointer that will be passed to the function and derivative |

#### Returns

The final residual sum, a negative number in the case of failure.

Since: 2.46

### gwy_math_nlfit_fit_idx_full ()

    gdouble
    gwy_math_nlfit_fit_idx_full (GwyNLFitter *nlfit,
                                 guint ndata,
                                 guint nparam,
                                 gdouble *param,
                                 const gboolean *fixed_param,
                                 const gint *link_map,
                                 gpointer user_data);

Performs a nonlinear fit of function on opaque indexed data, allowing some fixed parameters.

Initial values of linked (dependent) parameters are overwritten by master values, their `fixed_param` property is ignored and master's property controls whether all are fixed or all variable.

#### Parameters

nlfit | A Marquardt-Levenberg nonlinear fitter. |
ndata | The number of data points in `x` , `y` , `weight` . |
nparam | The nuber of parameters. |
param | Array of parameters (of size `nparam` ). Note the parameters must be initialized to reasonably near values. |
fixed_param | Which parameters should be treated as fixed (set corresponding element to `TRUE` for them). May be `NULL` if all parameters are variable. |
link_map | Map of linked parameters. One of linked parameters is master, Values in this array are indices of corresponding master parameter for each parameter (for independent parameters set `link_map` [i] == i). May be `NULL` if all parameter are independent. |
user_data | Pointer that will be passed to the function and derivative |

#### Returns

The final residual sum, a negative number in the case of failure.

Since: 2.46

### gwy_math_nlfit_get_max_iterations ()

    gint
    gwy_math_nlfit_get_max_iterations (GwyNLFitter *nlfit);

Returns the maximum number of iterations of nonlinear fitter `nlfit` .

#### Parameters

nlfit | A Marquardt-Levenberg nonlinear fitter. |

#### Returns

The maximum number of iterations.

### gwy_math_nlfit_set_max_iterations ()

    void
    gwy_math_nlfit_set_max_iterations (GwyNLFitter *nlfit,
                                       gint maxiter);

Sets the maximum number of iterations for nonlinear fitter `nlfit` .

#### Parameters

nlfit | A Marquardt-Levenberg nonlinear fitter. |
maxiter | The maximum number of iterations. |

### gwy_math_nlfit_get_approx_geometric ()

    gboolean
    gwy_math_nlfit_get_approx_geometric (GwyNLFitter *nlfit);

Reports if a non-linear fitter performs approximately orthogonal fitting.

This function does not do anything useful.

#### Parameters

nlfit | A Marquardt-Levenberg nonlinear fitter. |

#### Returns

`TRUE` if the fitting is approximately orthogonal; `FALSE` for ordinary least squares.

Since: 2.47

### gwy_math_nlfit_set_approx_geometric ()

    void
    gwy_math_nlfit_set_approx_geometric (GwyNLFitter *nlfit,
                                         gboolean setting);

Sets a non-linear fitter to perform ordinary or approximately orthogonal fitting.

This function does not do anything useful. Since 2.56 it is no-op.

#### Parameters

nlfit | A Marquardt-Levenberg nonlinear fitter. |
setting | `TRUE` to approximately orthogonal (geometrical) fitting. |

Since: 2.47

### gwy_math_nlfit_succeeded ()

    gboolean
    gwy_math_nlfit_succeeded (GwyNLFitter *nlfit);

Obtains the status of the last fitting.

Fitting failure can be (and usually should be) also determined by checking for negative return value of `gwy_math_nlfit_fit()` or `gwy_math_nlfit_fit_full()`. This function allows to test it later.

#### Parameters

nlfit | A Marquardt-Levenberg nonlinear fitter. |

#### Returns

`TRUE` if the last fitting suceeded, `FALSE` if it failed.

Since: 2.7

### gwy_math_nlfit_get_dispersion ()

    gdouble
    gwy_math_nlfit_get_dispersion (GwyNLFitter *nlfit);

Returns the residual sum divided by the number of degrees of freedom.

This function can be used only after a successful fit.

#### Parameters

nlfit | A Marquardt-Levenberg nonlinear fitter. |

#### Returns

The dispersion.

### gwy_math_nlfit_get_correlations ()

    gdouble
    gwy_math_nlfit_get_correlations (GwyNLFitter *nlfit,
                                     gint par1,
                                     gint par2);

Returns the correlation coefficient between `par1` -th and `par2` -th parameter.

This function can be used only after a successful fit.

#### Parameters

nlfit | A Marquardt-Levenberg nonlinear fitter. |
par1 | First parameter index. |
par2 | Second parameter index. |

#### Returns

The correlation coefficient.

### gwy_math_nlfit_get_eval ()

    gboolean
    gwy_math_nlfit_get_eval (GwyNLFitter *nlfit);

Gets the state of a nonlinear fitter.

#### Parameters

nlfit | A Marquardt-Levenberg nonlinear fitter. |

#### Returns

`TRUE` if the last fit succeeded, `FALSE` if it failed.

Since: 2.47

### gwy_math_nlfit_get_covar ()

    const gdouble *
    gwy_math_nlfit_get_covar (GwyNLFitter *nlfit);

Gets the covariance matrix of a nonlinear fitter.

The returned matrix may be only used between fits. Any fitting can free and reallocate it.

#### Parameters

nlfit | A Marquardt-Levenberg nonlinear fitter. |

#### Returns

The covariance matrix, as lower triangular matrix, owned by the fitter. The return value will be `NULL` if the last fit did not succeed.

Since: 2.47

### gwy_math_nlfit_get_nparam ()

    gint
    gwy_math_nlfit_get_nparam (GwyNLFitter *nlfit);

Gets the number of parameters of a nonlinear fitter.

The number of parameters determines the size of covariance matrix obtained by `gwy_math_nlfit_get_covar()` and valid arguments for `gwy_math_nlfit_get_correlations()`.

#### Parameters

nlfit | A Marquardt-Levenberg nonlinear fitter. |

#### Returns

The number of parameters for the last fit. If the last fit was not successful zero is returned.

Since: 2.47

### gwy_math_nlfit_get_sigma ()

    gdouble
    gwy_math_nlfit_get_sigma (GwyNLFitter *nlfit,
                              gint par);

Returns the standard deviation of parameter number `par` .

This function makes sense only after a successful fit and for a free parameter.

#### Parameters

nlfit | A Marquardt-Levenberg nonlinear fitter. |
par | Parameter index. |

#### Returns

The SD of `par` -th parameter.

### gwy_math_nlfit_set_callbacks ()

    void
    gwy_math_nlfit_set_callbacks (GwyNLFitter *nlfit,
                                  GwySetFractionFunc set_fraction,
                                  GwySetMessageFunc set_message);

Sets callbacks reporting a non-linear least squares fitter progress.

#### Parameters

nlfit | A Marquardt-Levenberg nonlinear fitter. |
set_fraction | Function that sets fraction to output (or `NULL`). |
set_message | Function that sets message to output (or `NULL`). |

Since: 2.46

### gwy_math_nlfit_diff ()

    void
    gwy_math_nlfit_diff (gdouble x,
                         gint nparam,
                         const gdouble *param,
                         const gboolean *fixed_param,
                         GwyNLFitFunc func,
                         gpointer user_data,
                         gdouble *der,
                         gboolean *success);

Numerically computes the partial derivatives of a function.

#### Parameters

x | The value to compute the derivative at. |
nparam | The nuber of parameters. |
param | Array of parameters (of size `nparam` ). |
fixed_param | Which parameters should be treated as fixed (corresponding entries are set to `TRUE`). |
func | The fitted function. |
user_data | User data to be passed to `func` . |
der | Array where the put the result to. |
success | Set to `TRUE` if succeeds, `FALSE` on failure. |

Since: 2.46

### gwy_math_nlfit_derive ()

    void
    gwy_math_nlfit_derive (gdouble x,
                           gint nparam,
                           const gdouble *param,
                           const gboolean *fixed_param,
                           GwyNLFitFunc func,
                           gpointer user_data,
                           gdouble *der,
                           gboolean *success);

Numerically computes the partial derivatives of a function.

This is a legacy name for function `gwy_math_nlfit_diff()`.

#### Parameters

x | The value to compute the derivative at. |
nparam | The nuber of parameters. |
param | Array of parameters (of size `nparam` ). |
fixed_param | Which parameters should be treated as fixed (corresponding entries are set to `TRUE`). |
func | The fitted function. |
user_data | User data to be passed to `func` . |
der | Array where the put the result to. |
success | Set to `TRUE` if succeeds, `FALSE` on failure. |

### gwy_math_nlfit_diff_idx ()

    void
    gwy_math_nlfit_diff_idx (guint i,
                             gint nparam,
                             const gdouble *param,
                             const gboolean *fixed_param,
                             GwyNLFitIdxFunc func,
                             gpointer user_data,
                             gdouble *der,
                             gboolean *success);

Numerically computes the partial derivatives of an opaque function.

This function cannot be passed as derivative calculation function to `gwy_math_nlfit_new_idx()` because it is not of the GwyNLFitIdxDiffFunc. Just pass `NULL` to `gwy_math_nlfit_new_idx()` if you want automatic numerical derivatives.

You can employ this function in your own GwyNLFitIdxDiffFunc function if you need to modify the derivatives somehow, for instance to apply weighting.

#### Parameters

i | Data index from the set {0, 1, 2, ..., ndata-1}. |
nparam | The nuber of parameters. |
param | Array of parameters (of size `nparam` ). |
fixed_param | Which parameters should be treated as fixed (corresponding entries are set to `TRUE`). |
func | The fitted function. |
user_data | User data to be passed to `func` . |
der | Array where the put the result to. |
success | Set to `TRUE` if succeeds, `FALSE` on failure. |

Since: 2.46

### gwy_math_nlfit_map_free_params ()

    gint
    gwy_math_nlfit_map_free_params (const gboolean *fixed_param,
                                    gint n,
                                    gint *id_map);

Creates a map from free parameter ids to all-parameter ids.

This is a helper function for reduction of full parameter vectors and covariance matrices to only free parameters.

The array `id_map` must at least as many elements as there are free parameters. However, it is usually better to just pass an array of size `n` because the number of free parameters is what this function calculates.

#### Parameters

fixed_param | Which parameters are fixed. |
n | Length of `fixed_param` array. |
id_map | Parameter id map to fill. |

#### Returns

The number of free parameters. This is the number of ids filled in `id_map` .

Since: 2.50

## Types and Values

### struct GwyNLFitter

    struct GwyNLFitter {
        GwyNLFitFunc fmarq;  /* fitting function */
        GwyNLFitDerFunc dmarq;  /* fitting function derivations */
        gint maxiter;  /* max number of iterations */
        gboolean eval;  /* success? */
        gdouble *covar; /* covariance matrix  */
        gdouble dispersion; /* dispersion */
        gdouble mfi;    /* fitting parameters --
                           fi, decrease, increase of lambda, minimum lambda */
        gdouble mdec;
        gdouble minc;
        gdouble mtol;
    };

Non-linear least-squares fitter.

The fields should be considered private.

Use `gwy_math_nlfit_get_eval()`, `gwy_math_nlfit_get_covar()` and `gwy_math_nlfit_get_dispersion()` and `gwy_math_nlfit_succeeded()` to examine the fitter state.

Use `gwy_math_nlfit_set_max_iterations()` to set the maximum iteration.

In rare occasions you might want modify `mdec` or `minc` . The rest is better left untouched.

#### Members

GwyNLFitFunc `fmarq`; | Evaluates the fitted function. |
GwyNLFitDerFunc `dmarq`; | Evaluates derivatives of the fitted function. |
gint `maxiter`; | Maximum number of iteration. |
gboolean `eval`; | `TRUE` if last evaluation succeeded. |
gdouble *`covar`; | Covariance matrix (set upon successful fit). |
gdouble `dispersion`; | Mean residual sum of squares per point, set to -1 on failure. |
gdouble `mfi`; | Lambda parameter is multiplied by it. Probably keep at 1. |
gdouble `mdec`; | Decrease of lambda parameter after an unsuccessful step. |
gdouble `minc`; | Increase of lambda parameter after a successful step. |
gdouble `mtol`; | If lambda parameter becomes zero it is set to this value. |

## See Also

GwyNLFitPreset