-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathMPFit.c
2297 lines (2129 loc) · 59.8 KB
/
MPFit.c
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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* MINPACK-1 Least Squares Fitting Library
*
* Original public domain version by B. Garbow, K. Hillstrom, J. More'
* (Argonne National Laboratory, MINPACK project, March 1980)
* See the file DISCLAIMER for copyright information.
*
* Tranlation to C Language by S. Moshier (moshier.net)
*
* Enhancements and packaging by C. Markwardt
* (comparable to IDL fitting routine MPFIT
* see http://cow.physics.wisc.edu/~craigm/idl/idl.html)
*/
/* Main mpfit library routines (double precision)
$Id: mpfit.c,v 1.20 2010/11/13 08:15:35 craigm Exp $
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include "mpfit.h"
/* Forward declarations of functions in this module */
static int mp_fdjac2(mp_func funct,
int m, int n, int *ifree, int npar, double *x, double *fvec,
double *fjac, int ldfjac, double epsfcn,
double *wa, void *priv, int *nfev,
double *step, double *dstep, int *dside,
int *qulimited, double *ulimit,
int *ddebug, double *ddrtol, double *ddatol);
static void mp_qrfac(int m, int n, double *a, int lda,
int pivot, int *ipvt, int lipvt,
double *rdiag, double *acnorm, double *wa);
static void mp_qrsolv(int n, double *r, int ldr, int *ipvt, double *diag,
double *qtb, double *x, double *sdiag, double *wa);
static void mp_lmpar(int n, double *r, int ldr, int *ipvt, int *ifree, double *diag,
double *qtb, double delta, double *par, double *x,
double *sdiag, double *wa1, double *wa2);
static double mp_enorm(int n, double *x);
static double mp_dmax1(double a, double b);
static double mp_dmin1(double a, double b);
static int mp_min0(int a, int b);
static int mp_covar(int n, double *r, int ldr, int *ipvt, double tol, double *wa);
/* Macro to call user function */
#define mp_call(funct, m, n, x, fvec, dvec, priv) (*(funct))(m,n,x,fvec,dvec,priv)
/* Macro to safely allocate memory */
#define mp_malloc(dest,type,size) \
dest = (type *) malloc( sizeof(type)*size ); \
if (dest == 0) { \
info = MP_ERR_MEMORY; \
goto CLEANUP; \
} else { \
int _k; \
for (_k=0; _k<(size); _k++) dest[_k] = 0; \
}
/*
* **********
*
* subroutine mpfit
*
* the purpose of mpfit is to minimize the sum of the squares of
* m nonlinear functions in n variables by a modification of
* the levenberg-marquardt algorithm. the user must provide a
* subroutine which calculates the functions. the jacobian is
* then calculated by a finite-difference approximation.
*
* mp_funct funct - function to be minimized
* int m - number of data points
* int npar - number of fit parameters
* double *xall - array of n initial parameter values
* upon return, contains adjusted parameter values
* mp_par *pars - array of npar structures specifying constraints;
* or 0 (null pointer) for unconstrained fitting
* [ see README and mpfit.h for definition & use of mp_par]
* mp_config *config - pointer to structure which specifies the
* configuration of mpfit(); or 0 (null pointer)
* if the default configuration is to be used.
* See README and mpfit.h for definition and use
* of config.
* void *private - any private user data which is to be passed directly
* to funct without modification by mpfit().
* mp_result *result - pointer to structure, which upon return, contains
* the results of the fit. The user should zero this
* structure. If any of the array values are to be
* returned, the user should allocate storage for them
* and assign the corresponding pointer in *result.
* Upon return, *result will be updated, and
* any of the non-null arrays will be filled.
*
*
* FORTRAN DOCUMENTATION BELOW
*
*
* the subroutine statement is
*
* subroutine lmdif(fcn,m,n,x,fvec,ftol,xtol,gtol,maxfev,epsfcn,
* diag,mode,factor,nprint,info,nfev,fjac,
* ldfjac,ipvt,qtf,wa1,wa2,wa3,wa4)
*
* where
*
* fcn is the name of the user-supplied subroutine which
* calculates the functions. fcn must be declared
* in an external statement in the user calling
* program, and should be written as follows.
*
* subroutine fcn(m,n,x,fvec,iflag)
* integer m,n,iflag
* double precision x(n),fvec(m)
* ----------
* calculate the functions at x and
* return this vector in fvec.
* ----------
* return
* end
*
* the value of iflag should not be changed by fcn unless
* the user wants to terminate execution of lmdif.
* in this case set iflag to a negative integer.
*
* m is a positive integer input variable set to the number
* of functions.
*
* n is a positive integer input variable set to the number
* of variables. n must not exceed m.
*
* x is an array of length n. on input x must contain
* an initial estimate of the solution vector. on output x
* contains the final estimate of the solution vector.
*
* fvec is an output array of length m which contains
* the functions evaluated at the output x.
*
* ftol is a nonnegative input variable. termination
* occurs when both the actual and predicted relative
* reductions in the sum of squares are at most ftol.
* therefore, ftol measures the relative error desired
* in the sum of squares.
*
* xtol is a nonnegative input variable. termination
* occurs when the relative error between two consecutive
* iterates is at most xtol. therefore, xtol measures the
* relative error desired in the approximate solution.
*
* gtol is a nonnegative input variable. termination
* occurs when the cosine of the angle between fvec and
* any column of the jacobian is at most gtol in absolute
* value. therefore, gtol measures the orthogonality
* desired between the function vector and the columns
* of the jacobian.
*
* maxfev is a positive integer input variable. termination
* occurs when the number of calls to fcn is at least
* maxfev by the end of an iteration.
*
* epsfcn is an input variable used in determining a suitable
* step length for the forward-difference approximation. this
* approximation assumes that the relative errors in the
* functions are of the order of epsfcn. if epsfcn is less
* than the machine precision, it is assumed that the relative
* errors in the functions are of the order of the machine
* precision.
*
* diag is an array of length n. if mode = 1 (see
* below), diag is internally set. if mode = 2, diag
* must contain positive entries that serve as
* multiplicative scale factors for the variables.
*
* mode is an integer input variable. if mode = 1, the
* variables will be scaled internally. if mode = 2,
* the scaling is specified by the input diag. other
* values of mode are equivalent to mode = 1.
*
* factor is a positive input variable used in determining the
* initial step bound. this bound is set to the product of
* factor and the euclidean norm of diag*x if nonzero, or else
* to factor itself. in most cases factor should lie in the
* interval (.1,100.). 100. is a generally recommended value.
*
* nprint is an integer input variable that enables controlled
* printing of iterates if it is positive. in this case,
* fcn is called with iflag = 0 at the beginning of the first
* iteration and every nprint iterations thereafter and
* immediately prior to return, with x and fvec available
* for printing. if nprint is not positive, no special calls
* of fcn with iflag = 0 are made.
*
* info is an integer output variable. if the user has
* terminated execution, info is set to the (negative)
* value of iflag. see description of fcn. otherwise,
* info is set as follows.
*
* info = 0 improper input parameters.
*
* info = 1 both actual and predicted relative reductions
* in the sum of squares are at most ftol.
*
* info = 2 relative error between two consecutive iterates
* is at most xtol.
*
* info = 3 conditions for info = 1 and info = 2 both hold.
*
* info = 4 the cosine of the angle between fvec and any
* column of the jacobian is at most gtol in
* absolute value.
*
* info = 5 number of calls to fcn has reached or
* exceeded maxfev.
*
* info = 6 ftol is too small. no further reduction in
* the sum of squares is possible.
*
* info = 7 xtol is too small. no further improvement in
* the approximate solution x is possible.
*
* info = 8 gtol is too small. fvec is orthogonal to the
* columns of the jacobian to machine precision.
*
* nfev is an integer output variable set to the number of
* calls to fcn.
*
* fjac is an output m by n array. the upper n by n submatrix
* of fjac contains an upper triangular matrix r with
* diagonal elements of nonincreasing magnitude such that
*
* t t t
* p *(jac *jac)*p = r *r,
*
* where p is a permutation matrix and jac is the final
* calculated jacobian. column j of p is column ipvt(j)
* (see below) of the identity matrix. the lower trapezoidal
* part of fjac contains information generated during
* the computation of r.
*
* ldfjac is a positive integer input variable not less than m
* which specifies the leading dimension of the array fjac.
*
* ipvt is an integer output array of length n. ipvt
* defines a permutation matrix p such that jac*p = q*r,
* where jac is the final calculated jacobian, q is
* orthogonal (not stored), and r is upper triangular
* with diagonal elements of nonincreasing magnitude.
* column j of p is column ipvt(j) of the identity matrix.
*
* qtf is an output array of length n which contains
* the first n elements of the vector (q transpose)*fvec.
*
* wa1, wa2, and wa3 are work arrays of length n.
*
* wa4 is a work array of length m.
*
* subprograms called
*
* user-supplied ...... fcn
*
* minpack-supplied ... dpmpar,enorm,fdjac2,lmpar,qrfac
*
* fortran-supplied ... dabs,dmax1,dmin1,dsqrt,mod
*
* argonne national laboratory. minpack project. march 1980.
* burton s. garbow, kenneth e. hillstrom, jorge j. more
*
* ********** */
int mpfit(mp_func funct, int m, int npar,
double *xall, mp_par *pars, mp_config *config, void *private_data,
mp_result *result)
{
mp_config conf;
int i, j, info, iflag, nfree, npegged, iter;
int qanylim = 0;
//int qanypegged = 0; //variable never read.
int ij,jj,l;
double actred,delta,dirder,fnorm,fnorm1,gnorm, orignorm;
double par,pnorm,prered,ratio;
double sum,temp,temp1,temp2,temp3,xnorm, alpha;
static double one = 1.0;
static double p1 = 0.1;
static double p5 = 0.5;
static double p25 = 0.25;
static double p75 = 0.75;
static double p0001 = 1.0e-4;
static double zero = 0.0;
int nfev = 0;
double *step = 0, *dstep = 0, *llim = 0, *ulim = 0;
int *pfixed = 0, *mpside = 0, *ifree = 0, *qllim = 0, *qulim = 0;
int *ddebug = 0;
double *ddrtol = 0, *ddatol = 0;
double *fvec = 0, *qtf = 0;
double *x = 0, *xnew = 0, *fjac = 0, *diag = 0;
double *wa1 = 0, *wa2 = 0, *wa3 = 0, *wa4 = 0;
int *ipvt = 0;
int ldfjac;
/* Default configuration */
conf.ftol = 1e-10;
conf.xtol = 1e-10;
conf.gtol = 1e-10;
conf.stepfactor = 100.0;
conf.nprint = 1;
conf.epsfcn = MP_MACHEP0;
conf.maxiter = 200;
conf.douserscale = 0;
conf.maxfev = 0;
conf.covtol = 1e-14;
conf.nofinitecheck = 0;
if (config) {
/* Transfer any user-specified configurations */
if (config->ftol > 0) conf.ftol = config->ftol;
if (config->xtol > 0) conf.xtol = config->xtol;
if (config->gtol > 0) conf.gtol = config->gtol;
if (config->stepfactor > 0) conf.stepfactor = config->stepfactor;
if (config->nprint >= 0) conf.nprint = config->nprint;
if (config->epsfcn > 0) conf.epsfcn = config->epsfcn;
if (config->maxiter > 0) conf.maxiter = config->maxiter;
if (config->douserscale != 0) conf.douserscale = config->douserscale;
if (config->covtol > 0) conf.covtol = config->covtol;
if (config->nofinitecheck > 0) conf.nofinitecheck = config->nofinitecheck;
conf.maxfev = config->maxfev;
}
info = 0;
//obviously not read anymore
//iflag = 0;
//nfree = 0;
//npegged = 0;
if (funct == 0) {
return MP_ERR_FUNC;
}
if ((m <= 0) || (xall == 0)) {
return MP_ERR_NPOINTS;
}
if (npar <= 0) {
return MP_ERR_NFREE;
}
//fnorm = -1.0;//never read?
fnorm1 = -1.0;
xnorm = -1.0;
delta = 0.0;
/* FIXED parameters? */
mp_malloc(pfixed, int, npar);
if (pars) for (i=0; i<npar; i++) {
pfixed[i] = (pars[i].fixed)?1:0;
}
/* Finite differencing step, absolute and relative, and sidedness of deriv */
mp_malloc(step, double, npar);
mp_malloc(dstep, double, npar);
mp_malloc(mpside, int, npar);
mp_malloc(ddebug, int, npar);
mp_malloc(ddrtol, double, npar);
mp_malloc(ddatol, double, npar);
if (pars) for (i=0; i<npar; i++) {
step[i] = pars[i].step;
dstep[i] = pars[i].relstep;
mpside[i] = pars[i].side;
ddebug[i] = pars[i].deriv_debug;
ddrtol[i] = pars[i].deriv_reltol;
ddatol[i] = pars[i].deriv_abstol;
}
/* Finish up the free parameters */
nfree = 0;
mp_malloc(ifree, int, npar);
for (i=0, j=0; i<npar; i++) {
if (pfixed[i] == 0) {
nfree++;
ifree[j++] = i;
}
}
if (nfree == 0) {
info = MP_ERR_NFREE;
goto CLEANUP;
}
if (pars) {
for (i=0; i<npar; i++) {
if ( (pars[i].limited[0] && (xall[i] < pars[i].limits[0])) ||
(pars[i].limited[1] && (xall[i] > pars[i].limits[1])) ) {
info = MP_ERR_INITBOUNDS;
goto CLEANUP;
}
if ( (pars[i].fixed == 0) && pars[i].limited[0] && pars[i].limited[1] &&
(pars[i].limits[0] >= pars[i].limits[1])) {
info = MP_ERR_BOUNDS;
goto CLEANUP;
}
}
mp_malloc(qulim, int, nfree);
mp_malloc(qllim, int, nfree);
mp_malloc(ulim, double, nfree);
mp_malloc(llim, double, nfree);
for (i=0; i<nfree; i++) {
qllim[i] = pars[ifree[i]].limited[0];
qulim[i] = pars[ifree[i]].limited[1];
llim[i] = pars[ifree[i]].limits[0];
ulim[i] = pars[ifree[i]].limits[1];
if (qllim[i] || qulim[i]) qanylim = 1;
}
}
/* Sanity checking on input configuration */
if ((npar <= 0) || (conf.ftol <= 0) || (conf.xtol <= 0) ||
(conf.gtol <= 0) || (conf.maxiter < 0) ||
(conf.stepfactor <= 0)) {
info = MP_ERR_PARAM;
goto CLEANUP;
}
/* Ensure there are some degrees of freedom */
if (m < nfree) {
info = MP_ERR_DOF;
goto CLEANUP;
}
/* Allocate temporary storage */
mp_malloc(fvec, double, m);
mp_malloc(qtf, double, nfree);
mp_malloc(x, double, nfree);
mp_malloc(xnew, double, npar);
mp_malloc(fjac, double, m*nfree);
ldfjac = m;
mp_malloc(diag, double, npar);
mp_malloc(wa1, double, npar);
mp_malloc(wa2, double, npar);
mp_malloc(wa3, double, npar);
mp_malloc(wa4, double, m);
mp_malloc(ipvt, int, npar);
/* Evaluate user function with initial parameter values */
iflag = mp_call(funct, m, npar, xall, fvec, 0, private_data);
nfev += 1;
if (iflag < 0) {
goto CLEANUP;
}
fnorm = mp_enorm(m, fvec);
orignorm = fnorm*fnorm;
/* Make a new copy */
for (i=0; i<npar; i++) {
xnew[i] = xall[i];
}
/* Transfer free parameters to 'x' */
for (i=0; i<nfree; i++) {
x[i] = xall[ifree[i]];
}
/* Initialize Levelberg-Marquardt parameter and iteration counter */
par = 0.0;
iter = 1;
for (i=0; i<nfree; i++) {
qtf[i] = 0;
}
/* Beginning of the outer loop */
OUTER_LOOP:
for (i=0; i<nfree; i++) {
xnew[ifree[i]] = x[i];
}
/* XXX call iterproc */
/* Calculate the jacobian matrix */
iflag = mp_fdjac2(funct, m, nfree, ifree, npar, xnew, fvec, fjac, ldfjac,
conf.epsfcn, wa4, private_data, &nfev,
step, dstep, mpside, qulim, ulim,
ddebug, ddrtol, ddatol);
if (iflag < 0) {
goto CLEANUP;
}
/* Determine if any of the parameters are pegged at the limits */
//qanypegged = 0; //variable never read.
if (qanylim) {
for (j=0; j<nfree; j++) {
int lpegged = (qllim[j] && (x[j] == llim[j]));
int upegged = (qulim[j] && (x[j] == ulim[j]));
sum = 0;
if (lpegged || upegged) {
//qanypegged = 1; //variable never read.
ij = j*ldfjac;
for (i=0; i<m; i++, ij++) {
sum += fvec[i] * fjac[ij];
}
}
if (lpegged && (sum > 0)) {
ij = j*ldfjac;
for (i=0; i<m; i++, ij++) fjac[ij] = 0;
}
if (upegged && (sum < 0)) {
ij = j*ldfjac;
for (i=0; i<m; i++, ij++) fjac[ij] = 0;
}
}
}
/* Compute the QR factorization of the jacobian */
mp_qrfac(m,nfree,fjac,ldfjac,1,ipvt,nfree,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 (conf.douserscale == 0) {
for (j=0; j<nfree; j++) {
diag[ifree[j]] = wa2[j];
if (wa2[j] == zero ) {
diag[ifree[j]] = one;
}
}
}
/*
* on the first iteration, calculate the norm of the scaled x
* and initialize the step bound delta.
*/
for (j=0; j<nfree; j++ ) {
wa3[j] = diag[ifree[j]] * x[j];
}
xnorm = mp_enorm(nfree, wa3);
delta = conf.stepfactor*xnorm;
if (delta == zero) delta = conf.stepfactor;
}
/*
* form (q transpose)*fvec and store the first n components in
* qtf.
*/
for (i=0; i<m; i++ ) {
wa4[i] = fvec[i];
}
jj = 0;
for (j=0; j<nfree; j++ ) {
temp3 = fjac[jj];
if (temp3 != zero) {
sum = zero;
ij = jj;
for (i=j; i<m; i++ ) {
sum += fjac[ij] * wa4[i];
ij += 1; /* fjac[i+m*j] */
}
temp = -sum / temp3;
ij = jj;
for (i=j; i<m; i++ ) {
wa4[i] += fjac[ij] * temp;
ij += 1; /* fjac[i+m*j] */
}
}
fjac[jj] = wa1[j];
jj += m+1; /* fjac[j+m*j] */
qtf[j] = wa4[j];
}
/* ( From this point on, only the square matrix, consisting of the
triangle of R, is needed.) */
if (conf.nofinitecheck) {
/* Check for overflow. This should be a cheap test here since FJAC
has been reduced to a (small) square matrix, and the test is
O(N^2). */
int off = 0, nonfinite = 0;
for (j=0; j<nfree; j++) {
for (i=0; i<nfree; i++) {
if (mpfinite(fjac[off+i]) == 0) nonfinite = 1;
}
off += ldfjac;
}
if (nonfinite) {
info = MP_ERR_NAN;
goto CLEANUP;
}
}
/*
* compute the norm of the scaled gradient.
*/
gnorm = zero;
if (fnorm != zero) {
jj = 0;
for (j=0; j<nfree; j++ ) {
l = ipvt[j];
if (wa2[l] != zero) {
sum = zero;
ij = jj;
for (i=0; i<=j; i++ ) {
sum += fjac[ij]*(qtf[i]/fnorm);
ij += 1; /* fjac[i+m*j] */
}
gnorm = mp_dmax1(gnorm,fabs(sum/wa2[l]));
}
jj += m;
}
}
/*
* test for convergence of the gradient norm.
*/
if (gnorm <= conf.gtol) info = MP_OK_DIR;
if (info != 0) goto L300;
if (conf.maxiter == 0) goto L300;
/*
* rescale if necessary.
*/
if (conf.douserscale == 0) {
for (j=0; j<nfree; j++ ) {
diag[ifree[j]] = mp_dmax1(diag[ifree[j]],wa2[j]);
}
}
/*
* beginning of the inner loop.
*/
L200:
/*
* determine the levenberg-marquardt parameter.
*/
mp_lmpar(nfree,fjac,ldfjac,ipvt,ifree,diag,qtf,delta,&par,wa1,wa2,wa3,wa4);
/*
* store the direction p and x + p. calculate the norm of p.
*/
for (j=0; j<nfree; j++ ) {
wa1[j] = -wa1[j];
}
alpha = 1.0;
if (qanylim == 0) {
/* No parameter limits, so just move to new position WA2 */
for (j=0; j<nfree; j++ ) {
wa2[j] = x[j] + wa1[j];
}
} else {
/* Respect the limits. If a step were to go out of bounds, then
* we should take a step in the same direction but shorter distance.
* The step should take us right to the limit in that case.
*/
for (j=0; j<nfree; j++) {
int lpegged = (qllim[j] && (x[j] <= llim[j]));
int upegged = (qulim[j] && (x[j] >= ulim[j]));
int dwa1 = fabs(wa1[j]) > MP_MACHEP0;
if (lpegged && (wa1[j] < 0)) wa1[j] = 0;
if (upegged && (wa1[j] > 0)) wa1[j] = 0;
if (dwa1 && qllim[j] && ((x[j] + wa1[j]) < llim[j])) {
alpha = mp_dmin1(alpha, (llim[j]-x[j])/wa1[j]);
}
if (dwa1 && qulim[j] && ((x[j] + wa1[j]) > ulim[j])) {
alpha = mp_dmin1(alpha, (ulim[j]-x[j])/wa1[j]);
}
}
/* Scale the resulting vector, advance to the next position */
for (j=0; j<nfree; j++) {
double sgnu, sgnl;
double ulim1, llim1;
wa1[j] = wa1[j] * alpha;
wa2[j] = x[j] + wa1[j];
/* Adjust the output values. If the step put us exactly
* on a boundary, make sure it is exact.
*/
sgnu = (ulim[j] >= 0) ? (+1) : (-1);
sgnl = (llim[j] >= 0) ? (+1) : (-1);
ulim1 = ulim[j]*(1-sgnu*MP_MACHEP0) - ((ulim[j] == 0)?(MP_MACHEP0):0);
llim1 = llim[j]*(1+sgnl*MP_MACHEP0) + ((llim[j] == 0)?(MP_MACHEP0):0);
if (qulim[j] && (wa2[j] >= ulim1)) {
wa2[j] = ulim[j];
}
if (qllim[j] && (wa2[j] <= llim1)) {
wa2[j] = llim[j];
}
}
}
for (j=0; j<nfree; j++ ) {
wa3[j] = diag[ifree[j]]*wa1[j];
}
pnorm = mp_enorm(nfree,wa3);
/*
* on the first iteration, adjust the initial step bound.
*/
if (iter == 1) {
delta = mp_dmin1(delta,pnorm);
}
/*
* evaluate the function at x + p and calculate its norm.
*/
for (i=0; i<nfree; i++) {
xnew[ifree[i]] = wa2[i];
}
iflag = mp_call(funct, m, npar, xnew, wa4, 0, private_data);
nfev += 1;
if (iflag < 0) goto L300;
fnorm1 = mp_enorm(m,wa4);
/*
* compute the scaled actual reduction.
*/
actred = -one;
if ((p1*fnorm1) < fnorm) {
temp = fnorm1/fnorm;
actred = one - temp * temp;
}
/*
* compute the scaled predicted reduction and
* the scaled directional derivative.
*/
jj = 0;
for (j=0; j<nfree; j++ ) {
wa3[j] = zero;
l = ipvt[j];
temp = wa1[l];
ij = jj;
for (i=0; i<=j; i++ ) {
wa3[i] += fjac[ij]*temp;
ij += 1; /* fjac[i+m*j] */
}
jj += m;
}
/* Remember, alpha is the fraction of the full LM step actually
* taken
*/
temp1 = mp_enorm(nfree,wa3)*alpha/fnorm;
temp2 = (sqrt(alpha*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 = zero;
if (prered != zero) {
ratio = actred/prered;
}
/*
* update the step bound.
*/
if (ratio <= p25) {
if (actred >= zero) {
temp = p5;
} else {
temp = p5*dirder/(dirder + p5*actred);
}
if (((p1*fnorm1) >= fnorm)
|| (temp < p1) ) {
temp = p1;
}
delta = temp*mp_dmin1(delta,pnorm/p1);
par = par/temp;
} else {
if ((par == zero) || (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<nfree; j++ ) {
x[j] = wa2[j];
wa2[j] = diag[ifree[j]]*x[j];
}
for (i=0; i<m; i++ ) {
fvec[i] = wa4[i];
}
xnorm = mp_enorm(nfree,wa2);
fnorm = fnorm1;
iter += 1;
}
/*
* tests for convergence.
*/
if ((fabs(actred) <= conf.ftol) && (prered <= conf.ftol) &&
(p5*ratio <= one) ) {
info = MP_OK_CHI;
}
if (delta <= conf.xtol*xnorm) {
info = MP_OK_PAR;
}
if ((fabs(actred) <= conf.ftol) && (prered <= conf.ftol) && (p5*ratio <= one)
&& ( info == 2) ) {
info = MP_OK_BOTH;
}
if (info != 0) {
goto L300;
}
/*
* tests for termination and stringent tolerances.
*/
if ((conf.maxfev > 0) && (nfev >= conf.maxfev)) {
/* Too many function evaluations */
info = MP_MAXITER;
}
if (iter >= conf.maxiter) {
/* Too many iterations */
info = MP_MAXITER;
}
if ((fabs(actred) <= MP_MACHEP0) && (prered <= MP_MACHEP0) && (p5*ratio <= one) ) {
info = MP_FTOL;
}
if (delta <= MP_MACHEP0*xnorm) {
info = MP_XTOL;
}
if (gnorm <= MP_MACHEP0) {
info = MP_GTOL;
}
if (info != 0) {
goto L300;
}
/*
* end of the inner loop. repeat if iteration unsuccessful.
*/
if (ratio < p0001) goto L200;
/*
* end of the outer loop.
*/
goto OUTER_LOOP;
L300:
/*
* termination, either normal or user imposed.
*/
if (iflag < 0) {
info = iflag;
}
//iflag = 0; //variable never read.
for (i=0; i<nfree; i++) {
xall[ifree[i]] = x[i];
}
if ((conf.nprint > 0) && (info > 0)) {
//iflag = mp_call(funct, m, npar, xall, fvec, 0, private_data); //variable never read.
nfev += 1;
}
/* Compute number of pegged parameters */
npegged = 0;
if (pars) for (i=0; i<npar; i++) {
if ((pars[i].limited[0] && (pars[i].limits[0] == xall[i])) ||
(pars[i].limited[1] && (pars[i].limits[1] == xall[i]))) {
npegged ++;
}
}
/* Compute and return the covariance matrix and/or parameter errors */
if (result && (result->covar || result->xerror)) {
mp_covar(nfree, fjac, ldfjac, ipvt, conf.covtol, wa2);
if (result->covar) {
/* Zero the destination covariance array */
for (j=0; j<(npar*npar); j++) result->covar[j] = 0;
/* Transfer the covariance array */
for (j=0; j<nfree; j++) {
for (i=0; i<nfree; i++) {
result->covar[ifree[j]*npar+ifree[i]] = fjac[j*ldfjac+i];
}
}
}
if (result->xerror) {
for (j=0; j<npar; j++) result->xerror[j] = 0;
for (j=0; j<nfree; j++) {
double cc = fjac[j*ldfjac+j];
if (cc > 0) result->xerror[ifree[j]] = sqrt(cc);
}
}
}
if (result) {
strcpy(result->version, MPFIT_VERSION);
result->bestnorm = mp_dmax1(fnorm,fnorm1);
result->bestnorm *= result->bestnorm;
result->orignorm = orignorm;
result->status = info;
result->niter = iter;
result->nfev = nfev;
result->npar = npar;
result->nfree = nfree;
result->npegged = npegged;
result->nfunc = m;
/* Copy residuals if requested */
if (result->resid) {
for (j=0; j<m; j++) result->resid[j] = fvec[j];
}
}
CLEANUP:
if (fvec) free(fvec);
if (qtf) free(qtf);
if (x) free(x);
if (xnew) free(xnew);
if (fjac) free(fjac);
if (diag) free(diag);
if (wa1) free(wa1);
if (wa2) free(wa2);
if (wa3) free(wa3);
if (wa4) free(wa4);
if (ipvt) free(ipvt);
if (pfixed) free(pfixed);
if (step) free(step);
if (dstep) free(dstep);
if (mpside) free(mpside);
if (ddebug) free(ddebug);
if (ddrtol) free(ddrtol);
if (ddatol) free(ddatol);
if (ifree) free(ifree);
if (qllim) free(qllim);
if (qulim) free(qulim);
if (llim) free(llim);
if (ulim) free(ulim);
return info;
}
/************************fdjac2.c*************************/
static
int mp_fdjac2(mp_func funct,
int m, int n, int *ifree, int npar, double *x, double *fvec,
double *fjac, int ldfjac, double epsfcn,
double *wa, void *priv, int *nfev,
double *step, double *dstep, int *dside,
int *qulimited, double *ulimit,
int *ddebug, double *ddrtol, double *ddatol)
{
/*
* **********
*
* subroutine fdjac2
*
* this subroutine computes a forward-difference approximation
* to the m by n jacobian matrix associated with a specified
* problem of m functions in n variables.
*
* the subroutine statement is
*
* subroutine fdjac2(fcn,m,n,x,fvec,fjac,ldfjac,iflag,epsfcn,wa)