income_demographics.py

All source files · Download income_demographics.py

"""Australia-only, 2019–20 household income distribution fitted to ABS SIH tables.

This is a statistical reconstruction, not a statutory benefit calculator.
It estimates frequency and expected taxes/benefits by family and private income.
A lognormal gross-income prior is calibrated to observed family income moments,
benefit reliance, and family composition across gross-income quintiles. Zero
private income is a separate atom; negative-income households are retained.
Calibration minimises relative entropy: it changes the prior weights only as
needed to meet the published controls. Benefits are represented jointly with
income, using ABS's observed benefit-to-gross-income bands. Expected taxes are
fitted separately to observed gross-minus-disposable amounts.

All incomes are annual, unequivalised AUD. Household weights are counts, not
person weights. No national-account cash-base substitution, VoTa calculation,
network access, document generation or plot mutation occurs here.

Run: python income_demographics.py [--json FILE] [--csv FILE]
Requires numpy and scipy. Source extraction: extract_income_demographics.py.

Example: model.summary("one_parent", lower=30_000, upper=40_000) returns the
number of households in that private-income band and their aggregate cashflows.
Divide each cashflow by "households" for the expected per-household amount.
These fitted historical averages cannot predict a change in Australian policy.
"""

import argparse
import csv
from dataclasses import dataclass
import json
from pathlib import Path

import numpy as np
from scipy.optimize import least_squares, minimize
from scipy.special import expit, logit, logsumexp, ndtr
from scipy.sparse import csr_matrix, vstack

DATA = Path(__file__).with_name("data") / "income-demographics-2019-20.json"
BENEFIT_RATIOS = ((0, .005), (.04, .10, .17), (.25, .35, .45),
                  (.55, .70, .85), (.92, .96, .99, 1.0))


def load_data(path=DATA):
    return json.loads(Path(path).read_text())


def rake(matrix, row_totals, column_totals, tolerance=1e-10):
    """Reconcile independently rounded margins without changing their scale."""
    a = np.asarray(matrix, dtype=float).copy()
    rows, cols = np.asarray(row_totals), np.asarray(column_totals)
    if np.any(a <= 0) or np.any(rows <= 0) or np.any(cols <= 0):
        raise ValueError("Raking requires positive inputs")
    if not np.isclose(sum(rows), sum(cols), rtol=1e-10):
        raise ValueError("Raking margins have different totals")
    for _ in range(10000):
        a *= (rows / a.sum(axis=1))[:, None]
        a *= (cols / a.sum(axis=0))[None, :]
        if np.max(np.abs(a.sum(axis=1) / rows - 1)) < tolerance:
            return a
    raise RuntimeError("Raking did not converge")


def weighted_quantile(values, weights, probability):
    order = np.argsort(values)
    cumulative = np.cumsum(weights[order])
    index = np.searchsorted(cumulative, probability * cumulative[-1], side="left")
    return float(values[order[min(index, len(order) - 1)]])


def weighted_gini(values, weights):
    order = np.argsort(values)
    y, w = values[order], weights[order]
    return float(np.sum(w * (2 * np.cumsum(w) - w - w.sum()) * y)
                 / (w.sum() * np.sum(w * y)))


@dataclass
class IncomeDemographics:
    data: dict
    profile: np.ndarray
    gross: np.ndarray
    benefits: np.ndarray
    weights: np.ndarray
    tax: np.ndarray
    quintile: np.ndarray
    fit_diagnostics: dict

    @property
    def private(self):
        return self.gross - self.benefits

    @property
    def disposable(self):
        return self.gross - self.tax

    def select(self, family=None, lower=-np.inf, upper=np.inf):
        """Half-open PRIVATE-income band, including the zero atom at lower=0.

        family accepts either a detailed profile id or a broad family type.
        For zero income alone use zero_private_income() instead of a band.
        """
        if lower >= upper:
            raise ValueError("Income band must have lower < upper")
        mask = (self.private >= lower) & (self.private < upper)
        if family is not None:
            ids = [i for i, p in enumerate(self.data["profiles"])
                   if family in (p["id"], p["family"])]
            if not ids:
                raise ValueError(f"Unknown family type: {family}")
            mask &= np.isin(self.profile, ids)
        return mask

    def summary(self, family=None, lower=-np.inf, upper=np.inf):
        mask = self.select(family, lower, upper)
        w = self.weights[mask]
        result = {"households": float(w.sum())}
        for name in ("private", "benefits", "gross", "tax", "disposable"):
            result[name] = float(np.sum(w * getattr(self, name)[mask]))
        return result

    def zero_private_income(self, family=None):
        mask = self.select(family) & (self.private == 0)
        return float(self.weights[mask].sum())

    def report(self):
        totals = self.summary()
        n = totals["households"]
        published = self.data["published_all_households"]
        checks = {}
        for key in ("private", "benefits", "gross", "disposable"):
            observed = published["households"] * published[f"mean_{key}"]
            checks[key] = {"model": totals[key], "published": observed,
                           "difference_percent": 100 * (totals[key] / observed - 1)}
        distribution = {
            "gross_gini": {"model": weighted_gini(self.gross, self.weights),
                           "published": self.data["gross_gini"]},
            "gross_deciles": [{"percentile": 10 * (i + 1),
                               "model": weighted_quantile(self.gross, self.weights, (i + 1) / 10),
                               "published": value}
                              for i, value in enumerate(self.data["gross_deciles"])],
        }
        groups = []
        for p in self.data["profiles"]:
            mask = self.select(p["id"])
            s = self.summary(p["id"])
            s.update(id=p["id"], label=p["label"],
                     zero_private_share=self.zero_private_income(p["id"]) / s["households"],
                     median_disposable=weighted_quantile(self.disposable[mask], self.weights[mask], .5),
                     published_median_disposable=p["median_disposable"])
            groups.append(s)
        external = self.data["external_comparison"]
        return {
            "year": self.data["year"], "scope": self.data["scope"],
            "totals": totals, "profiles": groups, "fit": self.fit_diagnostics,
            "published_aggregate_checks": checks,
            "distribution_checks": distribution,
            "population": {"model_households": n, "published_households": published["households"],
                           "represented_persons": sum(p["persons"] for p in self.data["profiles"])},
            "external_benefit_comparison": {
                **external, "model_benefits": totals["benefits"],
                "unallocated_difference": external["asna_pensions_allowances_adjusted_rounded"] - totals["benefits"],
            },
            "interpretation": [
                "Income means, benefit means/reliance, private/gross medians and quintile margins are calibration targets, not independent validation.",
                "Gross Gini, non-boundary gross deciles and disposable medians are checks not used in the fit.",
                "Conditional welfare/tax amounts are estimated averages; they are not entitlements or policy counterfactuals.",
                "Survey benefits include overseas pensions; the external Australian-pensions comparison is a scope check, not an exact accounting residual.",
                "The exact zero-private-income share and the unobserved joint distribution remain model estimates; vary zero_atom_prior to assess sensitivity.",
                "Average age counts and employment shares are source metadata, not synthetic individual ages or earnings splits.",
                "Child-count-specific and full government-account calibration are not established by these survey controls.",
            ],
        }

    def write_csv(self, path):
        with Path(path).open("w", newline="") as stream:
            writer = csv.writer(stream)
            writer.writerow(["profile", "households", "private_income", "benefits", "gross_income",
                             "income_tax", "disposable_income", "gross_quintile"])
            for i in range(len(self.weights)):
                writer.writerow([self.data["profiles"][self.profile[i]]["id"], self.weights[i],
                                 self.private[i], self.benefits[i], self.gross[i], self.tax[i],
                                 self.disposable[i], self.quintile[i] + 1])


def _prior(data, grid_size, zero_atom_prior):
    profiles = data["profiles"]
    n = sum(p["households"] for p in profiles)
    # Include both sides of observed median/decile boundaries so discrete
    # quadrature does not force mass onto one side of a calibration threshold.
    anchors = [data["gross_deciles"][i] for i in (1, 3, 5, 7)]
    anchors += [p["median_gross"] for p in profiles]
    grid = np.unique(np.r_[np.geomspace(100, 10_000_000, grid_size),
                          np.asarray(anchors) * .999, np.asarray(anchors) * 1.001])
    edges = np.r_[0, np.sqrt(grid[:-1] * grid[1:]), np.inf]
    family, gross, benefit, bucket, prior = [], [], [], [], []
    for i, p in enumerate(profiles):
        sigma = np.sqrt(2 * np.log(p["mean_gross"] / p["median_gross"]))
        with np.errstate(divide="ignore"):
            mass = np.diff(ndtr((np.log(edges) - np.log(p["median_gross"])) / sigma))
        shares = np.asarray(p["benefit_share_proportions"])
        shares = shares / shares.sum()
        # A generous support bound for the prior, not a legislated maximum.
        adults = max(1, p["persons"] / p["households"] - p["mean_under18"])
        cap = 40_000 * adults + 12_000 * p["mean_under18"]
        for k, ratios in enumerate(BENEFIT_RATIOS):
            ratio_weights = np.full(len(ratios), 1 / len(ratios))
            if k == 4:
                ratio_weights[:-1] = (1 - zero_atom_prior) / (len(ratios) - 1)
                ratio_weights[-1] = zero_atom_prior
            for ratio, ratio_weight in zip(ratios, ratio_weights):
                mask = grid * ratio <= cap
                gm = grid[mask]
                pm = np.maximum(mass[mask], 1e-18)
                pm = pm / pm.sum() * shares[k] * ratio_weight
                family.extend([i] * len(gm)); gross.extend(gm)
                benefit.extend(gm * ratio); bucket.extend([k] * len(gm))
                prior.extend(pm * p["households"] / n * (1-p["nonpositive_gross_share"]))
        if p["nonpositive_gross_share"]:
            # Table 6.4 B9: national mean for zero/negative gross-income homes.
            family.append(i); gross.append(-237 * 52); benefit.append(0); bucket.append(0)
            prior.append(p["households"] / n * p["nonpositive_gross_share"])
    return tuple(np.asarray(x) for x in (family, gross, benefit, bucket, prior))


def build_model(data=None, grid_size=180, zero_atom_prior=.5):
    """Fit a deterministic weighted population; do not draw random households.

    zero_atom_prior is the PRIOR fraction of the >=90%-benefit category placed
    at exactly zero private income. ABS does not identify that fraction here.
    Calibration can change it. Report sensitivity, rather than call it measured.
    """
    if grid_size < 40 or not 0 < zero_atom_prior < 1:
        raise ValueError("Use grid_size >= 40 and 0 < zero_atom_prior < 1")
    data = load_data() if data is None else data
    profiles = data["profiles"]
    n = sum(p["households"] for p in profiles)
    fid, gross, benefits, bucket, prior = _prior(data, grid_size, zero_atom_prior)
    private = gross - benefits
    boundaries = np.asarray(data["gross_deciles"])[[1, 3, 5, 7]]
    quintile = np.searchsorted(boundaries, gross, side="right")
    rows, targets, labels = [], [], []

    def control(label, values, target):
        rows.append(csr_matrix(values.reshape(1, -1)))
        targets.append(target)
        labels.append(label)

    for i, p in enumerate(profiles):
        mask = fid == i
        share = p["households"] / n
        control(p["id"] + ":count", mask.astype(float), share)
        control(p["id"] + ":private", mask * private / 100_000, share * p["mean_private"] / 100_000)
        control(p["id"] + ":benefits", mask * benefits / 10_000, share * p["mean_benefits"] / 10_000)
        control(p["id"] + ":private_median", mask * (private <= p["median_private"]), share * .5)
        control(p["id"] + ":gross_median", mask * (gross <= p["median_gross"]), share * .5)
        proportions = np.asarray(p["benefit_share_proportions"])
        proportions /= proportions.sum()
        for k in range(4):
            control(p["id"] + f":benefit_band{k}", mask * (bucket == k), share * proportions[k])
        if p["nonpositive_gross_share"]:
            control(p["id"] + ":nonpositive", mask * (gross <= 0), share * p["nonpositive_gross_share"])

    families = list(dict.fromkeys(p["family"] for p in profiles))
    row_counts = np.array([sum(p["households"] for p in profiles if p["family"] == f) for f in families])
    column_counts = np.array([q["households"] for q in data["quintiles"]])
    column_counts *= n / column_counts.sum()
    raw_joint = np.array([[q["households"] * q["family_proportions"][f]
                           for q in data["quintiles"]] for f in families])
    joint = rake(raw_joint, row_counts, column_counts)
    for j, family in enumerate(families):
        mask = np.isin(fid, [i for i, p in enumerate(profiles) if p["family"] == family])
        for q in range(4):  # fifth follows from family count and other four
            control(family + f":quintile{q+1}", mask * (quintile == q), joint[j, q] / n)
    for key, values, scale in (("private", private, 100_000), ("benefits", benefits, 10_000)):
        target = column_counts * np.array([q[f"mean_{key}"] for q in data["quintiles"]])
        total = sum(p["households"] * p[f"mean_{key}"] for p in profiles)
        target *= total / target.sum()
        for q in range(4):
            control(key + f":quintile{q+1}", (quintile == q) * values / scale, target[q] / n / scale)
    matrix = vstack(rows).tocsr()
    target = np.asarray(targets)
    # Scale each constraint by its prior RMS for numerical conditioning.
    scales = np.sqrt(matrix.power(2) @ prior)
    matrix = matrix.multiply((1 / scales)[:, None]).tocsr()
    target /= scales

    def objective(lam):
        log_weights = np.log(prior) + np.asarray(matrix.T @ lam)
        normalizer = logsumexp(log_weights)
        weights = np.exp(log_weights - normalizer)
        return float(normalizer - target @ lam), np.asarray(matrix @ weights - target)

    fit = minimize(objective, np.zeros(len(target)), jac=True, method="L-BFGS-B",
                   options={"maxiter": 8000, "maxcor": 50, "ftol": 1e-14, "gtol": 1e-9, "maxls": 40})
    log_weights = np.log(prior) + matrix.T @ fit.x
    weights = np.exp(log_weights - logsumexp(log_weights)) * n
    residual = (matrix @ (weights / n) - target) * scales
    error = float(np.max(np.abs(residual)))
    if error > 2e-5 or not np.all(np.isfinite(weights)):
        worst = labels[int(np.argmax(np.abs(residual)))]
        raise RuntimeError(f"Income calibration failed: {worst}, residual={error:g}; {fit.message}")
    tax, tax_diagnostics = _fit_tax(profiles, data["quintiles"], fid, quintile, gross, weights)
    diagnostics = {
        "income_max_absolute_control_error": error,
        "income_iterations": int(fit.nit), "income_optimizer_message": str(fit.message),
        "grid_size": grid_size, "zero_atom_prior": zero_atom_prior,
        "family_quintile_max_count_adjustment_percent": float(np.max(abs(joint / raw_joint - 1)) * 100),
        **tax_diagnostics,
    }
    return IncomeDemographics(data, fid, gross, benefits, weights, tax, quintile, diagnostics)


def _fit_tax(profiles, quintiles, fid, qid, gross, weights):
    """Calibrate a smooth expected tax burden, not a statutory tax schedule.

    Row and quintile tax totals come from observed gross minus disposable
    income. A logistic rate cap keeps every synthetic tax between 0 and 50%
    of positive gross income. No tax is assigned to business-loss households.
    """
    row_targets = np.array([p["households"] * (p["mean_private"] + p["mean_benefits"]
                                               - p["mean_disposable"]) for p in profiles])
    col_targets = np.array([q["households"] * (q["mean_gross"] - q["mean_disposable"])
                            for q in quintiles])
    col_targets *= row_targets.sum() / col_targets.sum()
    adults = np.array([max(1, p["persons"] / p["households"] - p["mean_under18"])
                       for p in profiles])
    positive = np.maximum(0, gross)
    income_per_adult = positive / adults[fid]
    seed = .47 * np.maximum(0, income_per_adult - 18_200) / (income_per_adult + 50_000)
    intercept = logit(np.clip(seed / .5, 1e-5, 1-1e-5))
    nr = len(profiles)

    def calculate(params):
        column = np.r_[params[nr:], 0.0]  # fix one redundant intercept
        return .5 * positive * expit(intercept + params[:nr][fid] + column[qid])

    def residual(params):
        tax = calculate(params) * weights
        row = np.bincount(fid, weights=tax, minlength=nr)
        col = np.bincount(qid, weights=tax, minlength=5)
        return np.r_[(row-row_targets)/row_targets, (col-col_targets)/col_targets]

    fit = least_squares(residual, np.zeros(nr + 4), max_nfev=500,
                        ftol=1e-11, xtol=1e-11, gtol=1e-11)
    error = float(np.max(abs(residual(fit.x))))
    if error > 1e-5:
        raise RuntimeError(f"Tax calibration failed: relative error {error:g}")
    return calculate(fit.x), {"tax_max_relative_control_error": error}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--json", type=Path)
    parser.add_argument("--csv", type=Path)
    parser.add_argument("--grid-size", type=int, default=180)
    parser.add_argument("--zero-atom-prior", type=float, default=.5)
    args = parser.parse_args()
    model = build_model(grid_size=args.grid_size, zero_atom_prior=args.zero_atom_prior)
    report = model.report()
    if args.json:
        args.json.write_text(json.dumps(report, indent=2) + "\n")
    if args.csv:
        model.write_csv(args.csv)
    print("Australia 2019–20: ABS private-household survey reconstruction")
    print(f"Households: {report['totals']['households']/1e6:.3f} million")
    print(f"{'Annual totals ($bn)':24} {'Model':>10} {'ABS survey':>12} {'Difference':>12}")
    for key, check in report["published_aggregate_checks"].items():
        print(f"{key:24} {check['model']/1e9:10.1f} {check['published']/1e9:12.1f}"
              f" {check['difference_percent']:11.2f}%")
    print(f"Income tax: ${report['totals']['tax']/1e9:,.1f} billion (inferred from survey income)")
    gini = report["distribution_checks"]["gross_gini"]
    print(f"Gross-income Gini: {gini['model']:.3f}; ABS {gini['published']:.3f} (not fitted)")
    median_error = max(abs(p['median_disposable']/p['published_median_disposable']-1)
                       for p in report['profiles'])
    print(f"Largest family disposable-median difference: {median_error:.1%} (not fitted)")
    gap = report['external_benefit_comparison']['unallocated_difference']
    print(f"Gap to adjusted national-account benefits: ${gap/1e9:.1f} billion; not allocated")
    print("Taxes and benefits are fitted historical averages, not statutory entitlements.")


if __name__ == "__main__":
    main()