ADMB Documentation  -a65f1c97
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
rwm.cpp
Go to the documentation of this file.
1 
2 // The random walk metropolis algorithm. This is copied from mcmc_routine
3 // function and modified by Cole.
10 #include <ctime>
11 #include <admodel.h>
12 
13 #if defined(_MSC_VER)
14  #include <conio.h>
15 #else
16  #define getch getchar
17 #endif
18 
19 #ifndef OPT_LIB
20  #include <cassert>
21  #include <climits>
22 #endif
23 
24 #ifdef ISZERO
25  #undef ISZERO
26 #endif
27 #define ISZERO(d) ((d)==0.0)
28 
29 double better_rand(long int&);
30 void set_labels_for_mcmc(void);
31 
32 void print_hist_data(const dmatrix& hist, const dmatrix& values,
33  const dvector& h, dvector& m, const dvector& s, const dvector& parsave,
34  int iseed, double size_scale);
35 
36 int minnz(const dvector& x);
37 int maxnz(const dvector& xa);
38 
39 void read_hessian_matrix_and_scale1(int nvar, const dmatrix& _SS, double s,
40  int mcmc2_flag);
41 
42 int read_hist_data(const dmatrix& hist, const dvector& h, dvector& m,
43  const dvector& s, const dvector& parsave, int& iseed,
44  const double& size_scale);
45 
46 void make_preliminary_hist(const dvector& s, const dvector& m,int nsim,
47  const dmatrix& values, dmatrix& hist, const dvector& h,int slots,
48  double total_spread,int probflag=0);
49 
50 void add_hist_values(const dvector& s, const dvector& m, const dmatrix& hist,
51  dvector& mcmc_values,double llc, const dvector& h,int nslots,
52  double total_spreadd,int probflag=0);
53 
54 void write_empirical_covariance_matrix(int ncor, const dvector& s_mean,
55  const dmatrix& s_covar, adstring& prog_name);
56 
57 void read_empirical_covariance_matrix(int nvar, const dmatrix& S,
58  const adstring& prog_name);
59 
60 void read_hessian_matrix_and_scale(int nvar, const dmatrix& S,
61  const dvector& pen_vector);
62 
63 int user_stop(void);
64 
65 extern int ctlc_flag;
66 
68  const dvector& b1, dmatrix& ch, const double& wght,double pprobe,
70  // const random_number_generator& rng);
71 
73  const dvector& b1, dmatrix& ch, const double& wght, const dvector& _y,
74  double pprobe, random_number_generator& rng);
75 
76 //void newton_raftery_bayes_estimate(double cbf,int ic, const dvector& lk,
77 // double d);
78 #if defined(USE_BAYES_FACTORS)
79 void newton_raftery_bayes_estimate_new(double cbf,int ic, const dvector& lk,
80  double d);
81 #endif
82 
84  (int feval,int iter,double fval,double gmax);
85 
86 void ad_update_function_minimizer_report(int feval,int iter,int phase,
87  double fval,double gmax,const char * cbuf);
88 void ad_update_mcmc_report(dmatrix& m,int i,int j,int ff=0);
89 void ad_update_mcmchist_report(dmatrix& mcmc_values,ivector& number_offsets,
90  dvector& mean_mcmc_values,dvector& h,int ff=0);
91 
92 void function_minimizer::rwm_mcmc_routine(int nmcmc,int iseed0, double dscale,
93  int restart_flag)
94 {
95 
96  uostream * pofs_psave=NULL;
97  dmatrix mcmc_display_matrix;
98  //int mcmc_save_index=1;
99  //int mcmc_wrap_flag=0;
100  //int mcmc_gui_length=10000;
101  //int nvar=initial_params::nvarcalc(); // get the number of active parameters
102 
103  // Cole set this to 1 to essentially turn this feature off since no one seems to use it.
104  int no_sd_mcmc=1;
105 
106  int on2=-1;
107  if ( (on2=option_match(ad_comm::argc,ad_comm::argv,"-nosdmcmc"))>-1)
108  {
109  cerr << "The sdmcmc feature is disabled, so -nosdmcmc does nothing" << endl;
110  }
111  if (mcmc2_flag==1)
112  {
114  //get the number of active parameters
115  //int nvar1=initial_params::nvarcalc();
116  }
117 
118  // if (stddev_params::num_stddev_params==0 & no_sd_mcmc==0)
119  // {
120  // cout << "No objects of type sdreport so cannot use sd report feature." << endl
121  // << "Use -nosdmcmc for future runs" << endl;
122  // no_sd_mcmc=1;
123  // // cerr << " You must declare at least one object of type sdreport "
124  // // << endl << " to do the mcmc calculations" << endl;
125  // }
126  {
127  ivector number_offsets;
128  dvector lkvector;
129  //double current_bf=0;
130 #if defined(USE_BAYES_FACTORS)
131  double lcurrent_bf=0;
132 #endif
133  double size_scale=1.0;
134  double total_spread=200;
135  //double total_spread=2500;
136  uostream * pofs_sd = NULL;
137 
139  // int nvar_x=initial_params::nvarcalc();
141  int nvar_re=initial_params::nvarcalc();
142 
143  int nvar=initial_params::nvarcalc(); // get the number of active parameters
144  //int scov_option=0;
145  dmatrix s_covar;
146  dvector s_mean;
147  int on=-1;
148  int nslots=800;
149  //int nslots=3600;
150  int initial_nsim=4800;
151  int ncor=0;
152  double bfsum=0;
153  int ibfcount=0;
154  double llbest;
155  double lbmax;
156 
157  //int ntmp=0;
158  //if ( (on=option_match(ad_comm::argc,ad_comm::argv,"-mcscov",ntmp))>-1)
159  //{
160  //scov_option=1;
161  s_covar.allocate(1,nvar,1,nvar);
162  s_mean.allocate(1,nvar);
163  s_mean.initialize();
164  s_covar.initialize();
165 
166  int ndvar=stddev_params::num_stddev_calc();
167  /*
168  int numdvar=stddev_params::num_stddev_number_calc();
169  if (adjm_ptr)
170  {
171  mcmc_display_matrix.allocate(1,numdvar,1,mcmc_gui_length);
172  number_offsets.allocate(1,numdvar);
173  number_offsets=stddev_params::copy_all_number_offsets();
174  }
175  */
176  if (mcmc2_flag==0)
177  {
179  nvar=initial_params::nvarcalc(); // get the number of active parameters
180  }
181  dvector x(1,nvar);
182  dvector scale(1,nvar);
183  dmatrix values;
184  int have_hist_flag=0;
186  dvector pen_vector(1,nvar);
187  {
188  initial_params::reset(dvar_vector(x),pen_vector);
189  //cout << pen_vector << endl << endl;
190  }
191 
195  dvector bmn(1,nvar);
196  dvector mean_mcmc_values(1,ndvar);
197  dvector s(1,ndvar);
198  dvector h(1,ndvar);
199  //dvector h;
200  dvector square_mcmc_values(1,ndvar);
201  square_mcmc_values.initialize();
202  mean_mcmc_values.initialize();
203  bmn.initialize();
204  int use_empirical_flag=0;
205  // chain number -- for console display purposes only
206  int chain=1;
207  int nopt=0;
208  if ( (on=option_match(ad_comm::argc,ad_comm::argv,"-chain",nopt))>-1) {
209  if (nopt) {
210  int iii=atoi(ad_comm::argv[on+1]);
211  if (iii <1) {
212  cerr << "Error: chain must be >= 1" << endl;
213  ad_exit(1);
214  } else {
215  chain=iii;
216  }
217  }
218  }
219  // console refresh rate
220  int refresh=1;
221  if(nmcmc>10) refresh = (int)floor(nmcmc/10);
222  if ( (on=option_match(ad_comm::argc,ad_comm::argv,"-refresh",nopt))>-1) {
223  int iii=atoi(ad_comm::argv[on+1]);
224  if (iii < -1) {
225  cerr << iii << endl;
226  cerr << "Error: refresh must be >= -1. Use -1 for no refresh or positive integer for rate." << endl;
227  ad_exit(1);
228  } else {
229  refresh=iii;
230  }
231  }
232  int diag_option=0;
233  if ( (on=option_match(ad_comm::argc,ad_comm::argv,"-mcdiag"))>-1)
234  {
235  diag_option=1;
236  cout << "Chain " << chain << ": Setting covariance matrix to diagonal with entries " << dscale
237  << endl;
238  }
239  dmatrix S(1,nvar,1,nvar);
240  dvector sscale(1,nvar);
241  if (!diag_option)
242  {
243  int nopt = 0;
244  int rescale_bounded_flag=0;
245  double rescale_bounded_power=0.5;
246  if ( (on=option_match(ad_comm::argc,ad_comm::argv,"-mcrb",nopt))>-1)
247  {
248  if (nopt)
249  {
250  int iii=atoi(ad_comm::argv[on+1]);
251  if (iii < 1 || iii > 9)
252  {
253  cerr << " -mcrb argument must be integer between 1 and 9 --"
254  " using default of 5" << endl;
255  rescale_bounded_power=0.5;
256  }
257  else
258  rescale_bounded_power=iii/10.0;
259  }
260  else
261  {
262  rescale_bounded_power=0.5;
263  }
264  rescale_bounded_flag=1;
265  }
266  if ( (on=option_match(ad_comm::argc,ad_comm::argv,"-mcec"))>-1)
267  {
268  use_empirical_flag=1;
269  }
270  if (use_empirical_flag)
271  {
273  }
274  else if (!rescale_bounded_flag)
275  {
276  int hbf;
277  if (mcmc2_flag==0)
278  {
279  read_covariance_matrix(S,nvar,hbf,sscale);
280  }
281  else
282  {
283  int tmp_nvar = 0;
284  adstring tmpstring = ad_comm::adprogram_name + ".bgs";
285  uistream uis((char*)(tmpstring));
286  if (!uis)
287  {
288  cerr << "error opening file " << tmpstring << endl;
289  ad_exit(1);
290  }
291  uis >> tmp_nvar;
292  if (!uis)
293  {
294  cerr << "error reading from file " << tmpstring << endl;
295  ad_exit(1);
296  }
297  if (tmp_nvar != nvar)
298  {
299  cerr << "size error reading from " << tmpstring << endl;
300  ad_exit(1);
301  }
302  uis >> S;
303  if (!uis)
304  {
305  cerr << "error reading from file " << tmpstring << endl;
306  ad_exit(1);
307  }
308  }
309  }
310  else
311  {
312  read_hessian_matrix_and_scale1(nvar,S,rescale_bounded_power,
313  mcmc2_flag);
314  //read_hessian_matrix_and_scale(nvar,S,pen_vector);
315  }
316 
317  { // scale covariance matrix for model space
318  dmatrix tmp(1,nvar,1,nvar);
319  for (int i=1;i<=nvar;i++)
320  {
321  tmp(i,i)=S(i,i)*(scale(i)*scale(i));
322  for (int j=1;j<i;j++)
323  {
324  tmp(i,j)=S(i,j)*(scale(i)*scale(j));
325  tmp(j,i)=tmp(i,j);
326  }
327  }
328  S=tmp;
329  }
330  }
331  else
332  {
333  S.initialize();
334  for (int i=1;i<=nvar;i++)
335  {
336  S(i,i)=dscale;
337  }
338  }
339 
340  // cout << sort(eigenvalues(S)) << endl;
341  dmatrix chd = choleski_decomp( (dscale*2.4/sqrt(double(nvar))) * S);
342  dmatrix chdinv=inv(chd);
343  dmatrix chdinv0=chdinv;
344  dmatrix symbds(1,2,1,nvar);
346  ofstream ofs_sd1((char*)(ad_comm::adprogram_name + adstring(".mc2")));
347 
348  {
349  int number_sims = 100000;
350  if (nmcmc > 0)
351  {
352  number_sims = nmcmc;
353  }
354  int iseed=0;
355  //cin >> iseed;
356  if (iseed0<=0)
357  {
358  iseed=-36519;
359  }
360  else
361  {
362  iseed=-iseed0;
363  }
364  if (iseed>0)
365  {
366  iseed=-iseed;
367  }
368  // cout << "Initial seed value " << iseed << endl;
369  random_number_generator rng(iseed);
370  rng.better_rand();
371  double lprob=0.0;
372  double lpinv=0.0;
373  // get lower and upper bounds
374 
375  independent_variables y(1,nvar);
376  independent_variables parsave(1,nvar_re);
378  nopt=0;
379 
380  // read in the mcmc values to date
381  int ii=1;
382  dmatrix hist;
383  if (restart_flag)
384  {
385  int tmp=0;
386  if (!no_sd_mcmc) {
387  hist.allocate(1,ndvar,-nslots,nslots);
388  tmp=read_hist_data(hist,h,mean_mcmc_values,s,parsave,iseed,
389  size_scale);
390  values.allocate(1,ndvar,-nslots,nslots);
391  for (int i=1;i<=ndvar;i++)
392  {
393  values(i).fill_seqadd(mean_mcmc_values(i)-0.5*total_spread*s(i)
394  +.5*h(i),h(i));
395  }
396  }
397  if (iseed>0)
398  {
399  iseed=-iseed;
400  }
401  /*double br=*/rng.better_rand();
402  if (tmp) have_hist_flag=1;
403  chd=size_scale*chd;
404  chdinv=chdinv/size_scale;
405  } else {
406  int nopt=0;
407  if ( (on=option_match(ad_comm::argc,ad_comm::argv,"-mcpin",nopt))>-1) {
408  if (nopt) {
409  cifstream cif((char *)ad_comm::argv[on+1]);
410  if (!cif) {
411  cerr << "Error trying to open mcmc par input file "
412  << ad_comm::argv[on+1] << endl;
413  ad_exit(1);
414  }
415  cif >> parsave;
416  if (!cif) {
417  cerr << "Error reading from mcmc par input file "
418  << ad_comm::argv[on+1] << endl;
419  ad_exit(1);
420  }
421  } else {
422  cerr << "Illegal option with -mcpin" << endl;
423  }
424  } else {
425  // If user didnt specify one, use MLE values. Store saved MLEs from
426  // admodel.hes file in bounded space into initial parameters z0
427  read_mle_hmc(nvar, parsave);
428  }
429  }
430 
431  ii=1;
432  // cout << endl << endl << endl << "printing starting values" << endl;
433  // cout << parsave << endl << endl;
435  // cout << endl << endl << endl << "printing starting values2" << endl;
436  // cout << parsave << endl << endl;
437  if (mcmc2_flag==0)
438  {
440  }
443  // cout << endl << endl << endl << "printing starting values3" << endl;
444  // cout << y << endl << endl;
445 
446  ofstream ogs("sims");
447  ogs << nvar << " " << number_sims << endl;
448  double llc=-get_monte_carlo_value(nvar,y);
449 
450  std::clock_t start0 = clock();
451  llbest=-get_monte_carlo_value(nvar,y);
452  double time_nll = static_cast<double>(std::clock()-start0)/CLOCKS_PER_SEC;
453  lbmax=llbest;
454  // store current mcmc variable values in param_values
455  //void store_mcmc_values(const ofstream& ofs);
456  //dmatrix store_mcmc_values(1,number_sims,1,ndvar);
457 #if defined(USE_BAYES_FACTORS)
458  lkvector.allocate(1,number_sims);
459 #endif
460  dvector mcmc_values(1,ndvar);
461  dvector mcmc_number_values;
462  //if (adjm_ptr) mcmc_number_values.allocate(1,numdvar);
463  int offs=1;
464  stddev_params::copy_all_values(mcmc_values,offs);
465 
466  /*
467  if (adjm_ptr)
468  {
469  offs=1;
470  stddev_params::copy_all_number_values(mcmc_number_values,offs);
471  }
472  */
473  int change_ball= (int)nmcmc/2;
474  int nopt = 0;
475  if ( (on=option_match(ad_comm::argc,ad_comm::argv,"-mcscale",nopt))>-1)
476  {
477  if (nopt)
478  {
479  // int iii=atoi(ad_comm::argv[on+1]); old way that was buggy
480  int iii=(int)atof(ad_comm::argv[on+1]); // better way
481  if (iii <=0)
482  {
483  cerr << " Invalid option following command line option -mcscale -- "
484  << endl << " ignored" << endl;
485  }
486  else
487  change_ball=iii;
488  }
489  }
490  int iac=0;
491  int liac=0;
492  int isim=0;
493  //int itmp=0;
494  double logr;
495  int u_option=0;
496  double ll;
497  int s_option=1;
498  int psvflag=0;
499  if ( (on=option_match(ad_comm::argc,ad_comm::argv,"-mcu"))>-1)
500  {
501  u_option=1;
502  }
503  if ( (on=option_match(ad_comm::argc,ad_comm::argv,"-mcnoscale"))>-1)
504  {
505  s_option=0;
506  }
507  //cout << llc << " " << llc << endl;
508  int iac_old=0;
509  int i_old=0;
510 
511  {
512  if (!restart_flag)
513  {
514  pofs_sd =
515  new uostream((char*)(ad_comm::adprogram_name + adstring(".mcm")));
516  }
517 
518  int mcsave_flag=0;
519  int mcrestart_flag=option_match(ad_comm::argc,ad_comm::argv,"-mcr");
520 
521  if ( (on=option_match(ad_comm::argc,ad_comm::argv,"-mcsave"))>-1)
522  {
523  int jj=(int)atof(ad_comm::argv[on+1]);
524  if (jj <=0)
525  {
526  cerr << " Invalid option following command line option -mcsave -- "
527  << endl;
528  }
529  else
530  {
531  mcsave_flag=jj;
532  if ( mcrestart_flag>-1)
533  {
534  // check that nvar is correct
535  {
536  uistream uis((char*)(ad_comm::adprogram_name + adstring(".psv")));
537  if (!uis)
538  {
539  cerr << "Error trying to open file" <<
540  ad_comm::adprogram_name + adstring(".psv") <<
541  " for mcrestart" << endl;
542  cerr << " I am starting a new file " << endl;
543  psvflag=1;
544  }
545  else
546  {
547  int nv1 = 0;
548  uis >> nv1;
549  if (nv1 !=nvar)
550  {
551  cerr << "wrong number of independent variables in"
552  << ad_comm::adprogram_name + adstring(".psv")
553  << "\n starting a new file " << endl;
554  psvflag=1;
555  }
556  }
557  }
558 
559  if (!psvflag) {
560  pofs_psave=
561  new uostream(
562  (char*)(ad_comm::adprogram_name + adstring(".psv")),ios::app);
563  } else {
564  pofs_psave= new uostream((char*)(ad_comm::adprogram_name
565  + adstring(".psv")));
566  }
567  } else {
568  pofs_psave=
569  new uostream((char*)(ad_comm::adprogram_name + adstring(".psv")));
570  }
571  if (!pofs_psave|| !(*pofs_psave))
572  {
573  cerr << "Error trying to open file" <<
575  mcsave_flag=0;
576  if (pofs_psave)
577  {
578  delete pofs_psave;
579  pofs_psave=NULL;
580  }
581  }
582  else
583  {
584  if (psvflag || (mcrestart_flag == -1) )
585  {
586  (*pofs_psave) << nvar_re;
587  }
588  }
589  }
590  }
591 
592  // Run duration. Can specify warmup and duration, or warmup and
593  // iter. Sampling period will stop after exceeding duration hours.
594  double duration=0;
595  bool use_duration=0; // whether to use this or iter
596  if ( (on=option_match(ad_comm::argc,ad_comm::argv,"-duration",nopt))>-1) {
597  double _duration=0;
598  use_duration=1;
599  if (nopt) {
600  istringstream ist(ad_comm::argv[on+1]);
601  ist >> _duration;
602  if (_duration <0) {
603  cerr << "Error: duration must be > 0" << endl;
604  ad_exit(1);
605  } else {
606  // input is in seconds, duration is in seconds so convert
607  duration=_duration*60;
608  }
609  }
610  }
611 
612  double pprobe=0.05;
613  int probe_flag=0;
614  nopt=0;
615  on = option_match(ad_comm::argc, ad_comm::argv, "-mcprobe", nopt);
616  if (on == -1)
617  {
618  on = option_match(ad_comm::argc,ad_comm::argv,"-mcgrope",nopt);
619  }
620  if (on > -1)
621  {
622  probe_flag=1;
623  if (nopt)
624  {
625  char* end = 0;
626  pprobe=strtod(ad_comm::argv[on+1],&end);
627  if (pprobe<=0.00001 || pprobe > .499)
628  {
629  cerr << "Invalid argument to option -mcprobe" << endl;
630  pprobe=-1.0;
631  probe_flag=0;
632  }
633  }
634  }
635  int java_quit_flag=0;
636 
637 
638  double time_warmup=0;
639  double time_total=0;
640  std::clock_t start = clock();
641  time_t now = time(0);
642  tm* localtm = localtime(&now);
643  std::string m=get_filename((char*)ad_comm::adprogram_name);
644  cout << endl << "Chain " << chain << ": Starting RWM for model '" << m <<
645  "' at " << asctime(localtm);
646  if(use_duration==1){
647  cout <<"Chain " << chain << ": Model will run for " << duration/60 <<
648  " minutes or until " << number_sims << " total iterations" << endl;
649  }
650 
651  // Need to save log-posterior (-NLL) to file to read in later.
652  ofstream rwm_lp("rwm_lp.txt", ios::trunc);
653  rwm_lp << "log-posterior" << endl;
654  // ofstream rotated("rotated.csv", ios::trunc);
655  // ofstream bounded("bounded.csv", ios::trunc);
656  ofstream unbounded("unbounded.csv", ios::trunc);
657  // cout << "Initial mle=" << mle << endl;
658  // cout << "Initial z=" << parsave << endl;
659  // cout << "Initial y=" << y << endl;
660  cout <<"Chain " << chain << ": Initial negative log density=" << -llbest << endl;
661  cout << "Chain " << chain << ": Model eval took " << time_nll <<
662  " sec. " << nmcmc << " iter will take approximately " ;
663  time_nll*= nmcmc;
664  if(time_nll<=60){
665  printf("%.2f", time_nll); cout << " seconds." << endl;
666  } else if(time_nll <=60*60){
667  printf("%.2f", time_nll/60); cout << " minutes." << endl;
668  } else if(time_nll <= (60*60*24)){
669  printf("%.2f", time_nll/(60*60)); cout << " hours." << endl;
670  } else {
671  printf("%.2f", time_nll/(24*60*60)); cout << " days." << endl;
672  }
673 
674  // Start of MCMC chain
675  for (int i=1;i<=number_sims;i++)
676  {
677  if (user_stop()) break;
678  if (java_quit_flag) break;
679 
680  if (!((i-1)%200))
681  {
682  // double ratio = double(iac)/i;
683  iac_old=iac-iac_old;
684  i_old=i-i_old;
685  // cout << llc << " " << llc << endl;
686  double tratio=double(liac)/200;
687  liac=0;
688  // cout << " mcmc sim " << i << " acceptance rate "
689  // << ratio << " " << tratio << endl;
690 
691  /*
692  int start_flag;
693  int der_flag,next_flag;
694  if (adjm_ptr && i>1)
695  {
696  ad_update_mcmc_report(mcmc_display_matrix,mcmc_save_index,
697  mcmc_wrap_flag);
698 
699  ad_update_mcmc_stats_report
700  (i,number_sims,100.*tratio,100.*ratio);
701 
702  if (allocated(hist)) ad_update_mcmchist_report(hist,
703  number_offsets,mean_mcmc_values,h);
704  void check_java_flags(int& start_flag,int& quit_flag,int& der_flag,
705  int& next_flag);
706  check_java_flags(start_flag,java_quit_flag,der_flag,next_flag);
707  ADSleep(50);
708  }
709  */
710 
711  if (i>50 && s_option && i<change_ball && !restart_flag)
712  {
713  if (tratio < .15)
714  {
715  chd=.2*chd;
716  size_scale*=0.2;
717  chdinv=chdinv/0.2;
718  //cout << "decreasing step size " << ln_det(chd,itmp) << endl;
719  }
720  if (tratio > .6)
721  {
722  chd=2.*chd;
723  size_scale*=2.0;
724  chdinv=chdinv/2.;
725  //cout << "increasing step size " << ln_det(chd,itmp) << endl;
726  }
727  else if (tratio > .5)
728  {
729  chd=1.5*chd;
730  size_scale*=1.5;
731  chdinv=chdinv/1.5;
732  //cout << "increasing step size " << ln_det(chd,itmp) << endl;
733  }
734  else if (tratio > .4)
735  {
736  chd=1.2*chd;
737  size_scale*=1.2;
738  chdinv=chdinv/1.2;
739  //cout << "increasing step size " << ln_det(chd,itmp) << endl;
740  }
741  }
742  }
743  ii=1;
745  {
748  if (mcmc2_flag==0)
749  {
751  }
752  }
753  else
754  {
756  }
758 
759  // option of generating uniform or normal random variables
760  dvector bmn1(1,nvar);
761  if (!u_option)
762  {
763  if (!probe_flag)
764  bmn1=bounded_multivariate_normal(nvar,symbds(1),symbds(2),
765  chd,lprob,rng);
766  else
768  nvar,symbds(1),symbds(2),chd,lprob,pprobe,rng);
769 
772  // get the simulation bounds for the inverse transition
774  if (!probe_flag)
775  bounded_multivariate_normal_mcmc(nvar,symbds(1),symbds(2),chd,
776  lpinv,-1*(chdinv*bmn1),rng);
777  else
779  symbds(2), chd,lpinv,-1*(chdinv*bmn1),pprobe,rng);
780 
781  ll=-get_monte_carlo_value(nvar,y);
783  {
785  }
786  //cout << ll << " " << llc << endl;
787  double ldiff=lprob-lpinv;
788  logr= ll - ldiff - llc;
789  }
790  else
791  {
792  bmn1=bounded_multivariate_uniform(nvar,symbds(1),symbds(2),
793  chd, lprob,rng);
796  // get the simulation bounds for the inverse transition
798  bounded_multivariate_uniform_mcmc(nvar,symbds(1),symbds(2),chd,
799  lpinv,-1*(chdinv*bmn1),rng);
800  ll=-get_monte_carlo_value(nvar,y);
801  double ldiff=lprob-lpinv;
802  logr= ll - ldiff - llc;
803  }
804  //cout << logr << endl;
805  // decide whether to accept the new point
806  isim++;
807  double br=rng.better_rand();
808  if (logr>=0 || br< exp(logr) )
809  {
810  ii=1;
811  // save current parameter values
813  ii=1;
814  // save current mcmc values
815  stddev_params::copy_all_values(mcmc_values,ii);
817  {
818  if (mcmc2_flag==0)
819  {
821  }
822  }
823  // update prob density for current point
824  llc =ll;
825  liac++;
826  iac++;
827  }
828  int mmin=mcmc_values.indexmin();
829  int mmax=mcmc_values.indexmax();
830  double lbf=llbest-llc;
831  if (lbf>lbmax) lbmax=lbf;
832  //of_bf << lbf << endl;
833  bfsum+=exp(lbf);
834  ibfcount+=1;
835 #if defined(USE_BAYES_FACTORS)
836  lkvector(ibfcount)=llc;
837  //current_bf=1.0/(bfsum/double(ibfcount))*exp(llbest);
838  lcurrent_bf=-1.*log(bfsum/double(ibfcount))+llbest;
839 #endif
840  if (mcsave_flag && (!((i-1)%mcsave_flag)))
841  {
842  // Save parameters and log posterior at each thinned iteration
843  (*pofs_psave) << parsave;
844  rwm_lp << llc << endl;
845  // Calculate rotated parameter vector
846  independent_variables xtemp(1,nvar);
847  xtemp=chdinv0*y;
848  for(int i=1;i<nvar;i++) {
849  // rotated << xtemp(i) << ", ";
850  unbounded << y(i) << ", ";
851  // bounded << parsave(i) << ", ";
852  }
853  // rotated << xtemp(nvar) << endl;
854  unbounded << y(nvar) << endl;
855  // bounded << parsave(nvar) << endl;
856  }
857  /*
858  if (adjm_ptr)
859  {
860  void save_mcmc_for_gui1(const dvector& mcmc_values,
861  dmatrix &mdm,int& ids,int& iwrap,ivector& no);
862  save_mcmc_for_gui1(mcmc_values,mcmc_display_matrix,
863  mcmc_save_index,mcmc_wrap_flag,number_offsets);
864  }
865  */
866  if (!no_sd_mcmc)
867  {
868  if (!have_hist_flag)
869  {
870  for (ii=mmin;ii<=mmax;ii++)
871  {
872  (*pofs_sd) << float(mcmc_values(ii));
873  }
874  (*pofs_sd) << (float)(llc);
875  mean_mcmc_values+=mcmc_values;
876  square_mcmc_values+=square(mcmc_values);
877  }
878  else
879  {
880  add_hist_values(s,mean_mcmc_values,hist,mcmc_values,llc,
881  h,nslots,total_spread);
882  }
883  }
884  //if (scov_option)
885  {
886  ncor++;
887  s_mean+=parsave;
888  s_covar+=outer_prod(parsave,parsave);
889  }
890  if (!no_sd_mcmc && iac>5 && isim>initial_nsim)
891  {
892  if (!have_hist_flag)
893  {
894  have_hist_flag=1;
895  delete pofs_sd;
896  pofs_sd=NULL;
897  mean_mcmc_values/=double(isim);
898  square_mcmc_values/=double(isim);
899 #if defined(USE_DDOUBLE)
900  s=2.*sqrt(double(1.e-20)+square_mcmc_values
901  -square(mean_mcmc_values));
902 #else
903  s=2.*sqrt(1.e-20+square_mcmc_values-square(mean_mcmc_values));
904 #endif
905  make_preliminary_hist(s,mean_mcmc_values,isim,values,hist,h,
906  nslots,total_spread);
907  }
908  }
909  if(i==change_ball)
910  time_warmup = static_cast<double>(std::clock()-start)/CLOCKS_PER_SEC;
911  time_total = static_cast<double>(std::clock()-start)/CLOCKS_PER_SEC;
912  if(use_duration==1 && time_total > duration){
913  // If duration option used, break loop after <duration> hours.
914  cout << "Chain " << chain << ": " << i << " samples generated after " << duration/60 <<
915  " minutes running." << endl;
916  break;
917  }
918  print_mcmc_progress(i, number_sims, change_ball, chain, refresh);
919  } // end of mcmc chain
920  print_mcmc_timing(time_warmup, time_total, chain);
921  }
922  if (!no_sd_mcmc && !have_hist_flag)
923  {
924  delete pofs_sd;
925  pofs_sd=NULL;
926  mean_mcmc_values/=double(isim);
927  square_mcmc_values/=double(isim);
928 #if defined(USE_DDOUBLE)
929  s=2.*sqrt(double(1.e-20)+square_mcmc_values-square(mean_mcmc_values));
930 #else
931  s=2.*sqrt(1.e-20+square_mcmc_values-square(mean_mcmc_values));
932 #endif
933  make_preliminary_hist(s,mean_mcmc_values,isim,values,hist,h,nslots,
934  total_spread);
935  }
936  if (!no_sd_mcmc)
937  if (iac>5)
938  print_hist_data(hist,values,h,mean_mcmc_values,s,parsave,iseed,
939  size_scale);
940 #ifndef OPT_LIB
941  assert(isim != 0);
942 #endif
943  cout <<"Chain " << chain << ":Final acceptance ratio=";
944  printf("%.2f", iac/double(isim));
945  // cout << iac/double(isim) << endl;
946  cout << endl << endl;
948  /*
949  if (adjm_ptr)
950  {
951  ad_update_mcmc_report(mcmc_display_matrix,mcmc_save_index,
952  mcmc_wrap_flag,1);
953 
954  if (allocated(hist)) ad_update_mcmchist_report(hist,
955  number_offsets,mean_mcmc_values,h,1);
956  }
957  */
958  }
959 
960  // Cole commented this stuff out. Not sure what it does but shouldnt be needed
961  // write_empirical_covariance_matrix(ncor,s_mean,s_covar,
962  // ad_comm::adprogram_name);
963  //newton_raftery_bayes_estimate(current_bf,ibfcount,exp(lkvector),.01);
964  // #if defined(USE_BAYES_FACTORS)
965  // cout << "log current bayes factor " << lcurrent_bf << endl;
966  // newton_raftery_bayes_estimate_new(lcurrent_bf,ibfcount,lkvector,.01);
967  // #endif
968  if (pofs_psave)
969  {
970  delete pofs_psave;
971  pofs_psave=NULL;
972  }
973  }
974 }
void ad_update_mcmchist_report(dmatrix &mcmc_values, ivector &number_offsets, dvector &mean_mcmc_values, dvector &h, int ff=0)
static void restore_all_values(const dvector &x, const int &ii)
Definition: model3.cpp:105
dvector bounded_multivariate_uniform(int nvar, const dvector &a1, const dvector &b1, dmatrix &ch, const double &lprob, random_number_generator &rng)
Definition: monte.cpp:216
void make_preliminary_hist(const dvector &s, const dvector &m, int nsim, const dmatrix &values, dmatrix &hist, const dvector &h, int slots, double total_spread, int probflag=0)
Definition: xxmcmc.cpp:1241
void read_hessian_matrix_and_scale(int nvar, const dmatrix &S, const dvector &pen_vector)
Definition: xxmcmc.cpp:1362
static void set_NO_DERIVATIVES(void)
Disable accumulation of derivative information.
Definition: gradstrc.cpp:641
static void set_active_random_effects(void)
Definition: model.cpp:267
void allocate(void)
Author: David Fournier Copyright (c) 2008-2012 Regents of the University of California.
Definition: dmat0.cpp:8
void read_mle_hmc(int nvar, dvector &mle)
dvector new_probing_bounded_multivariate_normal(int nvar, const dvector &a1, const dvector &b1, dmatrix &ch, const double &wght, double pprobe, random_number_generator &rng)
Definition: prmonte.cpp:14
void ad_update_mcmc_stats_report(int feval, int iter, double fval, double gmax)
int read_hist_data(const dmatrix &hist, const dvector &h, dvector &m, const dvector &s, const dvector &parsave, long int &iseed, const double &size_scale)
#define x
Vector of double precision numbers.
Definition: dvector.h:50
int indexmin() const
Get minimum valid index.
Definition: dvector.h:199
static char ** argv
Definition: fvar.hpp:8866
void allocate(int ncl, int ncu)
Allocate memory for a dvector.
Definition: dvector.cpp:409
static void add_random_vector(const dvector &x)
Author: David Fournier Copyright (c) 2008-2012 Regents of the University of California.
Definition: mod_mc1.cpp:7
void print_hist_data(const dmatrix &hist, const dmatrix &values, const dvector &h, dvector &m, const dvector &s, const dvector &parsave, long int iseed, double size_scale)
void rwm_mcmc_routine(int, int, double, int)
Definition: rwm.cpp:92
void print_mcmc_progress(int is, int nmcmc, int nwarmup, int chain, int refresh)
exitptr ad_exit
Definition: gradstrc.cpp:53
void set_labels_for_mcmc(void)
dvector bounded_multivariate_normal(int nvar, const dvector &a1, const dvector &b1, dmatrix &ch, const double &_wght, const random_number_generator &rng)
static dvariable reset(const dvar_vector &x)
Definition: model.cpp:345
void ad_update_function_minimizer_report(int feval, int iter, int phase, double fval, double gmax, const char *cbuf)
ADMB variable vector.
Definition: fvar.hpp:2172
static void set_all_simulation_bounds(const dmatrix &symbds)
Definition: montebds.cpp:25
static void restore_start_phase(void)
Definition: model.cpp:275
static adstring adprogram_name
Definition: fvar.hpp:8860
static int num_stddev_calc(void)
Definition: model2.cpp:51
double better_rand()
Random number generator.
Definition: rngen.cpp:134
int atoi(adstring &s)
Returns a integer converted from input s.
Definition: atoi.cpp:20
df1_one_matrix choleski_decomp(const df1_one_matrix &MM)
Definition: df11fun.cpp:606
static int nvarcalc()
Definition: model.cpp:152
Description not yet available.
Definition: fvar.hpp:7951
void ad_update_mcmc_report(dmatrix &m, int i, int j, int ff=0)
void write_empirical_covariance_matrix(int ncor, const dvector &s_mean, const dmatrix &s_covar, adstring &prog_name)
Writes the covariance matrix out to a file, which is prog_name prepended to the extension &#39;...
Definition: xxmcmc.cpp:917
prnstream & endl(prnstream &)
Description not yet available.
Definition: fvar.hpp:1937
Array of integers(int) with indexes from index_min to indexmax.
Definition: ivector.h:50
d3_array sqrt(const d3_array &arr3)
Author: David Fournier Copyright (c) 2008-2012 Regents of the University of California.
Definition: d3arr2c.cpp:11
Description not yet available.
Definition: fvar.hpp:3398
static int argc
Definition: fvar.hpp:8863
int indexmax() const
Get maximum valid index.
Definition: dvector.h:204
Description not yet available.
static void xinit(const dvector &x)
Definition: model.cpp:226
d3_array exp(const d3_array &arr3)
Returns d3_array results with computed exp from elements in arr3.
Definition: d3arr2a.cpp:28
static void set_inactive_random_effects(void)
Definition: model.cpp:288
dmatrix outer_prod(const dvector &v1, const dvector &v2)
Description not yet available.
Definition: dmat23.cpp:17
Description not yet available.
Definition: fvar.hpp:2819
void read_covariance_matrix(const dmatrix &S, int nvar, int &hbf, dvector &sscale)
Definition: xxmcmc.cpp:1320
void initialize(void)
Initialze all elements of dvector to zero.
Definition: dvect5.cpp:10
values
Definition: adjson.h:22
static void copy_all_values(const dvector &x, const int &ii)
Definition: model3.cpp:9
int user_stop(void)
Definition: xxmcmc.cpp:1558
void read_empirical_covariance_matrix(int nvar, const dmatrix &S, const adstring &prog_name)
Reads the covariance matrix from a file, which is the program name prepended to the extension &#39;...
Definition: xxmcmc.cpp:961
int option_match(int argc, char *argv[], const char *string)
Checks if the program has been invoked with a particular command line argument (&quot;string&quot;).
Definition: optmatch.cpp:25
void print_mcmc_timing(double time_warmup, double time_total, int chain)
void bounded_multivariate_uniform_mcmc(int nvar, const dvector &a1, const dvector &b1, dmatrix &ch, const double &wght, const dvector &y, const random_number_generator &rng)
Definition: xmonte2.cpp:138
int maxnz(const dvector &xa)
Definition: xxmcmc.cpp:1161
void new_probing_bounded_multivariate_normal_mcmc(int nvar, const dvector &a1, const dvector &b1, dmatrix &ch, const double &wght, const dvector &_y, double pprobe, random_number_generator &rng)
Definition: prmonte.cpp:167
int minnz(const dvector &x)
Definition: xxmcmc.cpp:1144
double better_rand(long int &idum)
Description not yet available.
Definition: bet_rand.cpp:18
Description not yet available.
Definition: fvar.hpp:3516
static void copy_all_values(const dvector &x, const int &ii)
Definition: model4.cpp:9
void read_hessian_matrix_and_scale1(int nvar, const dmatrix &_SS, double s, int mcmc2_flag)
Definition: xxmcmc.cpp:1453
std::string get_filename(const char *f)
double get_monte_carlo_value(int nvar, const independent_variables &x)
Definition: mod_mc2.cpp:11
static int stddev_scale(const dvector &d, const dvector &x)
Definition: model.cpp:202
static int mc_phase
Definition: admodel.h:846
void initialize(void)
Author: David Fournier Copyright (c) 2008-2012 Regents of the University of California.
Definition: dmat7.cpp:12
void add_hist_values(const dvector &s, const dvector &m, const dmatrix &hist, dvector &mcmc_values, double llc, const dvector &h, int nslots, double total_spreadd, int probflag=0)
Definition: xxmcmc.cpp:1178
void bounded_multivariate_normal_mcmc(int nvar, const dvector &a1, const dvector &b1, dmatrix &ch, const double &wght, const dvector &y, const random_number_generator &rng)
Definition: xmonte2.cpp:14
double square(const double value)
Return square of value; constant object.
Definition: d3arr4.cpp:16
df1_one_variable inv(const df1_one_variable &x)
Definition: df11fun.cpp:384
d3_array log(const d3_array &arr3)
Author: David Fournier Copyright (c) 2008-2012 Regents of the University of California.
Definition: d3arr2a.cpp:13
static int random_effects_flag
Definition: admodel.h:1857
int ctlc_flag
Definition: gradstrc.cpp:68