population_comparison_2025.py

All source files · Download population_comparison_2025.py

"""July 2025 household cash-boundary diagnostic, not a fair system comparison.

The default CLI reports consolidated national reconciliation. Use
--cash-boundary-diagnostic only to inspect the incomplete cash-income model.
That diagnostic excludes the allocation of embedded taxes. Its UBI, rankings
and consumption differences must not be presented as a fair VoTa comparison.

Older SIH data supplies distribution shapes, not the comparison year. Reweight
households to June 2025 children/adults/seniors and uprate private income using
growth in aggregate compensation of employees. The latter is a proxy for growth
in all survey private income, not a new measured cash-income aggregate.

The population tax/benefit allocation is statistical: observed 2024-25 totals
are allocated using SIH conditional patterns. Matching these totals is a
calibration, NOT independent validation of a July 2025 welfare microsimulation.
The separate family comparisons use the actual existing July 2025 rule engine.
No policy thresholds, chapters or charts are changed by this script.

This distinction matters: SIH does not supply individual earnings, assets,
eligibility or exact children counts. Do not describe its synthetic nodes as
individual statutory entitlements. The population model diagnoses aggregate
accounting; the family scenarios show the policy effects for specified families.

Run: OPENBLAS_NUM_THREADS=1 python3 population_comparison_2025.py --json FILE
"""

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

import numpy as np
from scipy.optimize import brentq, least_squares
from scipy.special import expit, logit

from calibration import Calibration, load_population, ubi_weight
from income_demographics import build_model

CONTROLS = Path(__file__).with_name("data") / "income-demographics-2025-controls.json"


def load_controls():
    return json.loads(CONTROLS.read_text())


def amount(controls, table, column, year="2024-25"):
    return controls["tables"][table][column][year] * 1e6


def population_weights(model, population):
    """Minimum-change profile counts matching three 2025 age-group totals.

    Source age means are rounded; derive the middle group as the remainder so
    persons always add up. Full resident coverage is an explicit extrapolation
    of private-household profiles to the population missing from the survey.
    """
    profiles = model.data["profiles"]
    ages = np.array([[p["mean_under18"],
                      p["persons"] / p["households"] - p["mean_under18"] - p["mean_age65plus"],
                      p["mean_age65plus"]] for p in profiles])
    counts = np.bincount(model.profile, weights=model.weights, minlength=len(profiles))
    targets = np.array([sum(n for a, n in population.items() if a < 18),
                        sum(n for a, n in population.items() if 18 <= a < 65),
                        sum(n for a, n in population.items() if a >= 65)])

    def residual(parameters):
        return (ages.T @ (counts * np.exp(ages @ parameters)) - targets) / targets

    fit = least_squares(residual, np.zeros(3), gtol=1e-13, xtol=1e-13, ftol=1e-13)
    if np.max(abs(residual(fit.x))) > 1e-8:
        raise RuntimeError("2025 age/population calibration failed")
    factors = np.exp(ages @ fit.x)
    return model.weights * factors[model.profile], ages, factors, targets


def allocate_tax(prior, gross, weights, target):
    """Preserve observed conditional tax pattern with a bounded rate shift.

    Zero-tax nodes stay zero; taxes cannot exceed 50% of positive gross income.
    This allocates a macro control, including its scope differences (e.g. CGT),
    rather than claiming all of that tax follows from ordinary earnings rules.
    """
    cap = .5 * np.maximum(gross, 0)
    active = (prior > 0) & (cap > 0)
    if target <= 0 or target >= weights[active] @ cap[active]:
        raise ValueError("Tax target outside supported allocation")
    seed = logit(np.clip(prior[active] / cap[active], 1e-12, 1-1e-12))
    shift = brentq(lambda x: weights[active] @ (cap[active] * expit(seed+x)) - target,
                   -50, 50)
    result = np.zeros_like(gross)
    result[active] = cap[active] * expit(seed+shift)
    return result, shift


@dataclass
class Population2025:
    historical: object
    controls: dict
    weights: np.ndarray
    private: np.ndarray
    benefits: np.ndarray
    tax: np.ndarray
    household_ubi_weights: np.ndarray
    calibration: Calibration
    diagnostics: dict

    @property
    def australia_buying_power(self):
        # Australian advertised (GST-inclusive) prices: spendable cash.
        return self.private + self.benefits - self.tax

    @property
    def ubi(self):
        return self.household_ubi_weights * self.calibration.adult_ubi

    @property
    def vota_buying_power(self):
        c = self.calibration
        return 1.1 * (1-c.ubi_rate-c.svc_rate) * (self.private+self.ubi)

    def totals(self, mask=None):
        if mask is None:
            mask = np.ones(len(self.weights), dtype=bool)
        w = self.weights[mask]
        result = {"households": float(w.sum())}
        for key in ("private", "benefits", "tax", "ubi", "australia_buying_power", "vota_buying_power"):
            result[key] = float(w @ getattr(self, key)[mask])
        difference = self.vota_buying_power[mask] - self.australia_buying_power[mask]
        result.update(gains=float(w @ np.maximum(difference, 0)),
                      losses=float(w @ np.maximum(-difference, 0)),
                      winning_households=float(w[difference > 0].sum()),
                      difference=float(w @ difference))
        return result


def build_population(historical=None, *, ubi_rate=.30, svc_rate=.22, income_multiplier=1.0):
    if income_multiplier <= 0:
        raise ValueError("Income multiplier must be positive")
    historical = build_model() if historical is None else historical
    controls, population = load_controls(), load_population()
    weights, ages, factors, age_targets = population_weights(historical, population)
    # Aggregate growth ALREADY includes employment/population growth. Do not
    # multiply it by population growth a second time.
    growth = amount(controls, "household", "D") / amount(controls, "household", "D", "2019-20")
    aggregate_income = historical.summary()["private"] * growth * income_multiplier
    private_scale = aggregate_income / (weights @ historical.private)
    private = historical.private * private_scale
    adjustment = controls["benefit_scope_adjustments"]
    cash_benefits = amount(controls, "household", "M") - 1e6 * (
        adjustment["ccs_aud_million"] + adjustment["private_health_rebate_aud_million"])
    benefits_scale = cash_benefits / (weights @ historical.benefits)
    benefits = historical.benefits * benefits_scale
    tax_target = amount(controls, "household", "AA")
    tax, tax_shift = allocate_tax(historical.tax * private_scale, private+benefits, weights, tax_target)
    child_weight = sum(n*ubi_weight(a) for a, n in population.items() if a < 18) / age_targets[0]
    profile_ubi_weights = ages[:, 0]*child_weight + ages[:, 1] + ages[:, 2]
    household_ubi_weights = profile_ubi_weights[historical.profile]
    calibration = Calibration(sum(population.values()),
                              sum(n*ubi_weight(a) for a, n in population.items()),
                              float(weights @ private), ubi_rate, svc_rate)
    diagnostics = {
        "population_targets_under18_18to64_65plus": age_targets.tolist(),
        "profile_count_factors": factors.tolist(),
        "aggregate_income_growth_proxy": growth,
        "per_household_income_scale": private_scale,
        "benefits_scale": benefits_scale,
        "tax_log_odds_shift": tax_shift,
        "income_multiplier_sensitivity": income_multiplier,
        "income_basis": "SIH private income uprated by aggregate employee compensation growth; proxy, not measured 2025 cash total",
        "tax_benefit_basis": "2024-25 aggregate controls statistically allocated; not a population statutory simulation",
        "scope": "Private-household composition extrapolated to all June 2025 residents",
    }
    return Population2025(historical, controls, weights, private, benefits, tax,
                          household_ubi_weights, calibration, diagnostics)


def government_accounts(controls):
    """Reconcile one ASNA vintage, all levels consolidated, AUD.

    Exclude depreciation on both sides, include capital spending and borrowing.
    The remainder after household benefits is NOT all public services: it also
    includes interest, subsidies, investment and other transfers.
    """
    g = lambda col: amount(controls, "government", col)
    k = lambda col: amount(controls, "capital", col)
    receipts = g("CK") - g("BS")
    borrowing = -k("AU")
    uses = g("CV") + g("CX") - g("CZ") - k("AK") + k("AR") + k("AS") + k("AT")
    return {"receipts_excluding_depreciation": receipts, "net_borrowing": borrowing,
            "uses_excluding_depreciation": uses,
            "published_rounding_residual": receipts+borrowing-uses,
            "direct_government_consumption_excluding_depreciation": g("CX")-g("CZ"),
            "investment_and_net_other_capital_uses": -k("AK")+k("AR")+k("AS")+k("AT"),
            "government_interest": g("CN"), "government_subsidies": g("CP"),
            "individual_income_tax": g("CC"), "corporation_income_tax": g("CD"),
            "production_import_taxes": g("BT"),
            "social_assistance_including_provider_subsidies": g("CR")}


def accounting_bridge(population):
    t, c = population.totals(), population.calibration
    government = government_accounts(population.controls)
    # Preserve the user's all-GST, full-consumption convention. This is NOT
    # actual GST receipts; the government residual explicitly absorbs the
    # difference between this counterfactual basket and observed tax receipts.
    au_consumption = t["australia_buying_power"] / 1.1
    au_gst = t["australia_buying_power"] - au_consumption
    au_net_household_funding = t["tax"] + au_gst - t["benefits"]
    remaining_receipts = government["receipts_excluding_depreciation"] - t["tax"] - au_gst
    other_uses = government["uses_excluding_depreciation"] - t["benefits"]
    v_consumption = t["vota_buying_power"] / 1.1
    total_v_tax = (c.ubi_rate+c.svc_rate)*c.total_consumption
    bridge = {
        "australia_consumption_before_GST": au_consumption,
        "australia_GST_under_all_GST_convention": au_gst,
        "australia_net_funding_from_modelled_household_cash": au_net_household_funding,
        "vota_gross_consumption_tax": total_v_tax,
        "vota_ubi_pool": c.ubi_pool,
        "vota_services_pool": c.services_pool,
        "vota_consumption_before_tax": v_consumption,
        "cash_boundary_gap_before_embedded_tax_adjustment": c.services_pool-au_net_household_funding,
        "australia_remaining_receipts_after_modelled_tax": remaining_receipts,
        "australia_other_public_uses_after_cash_benefits": other_uses,
        "australia_other_uses_minus_vota_service_funding": other_uses-c.services_pool,
        "government": government,
        "interpretation": [
            "This difference is a cash-boundary diagnostic, not a difference in total burdens on households. Embedded taxes have not been allocated.",
            "Company/other taxes and non-tax income are not free resources outside households. Consolidate national resources before allocating these flows; do not simply add all government receipts to household income.",
            "Borrowing is separate from receipts. Other public uses include more than services; do not use this residual as an unqualified services target.",
            "Gross UBI includes money subsequently taxed back. Compare household purchasing power and net funding as well as gross transfers.",
        ],
    }
    return bridge


def family_scenarios(calibration):
    """July 2025 statutory scenarios; do not confuse these with fitted averages.

    One/two parents, zero to four children, one/two earners. Children span the
    under-18 range; exact ages are included in every result. No rent/childcare
    subsidies here, matching the basic-cash tables. Eligible working-age adults.
    """
    from emtr import Australia1July2025, Household, VoTa
    au, vota = Australia1July2025(), VoTa(calibration=calibration)
    result = []
    for parents in (1, 2):
        for children in range(5):
            ages = [40]*parents + [3, 7, 11, 15][:children]
            for income in (0, 30_000, 60_000, 120_000, 240_000):
                for partner_fraction in ((0, .5) if parents == 2 and income else (0,)):
                    hh = Household(ages, partner_income=income*partner_fraction)
                    primary = income*(1-partner_fraction)
                    a = au.breakdown(primary, hh)
                    v = 1.1*vota.disposable_income(primary, hh)
                    result.append({"parents": parents, "children": children,
                                   "member_ages": ages, "household_private_income": income,
                                   "partner_income_fraction": partner_fraction,
                                   "annual_ubi": vota.household_ubi(hh),
                                   "australia_buying_power": a["cash_after_tax"],
                                   "vota_buying_power": v,
                                   "difference": v-a["cash_after_tax"]})
    return result


def report(population, include_scenarios=True):
    c = population.calibration
    groups = [{"id": p["id"], "label": p["label"],
               **population.totals(population.historical.profile == i)}
              for i, p in enumerate(population.historical.data["profiles"])]
    bands = [-np.inf, 0, 30_000, 60_000, 120_000, 240_000, np.inf]
    by_income = [{"lower": lo if np.isfinite(lo) else None,
                  "upper": hi if np.isfinite(hi) else None,
                  **population.totals((population.private >= lo) & (population.private < hi))}
                 for lo, hi in zip(bands[:-1], bands[1:])]
    result = {"status": "INCOMPLETE CASH-BOUNDARY DIAGNOSTIC: embedded-tax incidence is not allocated; not a fair system comparison",
              "reference_date": "2025-07-01", "aggregate_reference_year": "2024-25",
              "buying_power_units": "AUD at Australian GST-inclusive advertised prices; all purchases assumed GST-taxed",
              "rates": {"u": c.ubi_rate, "s": c.svc_rate},
              "adult_ubi": c.adult_ubi, "population": c.population,
              "total_ubi_weight": c.total_weight,
              "diagnostics": population.diagnostics, "totals": population.totals(),
              "profiles": groups, "income_bands": by_income,
              "accounting_bridge": accounting_bridge(population),
              "limitations": [
                  "Income uplift is an approximation. Household structures and conditional income/tax/benefit patterns originate in SIH 2019-20.",
                  "Population benefit and income-tax totals are fitted controls, not independent predictions from eligibility rules.",
                  "The income-tax control includes taxes on income absent from survey regular income, including capital gains; the allocation is a macro benchmark.",
                  "Child counts and earners within each survey profile are averages. Statutory scenarios have explicit family sizes but are not assigned population frequencies.",
                  "Negative private-income nodes are retained as business losses in aggregate accounting, not interpreted as negative shopping baskets.",
              ]}
    if include_scenarios:
        result["july_2025_statutory_family_scenarios"] = family_scenarios(c)
    return result


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--json", type=Path)
    parser.add_argument("--ubi-rate", type=float, default=.30)
    parser.add_argument("--svc-rate", type=float, default=.22)
    parser.add_argument("--cash-boundary-diagnostic", action="store_true",
                        help="Inspect the incomplete household cash model; not a fair comparison")
    args = parser.parse_args()
    if not args.cash_boundary_diagnostic:
        from national_reconciliation_2025 import reconcile
        output = reconcile()
        if args.json:
            args.json.write_text(json.dumps(output, indent=2, allow_nan=False)+"\n")
        print("Consolidated July 2025 accounting basis (2024-25 annual aggregates)")
        for key, value in output["resources"].items():
            print(f"{key}: ${value/1e9:,.1f} billion")
        print(f"Accounting checks passed: {len(output['checks'])}")
        print("The cash-only UBI and household rankings are not a fair system comparison.")
        return
    historical = build_model()
    population = build_population(historical, ubi_rate=args.ubi_rate, svc_rate=args.svc_rate)
    output = report(population)
    output["income_scale_sensitivity"] = []
    for multiplier in (.9, 1.1):
        variant = build_population(historical, ubi_rate=args.ubi_rate, svc_rate=args.svc_rate,
                                   income_multiplier=multiplier)
        output["income_scale_sensitivity"].append({"income_multiplier": multiplier,
            "adult_ubi": variant.calibration.adult_ubi,
            "aggregate_buying_power_difference": variant.totals()["difference"]})
    if args.json:
        args.json.write_text(json.dumps(output, indent=2, allow_nan=False)+"\n")
    print(output["status"])
    print(f"Cash-only UBI diagnostic, not a comparable payment: ${output['adult_ubi']:,.0f}")
    for key in ("private", "benefits", "tax", "ubi", "australia_buying_power", "vota_buying_power", "difference"):
        print(f"{key}: ${output['totals'][key]/1e9:,.1f} billion")
    bridge = output["accounting_bridge"]
    for key in ("australia_net_funding_from_modelled_household_cash", "vota_services_pool",
                "cash_boundary_gap_before_embedded_tax_adjustment", "australia_remaining_receipts_after_modelled_tax"):
        print(f"{key}: ${bridge[key]/1e9:,.1f} billion")
    print("Income-tax/benefit aggregate matches are calibration, not independent validation.")


if __name__ == "__main__":
    main()