---
title: "Joint Margin-Constrained Intersectional Estimation"
author: "Leila Marvian Mashhad"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Joint Margin-Constrained Intersectional Estimation}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

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

## Problem

A probability survey observes an outcome and a rich set of person-level
attributes. Census dissemination supplies reliable aggregate tables, but the
full cross-classification is unavailable. `interSAE` treats the unobserved
multiway census table as a latent population constrained by every published
margin.

## Fit

```{r}
library(interSAE)
x <- inter_example()
design <- inter_design(x$survey, "weight", "area", "strata", "psu")
margins <- census_margins(x$margins)
fit <- fit_inter_sae(
  unemployed ~ sex + age + residence + area,
  design, margins,
  family = "binomial",
  domain = c("area", "sex")
)
head(inter_estimates(fit))
```

The `synthetic` column is the census-cell prediction aggregated with the
reconstructed population counts. The residual correction is a calibrated
survey residual total divided by domain population. Their sum gives the
model-assisted estimate.

## Coherence and identification

```{r}
max(margin_diagnostics(fit)$relative_error)
check_identifiability(fit)
```

Nullity greater than zero means that overlapping margins do not uniquely
identify the full latent table. It is not an algorithmic failure. It is a
property of the available information.

When `lpSolve` is installed, association sensitivity can be evaluated by
restricting each latent cell to a multiplicative neighborhood of its fitted
value while maintaining all census margins exactly.

```{r, eval=requireNamespace("lpSolve", quietly=TRUE)}
inter_sensitivity(
  fit,
  gamma = c(1, 1.25, 1.5, 2),
  domain = list(area = "A1", sex = "Female")
)
```

## Bootstrap inference

The multiplier bootstrap assigns one exponential multiplier per PSU and
renormalizes within strata. Every replicate repeats both population
reconstruction and outcome-model fitting.

```{r, eval=FALSE}
boot <- inter_bootstrap(fit, R = 199, type = "multiplier", seed = 42)
boot$summary
```

Bootstrap variation and identification width should not be silently collapsed
into one standard error. `decompose_uncertainty()` reports them separately.
