File: lmdif.c

package info (click to toggle)
gretl 2016d-1
  • links: PTS
  • area: main
  • in suites: stretch
  • size: 48,620 kB
  • ctags: 22,779
  • sloc: ansic: 345,830; sh: 4,648; makefile: 2,712; xml: 570; perl: 364
file content (507 lines) | stat: -rw-r--r-- 14,635 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
/* 
   This source file based on Minpack: initially converted from 
   fortran using f2c, then rendered into relatively idiomatic
   C with zero-based indexing throughout and pass-by-value for
   parameters that do not function as pointers. We also rely
   on <float.h> for the machine precision rather than Minpack's
   dpmpar().

   See README in this directory for the Minpack Copyright.

   Allin Cottrell, Wake Forest University, April 2012
*/

#include "minpack.h"
#include <math.h>
#include <float.h>

/*
c     lmdif:
c
c     the purpose of lmdif is to minimize the sum of the squares of
c     m nonlinear functions in n variables by a modification of
c     the levenberg-marquardt algorithm. the user must provide a
c     subroutine which calculates the functions. the jacobian is
c     then calculated by a forward-difference approximation.
c
c     the subroutine statement is
c
c       subroutine lmdif(fcn,m,n,x,fvec,ftol,xtol,gtol,maxfev,epsfcn,
c                        diag,mode,factor,nprint,info,nfev,fjac,
c                        ldfjac,ipvt,qtf,wa1,wa2,wa3,wa4)
c
c     where
c
c       fcn is the name of the user-supplied subroutine which
c         calculates the functions. fcn must be declared
c         in an external statement in the user calling
c         program, and should be written as follows.
c
c         subroutine fcn(m,n,x,fvec,iflag)
c         integer m,n,iflag
c         double precision x(n),fvec(m)
c         ----------
c         calculate the functions at x and
c         return this vector in fvec.
c         ----------
c         return
c         end
c
c         the value of iflag should not be changed by fcn unless
c         the user wants to terminate execution of lmdif.
c         in this case set iflag to a negative integer.
c
c       m is a positive integer input variable set to the number
c         of functions.
c
c       n is a positive integer input variable set to the number
c         of variables. n must not exceed m.
c
c       x is an array of length n. on input x must contain
c         an initial estimate of the solution vector. on output x
c         contains the final estimate of the solution vector.
c
c       fvec is an output array of length m which contains
c         the functions evaluated at the output x.
c
c       ftol is a nonnegative input variable. termination
c         occurs when both the actual and predicted relative
c         reductions in the sum of squares are at most ftol.
c         therefore, ftol measures the relative error desired
c         in the sum of squares.
c
c       xtol is a nonnegative input variable. termination
c         occurs when the relative error between two consecutive
c         iterates is at most xtol. therefore, xtol measures the
c         relative error desired in the approximate solution.
c
c       gtol is a nonnegative input variable. termination
c         occurs when the cosine of the angle between fvec and
c         any column of the jacobian is at most gtol in absolute
c         value. therefore, gtol measures the orthogonality
c         desired between the function vector and the columns
c         of the jacobian.
c
c       maxfev is a positive integer input variable. termination
c         occurs when the number of calls to fcn is at least
c         maxfev by the end of an iteration.
c
c       epsfcn is an input variable used in determining a suitable
c         step length for the forward-difference approximation. this
c         approximation assumes that the relative errors in the
c         functions are of the order of epsfcn. if epsfcn is less
c         than the machine precision, it is assumed that the relative
c         errors in the functions are of the order of the machine
c         precision.
c
c       diag is an array of length n. if mode = 1 (see
c         below), diag is internally set. if mode = 2, diag
c         must contain positive entries that serve as
c         multiplicative scale factors for the variables.
c
c       mode is an integer input variable. if mode = 1, the
c         variables will be scaled internally. if mode = 2,
c         the scaling is specified by the input diag. other
c         values of mode are equivalent to mode = 1.
c
c       factor is a positive input variable used in determining the
c         initial step bound. this bound is set to the product of
c         factor and the euclidean norm of diag*x if nonzero, or else
c         to factor itself. in most cases factor should lie in the
c         interval (.1,100.). 100. is a generally recommended value.
c
c       nprint is an integer input variable that enables controlled
c         printing of iterates if it is positive. in this case,
c         fcn is called with iflag = 0 at the beginning of the first
c         iteration and every nprint iterations thereafter and
c         immediately prior to return, with x and fvec available
c         for printing. if nprint is not positive, no special calls
c         of fcn with iflag = 0 are made.
c
c       info is an integer output variable. if the user has
c         terminated execution, info is set to the (negative)
c         value of iflag. see description of fcn. otherwise,
c         info is set as follows.
c
c         info = 0  improper input parameters.
c
c         info = 1  both actual and predicted relative reductions
c                   in the sum of squares are at most ftol.
c
c         info = 2  relative error between two consecutive iterates
c                   is at most xtol.
c
c         info = 3  conditions for info = 1 and info = 2 both hold.
c
c         info = 4  the cosine of the angle between fvec and any
c                   column of the jacobian is at most gtol in
c                   absolute value.
c
c         info = 5  number of calls to fcn has reached or
c                   exceeded maxfev.
c
c         info = 6  ftol is too small. no further reduction in
c                   the sum of squares is possible.
c
c         info = 7  xtol is too small. no further improvement in
c                   the approximate solution x is possible.
c
c         info = 8  gtol is too small. fvec is orthogonal to the
c                   columns of the jacobian to machine precision.
c
c       nfev is an integer output variable set to the number of
c         calls to fcn.
c
c       fjac is an output m by n array. the upper n by n submatrix
c         of fjac contains an upper triangular matrix r with
c         diagonal elements of nonincreasing magnitude such that
c
c                t     t           t
c               p *(jac *jac)*p = r *r,
c
c         where p is a permutation matrix and jac is the final
c         calculated jacobian. column j of p is column ipvt(j)
c         (see below) of the identity matrix. the lower trapezoidal
c         part of fjac contains information generated during
c         the computation of r.
c
c       ldfjac is a positive integer input variable not less than m
c         which specifies the leading dimension of the array fjac.
c
c       ipvt is an integer output array of length n. ipvt
c         defines a permutation matrix p such that jac*p = q*r,
c         where jac is the final calculated jacobian, q is
c         orthogonal (not stored), and r is upper triangular
c         with diagonal elements of nonincreasing magnitude.
c         column j of p is column ipvt(j) of the identity matrix.
c
c       qtf is an output array of length n which contains
c         the first n elements of the vector (q transpose)*fvec.
c
c       wa1, wa2, and wa3 are work arrays of length n.
c
c       wa4 is a work array of length m.
c
c     subprograms called
c
c       user-supplied ...... fcn
c
c       minpack-supplied ... enorm,fdjac2,lmpar,qrfac
c
c     argonne national laboratory. minpack project. march 1980.
c     burton s. garbow, kenneth e. hillstrom, jorge j. more
*/

int lmdif_(S_fp fcn, int m, int n, double *x, double *fvec, 
	   double ftol, double xtol, double gtol, int maxfev, 
	   double epsfcn, double *diag, int mode, double factor, 
	   int nprint, int *info, int *nfev, double *fjac, 
	   int ldfjac, int *ipvt, double *qtf, double *wa1, 
	   double *wa2, double *wa3, double *wa4, void *p)
{
    const double p1 = .1;
    const double p5 = .5;
    const double p25 = .25;
    const double p75 = .75;
    const double p0001 = 1e-4;
    const double epsmch = DBL_EPSILON;
    double par, sum;
    double d, temp1, temp2;
    double ratio, delta = 0;
    double fnorm, gnorm, pnorm, fnorm1;
    double actred, dirder, prered;
    double temp = 0.0, xnorm = 0.0;
    int iter, iflag = 0;
    int i, j, l;

    *info = 0;
    *nfev = 0;

    /* check the input parameters for errors */

    if (n <= 0 || m < n || ldfjac < m || 
	ftol < 0.0 || xtol < 0.0 || gtol < 0.0 || 
	maxfev <= 0 || factor <= 0.0) {
	goto terminate;
    }

    if (mode == 2) {
	for (j = 0; j < n; ++j) {
	    if (diag[j] <= 0.0) {
		goto terminate;
	    }
	}
    }

    /* evaluate the function at the starting point
       and calculate its norm */

    iflag = 1;
    (*fcn)(m, n, x, fvec, &iflag, p);
    *nfev = 1;
    if (iflag < 0) {
	goto terminate;
    }
    fnorm = enorm_(m, fvec);

    /* initialize Levenberg-Marquardt parameter and iteration counter */
    par = 0.0;
    iter = 1;

    /* beginning of the outer loop */
 outer_start:

    /* calculate the jacobian matrix */

    iflag = 2;
    fdjac2_((S_fp)fcn, m, n, 0, x, fvec, fjac, ldfjac, &iflag, 
	    epsfcn, wa4, p);
    *nfev += n;
    if (iflag < 0) {
	goto terminate;
    }

    /* if requested, call fcn to enable printing of iterates */

    if (nprint > 0) {
	iflag = 0;
	if ((iter - 1) % nprint == 0) {
	    (*fcn)(m, n, x, fvec, &iflag, p);
	}
	if (iflag < 0) {
	    goto terminate;
	}
    }

    /* compute the QR factorization of the jacobian */
    qrfac_(m, n, fjac, ldfjac, ipvt, wa1, wa2, wa3);

    /* on the first iteration and if mode is 1, scale according
       to the norms of the columns of the initial jacobian 
    */
    if (iter == 1) {
	if (mode != 2) {
	    for (j = 0; j < n; ++j) {
		diag[j] = wa2[j];
		if (wa2[j] == 0.0) {
		    diag[j] = 1.0;
		}
	    }
	}
	/* on the first iteration, calculate the norm of the scaled x
	   and initialize the step bound delta */
	for (j = 0; j < n; ++j) {
	    wa3[j] = diag[j] * x[j];
	}
	xnorm = enorm_(n, wa3);
	delta = factor * xnorm;
	if (delta == 0.0) {
	    delta = factor;
	}
    }

    /* form Q'*fvec and store the first n components in qtf */

    for (i = 0; i < m; ++i) {
	wa4[i] = fvec[i];
    }
    for (j = 0; j < n; ++j) {
	if (fjac[j + j * ldfjac] != 0.0) {
	    sum = 0.0;
	    for (i = j; i < m; ++i) {
		sum += fjac[i + j * ldfjac] * wa4[i];
	    }
	    temp = -sum / fjac[j + j * ldfjac];
	    for (i = j; i < m; ++i) {
		wa4[i] += fjac[i + j * ldfjac] * temp;
	    }
	}
	fjac[j + j * ldfjac] = wa1[j];
	qtf[j] = wa4[j];
    }

    /* compute the norm of the scaled gradient */

    gnorm = 0.0;
    if (fnorm != 0.0) {
	for (j = 0; j < n; ++j) {
	    l = ipvt[j];
	    if (wa2[l] != 0.0) {
		sum = 0.0;
		for (i = 0; i <= j; ++i) {
		    sum += fjac[i + j * ldfjac] * (qtf[i] / fnorm);
		}
		d = fabs(sum / wa2[l]);
		gnorm = max(gnorm, d);
	    }
	}
    }

    /* test for convergence of the gradient norm */
    if (gnorm <= gtol) {
	*info = 4;
    }
    if (*info != 0) {
	goto terminate;
    }

    /* rescale if necessary */
    if (mode != 2) {
	for (j = 0; j < n; ++j) {
	    diag[j] = max(diag[j], wa2[j]);
	}
    }

    /* beginning of the inner loop */
 inner_start:

    /* determine the Levenberg-Marquardt parameter */
    lmpar_(n, fjac, ldfjac, ipvt, diag, qtf, delta, &par, 
	   wa1, wa2, wa3, wa4);

    /* store the direction p and x + p; calculate the norm of p */
    for (j = 0; j < n; ++j) {
	wa1[j] = -wa1[j];
	wa2[j] = x[j] + wa1[j];
	wa3[j] = diag[j] * wa1[j];
    }
    pnorm = enorm_(n, wa3);

    /* on the first iteration, adjust the initial step bound */
    if (iter == 1) {
	delta = min(delta, pnorm);
    }

    /* evaluate the function at x + p and calculate its norm */
    iflag = 1;
    (*fcn)(m, n, wa2, wa4, &iflag, p);
    *nfev += 1;
    if (iflag < 0) {
	goto terminate;
    }
    fnorm1 = enorm_(m, wa4);

    /* compute the scaled actual reduction */

    actred = -1.0;
    if (p1 * fnorm1 < fnorm) {
	d = fnorm1 / fnorm;
	actred = 1.0 - d * d;
    }

    /* compute the scaled predicted reduction and */
    /* the scaled directional derivative. */

    for (j = 0; j < n; ++j) {
	wa3[j] = 0.0;
	l = ipvt[j];
	temp = wa1[l];
	for (i = 0; i <= j; ++i) {
	    wa3[i] += fjac[i + j * ldfjac] * temp;
	}
    }
    temp1 = enorm_(n, wa3) / fnorm;
    temp2 = sqrt(par) * pnorm / fnorm;
    prered = temp1 * temp1 + temp2 * temp2 / p5;
    dirder = -(temp1 * temp1 + temp2 * temp2);

    /* compute the ratio of the actual to the predicted
       reduction */

    ratio = 0.0;
    if (prered != 0.0) {
	ratio = actred / prered;
    }

    /* update the step bound */

    if (ratio <= p25) {
	if (actred >= 0.0) {
	    temp = p5;
	}
	if (actred < 0.0) {
	    temp = p5 * dirder / (dirder + p5 * actred);
	}
	if (p1 * fnorm1 >= fnorm || temp < p1) {
	    temp = p1;
	}
	d = pnorm / p1;
	delta = temp * min(delta, d);
	par /= temp;
    } else if (par == 0.0 || ratio >= p75) {
	delta = pnorm / p5;
	par = p5 * par;
    }

    /* test for successful iteration */

    if (ratio >= p0001) {
	/* successful iteration: update x, fvec, and their norms */
	for (j = 0; j < n; ++j) {
	    x[j] = wa2[j];
	    wa2[j] = diag[j] * x[j];
	}
	for (i = 0; i < m; ++i) {
	    fvec[i] = wa4[i];
	}
	xnorm = enorm_(n, wa2);
	fnorm = fnorm1;
	++iter;
    }

    /* tests for convergence */

    if (fabs(actred) <= ftol && prered <= ftol && p5 * ratio <= 1.0) {
	*info = 1;
    }
    if (delta <= xtol * xnorm) {
	*info = 2;
    }
    if (fabs(actred) <= ftol && prered <= ftol && p5 * ratio <= 1.0 && *info 
	    == 2) {
	*info = 3;
    }
    if (*info != 0) {
	goto terminate;
    }

    /* tests for termination and stringent tolerances */

    if (*nfev >= maxfev) {
	*info = 5;
    }
    if (fabs(actred) <= epsmch && prered <= epsmch && p5 * ratio <= 1.0) {
	*info = 6;
    }
    if (delta <= epsmch * xnorm) {
	*info = 7;
    }
    if (gnorm <= epsmch) {
	*info = 8;
    }
    if (*info != 0) {
	goto terminate;
    }

    /* end of inner loop; repeat (only) if iteration unsuccessful */
    if (ratio < p0001) {
	goto inner_start;
    }

    /* end of the outer loop */
    goto outer_start;

 terminate:

    /* termination, either normal or user-imposed */
    if (iflag < 0) {
	*info = iflag;
    }
    if (nprint > 0) {
	iflag = 0;
	(*fcn)(m, n, x, fvec, &iflag, p);
    }

    return 0;
}