---
title: "Advanced workflow: dependence, evidence, agreement and ordinal outcomes"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Advanced workflow: dependence, evidence, agreement and ordinal outcomes}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

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

## Correlated continuous changes

Let $D_i=(D_{i1},D_{i2})^T$ be independent between subjects with a bivariate Gaussian distribution, mean $\mu=(\beta,\beta+\gamma)^T$ and covariance $\Sigma$. Raters within subjects need not be independent. The four models restrict $\Sigma$ to a common independent variance (M0), unequal independent variances (M1), a common variance with correlation (M2), or an unrestricted positive-definite covariance (M3).

```{r data}
S <- matrix(c(1, 0.65, 0.65, 1.5), 2)
scenario <- bivariate_scenario(N = 12, beta = 0.6, gamma = 0.2,
                               covariance = S)
dat <- simulate_bivariate(scenario, seed = 22, format = "long")
head(dat, 8)
fit_model_id <- function(model) {
  fit_bivariate(dat, id, time, rater, y, model = model,
                time_order = c("pre", "post"),
                rater_order = c("r1", "r2"))
}
f3 <- fit_model_id("M3")
f3$sample_cov
```

The simulated baseline is zero by construction because the target is paired change. It is not a simulation of four raw scores with realistic baseline structure.

## Posterior inference and the role of priors

Reference priors are improper: flat on the mean vector and proportional to the inverse free variance(s) in M0–M2, or $|\Sigma|^{-3/2}$ in M3. They are model-specific choices and are not universally optimal. M3 requires positive-definite scatter and at least three subjects. A Student distribution can exist without a finite posterior mean or variance.

```{r reference}
ref <- posterior_bivariate(f3, prior = "reference")
contrast_bivariate(ref, "reference")
contrast_bivariate(ref, "discrepancy")
```

Proper priors permit regularisation and evidence. The following settings are hypothetical prior judgements on the units of the artificial data, not recommended defaults. `kappa` is relative mean precision and `shape` controls variance concentration. The covariance argument is the prior expected covariance. Choose these quantities before inspecting the outcomes when evidence is the goal. The same prior location and covariance expectation do not imply identical prior laws across covariance models.

```{r prior}
prior <- bivariate_prior(location = c(0, 0), kappa = 0.5,
                         shape = 3, covariance = diag(2))
post <- posterior_bivariate(f3, prior)
contrast_bivariate(post, "reference", threshold = 0.3)
contrast_bivariate(post, "average", rope = c(-0.2, 0.2))
contrast_bivariate(post, "weighted", weight = 0.25)
contrast_bivariate(post, "discrepancy", target = "predictive")
```

`weight` is the second-rater weight. The posterior contrast concerns a population mean; the predictive contrast concerns a new subject. They answer different questions. Under M0 and M3, contrasts have univariate Student distributions. M1 and M2 can require convolution of independent Student components. `draw_bivariate()` provides independent joint posterior draws, useful for functions of parameters not covered by the analytical contrast interface.

```{r draw}
head(draw_bivariate(post, n_draws = 1000, seed = 23, predictive = TRUE))
```

## Evidence and sensitivity

```{r evidence}
bayesfactor_bivariate(post, "reference", null = 0)
bayesfactor_bivariate(post, "discrepancy", null = 0)
bayesfactor_bivariate(post, "discrepancy", hypothesis = "interval",
                      bounds = c(-0.2, 0.2))
prior_wide <- bivariate_prior(c(0, 0), kappa = 0.1,
                             shape = 3, covariance = 2 * diag(2))
sensitivity_bivariate(f3, list(initial = prior, wider = prior_wide),
                      contrast = "reference", null = 0)
```

BF10 is evidence for H1 relative to H0. For a point null, the nuisance prior under H0 is the conditional prior induced by the encompassing prior; changing this definition changes the BF. Directional and interval hypotheses use posterior odds divided by prior odds. The interval hypothesis above treats practical equivalence as H1. The reference prior cannot be used for ordinary marginal likelihoods or these Bayes factors.

```{r covariance-comparison}
models <- c("M0", "M1", "M2", "M3")
posts <- lapply(models, function(m) posterior_bivariate(fit_model_id(m), prior))
compare_bivariate(posts, reference = "M0",
                  model_prior = c(M0 = 1, M1 = 1, M2 = 1, M3 = 1))
```

Equal model weights here are illustrative. Evidence depends on model-specific prior distributions. Do not select a covariance structure solely on a BF or a non-significant test of correlation; consider substantive plausibility and sensitivity.

## Agreement on change

Let $A_i=D_{i2}-D_{i1}$. Its population mean is $\gamma$, and variance is $\Sigma_{11}+\Sigma_{22}-2\Sigma_{12}$. A zero mean can coexist with substantial individual disagreement.

```{r agreement}
ag <- agreement_bivariate(post, margin = 0.5, min_coverage = 0.8,
                          n_draws = 2000, seed = 24)
print(ag)
ag$practical
```

The margin of 0.5 is illustrative. Mean equivalence is $P(|\gamma|\leq 0.5\mid data)$. Individual predictive agreement is $P(|A_{new}|\leq 0.5\mid data)$. A population-level criterion instead concerns the posterior probability that conditional population coverage exceeds 0.8. Population limits of agreement, uncertainty intervals for those limits, and predictive intervals are distinct. These summaries concern observed change and do not separate true change from measurement error.

## Compare methods on the same simulated data

```{r simulation}
methods <- list(legacy = "legacy", paired_t = "paired_t",
                exact_M0 = list(model = "M0", prior = "reference"),
                exact_M3 = list(model = "M3", prior = "reference"),
                proper_M3 = list(model = "M3", prior = prior))
val <- validate_bivariate(scenario, methods, contrast = "reference",
                          R = 20, n_draws = 1000, seed = 25)
subset(summarise_validation(val), metric %in% c("bias", "rmse", "coverage"))
compare_validation(val, "exact_M3", "legacy", metric = "mse")
```

The paired-t benchmark applies a one-sample Student interval to the subject-level contrast. M0 exact versus legacy isolates the normal approximation under M0; M3 addresses dependence and heterogeneity. The number of repetitions above is a demonstration only. Report failure rates, the number of usable repetitions and MCSE alongside coverage and error. Bias and coverage depend on the specified generative mechanism and cannot validate a particular empirical effect.

```{r calibrated}
empirical <- scenario_from_fit(f3)
empirical$location
empirical$covariance
heavy <- bivariate_scenario(12, 0.6, 0.2, S,
                            distribution = "student", df = 5)
scenario_truth(heavy, "discrepancy", margin = 0.5)
```

Empirical calibration uses the observed means and unrestricted sample covariance; the fitted values are treated as fixed. Explicit ridge regularisation changes the target covariance. The Student mechanism uses the actual covariance, not the scale matrix. A scientific evaluation should vary sample size, effect, covariance, tails and prior specification (ADEMP; Morris et al., 2019). For a specified proper prior, SBC evaluates prior-predictive rank behaviour, not fixed-parameter coverage or model adequacy.

```{r sbc}
sbc <- sbc_bivariate(N = 8, model = "M3", prior = prior,
                     contrast = "reference", R = 20,
                     n_draws = 100, bins = 5, seed = 26)
names(sbc)
```

Twenty repetitions cannot support a calibration conclusion; use substantially larger studies for that purpose.

## Ordinal outcomes

The cumulative probit model assumes $Z_{itj}=\alpha+\delta I(j=2)+\beta I(t=post)+\gamma I(t=post,j=2)+b_{it}+e_{itj}$, with bivariate Gaussian occasion effects $(b_{i,pre}, b_{i,post})$ and independent standard normal residuals. Observed categories are defined by common ordered thresholds; the first threshold is zero and residual variance is fixed to one. The covariance of the occasion effects does not allow every possible residual dependence structure. Threshold invariance is an assumption, not a tested result. The latent effects are not numeric rating-score changes.

```{r ordinal-data}
ord <- simulate_ordinal(N = 20, coefficients = c(-0.3, 0.1, 0.5, 0.2),
                        random_covariance = matrix(c(0.5, 0.2, 0.2, 0.6), 2),
                        cutpoints = c(0, 1),
                        category_order = c("low", "middle", "high"), seed = 27)
op <- ordinal_prior(coefficient_mean = rep(0, 4), coefficient_sd = rep(1, 4),
                    random_df = 6, random_covariance = 0.5 * diag(2),
                    cutpoint_mean = 1, cutpoint_sd = 0.5)
```

The following code is executable, but is not run during vignette building to keep package checks tractable. It is not a claim that the example chains converge. Use model-wide and contrast-specific diagnostics; if they are inadequate, investigate the model and sampling before reporting estimates. Increasing draws alone may not resolve poor mixing.

```{r ordinal-fit, eval=FALSE}
of <- fit_ordinal(ord, id, time, rater, y,
                  category_order = c("low", "middle", "high"),
                  time_order = c("pre", "post"), rater_order = c("r1", "r2"),
                  prior = op, chains = 4, warmup = 1000, draws = 2000, seed = 28)
ordinal_diagnostics(of)
oc <- contrast_ordinal(of, "reference")
oc$diagnostics
if (all(ordinal_diagnostics(of)$adequate) && isTRUE(oc$diagnostics$adequate)) {
  print(oc)
  print(predict_ordinal(of))
}
```

The predictive summary integrates over subject occasion effects and describes marginal category probabilities and changes in cumulative exceedance. It does not identify individual transitions. For repeated-sampling evaluation use `validate_ordinal()` with specified generative parameters and proper priors, and report diagnostic failures as well as statistical performance.

## References

Albert, J. H., & Chib, S. (1993). Bayesian analysis of binary and polychotomous response data. *Journal of the American Statistical Association, 88*(422), 669–679. <https://doi.org/10.1080/01621459.1993.10476321>

Bland, J. M., & Altman, D. G. (1986). Statistical methods for assessing agreement between two methods of clinical measurement. *The Lancet, 327*(8476), 307–310. <https://doi.org/10.1016/S0140-6736(86)90837-8>

Morris, T. P., White, I. R., & Crowther, M. J. (2019). Using simulation studies to evaluate statistical methods. *Statistics in Medicine, 38*(11), 2074–2102. <https://doi.org/10.1002/sim.8086>

Talts, S., Betancourt, M., Simpson, D., Vehtari, A., & Gelman, A. (2018). *Validating Bayesian inference algorithms with simulation-based calibration*. arXiv. <https://arxiv.org/abs/1804.06788>

Vehtari, A., Gelman, A., Simpson, D., Carpenter, B., & Bürkner, P.-C. (2021). Rank-normalization, folding, and localization: An improved R-hat for assessing convergence of MCMC (with discussion). *Bayesian Analysis, 16*(2), 667–718. <https://doi.org/10.1214/20-BA1221>
