E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual

# NAG Library Routine DocumentE02BEF

Note:  before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

## 1  Purpose

E02BEF computes a cubic spline approximation to an arbitrary set of data points. The knots of the spline are located automatically, but a single parameter must be specified to control the trade-off between closeness of fit and smoothness of fit.

## 2  Specification

 SUBROUTINE E02BEF ( START, M, X, Y, W, S, NEST, N, LAMDA, C, FP, WRK, LWRK, IWRK, IFAIL)
 INTEGER M, NEST, N, LWRK, IWRK(NEST), IFAIL REAL (KIND=nag_wp) X(M), Y(M), W(M), S, LAMDA(NEST), C(NEST), FP, WRK(LWRK) CHARACTER(1) START

## 3  Description

E02BEF determines a smooth cubic spline approximation $s\left(x\right)$ to the set of data points $\left({x}_{\mathit{r}},{y}_{\mathit{r}}\right)$, with weights ${w}_{\mathit{r}}$, for $\mathit{r}=1,2,\dots ,m$.
The spline is given in the B-spline representation
 $sx=∑i=1 n-4ciNix,$ (1)
where ${N}_{i}\left(x\right)$ denotes the normalized cubic B-spline defined upon the knots ${\lambda }_{i},{\lambda }_{i+1},\dots ,{\lambda }_{i+4}$.
The total number $n$ of these knots and their values ${\lambda }_{1},\dots ,{\lambda }_{n}$ are chosen automatically by the routine. The knots ${\lambda }_{5},\dots ,{\lambda }_{n-4}$ are the interior knots; they divide the approximation interval $\left[{x}_{1},{x}_{m}\right]$ into $n-7$ sub-intervals. The coefficients ${c}_{1},{c}_{2},\dots ,{c}_{n-4}$ are then determined as the solution of the following constrained minimization problem:
minimize
 $η=∑i=5 n-4δi2$ (2)
subject to the constraint
 $θ=∑r=1mεr2≤S,$ (3)
 where ${\delta }_{i}$ stands for the discontinuity jump in the third order derivative of $s\left(x\right)$ at the interior knot ${\lambda }_{i}$, ${\epsilon }_{r}$ denotes the weighted residual ${w}_{r}\left({y}_{r}-s\left({x}_{r}\right)\right)$, and $S$ is a non-negative number to be specified by you.
The quantity $\eta$ can be seen as a measure of the (lack of) smoothness of $s\left(x\right)$, while closeness of fit is measured through $\theta$. By means of the parameter $S$, ‘the smoothing factor’, you can then control the balance between these two (usually conflicting) properties. If $S$ is too large, the spline will be too smooth and signal will be lost (underfit); if $S$ is too small, the spline will pick up too much noise (overfit). In the extreme cases the routine will return an interpolating spline $\left(\theta =0\right)$ if $S$ is set to zero, and the weighted least squares cubic polynomial $\left(\eta =0\right)$ if $S$ is set very large. Experimenting with $S$ values between these two extremes should result in a good compromise. (See Section 8.2 for advice on choice of $S$.)
The method employed is outlined in Section 8.3 and fully described in Dierckx (1975), Dierckx (1981) and Dierckx (1982). It involves an adaptive strategy for locating the knots of the cubic spline (depending on the function underlying the data and on the value of $S$), and an iterative method for solving the constrained minimization problem once the knots have been determined.
Values of the computed spline, or of its derivatives or definite integral, can subsequently be computed by calling E02BBF, E02BCF or E02BDF, as described in Section 8.4.

## 4  References

Dierckx P (1975) An algorithm for smoothing, differentiating and integration of experimental data using spline functions J. Comput. Appl. Math. 1 165–184
Dierckx P (1981) An improved algorithm for curve fitting with spline functions Report TW54 Department of Computer Science, Katholieke Univerciteit Leuven
Dierckx P (1982) A fast algorithm for smoothing data on a rectangular grid while using spline functions SIAM J. Numer. Anal. 19 1286–1304
Reinsch C H (1967) Smoothing by spline functions Numer. Math. 10 177–183

## 5  Parameters

1:     START – CHARACTER(1)Input
On entry: must be set to 'C' or 'W'.
${\mathbf{START}}=\text{'C'}$
The routine will build up the knot set starting with no interior knots. No values need be assigned to the parameters N, LAMDA, WRK or IWRK.
${\mathbf{START}}=\text{'W'}$
The routine will restart the knot-placing strategy using the knots found in a previous call of the routine. In this case, the parameters N, LAMDA, WRK, and IWRK must be unchanged from that previous call. This warm start can save much time in searching for a satisfactory value of ${\mathbf{S}}$.
Constraint: ${\mathbf{START}}=\text{'C'}$ or $\text{'W'}$.
2:     M – INTEGERInput
On entry: $m$, the number of data points.
Constraint: ${\mathbf{M}}\ge 4$.
3:     X(M) – REAL (KIND=nag_wp) arrayInput
On entry: the values ${x}_{\mathit{r}}$ of the independent variable (abscissa) $x$, for $\mathit{r}=1,2,\dots ,m$.
Constraint: ${x}_{1}<{x}_{2}<\cdots <{x}_{m}$.
4:     Y(M) – REAL (KIND=nag_wp) arrayInput
On entry: the values ${y}_{\mathit{r}}$ of the dependent variable (ordinate) $y$, for $\mathit{r}=1,2,\dots ,m$.
5:     W(M) – REAL (KIND=nag_wp) arrayInput
On entry: the values ${w}_{\mathit{r}}$ of the weights, for $\mathit{r}=1,2,\dots ,m$. For advice on the choice of weights, see Section 2.1.2 in the E02 Chapter Introduction.
Constraint: ${\mathbf{W}}\left(\mathit{r}\right)>0.0$, for $\mathit{r}=1,2,\dots ,m$.
6:     S – REAL (KIND=nag_wp)Input
On entry: the smoothing factor, $S$.
If $S=0.0$, the routine returns an interpolating spline.
If $S$ is smaller than machine precision, it is assumed equal to zero.
For advice on the choice of $S$, see Sections 3 and 8.2.
Constraint: ${\mathbf{S}}\ge 0.0$.
7:     NEST – INTEGERInput
On entry: an overestimate for the number, $n$, of knots required.
Constraint: ${\mathbf{NEST}}\ge 8$. In most practical situations, ${\mathbf{NEST}}={\mathbf{M}}/2$ is sufficient. NEST never needs to be larger than ${\mathbf{M}}+4$, the number of knots needed for interpolation $\left({\mathbf{S}}=0.0\right)$.
8:     N – INTEGERInput/Output
On entry: if the warm start option is used, the value of N must be left unchanged from the previous call.
On exit: the total number, $n$, of knots of the computed spline.
9:     LAMDA(NEST) – REAL (KIND=nag_wp) arrayInput/Output
On entry: if the warm start option is used, the values ${\mathbf{LAMDA}}\left(1\right),{\mathbf{LAMDA}}\left(2\right),\dots ,{\mathbf{LAMDA}}\left({\mathbf{N}}\right)$ must be left unchanged from the previous call.
On exit: the knots of the spline, i.e., the positions of the interior knots ${\mathbf{LAMDA}}\left(5\right),\phantom{\rule{0ex}{0ex}}{\mathbf{LAMDA}}\left(6\right),\dots ,{\mathbf{LAMDA}}\left({\mathbf{N}}-4\right)$ as well as the positions of the additional knots
 $LAMDA1=LAMDA2=LAMDA3=LAMDA4=x1$
and
 $LAMDA N-3=LAMDA N-2=LAMDA N-1=LAMDA N =xm$
needed for the B-spline representation.
10:   C(NEST) – REAL (KIND=nag_wp) arrayOutput
On exit: the coefficient ${c}_{\mathit{i}}$ of the B-spline ${N}_{\mathit{i}}\left(x\right)$ in the spline approximation $s\left(x\right)$, for $\mathit{i}=1,2,\dots ,n-4$.
11:   FP – REAL (KIND=nag_wp)Output
On exit: the sum of the squared weighted residuals, $\theta$, of the computed spline approximation. If ${\mathbf{FP}}=0.0$, this is an interpolating spline. FP should equal ${\mathbf{S}}$ within a relative tolerance of $0.001$ unless $n=8$ when the spline has no interior knots and so is simply a cubic polynomial. For knots to be inserted, ${\mathbf{S}}$ must be set to a value below the value of FP produced in this case.
12:   WRK(LWRK) – REAL (KIND=nag_wp) arrayCommunication Array
If the warm start option is used on entry, the values ${\mathbf{WRK}}\left(1\right),\dots ,{\mathbf{WRK}}\left(n\right)$ must be left unchanged from the previous call.
13:   LWRK – INTEGERInput
On entry: the dimension of the array WRK as declared in the (sub)program from which E02BEF is called.
Constraint: ${\mathbf{LWRK}}\ge 4×{\mathbf{M}}+16×{\mathbf{NEST}}+41$.
14:   IWRK(NEST) – INTEGER arrayCommunication Array
If the warm start option is used, on entry, the values ${\mathbf{IWRK}}\left(1\right),\dots ,{\mathbf{IWRK}}\left(n\right)$ must be left unchanged from the previous call.
This array is used as workspace.
15:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to $0$, $-1\text{​ or ​}1$. If you are unfamiliar with this parameter you should refer to Section 3.3 in the Essential Introduction for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value $-1\text{​ or ​}1$ is recommended. If the output of error messages is undesirable, then the value $1$ is recommended. Otherwise, if you are not familiar with this parameter, the recommended value is $0$. When the value $-\mathbf{1}\text{​ or ​}\mathbf{1}$ is used it is essential to test the value of IFAIL on exit.
On exit: ${\mathbf{IFAIL}}={\mathbf{0}}$ unless the routine detects an error or a warning has been flagged (see Section 6).

## 6  Error Indicators and Warnings

If on entry ${\mathbf{IFAIL}}={\mathbf{0}}$ or $-{\mathbf{1}}$, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
${\mathbf{IFAIL}}=1$
 On entry, ${\mathbf{START}}\ne \text{'C'}$ or $\text{'W'}$, or ${\mathbf{M}}<4$, or ${\mathbf{S}}<0.0$, or ${\mathbf{S}}=0.0$ and ${\mathbf{NEST}}<{\mathbf{M}}+4$, or ${\mathbf{NEST}}<8$, or ${\mathbf{LWRK}}<4×{\mathbf{M}}+16×{\mathbf{NEST}}+41$.
${\mathbf{IFAIL}}=2$
The weights are not all strictly positive.
${\mathbf{IFAIL}}=3$
The values of ${\mathbf{X}}\left(\mathit{r}\right)$, for $\mathit{r}=1,2,\dots ,{\mathbf{M}}$, are not in strictly increasing order.
${\mathbf{IFAIL}}=4$
The number of knots required is greater than NEST. Try increasing NEST and, if necessary, supplying larger arrays for the parameters LAMDA, C, WRK and IWRK. However, if NEST is already large, say ${\mathbf{NEST}}>{\mathbf{M}}/2$, then this error exit may indicate that S is too small.
${\mathbf{IFAIL}}=5$
The iterative process used to compute the coefficients of the approximating spline has failed to converge. This error exit may occur if S has been set very small. If the error persists with increased S, contact NAG.
If ${\mathbf{IFAIL}}={\mathbf{4}}$ or ${\mathbf{5}}$, a spline approximation is returned, but it fails to satisfy the fitting criterion (see (2) and (3)) – perhaps by only a small amount, however.

## 7  Accuracy

On successful exit, the approximation returned is such that its weighted sum of squared residuals $\theta$ (as in (3)) is equal to the smoothing factor $S$, up to a specified relative tolerance of $0.001$ – except that if $n=8$, $\theta$ may be significantly less than $S$: in this case the computed spline is simply a weighted least squares polynomial approximation of degree $3$, i.e., a spline with no interior knots.

### 8.1  Timing

The time taken for a call of E02BEF depends on the complexity of the shape of the data, the value of the smoothing factor $S$, and the number of data points. If E02BEF is to be called for different values of $S$, much time can be saved by setting ${\mathbf{START}}=\text{'W'}$ after the first call.

### 8.2  Choice of S

If the weights have been correctly chosen (see Section 2.1.2 in the E02 Chapter Introduction), the standard deviation of ${w}_{r}{y}_{r}$ would be the same for all $r$, equal to $\sigma$, say. In this case, choosing the smoothing factor $S$ in the range ${\sigma }^{2}\left(m±\sqrt{2m}\right)$, as suggested by Reinsch (1967), is likely to give a good start in the search for a satisfactory value. Otherwise, experimenting with different values of $S$ will be required from the start, taking account of the remarks in Section 3.
In that case, in view of computation time and memory requirements, it is recommended to start with a very large value for $S$ and so determine the least squares cubic polynomial; the value returned in FP, call it ${\theta }_{0}$, gives an upper bound for $S$. Then progressively decrease the value of $S$ to obtain closer fits – say by a factor of $10$ in the beginning, i.e., $S={\theta }_{0}/10$, $S={\theta }_{0}/100$, and so on, and more carefully as the approximation shows more details.
The number of knots of the spline returned, and their location, generally depend on the value of $S$ and on the behaviour of the function underlying the data. However, if E02BEF is called with ${\mathbf{START}}=\text{'W'}$, the knots returned may also depend on the smoothing factors of the previous calls. Therefore if, after a number of trials with different values of $S$ and ${\mathbf{START}}=\text{'W'}$, a fit can finally be accepted as satisfactory, it may be worthwhile to call E02BEF once more with the selected value for $S$ but now using ${\mathbf{START}}=\text{'C'}$. Often, E02BEF then returns an approximation with the same quality of fit but with fewer knots, which is therefore better if data reduction is also important.

### 8.3  Outline of Method Used

If $S=0$, the requisite number of knots is known in advance, i.e., $n=m+4$; the interior knots are located immediately as ${\lambda }_{\mathit{i}}={x}_{\mathit{i}-2}$, for $\mathit{i}=5,6,\dots ,n-4$. The corresponding least squares spline (see E02BAF) is then an interpolating spline and therefore a solution of the problem.
If $S>0$, a suitable knot set is built up in stages (starting with no interior knots in the case of a cold start but with the knot set found in a previous call if a warm start is chosen). At each stage, a spline is fitted to the data by least squares (see E02BAF) and $\theta$, the weighted sum of squares of residuals, is computed. If $\theta >S$, new knots are added to the knot set to reduce $\theta$ at the next stage. The new knots are located in intervals where the fit is particularly poor, their number depending on the value of $S$ and on the progress made so far in reducing $\theta$. Sooner or later, we find that $\theta \le S$ and at that point the knot set is accepted. The routine then goes on to compute the (unique) spline which has this knot set and which satisfies the full fitting criterion specified by (2) and (3). The theoretical solution has $\theta =S$. The routine computes the spline by an iterative scheme which is ended when $\theta =S$ within a relative tolerance of $0.001$. The main part of each iteration consists of a linear least squares computation of special form, done in a similarly stable and efficient manner as in E02BAF.
An exception occurs when the routine finds at the start that, even with no interior knots $\left(n=8\right)$, the least squares spline already has its weighted sum of squares of residuals $\text{}\le S$. In this case, since this spline (which is simply a cubic polynomial) also has an optimal value for the smoothness measure $\eta$, namely zero, it is returned at once as the (trivial) solution. It will usually mean that $S$ has been chosen too large.
For further details of the algorithm and its use, see Dierckx (1981).

### 8.4  Evaluation of Computed Spline

The value of the computed spline at a given value X may be obtained in the real variable S by the call:
```CALL E02BBF(N,LAMDA,C,X,S,IFAIL)
```
where N, LAMDA and C are the output parameters of E02BEF.
The values of the spline and its first three derivatives at a given value X may be obtained in the real array S of dimension at least $4$ by the call:
```CALL E02BCF(N,LAMDA,C,X,LEFT,S,IFAIL)
```
where if ${\mathbf{LEFT}}=1$, left-hand derivatives are computed and if ${\mathbf{LEFT}}\ne 1$, right-hand derivatives are calculated. The value of LEFT is only relevant if X is an interior knot (see E02BCF).
The value of the definite integral of the spline over the interval ${\mathbf{X}}\left(1\right)$ to ${\mathbf{X}}\left({\mathbf{M}}\right)$ can be obtained in the real variable DINT by the call:
```CALL E02BDF(N,LAMDA,C,DINT,IFAIL)
```
(see E02BDF).

## 9  Example

This example reads in a set of data values, followed by a set of values of ${\mathbf{S}}$. For each value of ${\mathbf{S}}$ it calls E02BEF to compute a spline approximation, and prints the values of the knots and the B-spline coefficients ${c}_{i}$.
The program includes code to evaluate the computed splines, by calls to E02BBF, at the points ${x}_{r}$ and at points mid-way between them. These values are not printed out, however; instead the results are illustrated by plots of the computed splines, together with the data points (indicated by $×$) and the positions of the knots (indicated by vertical lines): the effect of decreasing ${\mathbf{S}}$ can be clearly seen.

### 9.1  Program Text

Program Text (e02befe.f90)

### 9.2  Program Data

Program Data (e02befe.d)

### 9.3  Program Results

Program Results (e02befe.r)