## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)

## ----setup--------------------------------------------------------------------
library(seine)
data(elec_1968)

## -----------------------------------------------------------------------------
spec = ei_spec(
    elec_1968,
    predictors = vap_white:vap_other,
    outcome = pres_dem_hum:pres_abs,
    total = pres_total,
    covariates = c(state, pop_city:pop_rural, farm:educ_coll, inc_00_03k:inc_25_99k),
    preproc = function(x) {
        x = model.matrix(~ 0 + ., x) # convert factors to dummies
        bases::b_bart(x, trees = 200)
    }
)

m = ei_ridge(spec)

## -----------------------------------------------------------------------------
bounds = ei_bounds(spec, bounds = c(0, 1))
head(bounds)

## -----------------------------------------------------------------------------
ei_bounds(spec, bounds = c(0, 1), global = TRUE)

## -----------------------------------------------------------------------------
dim(as.array(bounds))

## -----------------------------------------------------------------------------
ei_bounds(spec, bounds = c(0, 1), contrast = list(predictor = c(1, -1, 0)))

## -----------------------------------------------------------------------------
b_cov = ei_local_cov(m, spec)
round(sqrt(diag(b_cov)), 3)
round(b_cov[1:3, 1:3], 3)

## ----fig.height=7.5, fig.alt = "Heatmap of the estimated correlation structure for local estimands"----
heatmap(
    cov2cor(b_cov),
    Rowv = NA,
    col = hcl.colors(n = 100, palette = "Spectral"),
    symm = TRUE,
    mar = c(12, 12)
)

## -----------------------------------------------------------------------------
e_rcov = ei_est_local(m, spec, b_cov = b_cov, bounds = c(0, 1), sum_one = TRUE)
e_orth = ei_est_local(m, spec, b_cov = 0,     bounds = c(0, 1), sum_one = TRUE)
e_nbhd = ei_est_local(m, spec, b_cov = 0.95,  bounds = c(0, 1), sum_one = TRUE)

c(
    estimated = mean(e_rcov$conf.high - e_rcov$conf.low),
    orthogonal = mean(e_orth$conf.high - e_orth$conf.low),
    neighborhood = mean(e_nbhd$conf.high - e_nbhd$conf.low)
)

## ----fig.alt="Histogram of local estimates for White support for Humphrey"----
hist(
    subset(e_rcov, predictor == "vap_white" & outcome == "pres_dem_hum")$estimate,
    breaks = 50,
    main = "White support for Humphrey",
    xlab = "% Humphrey"
)

## -----------------------------------------------------------------------------
subset(e_rcov, .row == 1)

## -----------------------------------------------------------------------------
head(as.array(e_rcov)[, , "pres_rep_nix"])

