-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunciones.cpp
101 lines (87 loc) · 2.32 KB
/
funciones.cpp
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
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
double getpi() {
return M_PI;
}
// [[Rcpp::export]]
double loglikelihood(NumericVector theta, NumericVector X, NumericVector Y){
double a = theta[0];
double b = theta[1];
double sd = theta[2];
int n = X.length();
NumericVector yy(n);
for(int i=0; i < n; i++){
yy[i] = a*X[i] + b ;
}
NumericVector singleLikelihood(n);
double num;
double den;
for (int i=0; i < n; i++){
num = exp(-pow((Y[i]-yy[i]), 2.0)/(2*sd*sd));
den = sd*sqrt(2*getpi());
singleLikelihood[i] = log(num/den);
//singleLikelihood[i] = R::dnorm(Y[i], yy[i], sd, true);
}
double sumAll = sum(singleLikelihood);
return (sumAll);
}
// [[Rcpp::export]]
double logPriori(NumericVector theta){
double a = theta[0];
double b = theta[1];
double sd = theta[2];
double a_ = R::dunif(a, -10, 10, true);
double b_ = R::dnorm(b, -1000, 1000, true);
double sd_ = R::dunif(sd, -1000,1000,true);
double aux = a_+b_+sd_;
return(aux);
}
// [[Rcpp::export]]
double logPosteriori(NumericVector theta, NumericVector X, NumericVector Y){
double aux1 = loglikelihood(theta, X, Y);
double aux2 = logPriori(theta);
aux2 = aux2 + aux1;
return(aux2);
}
// [[Rcpp::export]]
NumericVector proposal(NumericVector theta){
double a = theta[0];
double b = theta[1];
double sd = theta[2];
double p1 = R::rnorm(a,1135);
double p2 = R::rnorm(b,1135);
double p3 = R::rnorm(sd,1135);
NumericVector aux(3);
aux[0] = p1;
aux[1] = p2;
aux[2] = p3;
return (aux);
}
// [[Rcpp::export]]
NumericMatrix runMCMC(NumericVector x, NumericVector y, NumericVector startValue, int iterations){
NumericMatrix chain(iterations+1, 3);
for(int i=0; i < startValue.length(); i++){
chain(0,i) = startValue[i];
}
NumericVector prop(3);
NumericVector aux(3);
double probab;
for(int i=0; i < iterations; i++){
for(int j=0; j < 3; j++){ //auxiliar, vector parametros
aux[j] = chain(i, j);
}
prop = proposal(aux);
probab = exp(logPosteriori(prop, x, y) - logPosteriori(aux, x, y));
if(R::runif(0,1) < probab){
for(int j=0; j < startValue.length(); j++){
chain(i+1, j) = prop[j];
}
}else{
for(int j=0; j < startValue.length(); j++){
chain(i+1, j) = chain(i,j);
}
}
}
return(chain);
}