Debian Codegraph @

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

raw
1 /*
2 * Copyright (C) 1996-2011 Daniel Waggoner and Tao Zha
3 *
4 * This free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * It is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * If you did not received a copy of the GNU General Public License
15 * with this software, see <http://www.gnu.org/licenses/>.
16 */
17
18 #include "switch.h"
19 #include "switchio.h"
20 #include "switch_opt.h"
21 #include "VARbase.h"
22 #include "VARio.h"
23 #include "dw_error.h"
24 #include "dw_ascii.h"
25 #include "dw_parse_cmd.h"
26 #include "dw_rand.h"
27 #include "dw_sbvar_command_line.h"
28 #include "dw_std.h"
29 #include "sbvar_estimate.h"
30
31 #include "dw_csminwel.h"
32
33 #include <time.h>
34 #include <string.h>
35 #include <stdlib.h>
36 #include <math.h>
37
38 /*******************************************************************************/
39 /*******************************************************************************/
40 /*******************************************************************************//*
41 Obtains estimate info from command line.
42
43 Additional command line parameters
44
45 BLOCKWISE ESTIMATION CONTROL
46 -cb <real>
47 convergence criterion starting value (default value = 1.0e-03)
48 -ce <real>
49 convergence criterion ending value (default value = 1.03-06)
50 -ci <real>
51 convergence criterion increment value (default value = 0.1)
52 -ib <integer>
53 maximum interations starting value (default value = 50)
54 -ii <real>
55 maximum interations increment value (default value = 2.0)
56 -mb <integer>
57 maximum block iterations (default value = 100)
58
59 REPEATING ESTIMATION TO ENSURE LOCAL CONVERGENCE
60 -repeat_max <integer>
61 maximum number of times to repeat csminwel runs. (default value = 10)
62 -repeat_tol_obj <real>
63 convergence criterion for objective function (default value = 0.1)
64 -repeat_tol_parms <real>
65 convergence criterion for parameter values (default value = 0.1)
66
67 PERTURBATION TECHNIQUES TO ENSURE GLOBAL CONVERGENCE
68 -random <integer>
69 number of large perturbations to make at each stage of the estimation
70 process. (default value = 5)
71 -random_small <integer>
72 number of small perturbations to make after the large perturbations have
73 stopped inproving. (default value = 5)
74 -random_small_ndraws <integer>
75 number of consecutive posterior draws to make when producing a small
76 perturbation. (default value = 1)
77 -random_max <integer>
78 maximum number of stages allowed (default value = 20)
79 -random_tol_obj <real>
80 convergence criterion for objective function (default value = 0.1)
81 -random_tol_parms <real>
82 convergence criterion for parameter values (default value = 0.1)
83
84 */
85 TEstimateInfo* SetupEstimateFromVARCommandLine(int nargs, char **args, TVARCommandLine *cmd)
86 {
87 TEstimateInfo *info;
88
89 if (!cmd) return (TEstimateInfo*)NULL;
90
91 // Create info
92 info=(TEstimateInfo*)dw_malloc(sizeof(TEstimateInfo));
93 info->cmd=cmd;
94
95 // Default values
96 info->criterion_start=dw_ParseFloating_String(nargs,args,"cb",1.0e-3);
97 info->criterion_end=dw_ParseFloating_String(nargs,args,"ce",1.0e-6);
98 info->criterion_increment=dw_ParseFloating_String(nargs,args,"ci",0.1);
99 info->max_iterations_start=dw_ParseInteger_String(nargs,args,"ib",50);
100 info->max_iterations_increment=dw_ParseFloating_String(nargs,args,"ii",2.0);
101 info->max_block_iterations=dw_ParseInteger_String(nargs,args,"mb",100);
102
103 info->repeat_max=dw_ParseInteger_String(nargs,args,"repeat_max",10);
104 info->repeat_tol_obj=dw_ParseFloating_String(nargs,args,"repeat_tol_obj",0.1);
105 info->repeat_tol_parms=dw_ParseFloating_String(nargs,args,"repeat_tol_parms",0.1);
106
107 info->random=dw_ParseInteger_String(nargs,args,"random",5);
108 info->random_small=dw_ParseInteger_String(nargs,args,"random_small",5);
109 info->random_small_ndraws=dw_ParseInteger_String(nargs,args,"random_small_ndraws",1);
110 info->random_max=dw_ParseInteger_String(nargs,args,"random_max",20);
111 info->random_tol_obj=dw_ParseFloating_String(nargs,args,"random_tol_obj",0.1);
112 info->random_tol_parms=dw_ParseFloating_String(nargs,args,"random_tol_parms",0.1);
113
114 // Output tag
115 OutTag_VARCommandLine(info->cmd);
116
117 // Output filenames
118 info->csminwel_output_filename=CreateFilenameFromTag("%sest_csminwel_%s.out",info->cmd->out_tag,info->cmd->out_directory);
119 info->intermediate_output_filename=CreateFilenameFromTag("%sest_intermediate_%s.out",info->cmd->out_tag,info->cmd->out_directory);
120 if (info->cmd->out_filename)
121 info->final_output_filename=CreateFilenameFromTag("%s%s",info->cmd->out_filename,info->cmd->out_directory);
122 else
123 info->final_output_filename=CreateFilenameFromTag("%sest_final_%s.out",info->cmd->out_tag,info->cmd->out_directory);
124
125 return info;
126 }
127
128 TEstimateInfo* SetupEstimateFromCommandLine(int nargs, char **args)
129 {
130 return SetupEstimateFromVARCommandLine(nargs,args,CreateTStateModel_VARCommandLine(nargs,args,(TVARCommandLine*)NULL));
131 }
132
133 void FreeEstimateInfo(TEstimateInfo *info)
134 {
135 if (info)
136 {
137 if (info->csminwel_output_filename) dw_free(info->csminwel_output_filename);
138 if (info->intermediate_output_filename) dw_free(info->intermediate_output_filename);
139 if (info->final_output_filename) dw_free(info->final_output_filename);
140 Free_VARCommandLine(info->cmd);
141 dw_free(info);
142 }
143 }
144 /*******************************************************************************/
145 /*******************************************************************************/
146 /*******************************************************************************/
147
148 void FindMode_VAR_csminwel(TEstimateInfo *estimate, FILE *f)
149 {
150 TStateModel *model=estimate->cmd->model;
151 int iteration, total_iteration, i, j, size_VAR, pos_VAR, size_Q, pos_Q;
152 double objective, objective_last, likelihood, prior;
153 int **block;
154 FILE *f_out;
155 char *header, *fmt="Iteration %d: ";
156
157 // csminwel arguments
158 int itct, fcount, retcodeh, nit;
159 double *x, fh, crit;
160 TMatrix H;
161 TVector g;
162
163 f_out=f ? f : dw_CreateTextFile(estimate->intermediate_output_filename);
164
165 //==== Allocate memory ===
166 size_VAR=NumberFreeParametersTheta(model);
167 size_Q=NumberFreeParametersQ(model);
168 pos_VAR=0;
169 pos_Q=size_VAR;
170 x=(double*)dw_malloc((size_VAR + size_Q)*sizeof(double));
171
172 //=== Set starting value ===
173 ConvertQToFreeParameters(model,x+pos_Q);
174 ConvertThetaToFreeParameters(model,x+pos_VAR);
175
176 //=== Set csminwel output file ===
177 csminwel_SetPrintFile(estimate->csminwel_output_filename);
178
179 //=== Print Initial Values ===
180 fprintf(f_out,"\n//=== Initial Values ===//\n");
181 fprintf(f_out,"Likelihood value: %22.14le\n",objective=likelihood=LogLikelihood_StatesIntegratedOut(model));
182 fprintf(f_out,"Prior value: %22.14le\n",prior=LogPrior(model));
183 fprintf(f_out,"Posterior value: %22.14le\n\n",likelihood+prior);
184
185 header="Initial: ";
186 WriteBaseTransitionMatrices(f_out,(char*)NULL,header,model);
187 Write_VAR_Parameters(f_out,(char*)NULL,header,model);
188 fflush(f_out);
189
190 //=== Create blocking structure ===
191 block=dw_CreateRectangularArray_int(2,2);
192 block[0][0]=size_VAR; block[0][1]=pos_VAR;
193 block[1][0]=size_Q; block[1][1]=pos_Q;
194
195 //=== Objective ===
196 if (estimate->cmd->MLE)
197 objective=likelihood;
198 else
199 objective=likelihood+prior;
200
201 for (total_iteration=1, crit=estimate->criterion_start, nit=estimate->max_iterations_start;
202 crit >= estimate->criterion_end;
203 crit*=estimate->criterion_increment, nit*=(int)estimate->max_iterations_increment)
204 {
205 for (iteration=1; iteration <= estimate->max_block_iterations; total_iteration++, iteration++)
206 {
207 objective_last=objective;
208
209 fprintf(f_out,"\n\n//=== Iteration %d ===//\n",total_iteration);
210 fprintf(f_out,"Criterion/Max Iteration: %le %d\n",crit,nit);
211 fprintf(f_out,"Previous likelihood value: %22.14le\n",likelihood);
212 fprintf(f_out,"Previous prior value: %22.14le\n",prior);
213 fprintf(f_out,"Previous posterior value: %22.14le\n\n",prior+likelihood);
214 fflush(f_out);
215
216 for (i=0; i < dw_DimA(block); i++)
217 if (block[i][0] > 0)
218 {
219 g=CreateVector(block[i][0]);
220 H=IdentityMatrix((TMatrix)NULL,block[i][0]);
221 ProductMS(H,H,INI_H_CSMINWEL);
222
223 SetupObjectiveFunction(model,x+block[i][1],x+pos_Q,x+pos_VAR);
224
225 if (estimate->cmd->MLE)
226 csminwel(MLEObjectiveFunction_csminwel,x+block[i][1],block[i][0],pElementM(H),pElementV(g),NULL,
227 &fh,crit,&itct,nit,&fcount,&retcodeh,NULL,NULL);
228 else
229 csminwel(PosteriorObjectiveFunction_csminwel,x+block[i][1],block[i][0],pElementM(H),pElementV(g),NULL,
230 &fh,crit,&itct,nit,&fcount,&retcodeh,NULL,NULL);
231
232 ConvertFreeParametersToQ(model,x+pos_Q);
233 ConvertFreeParametersToTheta(model,x+pos_VAR);
234
235 FreeMatrix(H);
236 FreeVector(g);
237
238 fprintf(f_out,"Likelihood value after pass %d: %22.14le\n",i,likelihood=LogLikelihood_StatesIntegratedOut(model));
239 fprintf(f_out,"Prior value after pass %d: %22.14le\n",i,prior=LogPrior(model));
240 fprintf(f_out,"Posterior value after pass %d: %22.14le\n",i,likelihood+prior);
241 fprintf(f_out,"Csminwel return code: %d\n\n",retcodeh);
242 fflush(f_out);
243 }
244
245 for (j=10, i=1; total_iteration >= j; j*=10, i++);
246 sprintf(header=(char*)dw_malloc(strlen(fmt) + i - 1),fmt,total_iteration);
247 WriteBaseTransitionMatrices(f_out,(char*)NULL,header,model);
248 Write_VAR_Parameters(f_out,(char*)NULL,header,model);
249 dw_free(header);
250 fflush(f_out);
251
252 if (estimate->cmd->MLE)
253 objective=likelihood;
254 else
255 objective=likelihood+prior;
256
257 if (fabs(objective - objective_last) <= crit) break;
258 }
259
260 objective_last=objective;
261
262 fprintf(f_out,"\n\n//=== Iteration %d ===//\n",++total_iteration);
263 fprintf(f_out,"Criterion/Max Iteration: %le %d\n",crit,nit);
264 fprintf(f_out,"Previous likelihood value: %22.14le\n",likelihood);
265 fprintf(f_out,"Previous prior value: %22.14le\n",prior);
266 fprintf(f_out,"Previous posterior value: %22.14le\n\n",prior+likelihood);
267 fflush(f_out);
268
269 g=CreateVector(pos_Q+pos_VAR);
270 H=IdentityMatrix((TMatrix)NULL,pos_Q+pos_VAR);
271 ProductMS(H,H,INI_H_CSMINWEL);
272
273 SetupObjectiveFunction(model,x,x+pos_Q,x+pos_VAR);
274
275 if (estimate->cmd->MLE)
276 csminwel(MLEObjectiveFunction_csminwel,x,pos_Q+pos_VAR,pElementM(H),pElementV(g),NULL,
277 &fh,crit,&itct,nit,&fcount,&retcodeh,NULL,NULL);
278 else
279 csminwel(PosteriorObjectiveFunction_csminwel,x,pos_Q+pos_VAR,pElementM(H),pElementV(g),NULL,
280 &fh,crit,&itct,nit,&fcount,&retcodeh,NULL,NULL);
281
282 ConvertFreeParametersToQ(model,x+pos_Q);
283 ConvertFreeParametersToTheta(model,x+pos_VAR);
284
285 FreeMatrix(H);
286 FreeVector(g);
287
288 fprintf(f_out,"Likelihood value: %22.14le\n",likelihood=LogLikelihood_StatesIntegratedOut(model));
289 fprintf(f_out,"Prior value: %22.14le\n",prior=LogPrior(model));
290 fprintf(f_out,"Posterior value: %22.14le\n",likelihood+prior);
291 fprintf(f_out,"Csminwel return code: %d\n\n",retcodeh);
292 fflush(f_out);
293
294 for (j=10, i=1; total_iteration >= j; j*=10, i++);
295 sprintf(header=(char*)dw_malloc(strlen(fmt) + i - 1),fmt,total_iteration);
296 WriteBaseTransitionMatrices(f_out,(char*)NULL,header,model);
297 Write_VAR_Parameters(f_out,(char*)NULL,header,model);
298 dw_free(header);
299 fflush(f_out);
300
301 if (estimate->cmd->MLE)
302 objective=likelihood;
303 else
304 objective=likelihood+prior;
305 }
306
307 //=== Free memory ===
308 dw_free(x);
309 dw_FreeArray(block);
310
311 //=== Close File ===
312 if (!f) fclose(f_out);
313 }
314
315 /*******************************************************************************/
316 /******************************* Old Estimation ********************************/
317 /*******************************************************************************/
318 /*
319 There was a bug in the original coded that could cause a perturbation in the
320 initial values. If was found that this perturbation sometimes inproved the
321 performance of the estimation procedure. We include this technique so the
322 results of original code can reproduced. A more systematic approach to
323 perturbation is now used.
324 */
325 static void OriginalPerturbation(TEstimateInfo *info, FILE *f_intermediate)
326 {
327 ReadBaseTransitionMatrices((FILE*)NULL,info->cmd->parameters_filename_actual,info->cmd->parameters_header_actual,info->cmd->model);
328 Read_VAR_Parameters_Original((FILE*)NULL,info->cmd->parameters_filename_actual,info->cmd->parameters_header_actual,info->cmd->model);
329
330 FindMode_VAR_csminwel(info,f_intermediate);
331 }
332
333 /*******************************************************************************/
334 /*******************************************************************************/
335 /*******************************************************************************/
336
337 int RepeatEstimation(TEstimateInfo *info, FILE *f_intermediate, FILE *f_final)
338 {
339 TStateModel *model=info->cmd->model;
340 TVector old_parameters, parameters;
341 PRECISION old_obj, obj, norm;
342 time_t begin_time;
343 int i;
344
345 old_parameters=CreateVector(NumberFreeParametersTheta(model)+NumberFreeParametersQ(model));
346 parameters=CreateVector(NumberFreeParametersTheta(model)+NumberFreeParametersQ(model));
347
348 ConvertThetaToFreeParameters(model,pElementV(old_parameters));
349 ConvertQToFreeParameters(model,pElementV(old_parameters)+NumberFreeParametersTheta(model));
350 old_obj=info->cmd->MLE ? LogLikelihood_StatesIntegratedOut(model) : LogPosterior_StatesIntegratedOut(model);
351
352 begin_time=time((time_t*)NULL);
353 if (f_final)
354 {
355 fprintf(f_final,"Time stamp: %s",ctime(&begin_time));
356 fprintf(f_final,"Objective function (initial): %lg\n",old_obj);
357 }
358 for (i=0; i < info->repeat_max; i++)
359 {
360 FindMode_VAR_csminwel(info,f_intermediate);
361 ConvertThetaToFreeParameters(model,pElementV(parameters));
362 ConvertQToFreeParameters(model,pElementV(parameters)+NumberFreeParametersTheta(model));
363 obj=info->cmd->MLE ? LogLikelihood_StatesIntegratedOut(model) : LogPosterior_StatesIntegratedOut(model);
364 norm=Norm(SubtractVV(old_parameters,old_parameters,parameters));
365 if (f_final) fprintf(f_final,"Objective function (run %d): %lg (Norm parameter change: %le Objective function change: %le)\n",i+1,obj,norm,obj-old_obj);
366 if ((norm <= info->repeat_tol_parms) && (fabs(obj-old_obj) <= info->repeat_tol_obj)) break;
367 old_obj=obj;
368 EquateVector(old_parameters,parameters);
369 }
370
371 FreeVector(old_parameters);
372 FreeVector(parameters);
373
374 return i;
375 }
376
377 static void GetSimulation(TVector *simulation, TStateModel *model)
378 {
379 int tuning=30000, burnin=10000, thin=80, ndraws, count, i, begin_time, end_time, check, period=1000;
380 TVector parameters;
381 T_VAR_Parameters *p=(T_VAR_Parameters*)(model->theta);
382
383 // Allocate parameters workspace
384 parameters=CreateVector(NumberFreeParametersTheta(model)+NumberFreeParametersQ(model));
385
386 // Save initial parameters
387 ConvertThetaToFreeParameters(model,pElementV(parameters));
388 ConvertQToFreeParameters(model,pElementV(parameters)+NumberFreeParametersTheta(model));
389
390 // Burn-in period with calibration of jumping parameters
391 printf("Calibrating jumping parameters - %d draws\n",tuning);
392 begin_time=(int)time((time_t*)NULL);
393 AdaptiveMetropolisScale(model,tuning,1000,1,(FILE*)NULL); // tuning iterations - 1000 iterations before updating - verbose
394 end_time=(int)time((time_t*)NULL);
395 printf("Elapsed Time: %d seconds\n",end_time - begin_time);
396
397 // Reset initial parameters
398 ConvertFreeParametersToTheta(model,pElementV(parameters));
399 ConvertFreeParametersToQ(model,pElementV(parameters)+NumberFreeParametersTheta(model));
400
401 // Burn-in period
402 printf("Burn-in period - %d draws\n",burnin);
403 for (check=period, count=1; count <= burnin; count++)
404 {
405 DrawAll(model);
406
407 if (count == check)
408 {
409 check+=period;
410 printf("%d iterations completed out of %d\n",count,burnin);
411 end_time=(int)time((time_t*)NULL);
412 printf("Elapsed Time: %d seconds\n",end_time - begin_time);
413 }
414 }
415 end_time=(int)time((time_t*)NULL);
416 printf("Elapsed Time: %d seconds\n",end_time - begin_time);
417 ResetMetropolisInformation(p);
418
419 // Simulation
420 ndraws=dw_DimA(simulation);
421 printf("Simulating - %d draws\n",ndraws);
422 for (check=period, count=0; count < ndraws; count++)
423 {
424 for (i=thin; i > 0; i--) DrawAll(model);
425
426 ConvertThetaToFreeParameters(model,pElementV(simulation[count]));
427 ConvertQToFreeParameters(model,pElementV(simulation[count])+NumberFreeParametersTheta(model));;
428
429 if (count == check)
430 {
431 check+=period;
432 printf("%d * %d iterations completed out of %d * %d\n",count,thin,ndraws,thin);
433 end_time=(int)time((time_t*)NULL);
434 printf("Elapsed Time: %d seconds\n",end_time - begin_time);
435 }
436 }
437 end_time=(int)time((time_t*)NULL);
438 printf("Total Elapsed Time: %d seconds\n",end_time - begin_time);
439 }
440
441
442 /*
443 Additional command line parameters
444
445 See comments before the SetupEstimateFromVARCommandLine() routine.
446 */
447 void dw_sbvar_estimate_command_line(int nargs, char **args)
448 {
449 TStateModel *model;
450 TEstimateInfo *info;
451 FILE *f_out, *f_intermediate, *f_final, *f_free;
452 char *filename;
453 time_t begin_time, end_time;
454 int t, i, j, k, nsim=500, nq, ntheta, nparms;
455 PRECISION old_obj, max_obj, obj, norm;
456 TVector y, old_parameters, max_parameters, *simulation;
457
458 /* Get estimation information */
459 if (!(info=SetupEstimateFromCommandLine(nargs,args)) || !info->cmd)
460 dw_Error(MEM_ERR);
461 else
462 if (!info->cmd->model)
463 dw_UserError("Unable to setup SBVAR from command line parameters");
464 else
465 if (!info->cmd->parameters_filename_actual)
466 dw_UserError("Unable to initialize parameters from command line parameters");
467 else
468 {
469 model=info->cmd->model;
470 nparms=(ntheta=NumberFreeParametersTheta(model))+(nq=NumberFreeParametersQ(model));
471
472 // Setup no normalization
473 Setup_No_Normalization_VAR((T_VAR_Parameters*)model->theta);
474
475 /* Output header */
476 if (!info->cmd->out_header)
477 info->cmd->out_header=dw_DuplicateString(info->cmd->MLE ? "MLE: " : "Posterior mode: ");
478
479 /* Open temporary final output file */
480 if ((f_intermediate=dw_CreateTextFile(info->intermediate_output_filename)))
481 {
482 sprintf(filename=(char*)dw_malloc(5+strlen(info->final_output_filename)),"%s.tmp",info->final_output_filename);
483 if ((f_final=dw_CreateTextFile(filename)))
484 {
485 Write_VAR_Specification(f_final,(char*)NULL,model);
486 fprintf(f_final,"Specification file: %s\n",info->cmd->specification_filename_actual);
487 fprintf(f_final,"Initialization file: %s\n",info->cmd->parameters_filename_actual);
488 fprintf(f_final,"Initialization header: \"%s\"\n",info->cmd->parameters_header_actual);
489
490 fprintf(f_final,"Number free parameters in transition matrix: %d\n",NumberFreeParametersQ(model));
491 fprintf(f_final,"Number free parameters in theta: %d\n",NumberFreeParametersTheta(model));
492
493 fprintf(f_final,"Initial likelihood Value: %g\n",LogLikelihood_StatesIntegratedOut(model));
494 fprintf(f_final,"Initial prior Value: %g\n",LogPrior(model));
495 fprintf(f_final,"Initial posterior Value: %g\n",LogPosterior_StatesIntegratedOut(model));
496
497 begin_time=time((time_t*)NULL);
498
499 if (dw_FindArgument_String(nargs,args,"OriginalPerturbation") != -1)
500 {
501 OriginalPerturbation(info,f_intermediate);
502 }
503 else
504 {
505 /* First estimation */
506 RepeatEstimation(info,f_intermediate,f_final);
507
508 /* Random perturbations */
509 if (info->random_max > 0)
510 {
511 simulation=dw_CreateArray_vector(nsim);
512 for (i=nsim-1; i >= 0; i--) simulation[i]=CreateVector(nparms);
513 max_parameters=CreateVector(nparms);
514 old_parameters=CreateVector(nparms);
515
516 ConvertThetaToFreeParameters(model,pElementV(max_parameters));
517 ConvertQToFreeParameters(model,pElementV(max_parameters)+ntheta);
518 max_obj=info->cmd->MLE ? LogLikelihood_StatesIntegratedOut(model) : LogPosterior_StatesIntegratedOut(model);
519
520 fprintf(f_final,"//== End initial run: maximum objective = %le\n",max_obj);
521
522 for (i=0; i < info->random_max; i++)
523 {
524 EquateVector(old_parameters,max_parameters);
525 old_obj=max_obj;
526
527 /* Simulate */
528 GetSimulation(simulation,model);
529
530 for (j=0; j < info->random; j++)
531 {
532 /* Select draw */
533 k=(int)floor(nsim*dw_uniform_rnd());
534 ConvertFreeParametersToTheta(model,pElementV(simulation[k]));
535 ConvertFreeParametersToQ(model,pElementV(simulation[k])+ntheta);
536
537 /* Estimate */
538 RepeatEstimation(info,f_intermediate,f_final);
539
540 /* Uphill? */
541 obj=info->cmd->MLE ? LogLikelihood_StatesIntegratedOut(model) : LogPosterior_StatesIntegratedOut(model);
542 if (obj > max_obj)
543 {
544 ConvertThetaToFreeParameters(model,pElementV(max_parameters));
545 ConvertQToFreeParameters(model,pElementV(max_parameters)+ntheta);
546 max_obj=obj;
547 }
548 }
549
550 /* Reset parameters */
551 ConvertFreeParametersToTheta(model,pElementV(max_parameters));
552 ConvertFreeParametersToQ(model,pElementV(max_parameters)+ntheta);
553
554 /* Improved? */
555 norm=Norm(SubtractVV(old_parameters,old_parameters,max_parameters));
556 fprintf(f_final,"//== End perturbation run %d: maximum objective = %le (norm parameter change: %le objective function change: %le)\n",i+1,
557 max_obj,norm,max_obj-old_obj);
558 fflush(f_final);
559 if ((norm <= info->random_tol_parms) && (fabs(max_obj-old_obj) <= info->random_tol_obj))
560 {
561 EquateVector(old_parameters,max_parameters);
562 old_obj=max_obj;
563
564 /* Local perturbation */
565 for (j=0; j < info->random_small; j++)
566 {
567 /* Select draw */
568 for (k=info->random_small_ndraws; k > 0; k--) DrawAll(model);
569
570 /* Estimate */
571 RepeatEstimation(info,f_intermediate,f_final);
572
573 /* Uphill? */
574 obj=info->cmd->MLE ? LogLikelihood_StatesIntegratedOut(model) : LogPosterior_StatesIntegratedOut(model);
575 if (obj > max_obj)
576 {
577 ConvertThetaToFreeParameters(model,pElementV(max_parameters));
578 ConvertQToFreeParameters(model,pElementV(max_parameters)+ntheta);
579 max_obj=obj;
580 }
581
582 /* Reset Parameters */
583 ConvertFreeParametersToTheta(model,pElementV(max_parameters));
584 ConvertFreeParametersToQ(model,pElementV(max_parameters)+ntheta);
585 }
586
587 /* Improved? */
588 norm=Norm(SubtractVV(old_parameters,old_parameters,max_parameters));
589 fprintf(f_final,"//== End local perturbation run: maximum objective = %le (norm parameter change: %le objective function change: %le)\n",max_obj,norm,max_obj-old_obj);
590 fflush(f_final);
591 if ((norm <= info->random_tol_parms) && (fabs(max_obj-old_obj) <= info->random_tol_obj)) break;
592 }
593 }
594
595 FreeVector(old_parameters);
596 FreeVector(max_parameters);
597 dw_FreeArray(simulation);
598 }
599 }
600
601 end_time=time((time_t*)NULL);
602
603 /* Normalize */
604 Setup_Default_Recursive_Normalization_VAR((T_VAR_Parameters*)model->theta);
605 Normalize_VAR(model,(PRECISION*)NULL);
606
607 /* Write final output */
608 fprintf(f_final,"Time stamp: %s",ctime(&end_time));
609 fprintf(f_final,"Elapsed time: %d seconds\n",(int)end_time-(int)begin_time);
610
611 fprintf(f_final,"Final likelihood Value: %g\n",LogLikelihood_StatesIntegratedOut(model));
612 fprintf(f_final,"Final prior Value: %g\n",LogPrior(model));
613 fprintf(f_final,"Final posterior Value: %g\n\n",LogPosterior_StatesIntegratedOut(model));
614
615 fprintf(f_final,"//== %sFree parameters ==//\n",info->cmd->out_header);
616 WriteFreeParameters(f_final,(char*)NULL,model);
617 fprintf(f_final,"\n");
618
619 WriteBaseTransitionMatrices(f_final,(char*)NULL,info->cmd->out_header,model);
620 Write_VAR_Parameters(f_final,(char*)NULL,info->cmd->out_header,model);
621 fclose(f_final);
622
623 /* Rename temp file */
624 rename(filename,info->final_output_filename);
625 dw_free(filename);
626
627 /* Write Free Parameter File */
628 filename=CreateFilenameFromTag("%sest_free_%s.out",info->cmd->out_tag,info->cmd->out_directory);
629 if ((f_free = fopen(filename, "wt")))
630 {
631 max_parameters=CreateVector(nparms);
632 fprintf(f_free,"%le %le ",LogPosterior_StatesIntegratedOut(model),LogLikelihood_StatesIntegratedOut(model));
633 ConvertThetaToFreeParameters(model,pElementV(max_parameters));
634 ConvertQToFreeParameters(model,pElementV(max_parameters)+NumberFreeParametersTheta(model));
635 dw_PrintVector(f_free,max_parameters,"%le ");
636 fclose(f_free);
637 FreeVector(max_parameters);
638 }
639 dw_free(filename);
640
641 /* Write flat file */
642 filename=CreateFilenameFromTag("%sest_flat_header_%s.out",info->cmd->out_tag,info->cmd->out_directory);
643 if ((f_out=fopen(filename,"wt")))
644 {
645 WriteBaseTransitionMatricesFlat_Headers(f_out,model);
646 Write_VAR_ParametersFlat_Headers(f_out,model);
647 fprintf(f_out,"\n");
648 fclose(f_out);
649 }
650 dw_free(filename);
651 filename=CreateFilenameFromTag("%sest_flat_%s.out",info->cmd->out_tag,info->cmd->out_directory);
652 if ((f_out=fopen(filename,"wt")))
653 {
654 WriteBaseTransitionMatricesFlat(f_out,(char*)NULL,model,"%lf ");
655 if (dw_FindArgument_String(nargs,args,"nd1") >= 0)
656 Write_VAR_ParametersFlat_A0_Diagonal_One(f_out,model,"%lf ");
657 else
658 Write_VAR_ParametersFlat(f_out,model,"%lf ");
659 fprintf(f_out,"\n");
660 fclose(f_out);
661 }
662 dw_free(filename);
663 /**/
664
665 #if defined(MATLAB_MEX_FILE) || defined(OCTAVE_MEX_FILE)
666 /* Write Output to Matlab/Octave .mat file*/
667 Write_VAR_Parameters_Mat(model, info->cmd->out_tag);
668 #endif
669
670 /* Write aux output */
671 filename=CreateFilenameFromTag("%sest_aux_%s.out",info->cmd->out_tag,info->cmd->out_directory);
672 if ((f_out=fopen(filename,"wt")))
673 {
674 fprintf(f_out,"""ln(P(y[t]|Y[t-1],Z[t],theta,Q))"",""E[y[t]|Y[t-1],Z[t],theta,Q]""\n");
675
676 y=CreateVector(((T_VAR_Parameters*)(model->theta))->nvars);
677 for (t=1; t <= model->nobs; t++)
678 {
679 fprintf(f_out,"%le,",LogConditionalLikelihood_StatesIntegratedOut(t,model));
680 if (ExpectationSingleStep_StatesIntegratedOut(y,t,model))
681 dw_PrintVector(f_out,y,"%le,");
682 else
683 fprintf(f_out,"\n");
684 }
685
686 FreeVector(y);
687 fclose(f_out);
688 }
689 dw_free(filename);
690 /**/
691 }
692 else
693 dw_free(filename);
694 fclose(f_intermediate);
695 }
696 }
697
698 // Free memory
699 FreeEstimateInfo(info);
700 }