-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctions.cpp
More file actions
2386 lines (1804 loc) · 57.2 KB
/
Copy pathfunctions.cpp
File metadata and controls
2386 lines (1804 loc) · 57.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#define ARMA_USE_BLAS
#define ARMA_USE_LAPACK
#include <RcppArmadillo.h>
#include <iostream>
#include <Rmath.h>
#include <Rcpp.h>
#include <chrono>
using namespace Rcpp;
using namespace std;
using namespace arma;
//[[Rcpp::depends(RcppArmadillo)]]
double psev(double z)
{
double res;
res=1-exp(-exp(z));
return res;
}
vec psev_vec(const vec& z)
{
vec res;
res=1-exp(-exp(z));
return res;
}
vec pow_vec(double a, const vec& b)
{
int n=b.n_elem;
vec res=b;
int i;
for(i=0; i<n; i++)
{
res(i)=pow(a, b(i));
}
return(res);
}
double dsev(double z)
{
double res;
res=exp(z-exp(z));
return(res);
}
vec dsev_vec(const vec& z)
{
vec res;
res=exp(z-exp(z));
return(res);
}
double pnor(double z)
{
double res;
res=R::pnorm(z,0.0,1.0,1,0);
return res;
}
vec pnor_vec(const vec& z)
{
vec res;
res=normcdf(z);
return res;
}
double dnor(double z)
{
double res;
res=R::dnorm(z,0.0,1.0,0);
return res;
}
vec dnor_vec(const vec& z)
{
vec res;
res=normpdf(z);
return res;
}
vec tmpOneFun(const vec& zz)
{
vec res=zz;
return(res.ones());
}
vec tmpIdFun(const vec& zz)
{
return(zz);
}
vec tmpLogFun(const vec& zz)
{
vec res=log(zz);
return(res);
}
vec tmpExpFun(const vec& zz)
{
vec res=exp(zz);
return(res);
}
vec sev_dphiphi(const vec& zz)
{
vec res=1-exp(zz);
return(res);
}
vec nor_dphiphi(const vec& zz)
{
vec res=(-1)*zz;
return(res);
}
class distFuns
{
public:
vec (*Phi)(const vec&);
vec (*phi)(const vec&);
vec (*xtran)(const vec&);
vec (*ixtran)(const vec&);
vec (*dent)(const vec&);
vec (*dphiphi)(const vec&);
String dtype;
distFuns(String dd)
{
dtype=dd;
if(dd=="weibull") //Weibull distribution
{
Phi=&psev_vec;
phi=&dsev_vec;
xtran=&tmpLogFun;
ixtran=&tmpExpFun;
dent=&tmpIdFun;
dphiphi=&sev_dphiphi;
}
if(dd=="lognormal") //lognormal distribution
{
Phi=&pnor_vec;
phi=&dnor_vec;
xtran=&tmpLogFun;
ixtran=&tmpExpFun;
dent=&tmpIdFun;
dphiphi=&nor_dphiphi;
}
}
};
/*
double test_fun(double tt)
{
double res=exp((log(tt)-1.0)/2.0);
return(res);
}
*/
class gibbsModel
{
public:
List dat_list;
double (*log_post_ratio)(double, int, const vec&, const List&);
};
class gibbsOutput
{
public:
mat vmat;
vec arate;
vec th;
};
class gibsAdaptOutput
{
public:
int adap;
vec scale;
};
gibsAdaptOutput gibbs_adap_fun(const vec& scale0, const vec& acc, int no_iter)
{
double tmp, tmp1, dd;
int i, ind;
ind=0;
int p=acc.n_elem;
vec scale=scale0;
tmp=(double) no_iter;
tmp1=1/tmp;
int adap=0;
if(tmp1>.02)
{
dd=.02;
}else{
dd=tmp1;
}
for(i=0; i<p;i++)
{
if(acc[i]<=.35 && acc[i]>=.15)
{
ind++;
}
}
if(ind==p)
{
adap=1;
}else{
for(i=0;i<p;i++)
{
if(acc[i]>.35)
{
scale[i]+=dd;
}
if(acc[i]<.15)
{
scale[i]-=dd;
}
}
}
for(i=0;i<p;i++)
{
if(scale[i]<=0)
{
scale[i]/=2.0;
}
}
gibsAdaptOutput res;
res.adap=adap;
res.scale=scale;
return res;
}
/******************************************************************************/
gibbsOutput Gibbs(gibbsModel gibbs_model, const vec& th0, const vec& scale, int mm)
{
int p, m, i,j;
double f1, uu, ww, u;
double yy;
int pp=th0.n_elem;
mat vmat(mm, pp, fill::zeros);
vec th=th0;
vec arate=zeros(pp);
u=0.0;
p=pp; //dimension of unknown parameter vector
m=mm; //number of mcmc iter
GetRNGstate();
for (i=0;i<m; i++)
{
for (j=0;j<p;j++)
{
ww=norm_rand();//rnorm(0.0,1.0);
yy=ww * scale[j];
f1=gibbs_model.log_post_ratio(yy, j, th, gibbs_model.dat_list);
ww=exp(f1);
uu=unif_rand();//runif(0.0,1.0);
//Rprintf("%u, %lf, %lf, %lf, %lf,%lf,%lf \n",j, scale(j), th0(j), yy, f1, ww, uu);
//Rprintf("%u,%lf,%lf,%lf \n",j, ww,f1,f0);
if(uu<ww)
{
u=1.0;
th[j]+=yy;
}else{
u=0.0;
}
//Rprintf("%u, %lf, %lf, %lf, %lf, %lf, %lf, %lf \n",j, scale(j), th0(j), yy, f1, ww, uu, u);
vmat(i,j)=th[j]; //mcmc matrix
arate[j]+=u;
}
}
PutRNGstate();
for(i=0;i<p;i++)
{
arate[i]/=m;
}
gibbsOutput res;
res.vmat=vmat;
res.th=th;
res.arate=arate;
return res;
}
/******************************************************************************/
List Gibbs_adaptive(gibbsModel gibbs_model, const vec& th0, const vec& scale0, int mm, int mm1, int max_iter=400)
{
int adaptive, no_iter, adap;
adaptive=1;
adap=0;
no_iter=0;
int pp=th0.n_elem;
vec scale=scale0;
vec th=th0;
vec arate=zeros(pp);
while((adaptive==1)&& no_iter<max_iter)
{
no_iter++;
gibbsOutput gres1=Gibbs(gibbs_model, th, scale, mm1);
th=gres1.th;
arate=gres1.arate;
gibsAdaptOutput ares=gibbs_adap_fun(scale, arate, no_iter);
adap=ares.adap;
scale=ares.scale;
Rcout<<"Adaptation iter: "<< no_iter<<", arate range: ("<< arate.min()<<", "<<arate.max()<< "), scale range: ("<<scale.min()<<", "<<scale.max()<<")."<<endl;
if(adap==1)
{
adaptive=0;
Rcout<<"Adaptation done after "<< no_iter<<" iterations."<<endl;
}
}
if(no_iter==max_iter)
{
Rcout<<"max iter reached: "<< max_iter<<endl;
}
Rcout<<"Gibbs started. It may take a while."<<endl;
gibbsOutput gres=Gibbs(gibbs_model, th, scale, mm);
arate=gres.arate;
mat vmat=gres.vmat;
Rcout<<"Gibbs done."<<endl;
List res=List::create(Named("vmat")=vmat, Named("arate")=arate, Named("scale")=scale);
return res;
}
/*NUTS general code------------------------------------------------*/
class nutsModel
{
public:
//List dat_list;
double (*fn_val)(const vec&, const List&);
vec (*gn_val)(const vec&, const List&);
double (*joint_fn_val)(const vec&, const vec&, const vec&, const List&);
};
vec leapfrog_step_cpp(nutsModel nuts_model, const List& dat_list, const vec& vec_theta, const vec& vec_r, double eps, const vec& M_diag)
{
//Rcout<<"leap frog eps="<<eps<<endl;
int int_dim = vec_theta.n_elem;
vec vec_r_tilde(int_dim);
vec vec_theta_tilde(int_dim);
vec ret_vec(2 * int_dim);
// r_tilde <- r + 0.5 * eps * grad_f(theta=theta, dat=dat)
vec_r_tilde = vec_r + 0.5 * eps * nuts_model.gn_val(vec_theta, dat_list);
//vec_r_tilde = vec_r + 0.5 * eps * nuts_model.gn_val(vec_theta);
// theta_tilde <- theta + eps * r_tilde/M_diag
vec_theta_tilde = vec_theta + eps * vec_r_tilde/M_diag;
// r_tilde <- r_tilde + 0.5 * eps * grad_f(theta=theta_tilde, dat=dat)
vec_r_tilde = vec_r_tilde + 0.5 * eps * nuts_model.gn_val(vec_theta_tilde, dat_list);
//vec_r_tilde = vec_r_tilde + 0.5 * eps * nuts_model.gn_val(vec_theta_tilde);
// res=list(theta = theta_tilde, r = r_tilde)
ret_vec.subvec(0,int_dim-1) = vec_theta_tilde;
ret_vec.subvec(int_dim,2*int_dim-1) = vec_r_tilde;
return(ret_vec);
}
double find_reasonable_epsilon_cpp(nutsModel nuts_model, const List& dat_list, const vec& vec_theta, const vec& vec_M_diag, double num_eps = 1.0)
{
int int_dim = vec_theta.n_elem;
vec vec_r(int_dim);
vec_r = randn(int_dim)%sqrt(vec_M_diag);
vec proposed = leapfrog_step_cpp(nuts_model, dat_list, vec_theta, vec_r, num_eps, vec_M_diag);
double log_ratio =nuts_model.joint_fn_val(proposed.subvec(0,int_dim-1), proposed.subvec(int_dim,2*int_dim-1), vec_M_diag, dat_list) - nuts_model.joint_fn_val(vec_theta, vec_r, vec_M_diag, dat_list);
int int_alp = -1;
if(isnan(log_ratio))
{
int_alp = -1;
} else if(exp(log_ratio) > 0.5)
{
int_alp = 1;
}
int count = 1;
while (int_alp * log_ratio > (-int_alp)*log(2) || isnan(log_ratio))
{
num_eps = pow(2.0,int_alp) * num_eps;
proposed = leapfrog_step_cpp(nuts_model, dat_list, vec_theta, vec_r, num_eps, vec_M_diag);
log_ratio =nuts_model.joint_fn_val(proposed.subvec(0,int_dim-1), proposed.subvec(int_dim,2*int_dim-1), vec_M_diag, dat_list) - nuts_model.joint_fn_val(vec_theta, vec_r, vec_M_diag, dat_list);
count = count +1;
if(count > 100)
{
Rcout<<"Could not find reasonable epsilon in 100 iterations!"<<endl;
break;
}
}
Rcout<<"Reasonable epsilon found after "<<count<<" steps. eps="<<num_eps<<endl;
return num_eps;
}
class hmctree
{
public:
//list(theta_minus=theta, theta_plus=theta, theta=theta, r_minus=r, r_plus=r, s=s, n=n, alpha=alpha, n_alpha=1)
vec theta_minus;
vec theta_plus;
vec theta;
vec r_minus;
vec r_plus;
int s;
int n;
double alpha;
int n_alpha;
hmctree(int int_ndim)
{
n = int_ndim;
theta_minus.set_size(n);
theta_plus.set_size(n);
theta.set_size(n);
r_minus.set_size(n);
r_plus.set_size(n);
n_alpha = 1;
}
hmctree()
{
n_alpha = 1;
}
};
bool check_NUTS_cpp(int int_s, const vec& vec_theta_plus, const vec& vec_theta_minus, const vec& vec_r_plus, const vec& vec_r_minus)
{
bool condition1 = dot(vec_theta_plus - vec_theta_minus, vec_r_minus) >=0;
// crossprod(vec_theta_plus - theta_minus, r_minus) >= 0
bool condition2 = dot(vec_theta_plus - vec_theta_minus, vec_r_plus) >=0;
// crossprod(vec_theta_plus - theta_minus, r_plus) >= 0
bool res=(int_s & condition1 & condition2);
if(isnan(int_s))
{
return false;
}
return(res);
}
hmctree build_tree_cpp(nutsModel nuts_model, const List& dat_list, vec vec_theta, vec vec_r, double num_u, int int_v, int int_j, double num_eps, vec vec_theta0, vec vec_r0, vec vec_M_diag, int Delta_max = 1000)
{
int int_dim = vec_theta.n_elem;
vec proposed(2*int_dim);
//proposed = (theta,rtilde)
double log_prob,log_prob0,alpha;
int int_n, int_s, n_alpha;
vec vec_theta_minus;
vec vec_r_minus;
vec vec_theta_plus;
vec vec_r_plus;
hmctree res(int_dim);
hmctree obj0(int_dim);
hmctree obj1(int_dim);
if(int_j == 0)
{
proposed = leapfrog_step_cpp(nuts_model, dat_list, vec_theta, vec_r, int_v*num_eps , vec_M_diag);
vec_theta = proposed.subvec(0,int_dim-1);
vec_r = proposed.subvec(int_dim, 2*int_dim-1);
log_prob = nuts_model.joint_fn_val(vec_theta, vec_r, vec_M_diag, dat_list);
log_prob0 = nuts_model.joint_fn_val(vec_theta0, vec_r0, vec_M_diag, dat_list);
int_n = (log(num_u) <= log_prob);
int_s = (log(num_u) < (Delta_max + log_prob));
alpha = min(1.0, exp(log_prob - log_prob0));
// if(isnan(alpha))
// {
// Rcout<<"we have a nan alpha!"<<endl;
// terminate();
// }
if(isnan(int_s))
{
Rcout<<"nan s produced"<<endl;
int_s = 0;
}
if(isnan(int_n))
{
Rcout<<"nan n produced"<<endl;
int_n = 0;
}
// res=list(theta_minus=theta, theta_plus=theta, theta=theta, r_minus=r, r_plus=r, s=s, n=n, alpha=alpha, n_alpha=1)
res.theta_minus = vec_theta;
res.theta_plus = vec_theta;
res.theta = vec_theta;
res.r_minus = vec_r;
res.r_plus = vec_r;
res.s = int_s;
res.n = int_n;
res.alpha = alpha;
res.n_alpha = 1;
return(res);
} else
{
obj0 = build_tree_cpp(nuts_model, dat_list, vec_theta, vec_r, num_u, int_v, int_j-1, num_eps, vec_theta0, vec_r0,vec_M_diag);
vec_theta_minus = obj0.theta_minus;
vec_r_minus = obj0.r_minus;
vec_theta_plus = obj0.theta_plus;
vec_r_plus = obj0.r_plus;
vec_theta = obj0.theta;
if(obj0.s ==1)
{
if(int_v == -1)
{
obj1 = build_tree_cpp(nuts_model, dat_list, obj0.theta_minus, obj0.r_minus, num_u, int_v, int_j-1, num_eps, vec_theta0, vec_r0, vec_M_diag);
vec_theta_minus = obj1.theta_minus;
vec_r_minus = obj1.r_minus;
} else
{
obj1 = build_tree_cpp(nuts_model, dat_list, obj0.theta_plus, obj0.r_plus, num_u, int_v, int_j-1, num_eps, vec_theta0, vec_r0, vec_M_diag);
vec_theta_plus = obj1.theta_plus;
vec_r_plus = obj1.r_plus;
}
int_n = obj0.n + obj1.n;
if(int_n != 0)
{
double num_prob =(double) obj1.n / (double) int_n;
// updating theta
// vec vec_unif(1000);
// vec_unif.load("vec_unif.txt");
// Rcout<<"int_j = "<<int_j<<endl;
// Rcout<<"for debug, using unif.txt, unif = "<<vec_unif(int_j)<<endl;
if(randu() < num_prob)
{
vec_theta = obj1.theta;
}
}
int_s = check_NUTS_cpp(obj1.s, vec_theta_plus, vec_theta_minus, vec_r_plus, vec_r_minus);
alpha = obj0.alpha + obj1.alpha;
n_alpha = obj0.n_alpha + obj1.n_alpha;
} else
{
int_n = obj0.n;
int_s = obj0.s;
alpha = obj0.alpha;
n_alpha = obj0.n_alpha;
}
if(isnan(int_s))
{
int_s = 0;
}
if(isnan(int_n))
{
int_n = 0;
}
res.theta_minus = vec_theta_minus;
res.theta_plus = vec_theta_plus;
res.theta = vec_theta;
res.r_minus = vec_r_minus;
res.r_plus = vec_r_plus;
res.s = int_s;
res.n = int_n;
res.alpha = alpha;
res.n_alpha = n_alpha;
return(res);
}
}
// pars = list(eps = eps, eps_bar = eps_bar, H = H, mu = mu, M_adapt = M_adapt, M_diag = M_diag))
class parlist
{
public:
double eps;
double eps_bar;
double hmcmu;
double H;
int M_adapt;
vec M_diag;
parlist(int int_dim)
{
M_diag.set_size(int_dim);
M_diag.fill(1.0);
M_adapt = 50;
eps = 1.0;
hmcmu = log(10.0*eps);
H = 0.0;
eps_bar = 1.0;
}
parlist()
{
M_adapt = 50;
eps = 1.0;
hmcmu = log(10.0*eps);
H = 0.0;
eps_bar = 1.0;
M_diag.set_size(10);
M_diag.fill(datum::nan);
}
};
class thetaparlist
{
public:
parlist pl;
vec theta;
thetaparlist(int int_dim):
pl(int_dim)
{
}
thetaparlist():
pl()
{
}
};
void adapt(double &num_H, double &log_eps, double &num_epsbar, double &num_eps, const int& int_iter, const double& num_t0, const double &num_delta, const double &num_gamma, const double &num_kappa, const double &num_hmcmu, const int &int_alpha, const int &n_alpha)
{
num_H = (1.0 - 1.0/(double) (int_iter + 1 + num_t0))*num_H +
1.0/(double) (int_iter + 1 + num_t0) * (num_delta - int_alpha /(double) n_alpha);
log_eps = num_hmcmu - sqrt((double) (int_iter + 1))/(double) num_gamma * num_H;
num_epsbar = exp(pow((double) (int_iter+1),-1.0*num_kappa) * log_eps +
(1.0 - pow((double) (int_iter+1),(-1.0 * num_kappa))) * log(num_epsbar));
num_eps = exp(log_eps);
}
thetaparlist NUTS_one_step_cpp(nutsModel nuts_model, const List& dat_list, vec vec_theta, int int_iter, parlist pl,
double num_delta = 0.5, int max_treedepth = 10, double num_eps = 1)
{
int int_dim = vec_theta.n_elem;
double num_kappa = 0.75;
double num_t0 = 10;
double num_gamma = 0.05;
int int_M_adapt = pl.M_adapt;
vec vec_M_diag(int_dim);
double num_hmcmu;
double num_H;
double num_epsbar;
if(pl.M_diag.has_nan())
{
vec_M_diag.fill(1.0);
} else{
vec_M_diag = pl.M_diag;
}
if(int_iter == 0)
{
num_eps = find_reasonable_epsilon_cpp(nuts_model, dat_list, vec_theta, vec_M_diag, num_eps);
num_hmcmu = log(10.0*num_eps);
num_H = 0.0;
num_epsbar = 1.0;
} else{
num_eps = pl.eps;
num_epsbar = pl.eps_bar;
num_H = pl.H;
num_hmcmu = pl.hmcmu;
}
// r0 <- rnorm(length(theta), 0, sqrt(M_diag))
// u <- runif(1, 0, exp(joint_log_density(theta, r0, f, M_diag, dat)))
vec vec_r0 = randn(int_dim)%sqrt(vec_M_diag);
// Rcout<<"for debug, use constant vec_r0"<<endl;
// vec vec_r0(int_dim);
// vec_r0.load("vec_r0.txt");
double num_u = exp(nuts_model.joint_fn_val(vec_theta, vec_r0, vec_M_diag, dat_list));
num_u = randu()*num_u;
if(isnan(num_u))
{
Rcout<<"NUTS: sampled slice u is NaN"<<endl;
num_u = randu()*1e5;
}
vec vec_theta_minus = vec_theta;
vec vec_theta_plus = vec_theta;
vec vec_r_minus = vec_r0;
vec vec_r_plus = vec_r0;
int int_j=0;
int int_n=1;
int int_s=1;
if(int_iter > int_M_adapt-1)
{
num_eps = 0.9*num_epsbar + randu()*0.2*num_epsbar;// runif(1, 0.9*eps_bar, 1.1*eps_bar)
}
hmctree temp;
while(int_s == 1)
{
int int_direction = randi(distr_param(0,1));
if (int_direction==0)
{
int_direction = -1;
}// sample(c(-1, 1), 1)
// Rcout<<"for debug set int_direction = "<<-1<<endl;
// int_direction = -1;
if(int_direction == -1)
{
temp = build_tree_cpp(nuts_model, dat_list, vec_theta_minus, vec_r_minus, num_u, int_direction, int_j, num_eps, vec_theta, vec_r0, vec_M_diag);
vec_theta_minus = temp.theta_minus;
vec_r_minus = temp.r_minus;
} else{
temp = build_tree_cpp(nuts_model, dat_list, vec_theta_plus, vec_r_plus, num_u, int_direction, int_j, num_eps, vec_theta, vec_r0, vec_M_diag);
vec_theta_plus = temp.theta_plus;
vec_r_plus = temp.r_plus;
}
if(isnan(temp.s))
{
temp.s = 0;
}
if(temp.s == 1)
{
if(randu() < min(1.0, (double) temp.n/(double) int_n))
{
vec_theta = temp.theta;
}
// {
// Rcout<<"ratio = "<< (double) temp.n/(double) int_n<<endl;
// Rcout<<"temp.n = "<<temp.n<<"\t int_n = "<<int_n<<endl;
// Rcout<<"new theta not accepted!"<<endl;
// }
}
int_n = int_n + temp.n;
int_s = check_NUTS_cpp(temp.s, vec_theta_plus, vec_theta_minus, vec_r_plus, vec_r_minus);
int_j = int_j + 1;
if(int_j > max_treedepth)
{
// warning("NUTS: Reached max tree depth")
// Rcout<<"NUTS: Reached max tree depth, int_iter = "<<int_iter<<endl;
break;
}
}
double log_eps;
if(int_iter <= int_M_adapt-1)
{
adapt(num_H, log_eps, num_epsbar, num_eps, int_iter, num_t0, num_delta, num_gamma, num_kappa, num_hmcmu, temp.alpha, temp.n_alpha);
} else{
num_eps = num_epsbar;
}
//Rcout<<"iter = "<<int_iter<<" num_eps = "<<num_eps<<" "<<temp.alpha<<" "<<temp.n_alpha<<endl;
thetaparlist res;
parlist respl;
respl.eps = num_eps;
respl.eps_bar = num_epsbar;
respl.H = num_H;
respl.hmcmu = num_hmcmu;
respl.M_adapt = int_M_adapt;
respl.M_diag = vec_M_diag;
res.theta = vec_theta;
res.pl = respl;
// res=list(theta = theta, pars = list(eps = eps, eps_bar = eps_bar, H = H, mu = mu, M_adapt = M_adapt, M_diag = M_diag))
return res;
}
// NUTS <- function(theta, f, grad_f, dat, n_iter, M_diag = NULL, M_adapt = 50, delta = 0.5, max_treedepth = 10, eps = 1, verbose = TRUE)
mat Nuts_cpp(nutsModel nuts_model, const List& dat_list, vec vec_theta, int int_iter, vec vec_M_diag, int int_M_adapt = 50, double num_delta = 0.5, int int_max_treedepth = 10, double num_eps = 1)
{
int int_ndim = vec_theta.n_elem;
mat mat_theta_trace(int_ndim, int_iter, fill::ones);
//par_list <- list(M_adapt = M_adapt)
parlist pl(int_ndim);
pl.M_diag = vec_M_diag;
for(int i = 0; i<int_iter; i++)
{
//nuts <- NUTS_one_step(theta, iter, f, grad_f, par_list, delta = delta, max_treedepth = max_treedepth, eps = eps, verbose = verbose, dat)
thetaparlist nuts = NUTS_one_step_cpp(nuts_model, dat_list, vec_theta, i, pl, num_delta, int_max_treedepth, num_eps);
vec_theta = nuts.theta;
mat_theta_trace.col(i) = nuts.theta;
pl = nuts.pl;
if((i==0)| (i%1000 == 999))
{
Rcout<<"iter = "<<i + 1<<" finished."<<" eps = "<<nuts.pl.eps<<endl;
}
}
return mat_theta_trace.t();
}
/*------------------------------------------------*/
//customized code for specific models
double my_fn(const vec& vec_theta, const List& dat_list)
{
double num_val;
double num_mu=dat_list["num_mu"];
vec vec_w=dat_list["vec_w"];
mat mat_eps_inv=dat_list["mat_eps_inv"];
mat mat_alp_inv=dat_list["mat_alp_inv"];
num_val = as_scalar(vec_theta.t() * mat_alp_inv * vec_theta);
num_val += as_scalar((vec_w - num_mu - vec_theta).t() * mat_eps_inv * (vec_w - num_mu - vec_theta));
return num_val * (-0.5);
}
vec my_gn(const vec& vec_theta, const List& dat_list)
{
vec vec_val;
double num_mu=dat_list["num_mu"];
vec vec_w=dat_list["vec_w"];
mat mat_eps_inv=dat_list["mat_eps_inv"];
mat mat_alp_inv=dat_list["mat_alp_inv"];
vec_val = 2.0 * mat_alp_inv * vec_theta;
vec_val = vec_val - 2.0*mat_eps_inv * (vec_w - num_mu - vec_theta);
return vec_val*(-0.5);
}
double normal_fn(const vec& vec_theta, const List& dat_list)
{
double num_val;
vec mu=dat_list["mu"];
mat sigma_inv=dat_list["sigma_inv"];
num_val = as_scalar((vec_theta-mu).t() * sigma_inv * (vec_theta-mu));
return num_val * (-0.5);
}
vec normal_gn(const vec& vec_theta, const List& dat_list)
{
vec vec_val;
vec mu=dat_list["mu"];
mat sigma_inv=dat_list["sigma_inv"];
vec_val = sigma_inv * (vec_theta-mu);
return vec_val*(-1.0);
}
double loglik_ld_val(distFuns dfuns, const mat& Ymat, const vec& mu_vec, const vec& sigma_vec)
{
int nn=Ymat.n_rows;
vec ll(nn, fill::zeros);
vec delta(nn, fill::zeros);
vec tt=Ymat.col(2); //respU
vec censor_cate=Ymat.col(3);
vec wts_col=Ymat.col(4);
vec trun_cate=Ymat.col(7);
vec zL=(dfuns.xtran(Ymat.col(1))-mu_vec)/sigma_vec;
vec zU=(dfuns.xtran(Ymat.col(2))-mu_vec)/sigma_vec;
vec dd=dfuns.phi(zU)/(sigma_vec % dfuns.dent(tt));
vec pzU=dfuns.Phi(zU);
vec pzL=dfuns.Phi(zL);
uvec idx = find(censor_cate==1.0); //1 is none for censoring type
delta.elem(idx).fill(1.0);
idx = find(censor_cate==3.0); //left
pzL.elem(idx).fill(0.0);
idx = find(censor_cate==2.0); //right
pzU.elem(idx).fill(1.0);
vec ppc=pzU-pzL;
//
vec ztL=(dfuns.xtran(Ymat.col(5))-mu_vec)/sigma_vec;
vec ztR=(dfuns.xtran(Ymat.col(6))-mu_vec)/sigma_vec;
vec pztL=dfuns.Phi(ztL);
vec pztR=dfuns.Phi(ztR);
idx = find((trun_cate==2.0) || (trun_cate==1.0)); // right or none
pztL.elem(idx).fill(0.0);
idx = find((trun_cate==3.0) || (trun_cate==1.0)); // left or none
pztR.elem(idx).fill(1.0);
vec ppt=pztR-pztL;
vec term1=log(dd)-log(ppt); //exact
vec term2=log(ppc)-log(ppt); //censored
idx = find(delta==1.0);
ll.elem(idx)=term1.elem(idx);
idx = find(delta!=1.0);
ll.elem(idx)=term2.elem(idx);
//replace -inf values
idx = find(ll== (-1)*datum::inf);
vec rep_m_inf(nn);
rep_m_inf.fill(-743.7469);
ll.elem(idx)=rep_m_inf.elem(idx);
double res=as_scalar(sum(ll%wts_col));
//Rcout<<"beta0 is: "<<mu_vec(0)<<". loglik is: "<<sum(ll)<<endl;
return(res);
}
vec loglik_ld_der(distFuns dfuns, const mat& Ymat, const vec& mu_vec, const vec& sigma_vec)
{
int nn=Ymat.n_rows;
vec res(nn+1);
vec vone(nn, fill::ones);
mat der(nn, 2, fill::zeros);
vec tres(nn, fill::zeros);
vec delta(nn, fill::zeros);
//vec tt=Ymat.col(2); //respU
vec censor_cate=Ymat.col(3);
vec wts_col=Ymat.col(4);
vec trun_cate=Ymat.col(7);
vec zL=(dfuns.xtran(Ymat.col(1))-mu_vec)/sigma_vec;
vec zU=(dfuns.xtran(Ymat.col(2))-mu_vec)/sigma_vec;
//Rcout<<Ymat.row(0)<<endl;
vec dd=(-1)*dfuns.dphiphi(zU)/sigma_vec; //wrt mu
vec s_dd=(-1)*dfuns.dphiphi(zU)%zU; //wrt log(sigma)
//mat debug1 = join_horiz(zU, mu_vec, sigma_vec);
//Rcout<< debug1.row(0) <<endl;
vec pzU=dfuns.Phi(zU);
vec pzL=dfuns.Phi(zL);
vec dzU=(-1)*dfuns.phi(zU)/sigma_vec;
vec dzL=(-1)*dfuns.phi(zL)/sigma_vec;
vec s_dzU=(-1)*dfuns.phi(zU)%zU;
vec s_dzL=(-1)*dfuns.phi(zL)%zL;
uvec idx = find(censor_cate==1.0); //1 is none for censoring type
delta.elem(idx).fill(1.0);
idx = find(censor_cate==2.0); //right
pzU.elem(idx).fill(1.0);
dzU.elem(idx).fill(0.0);
s_dzU.elem(idx).fill(0.0);
idx = find(censor_cate==3.0); //left
pzL.elem(idx).fill(0.0);
dzL.elem(idx).fill(0.0);
s_dzL.elem(idx).fill(0.0);
vec ppc=pzU-pzL;
vec dpc=dzU-dzL;