Closed
Description
Consider the following model:
data{
int N;
vector[N] obs_times;
vector[N] t;
}
parameters{
real<lower=0> lambda;
}
model{
obs_times~exponential(lambda);
lambda~normal(0,5);
}
generated quantities{
//Draw survival function
vector[N] surv;
for(i in 1:N){
surv[i]=exp(-lambda*t[i]);
}
}
library(cmdstanr)
dat<-list(N=100,obs_times=data$x,t=seq(0,1.5,length=100))
mod<-cmdstan_model("surv_exp.stan")
fit<-mod$sample(data=dat,
chains=4,
parallel_chains=4)
If I convert the "cmdstanr" object to an "rstan" object and use extract() I can access the surv[i] objects in the following order.
library(rstan)
stanfit <- rstan::read_stan_csv(fit$output_files())
post<-extract(stanfit)
post$surv[1:2,]
iterations [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,] 1 0.960775 0.923088 0.886879 0.852091 0.818668 0.786555 0.755702 0.726060
[2,] 1 0.951013 0.904426 0.860121 0.817987 0.777916 0.739809 0.703568 0.669102
iterations [,10] [,11] [,12] [,13] [,14] [,15] [,16] [,17] [,18]
[1,] 0.697580 0.670217 0.643927 0.618669 0.594402 0.571086 0.548685 0.527163 0.506484
[2,] 0.636325 0.605154 0.575509 0.547317 0.520505 0.495008 0.470759 0.447698 0.425767
This does not seem to be possible using fit$draws(). The only solutions require using "posterior" and/or "tidybayes" (https://discourse.mc-stan.org/t/how-can-i-change-the-way-estimates-are-printed-by-fit-draws/26486)
> fit$draws("surv",format="list")
# A draws_list: 1000 iterations, 4 chains, and 100 variables
[chain = 1]
$`surv[1]`
[1] 1 1 1 1 1 1 1 1 1 1
$`surv[2]`
[1] 0.96 0.96 0.96 0.96 0.96 0.96 0.96 0.96 0.96 0.96
$`surv[3]`
[1] 0.92 0.92 0.93 0.93 0.91 0.92 0.92 0.92 0.92 0.92
$`surv[4]`
[1] 0.88 0.89 0.89 0.89 0.87 0.88 0.88 0.88 0.88 0.88
I think it would be useful to add this extract()-like feature to fit$draws().