Debian Codegraph @

contrib/ms-sbvar/switch_dw/state_space/sbvar/dw_csminwel.c

raw
1 /*
2 * Copyright (C) 1996 Christopher Sims
3 * Copyright (C) 2003 Karibzhanov, Waggoner, and Zha
4 *
5 * This free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * It is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * If you did not received a copy of the GNU General Public License
16 * with this software, see <http://www.gnu.org/licenses/>.
17 */
18
19 //======= Revisions by T. Zha.
20 //======= Fixing bugs: convering all if-else loop. 02/24/05
21 /*=========================================================
22 * csminwel.c
23 *
24 * Unconstrained minimization. Uses a quasi-Newton method with BFGS update of
25 * the estimated inverse hessian. It is robust against certain pathologies
26 * common on likelihood functions. It attempts to be robust against "cliffs",
27 * i.e. hyperplane discontinuities, though it is not really clear whether what
28 * it does in such cases succeeds reliably.
29 *
30 * function [fhat,xhat,ghat,Hhat,itct,fcount,retcodehat] = csminwelmex(fcn,x0,H0,grad,crit,nit,varargin)
31 * fcn: string naming the objective function to be minimized
32 * x0: initial value of the parameter vector
33 * H0: initial value for the inverse Hessian. Must be positive definite.
34 * grad: Either a string naming a function that calculates the gradient, or the null matrix.
35 * If it's null, the program calculates a numerical gradient. In this case fcn must
36 * be written so that it can take a matrix argument and produce a row vector of values.
37 * crit: Convergence criterion. Iteration will cease when it proves impossible to improve the
38 * function value by more than crit.
39 * nit: Maximum number of iterations.
40 * varargin: A list of optional length of additional parameters that get handed off to fcn each
41 * time it is called.
42 * Note that if the program ends abnormally, it is possible to retrieve the current x,
43 * f, and H from the files g1.mat and H.mat that are written at each iteration and at each
44 * hessian update, respectively. (When the routine hits certain kinds of difficulty, it
45 * write g2.mat and g3.mat as well. If all were written at about the same time, any of them
46 * may be a decent starting point. One can also start from the one with best function value.)
47 *
48 * retcodes: 0, normal step (converged). 1, zero gradient (converged).
49 * 4,2, back and forth adjustment of stepsize didn't finish.
50 * 3, smallest stepsize still improves too slow. 5, largest step still improves too fast.
51 * 6, no improvement found.
52 *---------------------
53 * Fixed 7/17/93 to use inverse-hessian instead of hessian itself in bfgs update.
54 * Fixed 7/19/93 to flip eigenvalues of H to get better performance when it's not psd.
55 *
56 * Note: to set the level of display output, change preprocessor definitions at the beginning of this file.
57 * to display all output, uncomment both VERBOSE_WARNINGS and VERBOSE_DETOUTPUT
58 * to display only warnings without output, uncomment VERBOSE_WARNINGS
59 * to display no ouput, comment both VERBOSE_DETOUTPUT and VERBOSE_WARNINGS
60 *
61 * MATLAB algorithm by Christopher Sims
62 * C implementation by Iskander Karibzhanov
63 * Modified by Dan Waggoner and Tao Zha
64 *
65 * Copyright(c) 1996 Christopher Sims
66 * Copyright(c) 2003 Karibzhanov, Waggoner, and Zha
67 *=======================================================
68 * Revision history by T. Zha:
69 *
70 * 10/3/2002 - 1. corrected problem with memory corruption in C-MEX-file (csminwelmex.c)
71 * (needed to switch fcnRhs[0] back to x[0] before destroying it.
72 * If we don't do this, we will later clear previously destroyed array
73 * (one of x[1], x[2] or x[3]) which causes memory fault.
74 * The reason why fcnRhs[0] pointed to array other than x[0] is
75 * because we use mxSetPr in feval and gfeval.
76 * This was not a problem in C-file (csminwel.c).
77 *
78 * 10/11/2002 - 1. changed csminit function to avoid using fPeak without first initializing it
79 * 2. added two switches in csminit function to assign retcode to 7 for lambda>=4
80 * 3. added one more verbose level to display only warnings or all output *
81 *
82 * 07/13/2005 - Change #define GRADSTPS_CSMINWEL to double GRADSTPS_CSMINWEL in the .h file so the user can change the value.
83 * INDXNUMGRAD_CSMINWEL (gradient method) is now defined in optpackage.h.
84 *
85 * 03/10/2006 - Iskander's use of randmax=1/RAND_MAX is incorrect. Changed to randmax=1.0/RAND_MAX. Note rand() is in stdlib.h and time() is in time.h.
86 * - Fatal BUG by Iskander to have eye(n) instead of eye(nn). Corrected by TZ.
87 *
88 * 02/07/2011 - Modified code and .h so not to use Zha's matrix and optimization packages.
89 ========================================================*/
90
91 #include "dw_csminwel.h"
92 #include "dw_error.h"
93 #include "dw_std.h"
94 #include "dw_rand.h"
95
96 #include <stdio.h>
97 #include <time.h>
98 #include <string.h>
99 #include <math.h>
100 #include <float.h>
101
102 #define VERBOSE_WARNINGS //Display warnings.
103 #define VERBOSE_DETOUTPUT //Display detailed output.
104 #define STRLEN 192
105
106 double GRADSTPS_CSMINWEL = 1.0e-04; //Default value. Will be overwritten by the data in the input file if it exists.
107 //1.0e-04 (for monthly TBVAR)
108 //Step size for numerical gradient only when the value of x is less than 1.0 in absolute value.
109 //If abs(x)>1.0, the step size is GRADSTPS_CSMINWEL*x.
110
111 // Added by DW to eliminate the need for tzmatlab.
112 #define TZ_TRUE 1
113 #define TZ_FALSE 0
114 #define tzMalloc(n,type) dw_malloc(n*sizeof(type))
115 #define tzDestroy(buffer) {if (buffer) { dw_free(buffer); (buffer) = NULL; }}
116 #define tzFclose(file_ptr) {if (file_ptr) { fclose(file_ptr); (file_ptr) = (FILE *)NULL; }}
117 #define NEARINFINITY 1.0E+300
118
119
120 static double GLB_sclForHess;
121 static int numgrad(double *g, double *x, int n,
122 double (*fcn)(double *x, int n, double **args, int *dims),
123 double **args, int *dims);
124 static void csminit(double *fhat, double *xhat, int *fcount, int *retcode,
125 double *x0, double f0, double *g, int badg, double *H0, int n,
126 double (*fcn)(double *x, int n, double **args, int *dims),
127 double **args, int *dims);
128 static void bfgsi(double *H, double *dg, double *dx, int n, int nn);
129 static int peakwall(double *g, int retcode, double *x, int n,
130 int (*gfcn)(double *x, int n, double *g, double **args, int *dims),
131 double (*fcn)(double *x, int n, double **args, int *dims),
132 double **args, int *dims);
133 static double times(double *x, double *y, int n);
134 static double *mtimes(double *x, double *y, int n, int nn);
135 static double *mminus(double *x, double *y, int n);
136
137
138 static FILE *fptr_interesults = (FILE *)NULL; //Printing intermediate results to a file.
139 static char filename_sp2vecs[STRLEN]; //Two vectors. 1st row: numerical gradient; 2nd row: vectorized parameters.
140
141
142
143 #define MAX_NUM_POSSIBLE_BADCASES 25 //After this number, reset inverse hessian (especially dealing with the case for "Correct for low angle").
144 #define EPS (1.0e-10) //Small number to rectify special case of converging to exactly zero function value.
145 #define TERMINATEVALUE (1.0e+300) //If the value of the objective function at the intial value is greater than this, terminates the program.
146 void csminwel(double (*fcn)(double *x, int n, double **args, int *dims),
147 double *xh, int n, double *H, double *gh,
148 int (*gfcn)(double *x, int n, double *g, double **args, int *dims),
149 double *fh, double crit, int *itct, int nit,
150 int *fcount, int *retcodeh, double **args, int *dims)
151 {
152 //If gfcn is passed as NULL, numerical gradient is automatically computed.
153
154 int done=0, badg[4] = { 0, 0, 0, 0 }, badgh, nogh=1, stuck=0;
155 double *x[4], *g[4], f[4], *dg, *dx;
156 int retcode[3], fc=0, ih, nn, i;
157 int i_dw, verbose_err, terminal_err; // needed by DW changes
158 char *err_msg, *err_fmt; // needed by DW changes
159 int cnt_n_badcases = 0; //Must set to 0. Counts the number of bad cases before restarting with the initial diagonal (inverse of) Hessian. Added by TZ.
160 // TSdmatrix *H_dm = tzMalloc(1, TSdmatrix); //H_dm wil point to the same location as H. Removed by DW - only used to reset to diagonal matrix.
161 #ifdef VERBOSE_DETOUTPUT
162 time_t begtime, currentime;
163 #endif
164
165 GLB_sclForHess = H[0]; //The scale factor for the initial (inverse of) Hessian, which was supposed to be **diagonal**. Added by TZ.
166
167 nn = n*n; /* n: dimension size of x or xh */
168 *itct = -1; /* itct: number of actual iterations */
169 *fcount = -1; /* fcount: number of evaluations of the function */
170
171 for (i=0; i<4; i++)
172 x[i] = tzMalloc(n, double); //x[i] = calloc(n, sizeof(double)); Commented out by TZ.
173 memcpy(x[0],xh,n*sizeof(double));
174
175 for (i=0; i<4; i++)
176 g[i] = tzMalloc(n, double); //calloc(n, sizeof(double)); Commented out by TZ.
177
178 f[0] = fcn(x[0],n,args,dims);
179
180 if (f[0] > TERMINATEVALUE) {
181 printf("Bad initial parameter. Minimization is terminated without any returned value!\n");
182 return;
183 }
184
185 if (gfcn)
186 /* if grad is a string, compute it */
187 badg[0] = gfcn(x[0],n,g[0],args,dims);
188 else
189 /* if grad is not string, compute it */
190 badg[0] = numgrad(g[0],x[0],n,fcn,args,dims);
191 retcode[2] = 101;
192 /* iterate until done is false */
193 while (!done) {
194 #ifdef OCTAVE_MEX_FILE
195 OCTAVE_QUIT;
196 #elif defined(MATLAB_MEX_FILE)
197 if (utIsInterruptPending())
198 {
199 mexPrintf("\n\n** Ctrl-C detected, quitting...\n");
200 dw_exit(0);
201 }
202 #endif
203 #ifdef VERBOSE_DETOUTPUT
204 time(&begtime);
205 #endif
206
207 for (i=0; i<n; i++)
208 g[1][i] = g[2][i] = g[3][i] = 0;
209
210 // #ifdef VERBOSE_DETOUTPUT
211 // printf("-----------------\n-----------------\n");
212 // printf("f at the beginning of new iteration, %.10f\nx = ",f[0]);
213 // for (i=0; i<n; i++) {
214 // printf("%15.8g ",x[0][i]);
215 // if (i%4==3) printf("\n");
216 // }
217 // if (i%4>0) printf("\n");
218 // #endif
219
220 (*itct)++;
221 csminit(&f[1],x[1],&fc,&retcode[0],x[0],f[0],g[0],badg[0],H,n,fcn,args,dims);
222 *fcount += fc;
223 /* if retcode1=1 gradient is zero and you are at the peak */
224 if (retcode[0]!=1) {
225 badg[1] = peakwall(g[1],retcode[0],x[1],n,gfcn,fcn,args,dims);
226 /* Bad gradient or back and forth on step length.
227 Possibly at cliff edge. Try perturbing search direction. */
228 if (badg[1]) {
229 double *Hcliff = tzMalloc(nn, double); //calloc(nn,sizeof(double)); Commented out by TZ.
230 // double randmax=1.0/(double)RAND_MAX; //03/10/2006, changed from 1/ to 1.0/ to make randmax a legal double.
231 /* if stuck, give it another try by perturbing Hessian */
232 memcpy(Hcliff,H,nn*sizeof(double));
233 for (i=0; i<nn; i+=n+1)
234 Hcliff[i] *= 1+dw_uniform_rnd(); //rand()*randmax; //Random search. Hcliff[i] *= 1+0.5;
235
236 #ifdef VERBOSE_WARNINGS
237 printf("======= Random search takes place now. =======\n");
238 printf("Cliff. Perturbing search direction.\n");
239 #endif
240
241 csminit(&f[2],x[2],&fc,&retcode[1],x[0],f[0],g[0],badg[0],Hcliff,n,fcn,args,dims);
242 *fcount += fc;
243 if (f[2] < f[0]) {
244 badg[2] = peakwall(g[2],retcode[1],x[2],n,gfcn,fcn,args,dims);
245 if (badg[2]) {
246 double *xx = tzMalloc(n, double), nx; //calloc(n,sizeof(double)), nx; Commented out by TZ.
247
248 #ifdef VERBOSE_WARNINGS
249 printf("Cliff again. Try traversing.\n");
250 #endif
251
252 for (i=0; i<n; i++)
253 xx[i] = x[2][i]-x[1][i];
254 nx = times(xx,xx,n);
255 if (sqrt(nx) < 1e-13) {
256 f[3] = f[0];
257 memcpy(x[3],x[0],n*sizeof(double));
258 badg[3] = 1;
259 retcode[2] = 101;
260 } else {
261 double *gcliff = tzMalloc(n, double), //calloc(n,sizeof(double)), Commented out by TZ.
262 *eye = tzMalloc(nn, double); //calloc(n,sizeof(double)); Bugs of Iskander. Changed from n to nn. 03/10/06.
263 double dfnx = (f[2]-f[1])/nx;
264 for (i=nn-1; i >= 0; i--) eye[i]=0.0; // We need eye to be the identity matrix and so have to zero it. DW - 06/20/2011
265 for (i=0; i<n; i++) {
266 gcliff[i] = dfnx*xx[i];
267 eye[i*(n+1)] = 1;
268 }
269 csminit(&f[3],x[3],&fc,&retcode[2],x[0],f[0],gcliff,0,eye,n,fcn,args,dims);
270 *fcount += fc;
271 badg[3] = peakwall(g[3],retcode[2],x[3],n,gfcn,fcn,args,dims);
272 tzDestroy(eye);
273 tzDestroy(gcliff);
274 }
275 tzDestroy(xx);
276 } else {
277 f[3] = f[0];
278 memcpy(x[3],x[0],n*sizeof(double));
279 badg[3] = 1;
280 retcode[2] = 101;
281 }
282 } else {
283 f[3] = f[0];
284 memcpy(x[3],x[0],n*sizeof(double));
285 badg[3] = 1;
286 retcode[2] = 101;
287 }
288 tzDestroy(Hcliff);
289 } else {
290 /* normal iteration, no walls, or else we're finished here. */
291 f[2] = f[0];
292 f[3] = f[0];
293 badg[2] = 1;
294 badg[3] = 1;
295 retcode[1] = 101;
296 retcode[2] = 101;
297 }
298 }
299 else //Bugs fixed by T. Zha -- 02/24/05.
300 {
301 f[1] = f[0];
302 f[2] = f[0];
303 f[3] = f[0];
304 retcode[1] = retcode[0];
305 retcode[2] = retcode[0];
306 }
307 // % normal iteration, no walls, or else we're finished here.
308 // f2=f; f3=f; badg2=1; badg3=1; retcode2=101; retcode3=101;
309 // f1=f; f2=f; f3=f; retcode2=retcode1; retcode3=retcode1;
310
311 /* how to pick gh and xh */
312 if (f[3]<f[0] && badg[3]==0) {
313 /* if 3 (transversing) was needed, it improved and gradient is good, take that */
314 ih = 3;
315 *fh = f[3];
316 memcpy(xh,x[3],n*sizeof(double));
317 memcpy(gh,g[3],n*sizeof(double));
318 badgh = badg[3];
319 *retcodeh = retcode[2];
320 }
321 else if (f[2]<f[0] && badg[2]==0) {
322 /* if 2 (perturbig) was needed, it improved and gradient is good, take that */
323 ih = 2;
324 *fh = f[2];
325 memcpy(xh,x[2],n*sizeof(double));
326 memcpy(gh,g[2],n*sizeof(double));
327 badgh = badg[2];
328 *retcodeh = retcode[1];
329 }
330 else if (f[1]<f[0] && badg[1]==0) {
331 /* if first try went fine, take that */
332 ih = 1;
333 *fh = f[1];
334 memcpy(xh,x[1],n*sizeof(double));
335 memcpy(gh,g[1],n*sizeof(double));
336 badgh = badg[1];
337 *retcodeh = retcode[0];
338 }
339 else {
340 /* if nothing worked, just take the min of your attempts and compute the gradient */
341 if (f[1] <= f[2])
342 if (f[1] <= f[3]) ih = 1;
343 else ih = 3;
344 else
345 if (f[2] <= f[3]) ih = 2;
346 else ih = 3;
347 *fh = f[ih];
348 memcpy(xh,x[ih],n*sizeof(double));
349 *retcodeh = retcode[ih-1];
350 if (nogh) {
351 nogh = 0;
352 if (gfcn)
353 badgh = gfcn(xh,n,gh,args,dims);
354 else
355 badgh = numgrad(gh,xh,n,fcn,args,dims);
356 }
357 badgh = 1;
358 }
359 /* end of picking */
360 stuck = fabs(*fh-f[0]) < crit; // Used if fh>0. TZ, 9/03.
361 //stuck = (2.0*fabs(*fh-f[0]) <= crit*(fabs(*fh)+fabs(f[0])+EPS)); //Used if fh<0. Added by TZ, 9/03.
362 /* if nothing REALLY worked, too bad, you're stuck */
363 if (!badg[0] && !badgh && !stuck) {
364 /* if you are not stuck, update H0 matrix */
365 dg = mminus(gh,g[0],n);
366 dx = mminus(xh,x[0],n);
367 bfgsi(H,dg,dx,n,nn);
368 tzDestroy(dx);
369 tzDestroy(dg);
370 }
371
372 #ifdef VERBOSE_DETOUTPUT
373 //=== Prints out intermediate results.
374 printf("========================================\n");
375 printf(" (1) New value of the obj. func. on iteration %d: %.9f\n (2) Old value: %.9f\n (3) Downhill improvement: %.9f\n",
376 (int)*itct, *fh, f[0], f[0]-(*fh));
377
378 time(&currentime);
379 //=== Times the iterative progress.
380 printf(" (4) Seconds to complete one iteration: %0.4f\n (5) Current time of day: %s\n\n", difftime(currentime, begtime), ctime(&currentime));
381 fflush(stdout); // Flush the buffer to get out this message without delay.
382 #endif
383
384 //--------- Prints outputs to a file. ---------
385 if ( !(fptr_interesults = fopen(filename_sp2vecs,"wt")) ) {
386 printf("\n\nUnable to create the starting point data file %s in csminwel.c!\n", filename_sp2vecs);
387 dw_exit(EXIT_FAILURE);
388 }
389 fprintf(fptr_interesults, "========= Only one block at a time if more-than-one blocks are used. ========== \n");
390 fprintf(fptr_interesults, "--------Numerical gradient---------\n");
391 for (i=0; i<n; i++) fprintf(fptr_interesults, " %0.16e ", gh[i]);
392 fprintf(fptr_interesults, "\n");
393 fprintf(fptr_interesults, "--------Restarting point---------\n");
394 for (i=0; i<n; i++) fprintf(fptr_interesults, " %0.16e ", xh[i]);
395 fprintf(fptr_interesults, "\n\n");
396 fflush(fptr_interesults);
397 tzFclose(fptr_interesults);
398
399 if ((int)*itct > nit) {
400 #ifdef VERBOSE_WARNINGS
401 // Changed by DW to avoid tzGetDebugFile() call
402 terminal_err=dw_SetTerminalErrors(0);
403 verbose_err=dw_SetVerboseErrors(USER_ERR);
404 err_fmt="Warning: Termination as the maximum number of iterations %d is reached with return code %d.";
405 sprintf(err_msg=dw_malloc(strlen(err_fmt)+21),err_fmt,nit,*retcodeh); // max of 24 digits total in nit and *retcodeh
406 dw_UserError(err_msg);
407 dw_free(err_msg);
408 dw_SetTerminalErrors(terminal_err);
409 dw_SetVerboseErrors(verbose_err);
410 /* printf("\nWarning: Termination as the maximum number of iterations %d is reached with return code %d.\n", nit, *retcodeh); */
411 /* fprintf(tzGetDebugFile(), "\nWarning: Termination as the maximum number of iterations %d is reached with return code %d.\n", nit, *retcodeh); */
412 #endif
413 done = 1;
414 }
415 else if (stuck) //stuck = 1 means fabs(*fh-f[0]) < crit, which means converged. why do we use the word "stuck" is beyond me.
416 {
417 #ifdef VERBOSE_DETOUTPUT
418 // Changed by DW to avoid tzGetDebugFile() call
419 terminal_err=dw_SetTerminalErrors(0);
420 verbose_err=dw_SetVerboseErrors(USER_ERR);
421 err_fmt="Convergence (improvement < crit %.4e) with return code %d.";
422 sprintf(err_msg=dw_malloc(strlen(err_fmt)+21),err_fmt,crit,*retcodeh); // max of 24 characters total in crit and *retcodeh
423 dw_UserError(err_msg);
424 dw_free(err_msg);
425 dw_SetTerminalErrors(terminal_err);
426 dw_SetVerboseErrors(verbose_err);
427 //printf("\nConvergence (improvement < crit %.4e) with return code %d.\n", crit, *retcodeh);
428 //fprintf(tzGetDebugFile(), "\nConvergence (improvement < crit %.4e) with return code %d.\n", crit, *retcodeh);
429 #endif
430
431 done = 1;
432 }
433
434
435 #ifdef VERBOSE_WARNINGS
436 switch (*retcodeh) {
437 case 1:
438 printf("\nConverged: Zero gradient.\n"); break;
439 case 2:
440 printf("\nWarning: Back adjustment of stepsize didn't finish.\n"); break;
441 case 3:
442 printf("\nWarning: Smallest stepsize still improving too slow.\n"); break;
443 case 4:
444 printf("\nWarning: Forth adjustment of stepsize didn't finish.\n"); break;
445 case 6:
446 printf("\nWarning: Smallest step still improving too slow, reversed gradient.\n"); break;
447 case 5:
448 printf("\nWarning: Largest stepsize still improving too fast.\n"); break;
449 case 7:
450 printf("\nWarning: Possible inaccuracy in Hessian matrix.\n"); break;
451 }
452 #endif
453
454 //=== Restarts from the initial (inverse of) Hessian when stuck for a while in bad cases. This can happen even *retcodeh=0 while stuck=0.
455 //if (*retcodeh && *retcodeh != 1)
456 if (!done)
457 if (cnt_n_badcases++ >= MAX_NUM_POSSIBLE_BADCASES)
458 {
459 // changed by DW to initialize H to diagonal matrix
460 for (i_dw=nn-1; i_dw >= 0; i_dw--) H[i_dw]=0.0;
461 for (i_dw=nn-1; i_dw >= 0; i_dw-=n+1) H[i_dw]=GLB_sclForHess;
462 /* H_dm->M = H; */
463 /* H_dm->nrows = H_dm->ncols = n; */
464 /* InitializeDiagonalMatrix_lf(H_dm, GLB_sclForHess); */
465 /* //H_dm->flag = M_GE | M_SU | M_SL; //Hessian is symmetric. */
466 cnt_n_badcases = 0; //Reset after we restart wtih the initial Hessian.
467 #ifdef VERBOSE_WARNINGS
468 // Changed by DW to avoid tzGetDebugFile() call
469 terminal_err=dw_SetTerminalErrors(0);
470 verbose_err=dw_SetVerboseErrors(USER_ERR);
471 err_fmt="Hessian is reset to the initial value because the maximum number of possibly bad cases, %d, is reached with return code %d!";
472 // max of 24 digits total in MAX_NUM_POSSIBLE_BADCASES and *retcodeh
473 sprintf(err_msg=dw_malloc(strlen(err_fmt)+21),err_fmt,MAX_NUM_POSSIBLE_BADCASES,*retcodeh);
474 dw_UserError(err_msg);
475 dw_free(err_msg);
476 dw_SetTerminalErrors(terminal_err);
477 dw_SetVerboseErrors(verbose_err);
478 /* printf("Hessian is reset to the initial value because the maximum number of possibly bad cases, %d, is reached with return code %d!\n", MAX_NUM_POSSIBLE_BADCASES, *retcodeh); */
479 /* fprintf(tzGetDebugFile(), "Hessian is reset to the initial value because the maximum number of possibly bad cases, %d, is reached with return code %d!\n", MAX_NUM_POSSIBLE_BADCASES, *retcodeh); */
480 #endif
481 }
482
483 f[0] = *fh;
484 memcpy(x[0],xh,n*sizeof(double));
485 memcpy(g[0],gh,n*sizeof(double));
486 badg[0] = badgh;
487 }
488
489
490 //--------- Prints outputs to a file. ---------
491 if ( !(fptr_interesults = fopen(filename_sp2vecs,"wt")) ) {
492 printf("\n\nUnable to create the starting point data file %s in csminwel.c!\n", filename_sp2vecs);
493 dw_exit(EXIT_FAILURE);
494 }
495 fprintf(fptr_interesults, "========= Only a block at a time if more-than-one blocks are used. ========== \n");
496 fprintf(fptr_interesults, "--------Numerical gradient---------\n");
497 for (i=0; i<n; i++) fprintf(fptr_interesults, " %0.16e ", g[0][i]);
498 fprintf(fptr_interesults, "\n");
499 fprintf(fptr_interesults, "--------Restarting point---------\n");
500 for (i=0; i<n; i++) fprintf(fptr_interesults, " %0.16e ", x[0][i]);
501 fprintf(fptr_interesults, "\n\n");
502 fflush(fptr_interesults);
503 tzFclose(fptr_interesults);
504
505
506 //=== Frees memory.
507 for (i=0; i<4; i++) {
508 tzDestroy(g[i]);
509 tzDestroy(x[i]);
510 }
511 // tzDestroy(H_dm); deleted by DW
512 }
513 #undef MAX_NUM_POSSIBLE_BADCASES
514 #undef EPS
515 #undef TERMINATEVALUE
516
517 #if INDXNUMGRAD_CSMINWEL == 1
518 #define SCALE 1.0
519 static int numgrad(double *g, double *x, int n,
520 double (*fcn)(double *x, int n, double **args, int *dims),
521 double **args, int *dims) {
522 //Forward difference gradient method.
523 double delta, deltai;
524 double f0, g0, ff, tmp, *xp;
525 int i;
526 int badg;
527 f0 = fcn(x,n,args,dims);
528 badg = 0;
529 for (i=0, xp=x; i<n; i++, xp++, g++) {
530 delta=SCALE*GRADSTPS_CSMINWEL, deltai=1.0/delta; //e+5/SCALE;
531
532 tmp = *xp;
533 *xp += delta;
534 delta = *xp - tmp; // This increases the precision slightly. Added by TZ.
535 if ( (ff=fcn(x,n,args,dims)) < NEARINFINITY ) g0 = (ff-f0)*deltai; //Not over the boundary.
536 else {
537 //Switches to the other side of the boundary.
538 *xp = tmp - delta;
539 g0 = (f0-fcn(x,n,args,dims))*deltai;
540 }
541
542 *xp = tmp; //Puts back to the original place. TZ, 9/03.
543 if (fabs(g0)<1.0e+15)
544 *g = g0;
545 else {
546 #ifdef VERBOSE_WARNINGS
547 printf("Bad gradient.\n");
548 #endif
549
550 *g = 0;
551 badg = 1;
552 }
553 }
554 return badg;
555 }
556 //#elif INDXNUMGRAD_CSMINWEL == 2
557 #else
558 //#define STPS 1.0e-04 // 6.0554544523933391e-6 step size = pow(DBL_EPSILON,1.0/3)
559 static int numgrad(double *g, double *x, int n,
560 double (*fcn)(double *x, int n, double **args, int *dims),
561 double **args, int *dims) {
562 //Central difference gradient method. Added by TZ.
563 double dh;
564 double f0, fp, fm, tmp, *xp;
565 int i;
566 int badg;
567
568 badg = 0;
569 for (i=0, xp=x; i<n; i++, xp++, g++) {
570 dh = fabs(*xp)<=1 ? GRADSTPS_CSMINWEL : GRADSTPS_CSMINWEL*(*xp);
571
572 tmp = *xp;
573 *xp += dh;
574 dh = *xp - tmp; // This increases the precision slightly.
575 fp = fcn(x,n,args,dims);
576 *xp = tmp - dh;
577 fm = fcn(x,n,args,dims);
578
579 //=== Checking the boundary condition for the minimization problem.
580 if (fp >= NEARINFINITY) {
581 *xp = tmp; //Puts back to the original place. TZ, 9/03.
582 f0 = fcn(x,n,args,dims);
583 *g = (f0-fm)/dh;
584 }
585 else if (fm >= NEARINFINITY) {
586 //Switches to the other side of the boundary.
587 *xp = tmp; //Puts back to the original place. TZ, 9/03.
588 f0 = fcn(x,n,args,dims);
589 *g = (fp-f0)/dh;
590 }
591 else {
592 *g = (fp-fm)/(2.0*dh);
593 *xp = tmp; //Puts back to the original place. TZ, 9/03.
594 }
595
596 if (fabs(*g)>1.0e+15) {
597 #ifdef VERBOSE_WARNINGS
598 printf("Bad gradient.\n");
599 #endif
600 *g = 0.0;
601 badg = 1;
602 }
603 }
604 return badg;
605 }
606 #endif
607 ////#undef INDXNUMGRAD_CSMINWEL
608 ////#undef GRADSTPS_CSMINWEL
609
610
611
612
613 #define ANGLE 0.01 //When output of this variable becomes negative, we have a wrong analytical graident.
614 //.005 works for identified VARs and OLS.
615 //.005 implies 89.71 degrees (acrcos(ANGLE)*180/pi).
616 //.01 implies 89.43 degrees (acrcos(ANGLE)*180/pi).
617 //.05 implies 87.13 degrees (acrcos(ANGLE)*180/pi).
618 //.1 implies 84.26 degrees (acrcos(ANGLE)*180/pi).
619 #define THETA .4 //(0<THETA<.5) THETA near .5 makes long line searches, possibly fewer iterations.
620 //.1 works for OLS or other nonlinear functions.
621 //.3 works for identified VARs.
622 #define FCHANGE 1000
623 #define MINLAMB 1e-9
624 #define MINDFAC .01
625 static void csminit(double *fhat, double *xhat, int *fcount, int *retcode,
626 double *x0, double f0, double *g, int badg, double *H0, int n,
627 double (*fcn)(double *x, int n, double **args, int *dims),
628 double **args, int *dims) {
629 double lambda=1, gnorm=0, dxnorm=0, factor=3, lambdaPeak=0;
630 double f, dfhat, a, tmp, fPeak=f0, lambdaMax=DBL_MAX;
631 double *dx, *dxtest;
632 int done=0, shrink=1, shrinkSignal, growSignal;
633 int i;
634
635 memcpy(xhat, x0, n*sizeof(double)); //Iskander's original code does not have this line, which is a major bug. Corrected by TZ.
636 *fhat = f0;
637 *fcount = 0;
638 *retcode = 0;
639 gnorm = sqrt(times(g,g,n));
640 if ((gnorm < 1.e-12) && !badg)
641 *retcode = 1; /* gradient convergence */
642 else {
643 /* with badg 1, we don't try to match rate of improvement to directional
644 derivative. We're satisfied just to get some improvement in f. */
645 dx = tzMalloc(n, double); //dx = calloc(n, sizeof(double)); Commented out by TZ.
646 //if (!dx) printf("Dynamic memory allocation error.\n"); Commnted out by TZ.
647 for (i=0; i<n; i++)
648 dx[i] = -times(&H0[i*n],g,n);
649 dxnorm = sqrt(times(dx,dx,n));
650 if (dxnorm > 1e12) {
651 #ifdef VERBOSE_WARNINGS
652 printf("Near-singular H problem.\n");
653 #endif
654
655 for (i=0; i<n; i++)
656 dx[i] *= FCHANGE/dxnorm;
657 }
658 dfhat = times(dx,g,n);
659 if (!badg) {
660 /* If the gradient is good, test for alignment of dx with gradient and fix if necessary */
661
662 if ((a=-dfhat/(gnorm*dxnorm))<ANGLE) {
663 tmp = (ANGLE*dxnorm+dfhat/gnorm)/gnorm;
664 for (i=0; i<n; i++)
665 dx[i] -= tmp*g[i];
666 dfhat = times(dx,g,n);
667 dxnorm = sqrt(times(dx,dx,n));
668
669 #ifdef VERBOSE_DETOUTPUT
670 printf("Correct for low angle: %g\n",a);
671 #endif
672 }
673 }
674
675 #ifdef VERBOSE_DETOUTPUT
676 printf("Predicted improvement: %18.9f, Norm of gradient: %18.9f\n", -dfhat*0.5, gnorm);
677 #endif
678
679 dxtest = tzMalloc(n, double); //calloc(n, sizeof(double)); Commented out by TZ.
680 while (!done) {
681 for (i=0; i<n; i++)
682 dxtest[i] = x0[i]+dx[i]*lambda;
683 f = fcn(dxtest,n,args,dims);
684
685 #ifdef VERBOSE_DETOUTPUT
686 printf("lambda = %10.5g; f = %20.7e\n",lambda,f);
687 #endif
688
689 if (f<*fhat) {
690 *fhat = f;
691 memcpy(xhat,dxtest,n*sizeof(double));
692 }
693 (*fcount)++;
694 tmp = -THETA*dfhat*lambda;
695
696 /* the optimal lambda should be such that f0-f > -THETA*dfhat*lambda (see Berndt et al.)
697 If that's not the case and grad is good, OR
698 if grad is bad and f is not going down, shrinkSignal = 1 */
699 shrinkSignal = ( !badg && (f0-f <= (tmp>0?tmp:0)) ) ||
700 ( badg && (f0-f < 0 ) );
701
702 /* the optimal lambda should also be such that f0-f<-(1-THETA)*dfhat*lambda
703 If that's not the case with lambda>0, AND grad is good, growthSignal = 1 */
704 growSignal = !badg && ( (lambda > 0) && (f0-f >= -(1-THETA)*dfhat*lambda) );
705
706 /* If shrinkSignal=1 AND ( lambda>lambdaPeak or lambda negative )
707 (note when lambdaPeak=0 the second part only excludes lambda=0)
708 try shrinking lambda */
709 if ( shrinkSignal && ( (lambda>lambdaPeak) || (lambda<0) ) ) {
710 /* if shrink=0 OR lambda/factor is already smaller than lambdaPeak, increase factor */
711 if ( (lambda>0) && ((!shrink) || (lambda/factor <= lambdaPeak)) ) {
712 shrink = 1;
713 factor = pow(factor,.6);
714 while (lambda/factor <= lambdaPeak)
715 factor = pow(factor,.6);
716 if (fabs(factor-1)<MINDFAC) {
717 if (fabs(lambda) < 4)
718 *retcode = 2;
719 else
720 *retcode = 7;
721 done = 1;
722 }
723 }
724 if ((lambda<lambdaMax) && (lambda>lambdaPeak))
725 lambdaMax=lambda;
726 /* shrink lambda */
727 lambda /= factor;
728 /* if lambda has already been shrunk as much as possible */
729 if (fabs(lambda) < MINLAMB)
730 {
731 /* if lambda is positive AND you have not made any improvement
732 try going against gradient, which may be inaccurate */
733 if ((lambda > 0) && (f0 <= *fhat))
734 lambda = -lambda*pow(factor,6);
735 else {
736 /* if lambda is negative: let it be known and quit trying */
737 if (lambda < 0)
738 *retcode = 6;
739 /* if you have not made any imporvement:
740 let it be known and quit trying */
741 else
742 *retcode = 3;
743 done = 1;
744 }
745 }
746 }
747 /* If growSignal=1 and lambda positive OR ( lambda>lambdaPeak or lambda negative )
748 (note when lambdaPeak=0 the second part only excludes lambda=0)
749 try increase lambda */
750 else
751 if ( (growSignal && (lambda > 0) ) ||
752 ( shrinkSignal && (lambda <= lambdaPeak) && (lambda > 0) ) ) {
753 if (shrink) {
754 shrink = 0;
755 factor = pow(factor,.6);
756 if (fabs(factor-1) < MINDFAC) {
757 if (fabs(lambda) < 4)
758 *retcode = 4;
759 else
760 *retcode = 7;
761 done = 1;
762 }
763 }
764 if ( (f<fPeak) && (lambda>0) ) {
765 fPeak = f;
766 lambdaPeak = lambda;
767 if (lambdaMax <= lambdaPeak)
768 lambdaMax = lambdaPeak*factor*factor;
769 }
770 /* increase lambda (up to 1e20) */
771 lambda *= factor;
772 /* if lambda has been increased up to the limit and
773 you have not made any imporvement:
774 let it be known and quit trying */
775 if (fabs(lambda) > 1e20) {
776 *retcode = 5;
777 done = 1;
778 }
779 }
780 /* If growthSignal=shrinkSignal=0 you found a good lambda, you are done */
781 else {
782 done = 1;
783 *retcode = factor<1.2 ? 7 : 0;
784 }
785 }
786 tzDestroy(dxtest);
787 tzDestroy(dx);
788 }
789 #ifdef VERBOSE_DETOUTPUT
790 printf("Norm of dx %10.5g\n", dxnorm);
791 #endif
792 }
793 #undef ANGLE
794 #undef THETA
795 #undef FCHANGE
796 #undef MINLAMB
797 #undef MINDFAC
798
799
800 static double times(double *x, double *y, int n) {
801 double z = 0;
802 int i;
803 for (i=0; i<n; i++, x++, y++)
804 z += (*x)*(*y);
805 return z;
806 }
807
808 static int peakwall(double *g, int retcode, double *x, int n,
809 int (*gfcn)(double *x, int n, double *g, double **args, int *dims),
810 double (*fcn)(double *x, int n, double **args, int *dims),
811 double **args, int *dims) {
812 /* if retcode=2 or 4 you have shrunk or increased lambda as much as you could:
813 exhausted search possibilities the csminit step has failed */
814 if (retcode==2 || retcode==4)
815 return 1;
816 else
817 /* if you are not at the peak but the csminit has improved,
818 compute the gradient again to update H0 */
819 if (gfcn)
820 return gfcn(x,n,g,args,dims);
821 else
822 return numgrad(g,x,n,fcn,args,dims);
823 }
824
825 static void bfgsi(double *H, double *dg, double *dx, int n, int nn) {
826 double *Hdg, *dxdx, *dxHdg, *Hdgdx;
827 double dgdx, m;
828 int i;
829 // TSdmatrix *H_dm = NULL; changed by DW
830
831 Hdg = tzMalloc(n, double); //calloc(n, sizeof(double)); Commented out by TZ.
832 //if (!Hdg) printf("Dynamic memory allocation error.\n"); Commented out by TZ.
833
834 /* Hdg = H0*dg; */
835 for (i=0; i<n; i++)
836 Hdg[i] = times(&H[i*n],dg,n);
837 /* dgdx = dg'*dx; */
838 dgdx = 1/times(dg,dx,n);
839 if (fabs(dgdx)<1e12) {
840 dxdx = mtimes(dx,dx,n,nn);
841 dxHdg = mtimes(dx,Hdg,n,nn);
842 Hdgdx = mtimes(Hdg,dx,n,nn);
843 m = 1+times(dg,Hdg,n)*dgdx;
844 for (i=0; i<nn; i++, H++, dxdx++, dxHdg++, Hdgdx++)
845 *H += (m*(*dxdx)-(*dxHdg)-(*Hdgdx))*dgdx;
846 dw_free(Hdgdx-nn);
847 Hdgdx=NULL;
848 dw_free(dxHdg-nn);
849 dxHdg = NULL;
850 dw_free(dxdx-nn);
851 dxdx = NULL;
852 }
853 else {
854 //=== Restarting the inverse of Hessian at its initial value. Added by TZ.
855 // changed by DW to eliminate matrix references.
856 for (i=nn-1; i >= 0; i--) H[i]=0.0;
857 for (i=nn-1; i >= 0; i-=n+1) H[i]=GLB_sclForHess;
858 /* H_dm = tzMalloc(1, TSdmatrix); //H_dm wil point to the same location as H. */
859 /* H_dm->M = H; */
860 /* H_dm->nrows = H_dm->ncols = n; */
861 /* InitializeDiagonalMatrix_lf(H_dm, GLB_sclForHess); */
862 /* //H_dm->flag = M_GE | M_SU | M_SL; //Hessian is symmetric. */
863 /* tzDestroy(H_dm); */
864
865 #ifdef VERBOSE_WARNINGS
866 printf("BFGS update failed.\n");
867 printf("|dg| = %f |dx| = %f\n",sqrt(times(dg,dg,n)),sqrt(times(dx,dx,n)));
868 printf("dg\'*dx = %f\n",dgdx);
869 printf("|H*dg| = %f\n",sqrt(times(Hdg,Hdg,n)));
870 #endif
871 }
872 tzDestroy(Hdg);
873 }
874
875 static double *mtimes(double *x, double *y, int n, int nn) {
876 double *x0;
877 double *z;
878 int i, j;
879 z = tzMalloc(nn, double); //calloc(nn, sizeof(double)); Commented out by TZ.
880 for (i=0, x0=x; i<n; i++, y++)
881 for (j=0, x=x0; j<n; j++, x++, z++)
882 *z = (*x)*(*y);
883 return z-nn;
884 }
885
886 static double *mminus(double *x, double *y, int n) {
887 double *z;
888 int i;
889 z = tzMalloc(n, double); //calloc(n, sizeof(double)); Commented out by TZ.
890 for (i=0; i<n; i++, x++, y++, z++)
891 *z = (*x)-(*y);
892 return z-n;
893 }
894
895
896 //=== The following two extern functions to be accessed by other C files.
897 void csminwel_SetPrintFile(char *filename) {
898 if (!filename) sprintf(filename_sp2vecs, "outdata5csminwel.prn"); //Default filename.
899 else if (STRLEN-1 < strlen(filename))
900 {
901 dw_SetTerminalErrors(USER_ERR);
902 dw_SetVerboseErrors(USER_ERR);
903 dw_UserError(".../csminwel.c: the allocated length STRLEN for filename_sp2vecs is too short. Must increase the string length");
904 }
905 else strcpy(filename_sp2vecs, filename);
906 }
907
908 #undef STRLEN
909
910
911