## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment  = "#>",
  fig.width = 7,
  fig.height = 4,
  dpi = 96
)

## ----setup--------------------------------------------------------------------
library(coresynth)

## ----dgp----------------------------------------------------------------------
set.seed(42)
N <- 10; TT <- 20; T_pre <- 10
f   <- cumsum(rnorm(TT, 0, 0.5))     # common factor
lam <- rnorm(N, 1, 0.3)              # unit loadings
dat <- expand.grid(time = seq_len(TT), id = paste0("u", seq_len(N)))
dat$y <- as.vector(outer(f, lam)) + rnorm(nrow(dat), 0, 0.3)
dat$d <- as.integer(dat$id == "u1" & dat$time > T_pre)
dat$y[dat$d == 1] <- dat$y[dat$d == 1] + 2.0   # inject the treatment effect

head(dat)

## ----fit-one------------------------------------------------------------------
fit <- scm_fit(y ~ d | id + time, data = dat, method = "scm")
fit

## ----estimate-----------------------------------------------------------------
fit$estimate

## ----compare------------------------------------------------------------------
methods <- c("scm", "sdid", "gsc", "mc", "tasc", "si")
fits    <- lapply(methods, function(m) scm_fit(y ~ d | id + time, data = dat, method = m))
names(fits) <- methods

data.frame(
  method   = methods,
  estimate = round(sapply(fits, `[[`, "estimate"), 3)
)

## ----plot-trend---------------------------------------------------------------
plot(fits$sdid, type = "trend")   # observed vs. synthetic

## ----plot-gap-----------------------------------------------------------------
plot(fits$scm, type = "gap")      # treatment effect over time

## ----plot-weights-------------------------------------------------------------
plot(fits$scm, type = "weights")  # donor weights

## ----broom--------------------------------------------------------------------
library(broom)

tidy(fits$scm)     # donor weights as a data frame
glance(fits$scm)   # one-row model summary

## ----export, eval = FALSE-----------------------------------------------------
# export_json(fits$scm, file = "scm_result.json")

