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

n <- 300
real <- data.frame(
  id     = seq_len(n),
  age    = round(rnorm(n, 62, 11)),
  sex    = sample(c("F", "M"), n, replace = TRUE, prob = c(0.45, 0.55)),
  smoker = sample(c(FALSE, TRUE), n, replace = TRUE, prob = c(0.7, 0.3))
)
real$sbp <- round(0.6 * real$age + ifelse(real$smoker, 8, 0) + rnorm(n, 90, 10))
head(real)

res <- synth(real, structure = ~ id, seed = 1)
res
syn <- as.data.frame(res)
head(syn)

analysis_vars <- c("age", "sex", "smoker", "sbp")
d <- diagnose(real, res, vars = analysis_vars)
d

plot(d)

disclosure_risk(real, res, quasi = c("age", "sex", "smoker", "sbp"), seed = 1)

list_methods()

ctrl <- synth_control(method = c(sbp = "norm", age = "cart"))
res2 <- synth(real, ~ id, tuning = ctrl, seed = 1)

res3 <- synth(real, ~ id,
              constraints = rule(sbp >= 80 & sbp <= 220),
              seed = 1)
range(as.data.frame(res3)$sbp)

