---
title: "DINA_HO_RT_sep"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{DINA_HO_RT_sep}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
```

```{r setup}
library(hmcdm)
```

### Load the spatial rotation data

```{r}
N = length(Test_versions)
J = nrow(Q_matrix)
K = ncol(Q_matrix)
L = nrow(Test_order)
```


## (1) Simulate responses and response times based on the HMDCM model with response times (no covariance between speed and learning ability)

```{r}
class_0 <- sample(1:2^K, N, replace = L)
Alphas_0 <- matrix(0,N,K)
for(i in 1:N){
  Alphas_0[i,] <- inv_bijectionvector(K,(class_0[i]-1))
}
thetas_true = rnorm(N,0,1)
tausd_true=0.5
taus_true = rnorm(N,0,tausd_true)
G_version = 3
phi_true = 0.8
lambdas_true <- c(-2, 1.6, .4, .055)       # empirical from Wang 2017
Alphas <- sim_alphas(model="HO_sep", 
                    lambdas=lambdas_true, 
                    thetas=thetas_true, 
                    Q_matrix=Q_matrix, 
                    Design_array=Design_array)
table(rowSums(Alphas[,,5]) - rowSums(Alphas[,,1])) # used to see how much transition has taken place
itempars_true <- matrix(runif(J*2,.1,.2), ncol=2)
RT_itempars_true <- matrix(NA, nrow=J, ncol=2)
RT_itempars_true[,2] <- rnorm(J,3.45,.5)
RT_itempars_true[,1] <- runif(J,1.5,2)

Y_sim <- sim_hmcdm(model="DINA",Alphas,Q_matrix,Design_array,
                   itempars=itempars_true)
L_sim <- sim_RT(Alphas,Q_matrix,Design_array,RT_itempars_true,taus_true,phi_true,G_version)
```


## (2) Run the MCMC to sample parameters from the posterior distribution

```{r}
output_HMDCM_RT_sep = hmcdm(Y_sim,Q_matrix,"DINA_HO_RT_sep",Design_array,
                            100, 30,
                            Latency_array = L_sim, G_version = G_version,
                            theta_propose = 2,deltas_propose = c(.45,.35,.25,.06))
output_HMDCM_RT_sep
summary(output_HMDCM_RT_sep)
a <- summary(output_HMDCM_RT_sep)
head(a$ss_EAP)

```



## (3) Check for parameter estimation accuracy

```{r}
(cor_thetas <- cor(thetas_true,a$thetas_EAP))
(cor_taus <- cor(taus_true,a$response_times_coefficients$taus_EAP))

(cor_ss <- cor(as.vector(itempars_true[,1]),a$ss_EAP))
(cor_gs <- cor(as.vector(itempars_true[,2]),a$gs_EAP))

AAR_vec <- numeric(L)
for(t in 1:L){
  AAR_vec[t] <- mean(Alphas[,,t]==a$Alphas_est[,,t])
}
AAR_vec

PAR_vec <- numeric(L)
for(t in 1:L){
  PAR_vec[t] <- mean(rowSums((Alphas[,,t]-a$Alphas_est[,,t])^2)==0)
}
PAR_vec
```


## (4) Evaluate the fit of the model to the observed response and response times data (here, Y_sim and R_sim)

```{r}
a$DIC
head(a$PPP_total_scores)
head(a$PPP_item_means)
head(a$PPP_item_ORs)
library(bayesplot)
pp_check(output_HMDCM_RT_sep, type="total_latency")
```

