knitr::opts_chunk$set(collapse = TRUE, comment = "#>")
set.seed(1)
library(flexsynth)

n_pat <- 120
base <- data.frame(
  id  = seq_len(n_pat),
  age = round(rnorm(n_pat, 60, 10)),
  sex = sample(c("F", "M"), n_pat, replace = TRUE)
)
n_visits <- 1 + rpois(n_pat, 2)                 # unequal length units

rows <- lapply(seq_len(n_pat), function(i) {
  k <- n_visits[i]
  sbp <- numeric(k)
  sbp[1] <- 0.6 * base$age[i] + rnorm(1, 95, 8)
  for (t in seq_len(k)[-1]) sbp[t] <- 0.8 * sbp[t - 1] + rnorm(1, 26, 6)
  data.frame(id = base$id[i], visit = seq_len(k),
             age = base$age[i], sex = base$sex[i],
             sbp = round(sbp))
})
real <- do.call(rbind, rows)
head(real, 8)

res <- synth(real, structure = ~ id / visit, seed = 1)
res

syn <- as.data.frame(res)

# unequal-length units are reproduced, not fixed-width
table(table(syn$id))

# baseline stays constant within each synthetic patient
all(tapply(syn$age, syn$id, function(a) length(unique(a)) == 1))

res_c <- synth(
  real, ~ id / visit,
  constraints = list(
    rule(sbp >= 60 & sbp <= 260),                       # row scope (default)
    rule(all(diff(visit) == 1), scope = "unit")         # consecutive visits
  ),
  seed = 1
)
syn_c <- as.data.frame(res_c)

# every synthetic unit's visits are 1, 2, 3, ...
all(tapply(syn_c$visit, syn_c$id,
           function(v) identical(v, seq_along(v))))

diagnose(real, res, vars = c("age", "sex", "sbp"))

