-
Notifications
You must be signed in to change notification settings - Fork 19
/
fit.R
305 lines (261 loc) · 13.8 KB
/
fit.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
300
301
302
303
304
305
# Integrate stanfit and stanoptim objects ---------------------------------
# This file contains all the implementation of those methods that should be
# available to both stanfit and stanoptim objects. Our goal is to unify
# these two objects as much as possible for the final user.
# extract_quantity --------------------------------------------------------
#' Extract estimated quantities from fit objects.
#'
#' This function extracts estimated quantities from fit objects. It works transparently with both Markov-chain Monte Carlo samples returned by \code{\link{draw_samples}} and maximum a posteriori estimates returned by \code{\link{optimizing}}. Most of the user-friendly extractors (e.g. \code{\link{extract_alpha}}) are built upon this function. As such, it was not designed to be used directly by users, except perhaps for the most advanced ones.
#'
#' Note that \emph{rstan} does not provide a unified way to extract quantities from full bayesian and optimization fits, and the structure of the returned objects are not homogeneous. \emph{extract_quantity} solves these two inconvenients. Additionally, it allows for regex expressions in the name of the quantities to be extracted.
#'
#' @param fit An object returned by \code{\link{fit}}, \code{\link{draw_samples}}, or \code{\link{optimizing}}.
#' @param pars A vector of characters with the name of the quantities to be extracted. The characters strings may include regular expressions. Further, wildcards are automatically translated into regex: \emph{?} matches a single character, while \emph{*} matches any character string including an empty one. For example, \emph{?pred} will match both ypred and zpred, and \emph{z*} will match zstar and zpred.
#' @param reduce A function applied to the samples generated by one chain for each parameters (i.e. "within chain"). Useful if only one or more summary measures of the generated samples is needed (e.g. the median of the generated sample). The function may return one of more elements. In the former case, the dimension is dropped in the returned object (read the \emph{Value} section below). Note that the user needs to supply a function as an argument, and not a character string with the name of the function. This argument is not used for maximum a posteriori estimates returned by \code{\link{optimizing}} since there is only one scalar per quantity.
#' @param combine A function applied to all the extracted quantities as an ensemble. In other words, instead of returning a named list where each element is one quantity, it returns the value returned by the function applied to the whole list (\code{\link{do.call}}). Useful when all the elements of the list have the same dimension, possibly because it is used in conjunction with the \emph{chain} and \emph{reduce} arguments.
#' @param chain Either "all" or any integer number between 1 and the number of chains M. In the latter case, the chain dimension in the returned object is dropped.
#' @param ... Arguments to be passed to rstan's \code{\link[rstan]{extract}} if the object \emph{fit} was returned by \code{\link{fit}} or \code{\link{draw_samples}}.
#' @return A list of named elements with type and dimension depending on the characteristics of the quantity. If the argument \emph{combine} is set, the returned value equals to the return value of the function given (e.g. a matrix if \code{\link{cbind}}) is used).
#'
#' @examples
#' \dontrun{
#' extract_quantity(myFit, c("z*"), reduce = mean, chain = 1, combine = cbind))
#' }
extract_quantity <- function(fit, pars, reduce = NULL,
combine = NULL, chain = "all", ...) {
UseMethod("extract_quantity", fit)
}
#' @keywords internal
#' @inherit extract_quantity
extract_quantity.Optimization <- function(fit, pars, reduce = NULL,
combine = NULL, chain = "all", ...) {
reduce <- NULL # Can't reduce in-chain cause there are not iterations
ind <- do.call(c, lapply(unique(pars), function(par) {
grep(
pattern = glob2rx(sprintf("%s*", par)),
x = names(fit$par)
)})
)
xs <- fit$par[ind]
l <- sapply(xs, function(x) {
drop(if (is.null(reduce)) { x } else { reduce(x) })
}, simplify = FALSE, USE.NAMES = TRUE)
if (is.null(combine)) { l } else { drop(do.call(combine, l)) }
}
#' @keywords internal
#' @inherit extract_quantity
extract_quantity.stanfit <- function(fit, pars, reduce = NULL,
combine = NULL, chain = "all", ...) {
ext <- function(p) {
# extract and set dimensions: x[iteration, chain, parDims ...]
x <- rstan::extract(fit, pars = p, permuted = FALSE, ...)
parDims <- if (is.empty(fit@par_dims[[p]])) { 1 } else { fit@par_dims[[p]] }
dim(x) <- c(dim(x)[1:2], parDims)
# reduce but keep dimensions
if (!is.null(reduce)) {
oDim <- dim(x)
x <- apply(x, seq.int(2, length(oDim)), reduce)
dim(x) <- replace(oDim, 1, length(x) / prod(oDim[-1]))
}
# subset/merge but keep dimensions
if (chain == "all")
invisible({})
if (chain %in% seq_len(extract_n_chains(fit))) {
oDim <- dim(x)
x <- x[slice.index(x, 2) == chain]
dim(x) <- replace(oDim, 2, 1)
}
if (chain == "merge")
warning("extract_quantity.stanfit: Merging chains not yet implemented.")
return(drop(x))
}
pars <- unlist(
lapply(unique(pars), function(p) {
grep(pattern = glob2rx(p), extract_parameter_names(fit), value = TRUE)
})
)
l <- sapply(pars, ext, simplify = FALSE, USE.NAMES = TRUE)
if (is.null(combine))
return(l)
drop(do.call(combine, l))
}
# extract_parameter_names -------------------------------------------------
#' Extract the names of all the model parameters in the fit object.
#'
#' @param fit An object returned by either \code{\link{draw_samples}} or \code{\link{optimizing}}.
#' @return A character vector with the selected model parameter names.
#' @seealso See \code{\link{select_parameters}} for extracting the names of part of the model.
#' @keywords internal
extract_parameter_names <- function(fit) {
UseMethod("extract_parameter_names", fit)
}
#' @keywords internal
#' @inherit extract_parameter_names
extract_parameter_names.Optimization <- function(fit) {
names(fit$par)
}
#' @keywords internal
#' @inherit extract_parameter_names
extract_parameter_names.stanfit <- function(fit) {
fit@model_pars
}
# extract_date ------------------------------------------------------------
#' Extract the date when the model was run.
#'
#' @param fit An object returned by either \code{\link{draw_samples}} or \code{\link{optimizing}}.
#' @return An integer with the date used to fit the model.
extract_date <- function(fit) {
UseMethod("extract_date", fit)
}
#' @keywords internal
#' @inherit extract_date
extract_date.Optimization <- function(fit) {
attr(fit, "date")
}
#' @keywords internal
#' @inherit extract_date
extract_date.stanfit <- function(fit) {
strptime(fit@date, "%a %b %d %H:%M:%S %Y")
}
# extract_time ------------------------------------------------------------
#' Extract the time elapsed when fitting the model.
#'
#' @param fit An object returned by either \code{\link{draw_samples}} or \code{\link{optimizing}}.
#' @return For objects fit via \code{\link{draw_samples}}, a named numeric matrix with two columns (warm-up and sample time) and one row per chain. For objects fit via \code{\link{optimizing}}, the system time elapsed.
extract_time <- function(fit) {
UseMethod("extract_time", fit)
}
#' @keywords internal
#' @inherit extract_time
extract_time.Optimization <- function(fit) {
attr(fit, "systemTime")
}
#' @keywords internal
#' @inherit extract_time
extract_time.stanfit <- function(fit) {
rstan::get_elapsed_time(fit)
}
# extract_seed ------------------------------------------------------------
#' Extract the seed used to fit the model.
#'
#' @param fit An object returned by either \code{\link{draw_samples}} or \code{\link{optimizing}}.
#' @return An integer with the seed used to fit the model.
extract_seed <- function(fit) {
UseMethod("extract_seed", fit)
}
#' @keywords internal
#' @inherit extract_seed
extract_seed.Optimization <- function(fit) {
attr(fit, "seed")
}
#' @keywords internal
#' @inherit extract_seed
extract_seed.stanfit <- function(fit) {
rstan::get_seed(fit)
}
# extract_stanmodel -------------------------------------------------------
#' Extract the stanmodel object of the fitted object.
#'
#' @param fit An object returned by either \code{\link{draw_samples}} or \code{\link{optimizing}}.
#' @return An integer with the stanmodel used to fit the model.
extract_stanmodel <- function(fit) {
UseMethod("extract_stanmodel", fit)
}
#' @keywords internal
#' @inherit extract_stanmodel
extract_stanmodel.Optimization <- function(fit) {
attr(fit, "stanmodel")
}
#' @keywords internal
#' @inherit extract_stanmodel
extract_stanmodel.stanfit <- function(fit) {
rstan::get_stanmodel(fit)
}
#' @keywords internal
#' @inherit extract_stanmodel
extract_stanmodel.stanmodel <- function(fit) {
fit
}
# classify_quantity -------------------------------------------------------
#' Classify observations based on latent state probabilities.
#'
#' Assign the hidden states at each time step \emph{t} to the hidden state \emph{k} with largest quantity of interest.
#'
#' @name classify_quantity
#' @param fit An object returned by either \code{\link{draw_samples}} or \code{\link{optimizing}}.
#' @param reduce An optional function applied to the samples corresponding to one time step \emph{t}, one hidden state \emph{k}, and one chain \emph{m}. The observation at time step \emph{t} is then assigned to the hidden state with largest value. Note that the user needs to supply a function as an argument, and not a character string with the name of the function. This argument is not used for maximum a posteriori estimates returned by \code{\link{optimizing}} since there is only one scalar per quantity. It defaults to the \code{\link{mean}} function.
#' @param chain Either "all" or any integer number between 1 and the number of chains M. In the latter case, only the samples generated by the selected chain are considered. This argument is not used for maximum a posteriori estimates returned by \code{\link{optimizing}} since there is only one result. It defaults to "all".
#' @param quantity A character string with the name of the parameter to be classified (most likely a probability such as "alpha" or "gamma"). Note that no every estimated parameter has the structure needed for classification.
#' @return A numeric vector with size equal to the time series length \emph{T} with values from 1 to the number of hidden states \emph{K}.
#' @keywords internal
classify_quantity <- function(fit, reduce, chain, quantity) {
f <- match.fun(paste0("extract_", quantity))
q <- f(fit, reduce = reduce, chain = chain)
dimLength <- length(dim(q))
if (dimLength < 2) {
stop("The dimension of the quantity is not enough for me to classify.")
} else if (length(dim(q)) == 2) {
return(apply(q, 2, which.max))
} else {
return(
apply(q, 1, function(q) {
apply(q, 2, which.max)
})
)
}
}
# classify_alpha ----------------------------------------------------------
#' Classify observations based on filtered probabilities.
#'
#' This function assigns the hidden states at each time step \emph{t} to the hidden state \emph{k} with largest estimated filtered probability (\emph{alpha}).
#' @inherit classify_quantity
classify_alpha <- function(fit, reduce = mean, chain = "all") {
UseMethod("classify_alpha", fit)
}
#' @keywords internal
#' @inherit classify_alpha
classify_alpha.Optimization <- function(fit, reduce = mean, chain = "all") {
apply(extract_alpha(fit), 2, which.max)
}
#' @keywords internal
#' @inherit classify_alpha
classify_alpha.stanfit <- function(fit, reduce = mean, chain = "all") {
classify_quantity(fit, reduce, chain, "alpha")
}
# classify_gamma ----------------------------------------------------------
#' Classify observations based on smoothed probabilities.
#'
#' This function assigns the hidden states at each time step \emph{t} to the hidden state \emph{k} with largest estimated smoothed probability (\emph{gamma}).
#' @inherit classify_quantity
classify_gamma <- function(fit, reduce = mean, chain = "all") {
UseMethod("classify_gamma", fit)
}
#' @keywords internal
#' @inherit classify_gamma
classify_gamma.Optimization <- function(fit, reduce = mean, chain = "all") {
apply(extract_gamma(fit), 2, which.max)
}
#' @keywords internal
#' @inherit classify_gamma
classify_gamma.stanfit <- function(fit, reduce = mean, chain = "all") {
classify_quantity(fit, reduce, chain, "gamma")
}
# classify_zstar ----------------------------------------------------------
#' Assign the hidden states to the most likely path (\emph{zstar}).
#'
#' This is the result of Viterbi algorithm, which considers the joint distribution of the states.
#' @inherit classify_quantity
#' @param reduce An optional function applied to the samples corresponding to one time step \emph{t}, one hidden state \emph{k}, and one chain \emph{m}. The observation at time step \emph{t} is then assigned to the hidden state with largest value. Note that the user needs to supply a function as an argument, and not a character string with the name of the function. This argument is not used for maximum a posteriori estimates returned by \code{\link{optimizing}} since there is only one scalar per quantity. It defaults to the \code{\link{posterior_mode}} function.
classify_zstar <- function(fit, reduce = posterior_mode, chain = "all") {
UseMethod("classify_zstar", fit)
}
#' @keywords internal
#' @inherit classify_zstar
classify_zstar.Optimization <- function(fit, reduce = posterior_mode, chain = "all") {
extract_zstar(fit)
}
#' @keywords internal
#' @inherit classify_zstar
classify_zstar.stanfit <- function(fit, reduce = posterior_mode, chain = "all") {
extract_zstar(fit, reduce = reduce, chain = chain)
}