This chapter describes routines for performing least squares fits to experimental data using linear combinations of functions.  The data may be weighted or unweighted, i.e. with known or unknown errors.  For weighted data the functions compute the best fit parameters and their associated covariance matrix.  For unweighted data the covariance matrix is estimated from the scatter of the points, giving a variance-covariance matrix.

The functions are divided into separate versions for simple one- or two-parameter regression and multiple-parameter fits.

Overview
========

Least-squares fits are found by minimizing \chi^2 (chi-squared), the weighted sum of squared residuals over n experimental datapoints (x_i, y_i) for the model Y(c,x),

     \chi^2 = \sum_i w_i (y_i - Y(c, x_i))^2

The p parameters of the model are $c = \c_0, c_1, \dots\$ c = {c_0, c_1, ...}.  The weight factors w_i are given by w_i = 1/\sigma_i^2, where \sigma_i is the experimental error on the data-point y_i.  The errors are assumed to be Gaussian and uncorrelated. For unweighted data the chi-squared sum is computed without any weight factors.

The fitting routines return the best-fit parameters c and their p \times p covariance matrix.  The covariance matrix measures the statistical errors on the best-fit parameters resulting from the errors on the data, \sigma_i, and is defined as $C_ab = \langle \delta c_a \delta c_b \rangle$ C_{ab} = <\delta c_a \delta c_b> where $\langle \, \rangle$ < > denotes an average over the Gaussian error distributions of the underlying datapoints.

The covariance matrix is calculated by error propagation from the data errors \sigma_i.  The change in a fitted parameter \delta c_a caused by a small change in the data \delta y_i is given by

     \delta c_a = \sum_i (dc_a/dy_i) \delta y_i

allowing the covariance matrix to be written in terms of the errors on the data,

     C_{ab} = \sum_{i,j} (dc_a/dy_i) (dc_b/dy_j) <\delta y_i \delta y_j>

For uncorrelated data the fluctuations of the underlying datapoints satisfy $\langle \delta y_i \delta y_j \rangle = \sigma_i^2 \delta_ij$ <\delta y_i \delta y_j> = \sigma_i^2 \delta_{ij}, giving a corresponding parameter covariance matrix of

     C_{ab} = \sum_i (1/w_i) (dc_a/dy_i) (dc_b/dy_i)

When computing the covariance matrix for unweighted data, i.e. data with unknown errors, the weight factors w_i in this sum are replaced by the single estimate w = 1/\sigma^2, where \sigma^2 is the computed variance of the residuals about the best-fit model, \sigma^2 = \sum (y_i - Y(c,x_i))^2 / (n-p). This is referred to as the variance-covariance matrix.

The standard deviations of the best-fit parameters are given by the square root of the corresponding diagonal elements of the covariance matrix, $\sigma_c_a = \sqrtC_aa$ \sigma_{c_a} = \sqrt{C_{aa}}. The correlation coefficient of the fit parameters c_a and c_b is given by $\rho_ab = C_ab / \sqrtC_aa C_bb$ \rho_{ab} = C_{ab} / \sqrt{C_{aa} C_{bb}}.

Linear regression
=================

The functions in this section are used to fit simple one or two parameter linear regression models. The functions are declared in the header file gsl_fit.h.

Linear regression with a constant term
--------------------------------------

The functions described in this section can be used to perform least-squares fits to a straight line model, Y(c,x) = c_0 + c_1 x.

 -- Function: int gsl_fit_linear (const double * X, const size_t XSTRIDE, const double * Y, const size_t YSTRIDE, size_t N, double * C0, double * C1, double * COV00, double * COV01, double * COV11, double * SUMSQ)
     This function computes the best-fit linear regression coefficients (C0,C1) of the model Y = c_0 + c_1 X for the dataset (X, Y), two vectors of length N with strides XSTRIDE and YSTRIDE.  The errors on Y are assumed unknown so the variance-covariance matrix for the parameters (C0, C1) is estimated from the scatter of the points around the best-fit line and returned via the parameters (COV00, COV01, COV11). The sum of squares of the residuals from the best-fit line is returned in SUMSQ.  Note: the correlation coefficient of the data can be computed using gsl_stats_correlation (see Correlation), it does not depend on the fit.

 -- Function: int gsl_fit_wlinear (const double * X, const size_t XSTRIDE, const double * W, const size_t WSTRIDE, const double * Y, const size_t YSTRIDE, size_t N, double * C0, double * C1, double * COV00, double * COV01, double * COV11, double * CHISQ)
     This function computes the best-fit linear regression coefficients (C0,C1) of the model Y = c_0 + c_1 X for the weighted dataset (X, Y), two vectors of length N with strides XSTRIDE and YSTRIDE.  The vector W, of length N and stride WSTRIDE, specifies the weight of each datapoint. The weight is the reciprocal of the variance for each datapoint in Y.

     The covariance matrix for the parameters (C0, C1) is computed using the weights and returned via the parameters (COV00, COV01, COV11).  The weighted sum of squares of the residuals from the best-fit line, \chi^2, is returned in CHISQ.

 -- Function: int gsl_fit_linear_est (double X, double C0, double C1, double COV00, double COV01, double COV11, double * Y, double * Y_ERR)
     This function uses the best-fit linear regression coefficients C0, C1 and their covariance COV00, COV01, COV11 to compute the fitted function Y and its standard deviation Y_ERR for the model Y = c_0 + c_1 X at the point X.

Linear regression without a constant term
-----------------------------------------

The functions described in this section can be used to perform least-squares fits to a straight line model without a constant term, Y = c_1 X.

 -- Function: int gsl_fit_mul (const double * X, const size_t XSTRIDE, const double * Y, const size_t YSTRIDE, size_t N, double * C1, double * COV11, double * SUMSQ)
     This function computes the best-fit linear regression coefficient C1 of the model Y = c_1 X for the datasets (X, Y), two vectors of length N with strides XSTRIDE and YSTRIDE.  The errors on Y are assumed unknown so the variance of the parameter C1 is estimated from the scatter of the points around the best-fit line and returned via the parameter COV11.  The sum of squares of the residuals from the best-fit line is returned in SUMSQ.

 -- Function: int gsl_fit_wmul (const double * X, const size_t XSTRIDE, const double * W, const size_t WSTRIDE, const double * Y, const size_t YSTRIDE, size_t N, double * C1, double * COV11, double * SUMSQ)
     This function computes the best-fit linear regression coefficient C1 of the model Y = c_1 X for the weighted datasets (X, Y), two vectors of length N with strides XSTRIDE and YSTRIDE.  The vector W, of length N and stride WSTRIDE, specifies the weight of each datapoint. The weight is the reciprocal of the variance for each datapoint in Y.

     The variance of the parameter C1 is computed using the weights and returned via the parameter COV11.  The weighted sum of squares of the residuals from the best-fit line, \chi^2, is returned in CHISQ.

 -- Function: int gsl_fit_mul_est (double X, double C1, double COV11, double * Y, double * Y_ERR)
     This function uses the best-fit linear regression coefficient C1 and its covariance COV11 to compute the fitted function Y and its standard deviation Y_ERR for the model Y = c_1 X at the point X.

Multi-parameter regression
==========================

This section describes routines which perform least squares fits to a linear model by minimizing the cost function

     \chi^2 = \sum_i w_i (y_i - \sum_j X_ij c_j)^2 = || y - Xc ||_W^2

where y is a vector of n observations, X is an n-by-p matrix of predictor variables, c is a vector of the p unknown best-fit parameters to be estimated, and ||r||_W^2 = r^T W r. The matrix W =  diag(w_1,w_2,...,w_n) defines the weights or uncertainties of the observation vector.

This formulation can be used for fits to any number of functions and/or variables by preparing the n-by-p matrix X appropriately.  For example, to fit to a p-th order polynomial in X, use the following matrix,

     X_{ij} = x_i^j

where the index i runs over the observations and the index j runs from 0 to p-1.

To fit to a set of p sinusoidal functions with fixed frequencies \omega_1, \omega_2, ..., \omega_p, use,

     X_{ij} = sin(\omega_j x_i)

To fit to p independent variables x_1, x_2, ..., x_p, use,

     X_{ij} = x_j(i)

where x_j(i) is the i-th value of the predictor variable x_j.

The solution of the general linear least-squares system requires an additional working space for intermediate results, such as the singular value decomposition of the matrix X.

These functions are declared in the header file gsl_multifit.h.

 -- Function: gsl_multifit_linear_workspace * gsl_multifit_linear_alloc (const size_t N, const size_t P)
     This function allocates a workspace for fitting a model to a maximum of N observations using a maximum of P parameters. The user may later supply a smaller least squares system if desired. The size of the workspace is O(np + p^2).

 -- Function: void gsl_multifit_linear_free (gsl_multifit_linear_workspace * WORK)
     This function frees the memory associated with the workspace W.

 -- Function: int gsl_multifit_linear_svd (const gsl_matrix * X, gsl_multifit_linear_workspace * WORK)
     This function performs a singular value decomposition of the matrix X and stores the SVD factors internally in WORK.

 -- Function: int gsl_multifit_linear_bsvd (const gsl_matrix * X, gsl_multifit_linear_workspace * WORK)
     This function performs a singular value decomposition of the matrix X and stores the SVD factors internally in WORK. The matrix X is first balanced by applying column scaling factors to improve the accuracy of the singular values.

 -- Function: int gsl_multifit_linear (const gsl_matrix * X, const gsl_vector * Y, gsl_vector * C, gsl_matrix * COV, double * CHISQ, gsl_multifit_linear_workspace * WORK)
     This function computes the best-fit parameters C of the model y = X c for the observations Y and the matrix of predictor variables X, using the preallocated workspace provided in WORK.  The p-by-p variance-covariance matrix of the model parameters COV is set to \sigma^2 (X^T X)^-1, where \sigma is the standard deviation of the fit residuals. The sum of squares of the residuals from the best-fit, \chi^2, is returned in CHISQ. If the coefficient of determination is desired, it can be computed from the expression R^2 = 1 - \chi^2 / TSS, where the total sum of squares (TSS) of the observations Y may be computed from gsl_stats_tss.

     The best-fit is found by singular value decomposition of the matrix X using the modified Golub-Reinsch SVD algorithm, with column scaling to improve the accuracy of the singular values. Any components which have zero singular value (to machine precision) are discarded from the fit.

 -- Function: int gsl_multifit_linear_tsvd (const gsl_matrix * X, const gsl_vector * Y, const double TOL, gsl_vector * C, gsl_matrix * COV, double * CHISQ, size_t * RANK, gsl_multifit_linear_workspace * WORK)
     This function computes the best-fit parameters C of the model y = X c for the observations Y and the matrix of predictor variables X, using a truncated SVD expansion. Singular values which satisfy s_i \le tol \times s_0 are discarded from the fit, where s_0 is the largest singular value. The p-by-p variance-covariance matrix of the model parameters COV is set to \sigma^2 (X^T X)^-1, where \sigma is the standard deviation of the fit residuals. The sum of squares of the residuals from the best-fit, \chi^2, is returned in CHISQ. The effective rank (number of singular values used in solution) is returned in RANK. If the coefficient of determination is desired, it can be computed from the expression R^2 = 1 - \chi^2 / TSS, where the total sum of squares (TSS) of the observations Y may be computed from gsl_stats_tss.

 -- Function: int gsl_multifit_wlinear (const gsl_matrix * X, const gsl_vector * W, const gsl_vector * Y, gsl_vector * C, gsl_matrix * COV, double * CHISQ, gsl_multifit_linear_workspace * WORK)
     This function computes the best-fit parameters C of the weighted model y = X c for the observations Y with weights W and the matrix of predictor variables X, using the preallocated workspace provided in WORK.  The p-by-p covariance matrix of the model parameters COV is computed as (X^T W X)^-1. The weighted sum of squares of the residuals from the best-fit, \chi^2, is returned in CHISQ. If the coefficient of determination is desired, it can be computed from the expression R^2 = 1 - \chi^2 / WTSS, where the weighted total sum of squares (WTSS) of the observations Y may be computed from gsl_stats_wtss.

 -- Function: int gsl_multifit_wlinear_tsvd (const gsl_matrix * X, const gsl_vector * W, const gsl_vector * Y, const double TOL, gsl_vector * C, gsl_matrix * COV, double * CHISQ, size_t * RANK, gsl_multifit_linear_workspace * WORK)
     This function computes the best-fit parameters C of the weighted model y = X c for the observations Y with weights W and the matrix of predictor variables X, using a truncated SVD expansion. Singular values which satisfy s_i \le tol \times s_0 are discarded from the fit, where s_0 is the largest singular value. The p-by-p covariance matrix of the model parameters COV is computed as (X^T W X)^-1. The weighted sum of squares of the residuals from the best-fit, \chi^2, is returned in CHISQ. The effective rank of the system (number of singular values used in the solution) is returned in RANK. If the coefficient of determination is desired, it can be computed from the expression R^2 = 1 - \chi^2 / WTSS, where the weighted total sum of squares (WTSS) of the observations Y may be computed from gsl_stats_wtss.

 -- Function: int gsl_multifit_linear_est (const gsl_vector * X, const gsl_vector * C, const gsl_matrix * COV, double * Y, double * Y_ERR)
     This function uses the best-fit multilinear regression coefficients C and their covariance matrix COV to compute the fitted function value Y and its standard deviation Y_ERR for the model y = x.c at the point X.

 -- Function: int gsl_multifit_linear_residuals (const gsl_matrix * X, const gsl_vector * Y, const gsl_vector * C, gsl_vector * R)
     This function computes the vector of residuals r = y - X c for the observations Y, coefficients C and matrix of predictor variables X.

 -- Function: size_t gsl_multifit_linear_rank (const double TOL, const gsl_multifit_linear_workspace * WORK)
     This function returns the rank of the matrix X which must first have its singular value decomposition computed. The rank is computed by counting the number of singular values \sigma_j which satisfy \sigma_j > tol \times \sigma_0, where \sigma_0 is the largest singular value.

Regularized regression
======================

Ordinary weighted least squares models seek a solution vector c which minimizes the residual

     \chi^2 = || y - Xc ||_W^2

where y is the n-by-1 observation vector, X is the n-by-p design matrix, c is the p-by-1 solution vector, W = diag(w_1,...,w_n) is the data weighting matrix, and ||r||_W^2 = r^T W r. In cases where the least squares matrix X is ill-conditioned, small perturbations (ie: noise) in the observation vector could lead to widely different solution vectors c. One way of dealing with ill-conditioned matrices is to use a ``truncated SVD'' in which small singular values, below some given tolerance, are discarded from the solution. The truncated SVD method is available using the functions gsl_multifit_linear_tsvd and gsl_multifit_wlinear_tsvd. Another way to help solve ill-posed problems is to include a regularization term in the least squares minimization

     \chi^2 = || y - Xc ||_W^2 + \lambda^2 || L c ||^2

for a suitably chosen regularization parameter \lambda and matrix L. This type of regularization is known as Tikhonov, or ridge, regression. In some applications, L is chosen as the identity matrix, giving preference to solution vectors c with smaller norms. Including this regularization term leads to the explicit ``normal equations'' solution

     c = ( X^T W X + \lambda^2 L^T L )^-1 X^T W y

which reduces to the ordinary least squares solution when L = 0. In practice, it is often advantageous to transform a regularized least squares system into the form

     \chi^2 = || y~ - X~ c~ ||^2 + \lambda^2 || c~ ||^2

This is known as the Tikhonov ``standard form'' and has the normal equations solution \tildec = \left( \tildeX^T \tildeX + \lambda^2 I \right)^-1 \tildeX^T \tildey. For an m-by-p matrix L which is full rank and has m >= p (ie: L is square or has more rows than columns), we can calculate the ``thin'' QR decomposition of L, and note that ||L c|| = ||R c|| since the Q factor will not change the norm. Since R is p-by-p, we can then use the transformation

     X~ = sqrt(W) X R^-1
     y~ = sqrt(W) y
     c~ = R c

to achieve the standard form. For a rectangular matrix L with m < p, a more sophisticated approach is needed (see Hansen 1998, chapter 2.3). In practice, the normal equations solution above is not desirable due to numerical instabilities, and so the system is solved using the singular value decomposition of the matrix \tildeX. The matrix L is often chosen as the identity matrix, or as a first or second finite difference operator, to ensure a smoothly varying coefficient vector c, or as a diagonal matrix to selectively damp each model parameter differently. If L \ne I, the user must first convert the least squares problem to standard form using gsl_multifit_linear_stdform1 or gsl_multifit_linear_stdform2, solve the system, and then backtransform the solution vector to recover the solution of the original problem (see gsl_multifit_linear_genform1 and gsl_multifit_linear_genform2).

In many regularization problems, care must be taken when choosing the regularization parameter \lambda. Since both the residual norm ||y - X c|| and solution norm ||L c|| are being minimized, the parameter \lambda represents a tradeoff between minimizing either the residuals or the solution vector. A common tool for visualizing the comprimise between the minimization of these two quantities is known as the L-curve. The L-curve is a log-log plot of the residual norm ||y - X c|| on the horizontal axis and the solution norm ||L c|| on the vertical axis. This curve nearly always as an L shaped appearance, with a distinct corner separating the horizontal and vertical sections of the curve. The regularization parameter corresponding to this corner is often chosen as the optimal value. GSL provides routines to calculate the L-curve for all relevant regularization parameters as well as locating the corner.

Another method of choosing the regularization parameter is known as Generalized Cross Validation (GCV). This method is based on the idea that if an arbitrary element y_i is left out of the right hand side, the resulting regularized solution should predict this element accurately. This leads to choosing the parameter \lambda which minimizes the GCV function

     G(\lambda) = (||y - X c_{\lambda}||^2) / Tr(I_n - X X^I)^2

where X_\lambda^I is the matrix which relates the solution c_\lambda to the right hand side y, ie: c_\lambda = X_\lambda^I y. GSL provides routines to compute the GCV curve and its minimum.

For most applications, the steps required to solve a regularized least squares problem are as follows:

 1. Construct the least squares system (X, y, W, L)

 2. Transform the system to standard form (\tildeX,\tildey). This step can be skipped if L = I_p and W = I_n.

 3. Calculate the SVD of \tildeX.

 4. Determine an appropriate regularization parameter \lambda (using for example L-curve or GCV analysis).

 5. Solve the standard form system using the chosen \lambda and the SVD of \tildeX.

 6. Backtransform the standard form solution \tildec to recover the original solution vector c.

 -- Function: int gsl_multifit_linear_stdform1 (const gsl_vector * L, const gsl_matrix * X, const gsl_vector * Y, gsl_matrix * XS, gsl_vector * YS, gsl_multifit_linear_workspace * WORK)
 -- Function: int gsl_multifit_linear_wstdform1 (const gsl_vector * L, const gsl_matrix * X, const gsl_vector * W, const gsl_vector * Y, gsl_matrix * XS, gsl_vector * YS, gsl_multifit_linear_workspace * WORK)
     These functions define a regularization matrix L = diag(l_0,l_1,...,l_p-1). The diagonal matrix element l_i is provided by the ith element of the input vector L. The n-by-p least squares matrix X and vector Y of length n are then converted to standard form as described above and the parameters (\tildeX,\tildey) are stored in XS and YS on output.  XS and YS have the same dimensions as X and Y. Optional data weights may be supplied in the vector W of length n. In order to apply this transformation, L^-1 must exist and so none of the l_i may be zero. After the standard form system has been solved, use gsl_multifit_linear_genform1 to recover the original solution vector. It is allowed to have X = XS and Y = YS for an in-place transform. In order to perform a weighted regularized fit with L = I, the user may call gsl_multifit_linear_applyW to convert to standard form.

 -- Function: int gsl_multifit_linear_L_decomp (gsl_matrix * L, gsl_vector * TAU)
     This function factors the m-by-p regularization matrix L into a form needed for the later transformation to standard form. L may have any number of rows m. If m \ge p the QR decomposition of L is computed and stored in L on output. If m < p, the QR decomposition of L^T is computed and stored in L on output. On output, the Householder scalars are stored in the vector TAU of size MIN(m,p). These outputs will be used by gsl_multifit_linear_wstdform2 to complete the transformation to standard form.

 -- Function: int gsl_multifit_linear_stdform2 (const gsl_matrix * LQR, const gsl_vector * LTAU, const gsl_matrix * X, const gsl_vector * Y, gsl_matrix * XS, gsl_vector * YS, gsl_matrix * M, gsl_multifit_linear_workspace * WORK)
 -- Function: int gsl_multifit_linear_wstdform2 (const gsl_matrix * LQR, const gsl_vector * LTAU, const gsl_matrix * X, const gsl_vector * W, const gsl_vector * Y, gsl_matrix * XS, gsl_vector * YS, gsl_matrix * M, gsl_multifit_linear_workspace * WORK)
     These functions convert the least squares system (X,Y,W,L) to standard form (\tildeX,\tildey) which are stored in XS and YS respectively. The m-by-p regularization matrix L is specified by the inputs LQR and LTAU, which are outputs from gsl_multifit_linear_L_decomp. The dimensions of the standard form parameters (\tildeX,\tildey) depend on whether m is larger or less than p. For m \ge p, XS is n-by-p, YS is n-by-1, and M is not used. For m < p, XS is (n - p + m)-by-m, YS is (n - p + m)-by-1, and M is additional n-by-p workspace, which is required to recover the original solution vector after the system has been solved (see gsl_multifit_linear_genform2). Optional data weights may be supplied in the vector W of length n, where W = diag(w).

 -- Function: int gsl_multifit_linear_solve (const double LAMBDA, const gsl_matrix * XS, const gsl_vector * YS, gsl_vector * CS, double * RNORM, double * SNORM, gsl_multifit_linear_workspace * WORK)
     This function computes the regularized best-fit parameters \tildec which minimize the cost function \chi^2 = || \tildey - \tildeX \tildec ||^2 + \lambda^2 || \tildec ||^2 which is in standard form. The least squares system must therefore be converted to standard form prior to calling this function. The observation vector \tildey is provided in YS and the matrix of predictor variables \tildeX in XS. The solution vector \tildec is returned in CS, which has length min(m,p). The SVD of XS must be computed prior to calling this function, using gsl_multifit_linear_svd. The regularization parameter \lambda is provided in LAMBDA. The residual norm || \tildey - \tildeX \tildec || = ||y - X c||_W is returned in RNORM. The solution norm || \tildec || = ||L c|| is returned in SNORM.

 -- Function: int gsl_multifit_linear_genform1 (const gsl_vector * L, const gsl_vector * CS, gsl_vector * C, gsl_multifit_linear_workspace * WORK)
     After a regularized system has been solved with L = diag(\l_0,\l_1,...,\l_p-1), this function backtransforms the standard form solution vector CS to recover the solution vector of the original problem C. The diagonal matrix elements l_i are provided in the vector L. It is allowed to have C = CS for an in-place transform.

 -- Function: int gsl_multifit_linear_genform2 (const gsl_matrix * LQR, const gsl_vector * LTAU, const gsl_matrix * X, const gsl_vector * Y, const gsl_vector * CS, const gsl_matrix * M, gsl_vector * C, gsl_multifit_linear_workspace * WORK)
 -- Function: int gsl_multifit_linear_wgenform2 (const gsl_matrix * LQR, const gsl_vector * LTAU, const gsl_matrix * X, const gsl_vector * W, const gsl_vector * Y, const gsl_vector * CS, const gsl_matrix * M, gsl_vector * C, gsl_multifit_linear_workspace * WORK)
     After a regularized system has been solved with a general rectangular matrix L, specified by (LQR,LTAU), this function backtransforms the standard form solution CS to recover the solution vector of the original problem, which is stored in C, of length p. The original least squares matrix and observation vector are provided in X and Y respectively. M is the matrix computed by gsl_multifit_linear_stdform2. For weighted fits, the weight vector W must also be supplied.

 -- Function: int gsl_multifit_linear_applyW (const gsl_matrix * X, const gsl_vector * W, const gsl_vector * Y, gsl_matrix * WX, gsl_vector * WY)
     For weighted least squares systems with L = I, this function may be used to convert the system to standard form by applying the weight matrix W = diag(W) to the least squares matrix X and observation vector Y. On output, WX is equal to W^1/2 X and WY is equal to W^1/2 y. It is allowed for WX = X and WY = Y for an in-place transform.

 -- Function: int gsl_multifit_linear_lcurve (const gsl_vector * Y, gsl_vector * REG_PARAM, gsl_vector * RHO, gsl_vector * ETA, gsl_multifit_linear_workspace * WORK)
     This function computes the L-curve for a least squares system using the right hand side vector Y and the SVD decomposition of the least squares matrix X, which must be provided to gsl_multifit_linear_svd prior to calling this function. The output vectors REG_PARAM, RHO, and ETA must all be the same size, and will contain the regularization parameters \lambda_i, residual norms ||y - X c_i||, and solution norms || L c_i || which compose the L-curve, where c_i is the regularized solution vector corresponding to \lambda_i. The user may determine the number of points on the L-curve by adjusting the size of these input arrays. The regularization parameters \lambda_i are estimated from the singular values of X, and chosen to represent the most relevant portion of the L-curve.

 -- Function: int gsl_multifit_linear_lcorner (const gsl_vector * RHO, const gsl_vector * ETA, size_t * IDX)
     This function attempts to locate the corner of the L-curve (||y - X c||, ||L c||) defined by the RHO and ETA input arrays respectively. The corner is defined as the point of maximum curvature of the L-curve in log-log scale. The RHO and ETA arrays can be outputs of gsl_multifit_linear_lcurve. The algorithm used simply fits a circle to 3 consecutive points on the L-curve and uses the circle's radius to determine the curvature at the middle point. Therefore, the input array sizes must be \ge 3. With more points provided for the L-curve, a better estimate of the curvature can be obtained. The array index corresponding to maximum curvature (ie: the corner) is returned in IDX. If the input arrays contain colinear points, this function could fail and return GSL_EINVAL.

 -- Function: int gsl_multifit_linear_lcorner2 (const gsl_vector * REG_PARAM, const gsl_vector * ETA, size_t * IDX)
     This function attempts to locate the corner of an alternate L-curve (\lambda^2, ||L c||^2) studied by Rezghi and Hosseini, 2009. This alternate L-curve can provide better estimates of the regularization parameter for smooth solution vectors. The regularization parameters \lambda and solution norms ||L c|| are provided in the REG_PARAM and ETA input arrays respectively. The corner is defined as the point of maximum curvature of this alternate L-curve in linear scale. The REG_PARAM and ETA arrays can be outputs of gsl_multifit_linear_lcurve. The algorithm used simply fits a circle to 3 consecutive points on the L-curve and uses the circle's radius to determine the curvature at the middle point. Therefore, the input array sizes must be \ge 3. With more points provided for the L-curve, a better estimate of the curvature can be obtained. The array index corresponding to maximum curvature (ie: the corner) is returned in IDX. If the input arrays contain colinear points, this function could fail and return GSL_EINVAL.

 -- Function: int gsl_multifit_linear_gcv_init(const gsl_vector * Y, gsl_vector * REG_PARAM, gsl_vector * UTY, double * DELTA0, gsl_multifit_linear_workspace * WORK)
     This function performs some initialization in preparation for computing the GCV curve and its minimum. The right hand side vector is provided in Y. On output, REG_PARAM is set to a vector of regularization parameters in decreasing order and may be of any size. The vector UTY of size p is set to U^T y. The parameter DELTA0 is needed for subsequent steps of the GCV calculation.

 -- Function: int gsl_multifit_linear_gcv_curve(const gsl_vector * REG_PARAM, const gsl_vector * UTY, const double DELTA0, gsl_vector * G, gsl_multifit_linear_workspace * WORK)
     This funtion calculates the GCV curve G(\lambda) and stores it in G on output, which must be the same size as REG_PARAM. The inputs REG_PARAM, UTY and DELTA0 are computed in gsl_multifit_linear_gcv_init.

 -- Function: int gsl_multifit_linear_gcv_min(const gsl_vector * REG_PARAM, const gsl_vector * UTY, const gsl_vector * G, const double DELTA0, double * LAMBDA, gsl_multifit_linear_workspace * WORK)
     This function computes the value of the regularization parameter which minimizes the GCV curve G(\lambda) and stores it in LAMBDA. The input G is calculated by gsl_multifit_linear_gcv_curve and the inputs REG_PARAM, UTY and DELTA0 are computed by gsl_multifit_linear_gcv_init.

 -- Function: double gsl_multifit_linear_gcv_calc(const double LAMBDA, const gsl_vector * UTY, const double DELTA0, gsl_multifit_linear_workspace * WORK)
     This function returns the value of the GCV curve G(\lambda) corresponding to the input LAMBDA.

 -- Function: int gsl_multifit_linear_gcv(const gsl_vector * Y, gsl_vector * REG_PARAM, gsl_vector * G, double * LAMBDA, double * G_LAMBDA, gsl_multifit_linear_workspace * WORK)
     This function combines the steps gcv_init, gcv_curve, and gcv_min defined above into a single function. The input Y is the right hand side vector. On output, REG_PARAM and G, which must be the same size, are set to vectors of \lambda and G(\lambda) values respectively. The output LAMBDA is set to the optimal value of \lambda which minimizes the GCV curve. The minimum value of the GCV curve is returned in G_LAMBDA.

 -- Function: int gsl_multifit_linear_Lk (const size_t P, const size_t K, gsl_matrix * L)
     This function computes the discrete approximation to the derivative operator L_k of order K on a regular grid of P points and stores it in L. The dimensions of L are (p-k)-by-p.

 -- Function: int gsl_multifit_linear_Lsobolev (const size_t P, const size_t KMAX, const gsl_vector * ALPHA, gsl_matrix * L, gsl_multifit_linear_workspace * WORK)
     This function computes the regularization matrix L corresponding to the weighted Sobolov norm ||L c||^2 = \sum_k \alpha_k^2 ||L_k c||^2 where L_k approximates the derivative operator of order k. This regularization norm can be useful in applications where it is necessary to smooth several derivatives of the solution. P is the number of model parameters, KMAX is the highest derivative to include in the summation above, and ALPHA is the vector of weights of size KMAX + 1, where ALPHA[k] = \alpha_k is the weight assigned to the derivative of order k.  The output matrix L is size P-by-P and upper triangular.

 -- Function: double gsl_multifit_linear_rcond (const gsl_multifit_linear_workspace * WORK)
     This function returns the reciprocal condition number of the least squares matrix X, defined as the ratio of the smallest and largest singular values, rcond = \sigma_min/\sigma_max. The routine gsl_multifit_linear_svd must first be called to compute the SVD of X.

Robust linear regression
========================

Ordinary least squares (OLS) models are often heavily influenced by the presence of outliers. Outliers are data points which do not follow the general trend of the other observations, although there is strictly no precise definition of an outlier. Robust linear regression refers to regression algorithms which are robust to outliers. The most common type of robust regression is M-estimation. The general M-estimator minimizes the objective function

     \sum_i \rho(e_i) = \sum_i \rho (y_i - Y(c, x_i))

where e_i = y_i - Y(c, x_i) is the residual of the ith data point, and \rho(e_i) is a function which should have the following properties:

  \rho(e) \ge 0

  \rho(0) = 0

  \rho(-e) = \rho(e)

  \rho(e_1) > \rho(e_2) for |e_1| > |e_2|

The special case of ordinary least squares is given by \rho(e_i) = e_i^2. Letting \psi = \rho' be the derivative of \rho, differentiating the objective function with respect to the coefficients c and setting the partial derivatives to zero produces the system of equations

     \sum_i \psi(e_i) X_i = 0

where X_i is a vector containing row i of the design matrix X. Next, we define a weight function w(e) = \psi(e)/e, and let w_i = w(e_i):

     \sum_i w_i e_i X_i = 0

This system of equations is equivalent to solving a weighted ordinary least squares problem, minimizing \chi^2 = \sum_i w_i e_i^2. The weights however, depend on the residuals e_i, which depend on the coefficients c, which depend on the weights. Therefore, an iterative solution is used, called Iteratively Reweighted Least Squares (IRLS).

 1. Compute initial estimates of the coefficients c^(0) using ordinary least squares

 2. For iteration k, form the residuals e_i^(k) = (y_i - X_i c^(k-1))/(t \sigma^(k) \sqrt1 - h_i), where t is a tuning constant depending on the choice of \psi, and h_i are the statistical leverages (diagonal elements of the matrix X (X^T X)^-1 X^T). Including t and h_i in the residual calculation has been shown to improve the convergence of the method. The residual standard deviation is approximated as \sigma^(k) = MAD / 0.6745, where MAD is the Median-Absolute-Deviation of the n-p largest residuals from the previous iteration.

 3. Compute new weights w_i^(k) = \psi(e_i^(k))/e_i^(k).

 4. Compute new coefficients c^(k) by solving the weighted least squares problem with weights w_i^(k).

 5. Steps 2 through 4 are iterated until the coefficients converge or until some maximum iteration limit is reached. Coefficients are tested for convergence using the critera:

          |c_i^(k) - c_i^(k-1)| \le \epsilon \times max(|c_i^(k)|, |c_i^(k-1)|)

     for all 0 \le i < p where \epsilon is a small tolerance factor.

The key to this method lies in selecting the function \psi(e_i) to assign smaller weights to large residuals, and larger weights to smaller residuals. As the iteration proceeds, outliers are assigned smaller and smaller weights, eventually having very little or no effect on the fitted model.

 -- Function: gsl_multifit_robust_workspace * gsl_multifit_robust_alloc (const gsl_multifit_robust_type * T, const size_t N, const size_t P)
     This function allocates a workspace for fitting a model to N observations using P parameters. The size of the workspace is O(np + p^2). The type T specifies the function \psi and can be selected from the following choices.
      -- Robust type: gsl_multifit_robust_default
          This specifies the gsl_multifit_robust_bisquare type (see below) and is a good general purpose choice for robust regression.

      -- Robust type: gsl_multifit_robust_bisquare
          This is Tukey's biweight (bisquare) function and is a good general purpose choice for robust regression. The weight function is given by

               w(e) = (1 - e^2)^2

          and the default tuning constant is t = 4.685.

      -- Robust type: gsl_multifit_robust_cauchy
          This is Cauchy's function, also known as the Lorentzian function. This function does not guarantee a unique solution, meaning different choices of the coefficient vector C could minimize the objective function. Therefore this option should be used with care. The weight function is given by

               w(e) = 1 / (1 + e^2)

          and the default tuning constant is t = 2.385.

      -- Robust type: gsl_multifit_robust_fair
          This is the fair \rho function, which guarantees a unique solution and has continuous derivatives to three orders. The weight function is given by

               w(e) = 1 / (1 + |e|)

          and the default tuning constant is t = 1.400.

      -- Robust type: gsl_multifit_robust_huber
          This specifies Huber's \rho function, which is a parabola in the vicinity of zero and increases linearly for a given threshold |e| > t. This function is also considered an excellent general purpose robust estimator, however, occasional difficulties can be encountered due to the discontinuous first derivative of the \psi function. The weight function is given by

               w(e) = 1/max(1,|e|)

          and the default tuning constant is t = 1.345.

      -- Robust type: gsl_multifit_robust_ols
          This specifies the ordinary least squares solution, which can be useful for quickly checking the difference between the various robust and OLS solutions. The weight function is given by

               w(e) = 1

          and the default tuning constant is t = 1.

      -- Robust type: gsl_multifit_robust_welsch
          This specifies the Welsch function which can perform well in cases where the residuals have an exponential distribution. The weight function is given by

               w(e) = \exp(-e^2)

          and the default tuning constant is t = 2.985.

 -- Function: void gsl_multifit_robust_free (gsl_multifit_robust_workspace * W)
     This function frees the memory associated with the workspace W.

 -- Function: const char * gsl_multifit_robust_name (const gsl_multifit_robust_workspace * W)
     This function returns the name of the robust type T specified to gsl_multifit_robust_alloc.

 -- Function: int gsl_multifit_robust_tune (const double TUNE, gsl_multifit_robust_workspace * W)
     This function sets the tuning constant t used to adjust the residuals at each iteration to TUNE. Decreasing the tuning constant increases the downweight assigned to large residuals, while increasing the tuning constant decreases the downweight assigned to large residuals.

 -- Function: int gsl_multifit_robust_maxiter (const size_t MAXITER, gsl_multifit_robust_workspace * W)
     This function sets the maximum number of iterations in the iteratively reweighted least squares algorithm to MAXITER. By default, this value is set to 100 by gsl_multifit_robust_alloc.

 -- Function: int gsl_multifit_robust_weights (const gsl_vector * R, gsl_vector * WTS, gsl_multifit_robust_workspace * W)
     This function assigns weights to the vector WTS using the residual vector R and previously specified weighting function. The output weights are given by wts_i = w(r_i / (t \sigma)), where the weighting functions w are detailed in gsl_multifit_robust_alloc. \sigma is an estimate of the residual standard deviation based on the Median-Absolute-Deviation and t is the tuning constant. This function is useful if the user wishes to implement their own robust regression rather than using the supplied gsl_multifit_robust routine below.

 -- Function: int gsl_multifit_robust (const gsl_matrix * X, const gsl_vector * Y, gsl_vector * C, gsl_matrix * COV, gsl_multifit_robust_workspace * W)
     This function computes the best-fit parameters C of the model y = X c for the observations Y and the matrix of predictor variables X, attemping to reduce the influence of outliers using the algorithm outlined above. The p-by-p variance-covariance matrix of the model parameters COV is estimated as \sigma^2 (X^T X)^-1, where \sigma is an approximation of the residual standard deviation using the theory of robust regression. Special care must be taken when estimating \sigma and other statistics such as R^2, and so these are computed internally and are available by calling the function gsl_multifit_robust_statistics.

     If the coefficients do not converge within the maximum iteration limit, the function returns GSL_EMAXITER. In this case, the current estimates of the coefficients and covariance matrix are returned in C and COV and the internal fit statistics are computed with these estimates.

 -- Function: int gsl_multifit_robust_est (const gsl_vector * X, const gsl_vector * C, const gsl_matrix * COV, double * Y, double * Y_ERR)
     This function uses the best-fit robust regression coefficients C and their covariance matrix COV to compute the fitted function value Y and its standard deviation Y_ERR for the model y = x.c at the point X.

 -- Function: int gsl_multifit_robust_residuals (const gsl_matrix * X, const gsl_vector * Y, const gsl_vector * C, gsl_vector * R, gsl_multifit_robust_workspace * W)
     This function computes the vector of studentized residuals r_i = y_i - (X c)_i \over \sigma \sqrt1 - h_i for the observations Y, coefficients C and matrix of predictor variables X. The routine gsl_multifit_robust must first be called to compute the statisical leverages h_i of the matrix X and residual standard deviation estimate \sigma.

 -- Function: gsl_multifit_robust_stats gsl_multifit_robust_statistics (const gsl_multifit_robust_workspace * W)
     This function returns a structure containing relevant statistics from a robust regression. The function gsl_multifit_robust must be called first to perform the regression and calculate these statistics. The returned gsl_multifit_robust_stats structure contains the following fields.

       double sigma_ols This contains the standard deviation of the residuals as computed from ordinary least squares (OLS).

       double sigma_mad This contains an estimate of the standard deviation of the final residuals using the Median-Absolute-Deviation statistic

       double sigma_rob This contains an estimate of the standard deviation of the final residuals from the theory of robust regression (see Street et al, 1988).

       double sigma This contains an estimate of the standard deviation of the final residuals by attemping to reconcile sigma_rob and sigma_ols in a reasonable way.

       double Rsq This contains the R^2 coefficient of determination statistic using the estimate sigma.

       double adj_Rsq This contains the adjusted R^2 coefficient of determination statistic using the estimate sigma.

       double rmse This contains the root mean squared error of the final residuals

       double sse This contains the residual sum of squares taking into account the robust covariance matrix.

       size_t dof This contains the number of degrees of freedom n - p

       size_t numit Upon successful convergence, this contains the number of iterations performed

       gsl_vector * weights This contains the final weight vector of length N

       gsl_vector * r This contains the final residual vector of length N, r = y - X c

Large dense linear systems
==========================

This module is concerned with solving large dense least squares systems X c = y where the n-by-p matrix X has n >> p (ie: many more rows than columns). This type of matrix is called a ``tall skinny'' matrix, and for some applications, it may not be possible to fit the entire matrix in memory at once to use the standard SVD approach. Therefore, the algorithms in this module are designed to allow the user to construct smaller blocks of the matrix X and accumulate those blocks into the larger system one at a time. The algorithms in this module never need to store the entire matrix X in memory. The large linear least squares routines support data weights and Tikhonov regularization, and are designed to minimize the residual

     \chi^2 = || y - Xc ||_W^2 + \lambda^2 || L c ||^2

where y is the n-by-1 observation vector, X is the n-by-p design matrix, c is the p-by-1 solution vector, W = diag(w_1,...,w_n) is the data weighting matrix, L is an m-by-p regularization matrix, \lambda is a regularization parameter, and ||r||_W^2 = r^T W r. In the discussion which follows, we will assume that the system has been converted into Tikhonov standard form,

     \chi^2 = || y~ - X~ c~ ||^2 + \lambda^2 || c~ ||^2

and we will drop the tilde characters from the various parameters. For a discussion of the transformation to standard form see Regularized regression.

The basic idea is to partition the matrix X and observation vector y as

     [ X_1 ] c = [ y_1 ]
     [ X_2 ]     [ y_2 ]
     [ X_3 ]     [ y_3 ]
     [ ... ]     [ ... ]
     [ X_k ]     [ y_k ]

into k blocks, where each block (X_i,y_i) may have any number of rows, but each X_i has p columns. The sections below describe the methods available for solving this partitioned system. The functions are declared in the header file gsl_multilarge.h.

Normal Equations Approach
-------------------------

The normal equations approach to the large linear least squares problem described above is popular due to its speed and simplicity. Since the normal equations solution to the problem is given by

     c = ( X^T X + \lambda^2 I )^-1 X^T y

only the p-by-p matrix X^T X and p-by-1 vector X^T y need to be stored. Using the partition scheme described above, these are given by

     X^T X = \sum_i X_i^T X_i
     X^T y = \sum_i X_i^T y_i

Since the matrix X^T X is symmetric, only half of it needs to be calculated. Once all of the blocks (X_i,y_i) have been accumulated into the final X^T X and X^T y, the system can be solved with a Cholesky factorization of the X^T X matrix. If the Cholesky factorization fails (occasionally due to numerical rounding errors), a QR decomposition is then used. In both cases, the X^T X matrix is first transformed via a diagonal scaling transformation to attempt to reduce its condition number as much as possible to recover a more accurate solution vector. The normal equations approach is the fastest method for solving the large least squares problem, and is accurate for well-conditioned matrices X. However, for ill-conditioned matrices, as is often the case for large systems, this method can suffer from numerical instabilities (see Trefethen and Bau, 1997).  The number of operations for this method is O(np^2 + 1 \over 3p^3).

Tall Skinny QR (TSQR) Approach
------------------------------

An algorithm which has better numerical stability for ill-conditioned problems is known as the Tall Skinny QR (TSQR) method. This method is based on computing the thin QR decomposition of the least squares matrix X = Q R, where Q is an n-by-p matrix with orthogonal columns, and R is a p-by-p upper triangular matrix. Once these factors are calculated, the residual becomes

     \chi^2 = || Q^T y - R c ||^2 + \lambda^2 || c ||^2

which can be written as the matrix equation

     [ R ; \lambda I ] c = [ Q^T b ; 0 ]

The matrix on the left hand side is now a much smaller 2p-by-p matrix which can be solved with a standard SVD approach. The Q matrix is just as large as the original matrix X, however it does not need to be explicitly constructed. The TSQR algorithm computes only the p-by-p matrix R and the p-by-1 vector Q^T y, and updates these quantities as new blocks are added to the system. Each time a new block of rows (X_i,y_i) is added, the algorithm performs a QR decomposition of the matrix

     [ R_(i-1) ; X_i ]

where R_i-1 is the upper triangular R factor for the matrix

     [ X_1 ; ... ; X_(i-1) ]

This QR decomposition is done efficiently taking into account the sparse structure of R_i-1. See Demmel et al, 2008 for more details on how this is accomplished. The number of operations for this method is O(2np^2 - 2 \over 3p^3).

Large Dense Linear Systems Solution Steps
-----------------------------------------

The typical steps required to solve large regularized linear least squares problems are as follows:

 1. Choose the regularization matrix L.

 2. Construct a block of rows of the least squares matrix, right hand side vector, and weight vector (X_i, y_i, w_i).

 3. Transform the block to standard form (\tildeX_i,\tildey_i). This step can be skipped if L = I and W = I.

 4. Accumulate the standard form block (\tildeX_i,\tildey_i) into the system.

 5. Repeat steps 2-4 until the entire matrix and right hand side vector have been accumulated.

 6. Determine an appropriate regularization parameter \lambda (using for example L-curve analysis).

 7. Solve the standard form system using the chosen \lambda.

 8. Backtransform the standard form solution \tildec to recover the original solution vector c.

Large Dense Linear Least Squares Routines
-----------------------------------------

 -- Function: gsl_multilarge_linear_workspace * gsl_multilarge_linear_alloc (const gsl_multilarge_linear_type * T, const size_t P)
     This function allocates a workspace for solving large linear least squares systems. The least squares matrix X has P columns, but may have any number of rows. The parameter T specifies the method to be used for solving the large least squares system and may be selected from the following choices

      -- Multilarge type: gsl_multilarge_linear_normal
          This specifies the normal equations approach for solving the least squares system. This method is suitable in cases where performance is critical and it is known that the least squares matrix X is well conditioned. The size of this workspace is O(p^2).

      -- Multilarge type: gsl_multilarge_linear_tsqr
          This specifies the sequential Tall Skinny QR (TSQR) approach for solving the least squares system. This method is a good general purpose choice for large systems, but requires about twice as many operations as the normal equations method for n >> p. The size of this workspace is O(p^2).

 -- Function: void gsl_multilarge_linear_free (gsl_multilarge_linear_workspace * W)
     This function frees the memory associated with the workspace W.

 -- Function: const char * gsl_multilarge_linear_name (gsl_multilarge_linear_workspace * W)
     This function returns a string pointer to the name of the multilarge solver.

 -- Function: int gsl_multilarge_linear_reset (gsl_multilarge_linear_workspace * W)
     This function resets the workspace W so it can begin to accumulate a new least squares system.

 -- Function: int gsl_multilarge_linear_stdform1 (const gsl_vector * L, const gsl_matrix * X, const gsl_vector * Y, gsl_matrix * XS, gsl_vector * YS, gsl_multilarge_linear_workspace * WORK)
 -- Function: int gsl_multilarge_linear_wstdform1 (const gsl_vector * L, const gsl_matrix * X, const gsl_vector * W, const gsl_vector * Y, gsl_matrix * XS, gsl_vector * YS, gsl_multilarge_linear_workspace * WORK)
     These functions define a regularization matrix L = diag(l_0,l_1,...,l_p-1). The diagonal matrix element l_i is provided by the ith element of the input vector L. The block (X,Y) is converted to standard form and the parameters (\tildeX,\tildey) are stored in XS and YS on output.  XS and YS have the same dimensions as X and Y. Optional data weights may be supplied in the vector W. In order to apply this transformation, L^-1 must exist and so none of the l_i may be zero. After the standard form system has been solved, use gsl_multilarge_linear_genform1 to recover the original solution vector. It is allowed to have X = XS and Y = YS for an in-place transform.

 -- Function: int gsl_multilarge_linear_L_decomp (gsl_matrix * L, gsl_vector * TAU)
     This function calculates the QR decomposition of the m-by-p regularization matrix L. L must have m \ge p.  On output, the Householder scalars are stored in the vector TAU of size p. These outputs will be used by gsl_multilarge_linear_wstdform2 to complete the transformation to standard form.

 -- Function: int gsl_multilarge_linear_stdform2 (const gsl_matrix * LQR, const gsl_vector * LTAU, const gsl_matrix * X, const gsl_vector * Y, gsl_matrix * XS, gsl_vector * YS, gsl_multilarge_linear_workspace * WORK)
 -- Function: int gsl_multilarge_linear_wstdform2 (const gsl_matrix * LQR, const gsl_vector * LTAU, const gsl_matrix * X, const gsl_vector * W, const gsl_vector * Y, gsl_matrix * XS, gsl_vector * YS, gsl_multilarge_linear_workspace * WORK)
     These functions convert a block of rows (X,Y,W) to standard form (\tildeX,\tildey) which are stored in XS and YS respectively. X, Y, and W must all have the same number of rows. The m-by-p regularization matrix L is specified by the inputs LQR and LTAU, which are outputs from gsl_multilarge_linear_L_decomp. XS and YS have the same dimensions as X and Y. After the standard form system has been solved, use gsl_multilarge_linear_genform2 to recover the original solution vector. Optional data weights may be supplied in the vector W, where W = diag(w).

 -- Function: int gsl_multilarge_linear_accumulate (gsl_matrix * X, gsl_vector * Y, gsl_multilarge_linear_workspace * W)
     This function accumulates the standard form block (X,y) into the current least squares system. X and Y have the same number of rows, which can be arbitrary.  X must have p columns. For the TSQR method, X and Y are destroyed on output. For the normal equations method, they are both unchanged.

 -- Function: int gsl_multilarge_linear_solve (const double LAMBDA, gsl_vector * C, double * RNORM, double * SNORM, gsl_multilarge_linear_workspace * W)
     After all blocks (X_i,y_i) have been accumulated into the large least squares system, this function will compute the solution vector which is stored in C on output. The regularization parameter \lambda is provided in LAMBDA. On output, RNORM contains the residual norm ||y - X c||_W and SNORM contains the solution norm ||L c||.

 -- Function: int gsl_multilarge_linear_genform1 (const gsl_vector * L, const gsl_vector * CS, gsl_vector * C, gsl_multilarge_linear_workspace * WORK)
     After a regularized system has been solved with L = diag(\l_0,\l_1,...,\l_p-1), this function backtransforms the standard form solution vector CS to recover the solution vector of the original problem C. The diagonal matrix elements l_i are provided in the vector L. It is allowed to have C = CS for an in-place transform.

 -- Function: int gsl_multilarge_linear_genform2 (const gsl_matrix * LQR, const gsl_vector * LTAU, const gsl_vector * CS, gsl_vector * C, gsl_multilarge_linear_workspace * WORK)
     After a regularized system has been solved with a regularization matrix L, specified by (LQR,LTAU), this function backtransforms the standard form solution CS to recover the solution vector of the original problem, which is stored in C, of length p.

 -- Function: int gsl_multilarge_linear_lcurve (gsl_vector * REG_PARAM, gsl_vector * RHO, gsl_vector * ETA, gsl_multilarge_linear_workspace * WORK)
     This function computes the L-curve for a large least squares system after it has been fully accumulated into the workspace WORK. The output vectors REG_PARAM, RHO, and ETA must all be the same size, and will contain the regularization parameters \lambda_i, residual norms ||y - X c_i||, and solution norms || L c_i || which compose the L-curve, where c_i is the regularized solution vector corresponding to \lambda_i. The user may determine the number of points on the L-curve by adjusting the size of these input arrays. For the TSQR method, the regularization parameters \lambda_i are estimated from the singular values of the triangular R factor. For the normal equations method, they are estimated from the eigenvalues of the X^T X matrix.

 -- Function: int gsl_multilarge_linear_rcond (double * RCOND, gsl_multilarge_linear_workspace * WORK)
     This function computes the reciprocal condition number, stored in RCOND, of the least squares matrix after it has been accumulated into the workspace WORK. For the TSQR algorithm, this is accomplished by calculating the SVD of the R factor, which has the same singular values as the matrix X. For the normal equations method, this is done by computing the eigenvalues of X^T X, which could be inaccurate for ill-conditioned matrices X.

Troubleshooting
===============

When using models based on polynomials, care should be taken when constructing the design matrix X. If the x values are large, then the matrix X could be ill-conditioned since its columns are powers of x, leading to unstable least-squares solutions. In this case it can often help to center and scale the x values using the mean and standard deviation:

     x' = (x - mu)/sigma

and then construct the X matrix using the transformed values x'.

Examples
========

The example programs in this section demonstrate the various linear regression methods.

Simple Linear Regression Example
--------------------------------

The following program computes a least squares straight-line fit to a simple dataset, and outputs the best-fit line and its associated one standard-deviation error bars.

          [file fitting.c not included]

The following commands extract the data from the output of the program and display it using the GNU plotutils graph utility,

     $ ./demo > tmp
     $ more tmp
     # best fit: Y = -106.6 + 0.06 X
     # covariance matrix:
     # [ 39602, -19.9
     #   -19.9, 0.01]
     # chisq = 0.8

     $ for n in data fit hi lo ;
        do
          grep "^$n" tmp | cut -d: -f2 > $n ;
        done
     $ graph -T X -X x -Y y -y 0 20 -m 0 -S 2 -Ie data
          -S 0 -I a -m 1 fit -m 2 hi -m 2 lo

Multi-parameter Linear Regression Example
-----------------------------------------

The following program performs a quadratic fit y = c_0 + c_1 x + c_2 x^2 to a weighted dataset using the generalised linear fitting function gsl_multifit_wlinear.  The model matrix X for a quadratic fit is given by,

     X = [ 1   , x_0  , x_0^2 ;
           1   , x_1  , x_1^2 ;
           1   , x_2  , x_2^2 ;
           ... , ...  , ...   ]

where the column of ones corresponds to the constant term c_0. The two remaining columns corresponds to the terms c_1 x and c_2 x^2.

The program reads N lines of data in the format (X, Y, ERR) where ERR is the error (standard deviation) in the value Y.

          [file fitting2.c not included]

A suitable set of data for fitting can be generated using the following program.  It outputs a set of points with gaussian errors from the curve y = e^x in the region 0 < x < 2.

          [file fitting3.c not included]

The data can be prepared by running the resulting executable program,

     $ GSL_RNG_TYPE=mt19937_1999 ./generate > exp.dat
     $ more exp.dat
     0.1 0.97935 0.110517
     0.2 1.3359 0.12214
     0.3 1.52573 0.134986
     0.4 1.60318 0.149182
     0.5 1.81731 0.164872
     0.6 1.92475 0.182212
     ....

To fit the data use the previous program, with the number of data points given as the first argument.  In this case there are 19 data points.

     $ ./fit 19 < exp.dat
     0.1 0.97935 +/- 0.110517
     0.2 1.3359 +/- 0.12214
     ...
     # best fit: Y = 1.02318 + 0.956201 X + 0.876796 X^2
     # covariance matrix:
     [ +1.25612e-02, -3.64387e-02, +1.94389e-02
       -3.64387e-02, +1.42339e-01, -8.48761e-02
       +1.94389e-02, -8.48761e-02, +5.60243e-02 ]
     # chisq = 23.0987

The parameters of the quadratic fit match the coefficients of the expansion of e^x, taking into account the errors on the parameters and the O(x^3) difference between the exponential and quadratic functions for the larger values of x.  The errors on the parameters are given by the square-root of the corresponding diagonal elements of the covariance matrix.  The chi-squared per degree of freedom is 1.4, indicating a reasonable fit to the data.

Regularized Linear Regression Example 1
---------------------------------------

The next program demonstrates the difference between ordinary and regularized least squares when the design matrix is near-singular. In this program, we generate two random normally distributed variables u and v, with v = u + noise so that u and v are nearly colinear. We then set a third dependent variable y = u + v + noise and solve for the coefficients c_1,c_2 of the model Y(c_1,c_2) = c_1 u + c_2 v. Since u \approx v, the design matrix X is nearly singular, leading to unstable ordinary least squares solutions.

Here is the program output:

     matrix condition number = 1.025113e+04
     === Unregularized fit ===
     best fit: y = -43.6588 u + 45.6636 v
     residual norm = 31.6248
     solution norm = 63.1764
     chisq/dof = 1.00213
     === Regularized fit (L-curve) ===
     optimal lambda: 4.51103
     best fit: y = 1.00113 u + 1.0032 v
     residual norm = 31.6547
     solution norm = 1.41728
     chisq/dof = 1.04499
     === Regularized fit (GCV) ===
     optimal lambda: 0.0232029
     best fit: y = -19.8367 u + 21.8417 v
     residual norm = 31.6332
     solution norm = 29.5051
     chisq/dof = 1.00314

We see that the ordinary least squares solution is completely wrong, while the L-curve regularized method with the optimal \lambda = 4.51103 finds the correct solution c_1 \approx c_2 \approx 1. The GCV regularized method finds a regularization parameter \lambda = 0.0232029 which is too small to give an accurate solution, although it performs better than OLS. The L-curve and its computed corner, as well as the GCV curve and its minimum are plotted below.

The program is given below.

          [file fitreg.c not included]

Regularized Linear Regression Example 2
---------------------------------------

The following example program minimizes the cost function

     ||y - X c||^2 + \lambda^2 ||x||^2

where X is the 10-by-8 Hilbert matrix whose entries are given by

     X_{ij} = 1 / (i + j - 1)

and the right hand side vector is given by y = [1,-1,1,-1,1,-1,1,-1,1,-1]^T. Solutions are computed for \lambda = 0 (unregularized) as well as for optimal parameters \lambda chosen by analyzing the L-curve and GCV curve.

Here is the program output:

     matrix condition number = 3.565872e+09
     === Unregularized fit ===
     residual norm = 2.15376
     solution norm = 2.92217e+09
     chisq/dof = 2.31934
     === Regularized fit (L-curve) ===
     optimal lambda: 7.11407e-07
     residual norm = 2.60386
     solution norm = 424507
     chisq/dof = 3.43565
     === Regularized fit (GCV) ===
     optimal lambda: 1.72278
     residual norm = 3.1375
     solution norm = 0.139357
     chisq/dof = 4.95076

Here we see the unregularized solution results in a large solution norm due to the ill-conditioned matrix. The L-curve solution finds a small value of \lambda = 7.11e-7 which still results in a badly conditioned system and a large solution norm. The GCV method finds a parameter \lambda = 1.72 which results in a well-conditioned system and small solution norm.

The L-curve and its computed corner, as well as the GCV curve and its minimum are plotted below.

The program is given below.

          [file fitreg2.c not included]

Robust Linear Regression Example
--------------------------------

The next program demonstrates the advantage of robust least squares on a dataset with outliers. The program generates linear (x,y) data pairs on the line y = 1.45 x + 3.88, adds some random noise, and inserts 3 outliers into the dataset. Both the robust and ordinary least squares (OLS) coefficients are computed for comparison.

          [file robfit.c not included]

The output from the program is shown in the following plot.

Large Dense Linear Regression Example
-------------------------------------

The following program demostrates the large dense linear least squares solvers. This example is adapted from Trefethen and Bau, and fits the function f(t) = \exp(\sin^3(10t)) on the interval [0,1] with a degree 15 polynomial. The program generates n = 50000 equally spaced points t_i on this interval, calculates the function value and adds random noise to determine the observation value y_i. The entries of the least squares matrix are X_ij = t_i^j, representing a polynomial fit. The matrix is highly ill-conditioned, with a condition number of about 1.4 \cdot 10^11. The program accumulates the matrix into the least squares system in 5 blocks, each with 10000 rows. This way the full matrix X is never stored in memory. We solve the system with both the normal equations and TSQR methods. The results are shown in the plot below. In the top left plot, we see the unregularized normal equations solution has larger error than TSQR due to the ill-conditioning of the matrix. In the bottom left plot, we show the L-curve, which exhibits multiple corners. In the top right panel, we plot a regularized solution using \lambda = 10^-6. The TSQR and normal solutions now agree, however they are unable to provide a good fit due to the damping. This indicates that for some ill-conditioned problems, regularizing the normal equations does not improve the solution. This is further illustrated in the bottom right panel, where we plot the L-curve calculated from the normal equations. The curve agrees with the TSQR curve for larger damping parameters, but for small \lambda, the normal equations approach cannot provide accurate solution vectors leading to numerical inaccuracies in the left portion of the curve.

          [file largefit.c not included]

References and Further Reading
==============================

A summary of formulas and techniques for least squares fitting can be found in the ``Statistics'' chapter of the Annual Review of Particle Physics prepared by the Particle Data Group,

  Review of Particle Properties, R.M. Barnett et al., Physical Review D54, 1 (1996) http://pdg.lbl.gov/

The Review of Particle Physics is available online at the website given above.

The tests used to prepare these routines are based on the NIST Statistical Reference Datasets. The datasets and their documentation are available from NIST at the following website,

http://www.nist.gov/itl/div898/strd/index.html.

More information on Tikhonov regularization can be found in

  Hansen, P. C. (1998), Rank-Deficient and Discrete Ill-Posed Problems: Numerical Aspects of Linear Inversion. SIAM Monogr. on Mathematical Modeling and Computation, Society for Industrial and Applied Mathematics

  M. Rezghi and S. M. Hosseini (2009), A new variant of L-curve for Tikhonov regularization, Journal of Computational and Applied Mathematics, Volume 231, Issue 2, pages 914-924.

The GSL implementation of robust linear regression closely follows the publications

  DuMouchel, W. and F. O'Brien (1989), "Integrating a robust option into a multiple regression computing environment," Computer Science and Statistics:  Proceedings of the 21st Symposium on the Interface, American Statistical Association

  Street, J.O., R.J. Carroll, and D. Ruppert (1988), "A note on computing robust regression estimates via iteratively reweighted least squares," The American Statistician, v. 42, pp. 152-154.

More information about the normal equations and TSQR approach for solving large linear least squares systems can be found in the publications

  Trefethen, L. N. and Bau, D. (1997), "Numerical Linear Algebra", SIAM.

  Demmel, J., Grigori, L., Hoemmen, M. F., and Langou, J. "Communication-optimal parallel and sequential QR and LU factorizations", UCB Technical Report No. UCB/EECS-2008-89, 2008.