-
Notifications
You must be signed in to change notification settings - Fork 1
/
functions.R
300 lines (278 loc) · 10.7 KB
/
functions.R
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
# Main function for finding distribution parameters
tuneParams <- function(distribution, targets) {
# Create and fit a stan model file
generateStanCode(distribution, targets)
# Find the parameters
fit <- stan(file='./model.stan', iter=1, warmup=0, chains=1,
algorithm="Fixed_param")
# Summarize return results
results <- summarizeResults(fit, distribution, targets)
return(results)
}
# -----------------------------------------------------------------------
# Functions for summarizing results
# -----------------------------------------------------------------------
summarizeResults <- function(fit, distribution, targets) {
results <- extract(fit)
results$lp__ <- NULL
# Extract the draws
draws <- as.vector(results$y_sim)
results$y_sim <- NULL
# Round parameters to nearest 6 decimal places
for (i in 1:length(results)) {results[[i]] <- round(results[[i]], 6)}
# Get the quantiles
quantiles <- quantile(draws, c(targets$dens_L, 1-targets$dens_U))
# Make a histogram of the draws
histogram <- makeHistogram(draws, quantiles)
# Return the results
return(list(
params=results, draws=draws, quantiles=quantiles, histogram=histogram))
}
makeHistogram = function(draws, quantiles) {
# Drop extreme values for better plotting
draws = draws[which(draws > quantile(draws, 0.001))]
draws = draws[which(draws < quantile(draws, 0.999))]
# Make the plot
histogram = ggplot(data.frame(draws), aes(x=draws)) +
geom_histogram(bins=30, fill='#DCBCBC', color='#C79999') +
geom_vline(xintercept=quantiles,
color='#B97C7C', linetype='dashed', size=1) +
# Color scheme copied from betanalpha (Thanks Michael!)
theme_bw() +
labs(x='x', y='Count')
return(histogram)
}
# -----------------------------------------------------------------------
# Functions for generating Stan code
# -----------------------------------------------------------------------
generateStanCode <- function(distribution, targets) {
stanCodeGenerator <- getStanCodeGenerator()
stanCode <- stanCodeGenerator[[distribution]](targets)
file <- file('./model.stan')
writeLines(stanCode, file)
close(file)
}
# Creates a list of functions indexed by the distribution name
getStanCodeGenerator <- function() {
return(list(
normal = getStanCode_normal,
lognormal = getStanCode_lognormal,
beta = getStanCode_beta,
gamma = getStanCode_gamma,
inv_gamma = getStanCode_inv_gamma))
}
# Code for generating Stan model for a Normal distribution
getStanCode_normal <- function(targets) {
mu_guess <- 0
sigma_guess <- 1
return(paste(
'functions {',
' // Differences between tail probabilities and target probabilities',
' vector tail_delta(vector y, vector theta, real[] x_r, int[] x_i) {',
' vector[2] deltas;',
paste(' deltas[1] = normal_cdf(theta[1], y[1], y[2]) - ',
targets$dens_L, ';', sep=''),
paste(' deltas[2] = 1 - normal_cdf(theta[2], y[1], y[2]) - ',
targets$dens_U, ';', sep=''),
' return deltas;',
' }',
'}',
'transformed data {',
' // Number of simulated observations in generated quantities',
' int<lower=0> N = 10000;',
' // Target quantiles',
paste(' real l = ', targets$bound_L, '; // Lower quantile', sep=''),
paste(' real u = ', targets$bound_U, '; // Upper quantile', sep=''),
" vector[2] theta = [l, u]';",
' // Initial guess at parameters',
paste(' real mu_guess = ', mu_guess, ';', sep=''),
paste(' real sigma_guess = ', sigma_guess, ';', sep=''),
" vector[2] y_guess = [mu_guess, sigma_guess]';",
' // Find parameters that ensures target density values',
' vector[2] y;',
' real x_r[0];',
' int x_i[0];',
' y = algebra_solver(tail_delta, y_guess, theta, x_r, x_i);',
'}',
'generated quantities {',
' real mu = y[1];',
' real sigma = y[2];',
' // Simulate data',
' real y_sim[N];',
' for (n in 1:N)',
' y_sim[n] = normal_rng(mu, sigma);',
'}',
sep='\n'))
}
# Code for generating Stan model for a Normal distribution
getStanCode_lognormal <- function(targets) {
mu_guess <- 0
sigma_guess <- 1
return(paste(
'functions {',
' // Differences between tail probabilities and target probabilities',
' vector tail_delta(vector y, vector theta, real[] x_r, int[] x_i) {',
' vector[2] deltas;',
paste(' deltas[1] = lognormal_cdf(theta[1], y[1], y[2]) - ',
targets$dens_L, ';', sep=''),
paste(' deltas[2] = 1 - lognormal_cdf(theta[2], y[1], y[2]) - ',
targets$dens_U, ';', sep=''),
' return deltas;',
' }',
'}',
'transformed data {',
' // Number of simulated observations in generated quantities',
' int<lower=0> N = 10000;',
' // Target quantiles',
paste(' real l = ', targets$bound_L, '; // Lower quantile', sep=''),
paste(' real u = ', targets$bound_U, '; // Upper quantile', sep=''),
" vector[2] theta = [l, u]';",
' // Initial guess at parameters',
paste(' real mu_guess = ', mu_guess, ';', sep=''),
paste(' real sigma_guess = ', sigma_guess, ';', sep=''),
" vector[2] y_guess = [mu_guess, sigma_guess]';",
' // Find parameters that ensures target density values',
' vector[2] y;',
' real x_r[0];',
' int x_i[0];',
' y = algebra_solver(tail_delta, y_guess, theta, x_r, x_i);',
'}',
'generated quantities {',
' real mu = y[1];',
' real sigma = y[2];',
' // Simulate data',
' real y_sim[N];',
' for (n in 1:N)',
' y_sim[n] = lognormal_rng(mu, sigma);',
'}',
sep='\n'))
}
# Code for generating Stan model for a Beta distribution
getStanCode_beta <- function(targets) {
alpha_guess <- 0.5
beta_guess <- 0.5
return(paste(
'functions {',
' // Differences between tail probabilities and target probabilities',
' vector tail_delta(vector y, vector theta, real[] x_r, int[] x_i) {',
' vector[2] deltas;',
paste(' deltas[1] = beta_cdf(theta[1], y[1], y[2]) - ',
targets$dens_L, ';', sep=''),
paste(' deltas[2] = 1 - beta_cdf(theta[2], y[1], y[2]) - ',
targets$dens_U, ';', sep=''),
' return deltas;',
' }',
'}',
'transformed data {',
' // Number of simulated observations in generated quantities',
' int<lower=0> N = 10000;',
' // Target quantiles',
paste(' real l = ', targets$bound_L, '; // Lower quantile', sep=''),
paste(' real u = ', targets$bound_U, '; // Upper quantile', sep=''),
" vector[2] theta = [l, u]';",
' // Initial guess at parameters',
paste(' real alpha_guess = ', alpha_guess, ';', sep=''),
paste(' real beta_guess = ', beta_guess, ';', sep=''),
" vector[2] y_guess = [alpha_guess, beta_guess]';",
' // Find parameters that ensures target density values',
' vector[2] y;',
' real x_r[0];',
' int x_i[0];',
' y = algebra_solver(tail_delta, y_guess, theta, x_r, x_i);',
'}',
'generated quantities {',
' real alpha = y[1];',
' real beta = y[2];',
' // Simulate data',
' real y_sim[N];',
' for (n in 1:N)',
' y_sim[n] = beta_rng(alpha, beta);',
'}',
sep='\n'))
}
# Code for generating Stan model for a Gamma distribution
getStanCode_gamma <- function(targets) {
alpha_guess <- 5
beta_guess <- 1
return(paste(
'functions {',
' // Differences between tail probabilities and target probabilities',
' vector tail_delta(vector y, vector theta, real[] x_r, int[] x_i) {',
' vector[2] deltas;',
paste(' deltas[1] = gamma_cdf(theta[1], exp(y[1]), exp(y[2])) - ',
targets$dens_L, ';', sep=''),
paste(' deltas[2] = 1 - gamma_cdf(theta[2], exp(y[1]), exp(y[2]))',
' - ', targets$dens_U, ';', sep=''),
' return deltas;',
' }',
'}',
'transformed data {',
' // Number of simulated observations in generated quantities',
' int<lower=0> N = 10000;',
' // Target quantiles',
paste(' real l = ', targets$bound_L, '; // Lower quantile', sep=''),
paste(' real u = ', targets$bound_U, '; // Upper quantile', sep=''),
" vector[2] theta = [l, u]';",
' // Initial guess at parameters',
paste(' real alpha_guess = ', alpha_guess, ';', sep=''),
paste(' real beta_guess = ', beta_guess, ';', sep=''),
" vector[2] y_guess = [log(alpha_guess), log(beta_guess)]';",
' // Find parameters that ensures target density values',
' vector[2] y;',
' real x_r[0];',
' int x_i[0];',
' y = algebra_solver(tail_delta, y_guess, theta, x_r, x_i);',
'}',
'generated quantities {',
' real alpha = exp(y[1]);',
' real beta = exp(y[2]);',
' // Simulate data',
' real y_sim[N];',
' for (n in 1:N)',
' y_sim[n] = gamma_rng(alpha, beta);',
'}',
sep='\n'))
}
# Code for generating Stan model for an Inverse Gamma distribution
getStanCode_inv_gamma <- function(targets) {
alpha_guess <- 5
beta_guess <- 1
return(paste(
'functions {',
' // Differences between tail probabilities and target probabilities',
' vector tail_delta(vector y, vector theta, real[] x_r, int[] x_i) {',
' vector[2] deltas;',
paste(' deltas[1] = inv_gamma_cdf(theta[1], exp(y[1]), exp(y[2])) - ',
targets$dens_L, ';', sep=''),
paste(' deltas[2] = 1 - inv_gamma_cdf(theta[2], exp(y[1]), exp(y[2]))',
' - ', targets$dens_U, ';', sep=''),
' return deltas;',
' }',
'}',
'transformed data {',
' // Number of simulated observations in generated quantities',
' int<lower=0> N = 10000;',
' // Target quantiles',
paste(' real l = ', targets$bound_L, '; // Lower quantile', sep=''),
paste(' real u = ', targets$bound_U, '; // Upper quantile', sep=''),
" vector[2] theta = [l, u]';",
' // Initial guess at parameters',
paste(' real alpha_guess = ', alpha_guess, ';', sep=''),
paste(' real beta_guess = ', beta_guess, ';', sep=''),
" vector[2] y_guess = [log(alpha_guess), log(beta_guess)]';",
' // Find parameters that ensures target density values',
' vector[2] y;',
' real x_r[0];',
' int x_i[0];',
' y = algebra_solver(tail_delta, y_guess, theta, x_r, x_i);',
'}',
'generated quantities {',
' real alpha = exp(y[1]);',
' real beta = exp(y[2]);',
' // Simulate data',
' real y_sim[N];',
' for (n in 1:N)',
' y_sim[n] = inv_gamma_rng(alpha, beta);',
'}',
sep='\n'))
}