-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweibullPH_funs.R
66 lines (58 loc) · 1.8 KB
/
weibullPH_funs.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
# Weibull PH custom response distribution for brms
# Andrea Discacciati
# 2022-10-27
weibullPH <- brms::custom_family(
"weibullPH",
dpars = c("mu", "gamma"),
links = c("log", "log"),
lb = c(0, 0),
ub = c(NA, NA),
type = "real"
)
stan_funs_weibullPH <- "
real weibullPH_lpdf(real y, real mu, real gamma) {
real sigma;
sigma = mu^(-1/gamma);
return weibull_lpdf(y | gamma, sigma);
}
real weibullPH_lcdf(real y, real mu, real gamma) {
real sigma;
sigma = mu^(-1/gamma);
return weibull_lcdf(y | gamma, sigma);
}
real weibullPH_lccdf(real y, real mu, real gamma) {
real sigma;
sigma = mu^(-1/gamma);
return weibull_lccdf(y | gamma, sigma);
}"
stanvars_weibullPH <- brms::stanvar(scode = stan_funs_weibullPH,
block = "functions")
posterior_epred_weibullPH <- function(prep) { # expected survival
mu <- brms::get_dpar(prep, "mu")
gamma <- brms::get_dpar(prep, "gamma")
mu^(-1/gamma) * gamma(1 + 1/gamma)
}
log_lik_weibullPH <- function(i, prep) { # log-likelihood
mu <- brms::get_dpar(prep, "mu", i = i)
gamma <- brms::get_dpar(prep, "gamma", i = i)
sigma <- mu^(-1/gamma) # PH -> AFT
args <- list(shape = gamma, scale = sigma)
out <- brms:::log_lik_censor(
dist = "weibull", args = args, i = i, prep = prep
)
out <- brms:::log_lik_truncate(
out, cdf = pweibull, args = args, i = i, prep = prep
)
return(out)
}
posterior_predict_weibullPH <- function(i, prep, ntrys = 5, ...) { # posterior predictive distribution
mu <- brms::get_dpar(prep, "mu", i = i)
gamma <- brms::get_dpar(prep, "gamma", i = i)
sigma <- mu^(-1/gamma) # PH -> AFT
brms:::rcontinuous(
n = prep$ndraws, dist = "weibull",
shape = gamma, scale = sigma,
lb = prep$data$lb[i], ub = prep$data$ub[i],
ntrys = ntrys
)
}