-
Notifications
You must be signed in to change notification settings - Fork 0
/
spbp.R
349 lines (302 loc) · 11.1 KB
/
spbp.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
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
#' Semiparametric Survival Analysis Using Bernstein Polynomial
#'
#' Fits Bernstein Polynomial based Proportional regression to survival data.
#'
#' @title spbp: The BP Based Survival Analysis Function
#' @param formula a Surv object with time to event, status and explanatory terms.
#' @param ... Arguments passed to `rstan::sampling` (e.g. iter, chains) or `rstan::optimizing`.
#' @seealso \code{\link[spsurv]{spbp.default}}
#' @examples
#'
#' library("spsurv")
#' data("veteran") ## imports from survival package
#'
#' fit_mle <- spbp(Surv(time, status) ~ karno + factor(celltype),
#' data = veteran, model = "po")
#' summary(fit_mle)
#'
#' fit_bayes <- spbp(Surv(time, status) ~ karno + factor(celltype),
#' data = veteran, model = "po", approach = "bayes",
#' cores = 1, iter = 300, chains = 1,
#' priors = list(beta = c("normal(0,4)"),
#' gamma = "lognormal(0,4)"))
#'
#' summary(fit_bayes)
#'
#' @rdname spbp
#' @export spbp
#' @seealso \code{\link[spsurv]{spbp.default}}, \code{\link[spsurv]{bpph}}, \code{\link[spsurv]{bppo}}, \code{\link[spsurv]{bpaft}}, \url{https://mc-stan.org/users/documentation/}
#' @return An object of class 'spbp'.
spbp <- function(formula, ...) {
UseMethod("spbp", formula)
}
#' @title spbp: The BP Based Semiparametric Survival Analysis Function
#' @param formula a Surv object with time to event, status and explanatory terms
#' @param degree Bernstein Polynomial degree
#' @param data a data.frame object
#' @param approach Bayesian or Maximum Likelihood estimation methods, default is approach = "bayes"
#' @param model Proportional Hazards or Proportional Odds BP based regression, default is model = "ph"
#' @param priors prior settings for the Bayesian approach; `normal` or `cauchy` for beta; `gamma`, `inv_gamma` or `lognormal` for gamma (BP coefficients)
#' @param scale logical; indicates whether to center and scale the data
#' @param ... further arguments passed to or from other methods
#' @param cores number of core threads to use
#' @return An object of class \code{spbp}
#' @method spbp default
#' @export
#' @importFrom rstan stan sampling optimizing
#' @importFrom survival Surv frailty
#' @importFrom MASS ginv
#' @importFrom loo waic loo
#' @importFrom coda HPDinterval
#' @importFrom stats .getXlevels as.formula contrasts dbeta density dist formula median model.extract pbeta pchisq printCoefmat qnorm rlogis rnorm rweibull sd terms
#'
spbp.default <-
function(formula, degree, data,
approach = c("mle", "bayes"),
model = c("ph", "po", "aft"),
priors = list(beta = c("normal(0,4)"),
gamma = "lognormal(0,10)"),
scale = TRUE, cores = parallel::detectCores(),
...){
# ---------------Definitions + error handling ---------------
## tau degree
if(missing(degree)){
degree <- ceiling(sqrt(nrow(data)))
}
## Call
Call <- match.call();
## model
if(length(model) == 3){model_flag = "ph"}
else{model_flag <- model}
model <- ifelse(match.arg(model) == "po", 0,
ifelse(match.arg(model) == "ph", 1, 2))
## approach
approach_flag <- match.arg(approach) ### saves string input
approach <- ifelse(approach_flag == "mle", 0, 1)
## error-handling nº1
handler1()
## terms
temp <- Call[c(1, aux)] # keep important args
temp[[1L]] <- quote(stats::model.frame) # model frame call
special <- c("frailty", "frailty.gamma", "frailty.gaussian", "frailty.t")
temp$formula <- terms(formula, special, data = data)
temp$formula <- terms(formula, data = data);
## error-handling nº2 -- Frailty (id, distribution, column)
handler2()
## error-handling nº3 -- Priors
handler3()
stanArgs <- list(...)
## error-handling nº4 -- stanArgs
handler4()
mf <- eval(temp, parent.frame())
Terms <- terms(mf)
Y <- model.extract(mf, "response") # time-to-event response
type <- attr(Y, "type")
## error-handling nº5 -- Model Frame
handler5()
# --------------- Data declaration + definitions ---------------
## + sample size + labels
data.n <- nrow(Y)
labels <- attributes(temp$formula)$term.labels
null <- 0
if (length(labels) > 1){
X <- model.matrix(Terms, mf)[, -1]
}
else if(length(labels) == 1){
X <- as.matrix(model.matrix(Terms, mf)[, -1], ncol = data.n)
colnames(X) <- labels
}
else{
X <- as.matrix(rep(0, data.n), ncol = data.n)
colnames(X) <- "non-parametric"
null <- 1
}
## time + status + features
features <- X
attr(X, "assign") <- attr(model.matrix(Terms, mf), "assign")[-1]
attr(X, "contrasts") <- attr(model.matrix(Terms, mf), "contrasts")
xlevels <- .getXlevels(Terms, mf)
contrasts <- attr(X, "contrasts")
assign <- attrassign(X, Terms)
q <- ncol(X)
time <- as.vector(Y[,1])
tau <- max(time)
status <- as.vector(Y[,2])
if(scale == T){
X <- scale(X)
## rescaled coefficients (correction)
means <- array(attr(X, "scaled:center"), dim = q)
std <- array(attr(X, "scaled:scale"), dim = q)
}
else{
std <- array(1, dim = q)
means <- array(0, dim = q)
}
## base calculations
base <- bp.basis(time, degree = degree, tau = tau)
## priors to num
priordist <- sapply(priordist,
function(x){
switch(x,
"normal" = 0,
"gamma" = 1,
"inv_gamma" = 2,
"lognormal" = 3)})
priordist_beta <- sapply(priordist_beta,
function(x){switch(x,
"normal" = 0,
"cauchy" = 1)})
## Recycling the prior specs
priordist_beta <- array(priordist_beta, dim = q)
location_beta <- array(as.numeric(location_beta), dim = q)
scale_beta <- array(as.numeric(scale_beta), dim = q)
## standata
standata <- list(time = time,
tau = tau,
n = data.n,
m = base$degree,
q = q,
status = status,
X = X,
B = base$B,
b = base$b,
approach = approach,
M = model,
null = null,
id = rep(1, data.n),
dist = dist,
z = rep(0, data.n),
priordist = priordist,
priorpars = priorpars,
priordist_beta = priordist_beta,
location_beta = location_beta,
scale_beta = scale_beta,
std = std,
means = means
)
# --------------- Fit ---------------
if(approach == 0){
tryCatch(expr = spbp.mle(standata = standata, ...),
error = function(e){warning(e); return(NaN)})
}
else{
tryCatch(expr = spbp.bayes(standata = standata, ...),
error = function(e){warning(e); return(NaN)})
}
}
spbp.mle <-
function(standata,
init = 0,
hessian = TRUE,
verbose = FALSE,
...){
e <- parent.frame()
#variable names in parent frame
vnames <- objects(, envir = e)
# "sourcing" the parent.frame
for(n in vnames) assign(n, get(n, e))
if(!is.null(frailty_idx)){
standata$X <- X[, -frailty_idx]
message("Frailty ignored, change approach to `bayes` for frailty estimation.")
}
stanfit <-
rstan::optimizing(stanmodels$spbp,
data = standata,
init = init,
hessian = hessian,
verbose = verbose,
...)
len <- length(stanfit$par)
## stanfit coefficients (beta, nu)
aux <- stanfit$par
coef <- aux[names(aux) %in% c(paste0("beta[", 1:q, "]"), paste0("gamma[", 1:degree, "]"))]
## regression estimates
beta <- array(coef[1:q], q)
gamma_std <- aux[names(aux) %in% paste0("gamma_std[", 1:degree, "]")]
## rescaled hessian matrix
info <- - stanfit$hessian
names(beta) <- colnames(X)
names(coef) <- c(names(beta),
paste0("gamma", 1:(degree))
)
## rescaled fisher info
jac <- diag(1/std, q)
var <- jac %*% blockSolve(info, q)[1:q, 1:q] %*% t(jac)
rownames(var) <- names(beta)
colnames(var) <- names(beta)
if(hessian == FALSE || null == 1){
stanfit$hessian <- matrix(rep(NA, q^2),
ncol = 1:q,
nrow = 1:q)
}
nulldata <- standata
nulldata$null <- 1
nullfit <- rstan::optimizing(stanmodels$spbp,
data = nulldata,
init = init,
hessian = hessian,
...)
output <- list(coefficients = coef,
var = var[1:q, 1:q],
loglik = c(nullfit$value, stanfit$value),
linear.predictors = c(features %*% beta),
means = colMeans(features),
method = "optimizing",
n = data.n,
nevent = sum(status),
q = q,
terms = Terms,
assign = assign,
wald.test = coxph.wtest(var[1:q, 1:q], beta)$test,
y = Y,
formula = formula,
xlevels = xlevels,
contrasts = contrasts,
return_code = stanfit$return_code,
tau = tau,
call = Call)
output$call$approach <- approach_flag
output$call$model <- model_flag
class(output) <- "spbp"
message('Priors are ignored due to mle approach.')
return(output)
}
spbp.bayes <- function(standata,
hessian = TRUE,
verbose = FALSE,
chains = 1,
...){
e <- parent.frame()
#variable names in parent frame
vnames <- objects(, envir = e)
# "sourcing" the parent.frame
for(n in vnames) assign(n, get(n, e))
# bayes
output <- list(y = Y)
if(dist == 0){
output$stanfit <- rstan::sampling(stanmodels$spbp,
data = standata,
verbose = verbose,
chains = chains, cores = cores,
...)
samp <- rstan::extract(output$stanfit, pars = c("beta", "gamma"))
output$pmode <- apply(X = cbind(samp[[1]], samp[[2]]), MARGIN = 2, FUN = mode)
# output$pmode <- apply(X = samp, MARGIN = 2, FUN = mode)
}
else{
standata$X <- X[, -frailty_idx]
output$stanfit <- rstan::sampling(stanmodels$spbp_frailty,
data = standata,
verbose = verbose,
chains = chains,
...)
output$pmode <- apply(rstan::extract(output$stanfit, c("beta", "gamma")), 2, mode)
}
output$loo <- loo::loo(loo::extract_log_lik(output$stanfit), cores = cores)
output$waic <- loo::waic(loo::extract_log_lik(output$stanfit), cores = cores)
output$call <- Call
output$call$approach <- approach_flag
output$call$model <- model_flag
class(output) <- "spbp"
return(output)
}