Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
0ee10c5
Place every GB area in a BRMA and rebuild Scotland's overlap on it (#…
juaristi22 Oct 16, 2026
0672fe8
Build BRMA rent quantiles from the lists of rents (#1262)
juaristi22 Oct 16, 2026
7addd43
Derive each placed household's BRMA and private rent from its area (#…
juaristi22 Oct 16, 2026
d2a550c
Name the incumbent's BRMA method by its short name (#1262)
juaristi22 Oct 16, 2026
f915c9c
Bind Scotland's private rents at BRMA grain (#1090, #1262)
juaristi22 Oct 16, 2026
4e30a48
Give the BRMA rows their own compile-parity rationales (#1262)
juaristi22 Oct 16, 2026
c2a5343
Add the private-rent receipt tools (#1262)
juaristi22 Oct 16, 2026
bf8ee71
Close the private-rent receipt's disclosure gaps (#1262)
juaristi22 Oct 17, 2026
402e0ef
Say where the region scale holds the FRS level (#1262)
juaristi22 Oct 17, 2026
6b5019a
Weigh the BRMA rows in the authority grain under every rule (#1262)
juaristi22 Oct 17, 2026
93bf098
Test the BRMA enum gate's structural stop (#1262)
juaristi22 Oct 17, 2026
3d16b3f
Close the BRMA and rent modes' edge paths (#1262)
juaristi22 Oct 17, 2026
5a86004
Withhold thin BRMA rows' model figures from what a build writes (#1262)
juaristi22 Oct 17, 2026
4a5bb50
Correct the rent declarations, parity rationales and layer checks (#1…
juaristi22 Oct 17, 2026
37fb247
Regenerate the local compile-parity receipt on the rent head (#1262)
juaristi22 Oct 17, 2026
85d7641
Write withheld BRMA rows by name only in the gate battery's outputs (…
juaristi22 Oct 18, 2026
a85614b
Restate the calibration diagnostics' totals over the published rows (…
juaristi22 Oct 18, 2026
e4f689a
Read a withheld BRMA row as withheld in the manifest, scorer and cont…
juaristi22 Oct 18, 2026
1b48506
Carry the BRMA withholding into the sign-off drafter and Orrery (#1262)
juaristi22 Oct 18, 2026
241397b
Floor each rent row on its own carriers in the private-rent receipt (…
juaristi22 Oct 18, 2026
f3bc827
Rank a thin sampled region on Great Britain's renters (#1262)
juaristi22 Oct 18, 2026
944ef88
Correct the BRMA texts, counts and record sets the re-review found (#…
juaristi22 Oct 18, 2026
7965d69
Keep every loss over all rows out of what a build publishes (#1262)
juaristi22 Oct 19, 2026
28e3387
Decide the local target fit on the published rows (#1262)
juaristi22 Oct 19, 2026
e1d69f0
Hold the release contract to every withheld field and total (#1262)
juaristi22 Oct 19, 2026
5d0449e
Test the withholding through its readers, and floor the receipt's gro…
juaristi22 Oct 19, 2026
9168acb
Say seven local gates everywhere, and count the spine's stages (#1262)
juaristi22 Oct 19, 2026
21f2851
Pin the rent report's engine, count the union's stages and one carrie…
juaristi22 Oct 19, 2026
9c9c600
Recompute the withheld totals in the contract, and give the guard one…
juaristi22 Oct 19, 2026
0ed2e61
Keep the national role's staged losses, and close the receipt's and d…
juaristi22 Oct 19, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ dist/
build/
out/
*.h5
# Licensed run outputs: pool tables and audit directories (UKDS CD137 cl. 8).
*.npz
audit-*/
!packages/*/build/
# microcosm.build is a real namespace package, not a build-artifact dir
!packages/microcosm-build/src/microcosm/build/
Expand Down
1 change: 1 addition & 0 deletions changelog.d/1090-scotland-brma-la-overlap.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Measure how Scotland's 18 Broad Rental Market Areas overlap its 32 council areas, and settle whether ONS's BRMA-grain private rents can become council targets (#1090, folding in #1092). `uk/scotland_brma_la_overlap.json` holds Census 2022 private-rented and all households for the 63 BRMA × council intersections, summed exactly from UV404 by output area in the pinned feed, with each output area's BRMA from the area-to-BRMA layer and its council from the Scotland atomic support; `tools/build_uk_scotland_brma_la_overlap.py` rebuilds it and `uk_runtime/scotland_brma_la_overlap.py` reads it. The table shows they cannot: 18 councils span more than one BRMA, 29 councils and 17 BRMAs form one connected block, and a household-weighted mean of BRMA rents would give every council inside a BRMA that BRMA's average (up to 30.9% from the council's own mean in Rent Service Scotland's 2020-21 market evidence, `experiments/1090-scotland-brma-la-rent-dispersion.json`). The decision is recorded in `docs/uk-scotland-private-rent-brma-1090.md`.
1 change: 1 addition & 0 deletions changelog.d/1090-uk-scotland-private-rent-brma.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Scotland's private rents bind at the grain ONS publishes them (microcosm#1090, #1262). `ons.rent.private_rent_brma` binds PIPR's 18 Scottish Broad Rental Market Area rows: each is 12 x the BRMA's calendar-2025 mean x its private renters, derived after reconciliation from the councils' `tenure/private_rent` cells through Census 2022's council shares of each BRMA's renters (`uk_private_rent_brma_mean_to_total`, `uk/scotland_brma_la_overlap.json`), so they add up to Scotland's reconciled renters. The local surface gains a partial `brma` area type: the crosswalk's `statistical_scope` level holds the 18 codes and each one's BRMA, a placed Scottish household joins its BRMA's cell through the BRMA of its assigned output area, and households outside Scotland belong to no BRMA area. The rows weigh inside the local-authority grain's private-rent family, are signature-incomplete beside the local-authority rent rows, and route as `no_higher_control`. The 32 council cells stay signed deferred with the reason restated, the `cross_grain_private_rent_scotland_brma` parity concern resolves to the BRMA rows, and calibration diagnostics gain a `brma` geography level (optional in reports written before it). A BRMA row's model figures leave a build only when at least ten distinct source households of positive weight carry them (María's ruling of 2026-10-17, UKDS CD137 clause 8). A thinner row keeps its place without its model figures: its estimates and errors are null in the calibration diagnostics, the targets table, the gate report, the manifest and the Orrery summaries. The fit gates decide on the published rows and count the withheld ones, so no output says whether a withheld row is inside the bound (María's ruling of 2026-10-19). It stays out of every rollup and the scorer, and while any row is withheld the diagnostics' totals cover the published rows (`uk_diagnostics.model_figures_withheld`; María's ruling of 2026-10-18), which the release contract recomputes from them. Every BRMA row states whether ten households carry it (`carrier_floor_met`), and the release contract warns about a row without that verdict.
1 change: 1 addition & 0 deletions changelog.d/1262-uk-brma-from-area.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
A placed household's Broad Rental Market Area now follows its assigned area (microcosm#1262, B1). `tools/build_uk_brma_area_layer.py` places every 2021 LSOA of England and Wales and every 2022 output area of Scotland in one BRMA from Chronicle's raw registrations (PolicyEngine/chronicle#314): England and Wales by population-weighted centroid in the VOA May 2020 and Rent Officers Wales May 2012 polygons with uk-data#516's six overrides, Scotland by centroid in the Scottish Government's polygons corrected by Rent Service Scotland's postcode lookup with microcosm#1092's two overrides. The layer, `uk/brma_area_layer.json` (192 BRMAs, OGL v3.0), reproduces the region-by-BRMA support of uk-data#516's census table and microcosm#1092's 63 Scottish BRMA-by-council pairs exactly; its provenance records both checks. The post-geography node `uk.full.geography.brma` (`--brma-localisation area`, the default on the atomic assignment; `none` for measurement builds, refused by a release candidate) reads each placed Great Britain clone's BRMA off its LSOA or output area, so its LHA rate describes the same place as its local authority and constituency. Northern Ireland and the national line keep the spine's `frs_brma` draw. A terminal release-blocking gate, `uk_local_brma_enum_domain`, rechecks the rewritten column against the engine's enum; the local gate battery has seven entries. The dense and full-battery contract digests, the declared gate count and the certification exclusions move with it, so a national or dense release certified before this change fails `validate_release` after it.
1 change: 1 addition & 0 deletions changelog.d/1262-uk-private-rent-from-area.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
A placed private renter's rent now comes from its assigned area's list of rents (microcosm#1262, B2; María's rulings of 2026-10-15/16). `tools/build_uk_brma_rent_quantiles.py` writes `uk/brma_rent_quantiles.json`, 25 quantile knots of the weekly rent for every Great Britain BRMA and LHA category B to E: England from VOA's April 2026 shadow list (lets from October 2024 to September 2025), Wales from Rent Officers Wales' list for October 2023 to September 2024 (Table 2 of FOI ATISN 25142), Scotland from the Scottish Government's 2025 quartiles and median by BRMA and bedrooms with the shape of Rent Service Scotland's 2016 to 2021 lettings outside them (implied means within 7 per cent of the published ones). A cell with 20 to 49 lets takes its own median and its nation's pooled shape. The post-geography node `uk.full.private_rent` (`--private-rent-localisation brma_list`, the default with area BRMAs) keeps each Great Britain private renter's rank among its FRS region and bedroom category's FRS-channel renters, in both channels, and reads that quantile off its assigned BRMA's list; one scale per region holds the region's FRS mean rent on the census private-renter mix, so the lists set the pattern within a region and the spread within a BRMA but not the level. Placement follows all households, so at design weights a region's level moves by the gap between that mix and where renters land until calibration's tenure rows restore it; after calibration the national line, which keeps FRS rents, agrees on regional levels. Category A is never used; owners, social renters, zero rents and Northern Ireland are untouched; the boarder, lodger, subletting, service-charge and reported Housing Benefit columns stay as reported. `ons.rent.private_rent` stays bound.
289 changes: 289 additions & 0 deletions docs/evidence/uk-private-rent-1262/scripts/engine_rent_diagnostics.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,289 @@
"""Engine diagnostics for UK private rents and BRMAs (microcosm#1262).

Runs policyengine-uk on a Microcosm local H5 and reports, for one year:

- Universal Credit, the UC housing element of UC recipients (all, private
renters, social renters) and Housing Benefit;
- people in poverty after housing costs;
- the mean weekly LHA rate of LHA-eligible renters;
- UC recipients with a housing element whose rent exceeds their UC LHA rate,
by nation, against DWP's May 2025 shares of private-rented UC households
whose LHA does not cover their rent (CIH UK Housing Review 2026 table 111b,
from DWP Stat-Xplore, as quoted on uk-data#521).
The definitions differ: reported rents against DWP's verified rents, and
benefit units against claim households.

With ``--pool`` (``tools/uk_private_rent_pool.py``), it also splits the
build's own change at its release weights into three variants:

- ``spine``: every household's spine BRMA and rent;
- ``area_brma``: the BRMA of its assigned area, with the spine's rent;
- ``built``: the build as published, with the redrawn rent too.

A control build's H5 (``--control-h5``) is measured as built.

Every figure is a weighted total, mean or share over Great Britain or a
nation. A share or mean carried by fewer than ten distinct source households,
or leaving out fewer than ten, reads "<10" (UKDS End User Licence CD137
clause 8, CD171 section 5.2.1). The output stays in the run's audit
directory; only its aggregates may be quoted.

Usage::

uv run --no-sync python \\
docs/evidence/uk-private-rent-1262/scripts/engine_rent_diagnostics.py \\
--h5 <runs/head>/microcosm_uk_2024_25_local.h5 \\
[--pool <runs/head>/audit-1262/pool.npz] [--control-h5 <control.h5>] \\
--out <runs/head>/audit-1262/engine_diagnostics.json
"""

from __future__ import annotations

import argparse
import json
from collections.abc import Iterable, Mapping
from pathlib import Path
from typing import Any

import numpy as np
import pandas as pd

MIN_SOURCE_HOUSEHOLDS = 10
WEEKS_IN_YEAR = 365.25 / 7

#: DWP via CIH UK Housing Review 2026 table 111b, May 2025: private-rented UC
#: households with a housing element whose LHA does not cover their rent.
#: Copied by hand from the quotation on uk-data#521; no Chronicle fact
#: carries the table, so the comparison is indicative.
DWP_RENT_ABOVE_LHA_MAY_2025 = {"England": 0.521, "Wales": 0.630, "Scotland": 0.399}
DWP_SOURCE = (
"CIH UK Housing Review 2026 table 111b (from DWP Stat-Xplore), May 2025, "
"copied by hand from its quotation on uk-data#521 and not a registered "
"Chronicle fact: an indicative comparison"
)

REGION_NATION = {
"NORTH_EAST": "England",
"NORTH_WEST": "England",
"YORKSHIRE": "England",
"EAST_MIDLANDS": "England",
"WEST_MIDLANDS": "England",
"EAST_OF_ENGLAND": "England",
"LONDON": "England",
"SOUTH_EAST": "England",
"SOUTH_WEST": "England",
"WALES": "Wales",
"SCOTLAND": "Scotland",
"NORTHERN_IRELAND": "Northern Ireland",
}


def _households(h5: Path) -> pd.DataFrame:
return pd.read_hdf(
h5,
"household",
columns=["household_id", "region", "source_household_key"],
).set_index("household_id")


def _dataset_year(h5: Path) -> int:
return int(np.asarray(pd.read_hdf(h5, "time_period")).ravel()[0])


def _array(sim, name: str, year: int, **kwargs) -> np.ndarray:
return np.asarray(sim.calculate(name, year, **kwargs).values)


def _share(
mask: np.ndarray, within: np.ndarray, weight: np.ndarray, source: np.ndarray
) -> float | str | None:
"""The weighted share of ``within`` that ``mask`` covers, under control."""

denominator = float(weight[within].sum())
if denominator <= 0:
return None
for side in (within & mask, within & ~mask):
carriers = len(pd.unique(source[side]))
if 0 < carriers < MIN_SOURCE_HOUSEHOLDS:
return "<10"
return round(float(weight[within & mask].sum()) / denominator, 4)


def _mean(
values: np.ndarray, within: np.ndarray, weight: np.ndarray, source: np.ndarray
) -> float | str | None:
total = float(weight[within].sum())
if total <= 0:
return None
if len(pd.unique(source[within])) < MIN_SOURCE_HOUSEHOLDS:
return "<10"
return round(float((weight * values)[within].sum()) / total, 2)


def diagnostics(sim, *, year: int, households: pd.DataFrame) -> dict[str, Any]:
"""The rent-sensitive aggregates of one simulation."""

benunit_household = _array(sim, "household_id", year, map_to="benunit").astype(
np.int64
)
lineage = households.reindex(benunit_household)
nation = lineage["region"].map(REGION_NATION).to_numpy(dtype=object)
source = lineage["source_household_key"].astype(str).to_numpy()
weight = _array(sim, "benunit_weight", year).astype(float)
uc = _array(sim, "universal_credit", year).astype(float)
element = _array(sim, "uc_housing_costs_element", year).astype(float)
benefit = _array(sim, "housing_benefit", year).astype(float)
tenure = _array(sim, "benunit_tenure_type", year).astype(str)
rent = _array(sim, "benunit_rent", year).astype(float)
uc_cap = _array(sim, "uc_LHA_cap", year).astype(float)
lha = _array(sim, "BRMA_LHA_rate", year).astype(float)
eligible = _array(sim, "LHA_eligible", year).astype(bool)

person_weight = _array(sim, "person_weight", year).astype(float)
poverty = _array(sim, "in_poverty_ahc", year, map_to="person").astype(float)

on_uc = uc > 0
private = tenure == "RENT_PRIVATELY"
social = np.isin(tenure, ["RENT_FROM_COUNCIL", "RENT_FROM_HA"])
housed = on_uc & (element > 0)
out: dict[str, Any] = {
"universal_credit_bn": round(float((weight * uc).sum()) / 1e9, 3),
"uc_housing_element_of_uc_recipients_bn": {
"all": round(float((weight * element)[on_uc].sum()) / 1e9, 3),
"private_renters": round(
float((weight * element)[on_uc & private].sum()) / 1e9, 3
),
"social_renters": round(
float((weight * element)[on_uc & social].sum()) / 1e9, 3
),
},
"housing_benefit_bn": round(float((weight * benefit).sum()) / 1e9, 3),
"people_in_ahc_poverty_m": round(
float((person_weight * poverty).sum()) / 1e6, 3
),
"mean_weekly_lha_lha_eligible_renters": {},
"uc_recipients_rent_above_uc_lha": {},
}
above = rent > uc_cap
for name in ("Great Britain", "England", "Wales", "Scotland"):
scope = (
nation != "Northern Ireland" if name == "Great Britain" else nation == name
)
out["mean_weekly_lha_lha_eligible_renters"][name] = _mean(
lha / WEEKS_IN_YEAR, scope & eligible & (lha > 0), weight, source
)
within = scope & housed & private
out["uc_recipients_rent_above_uc_lha"][name] = {
"model": _share(above, within, weight, source),
"dwp_may_2025": DWP_RENT_ABOVE_LHA_MAY_2025.get(name),
}
return out


def _simulation(h5: Path, *, year: int, overrides: Mapping[str, np.ndarray] | None):
from policyengine_uk import Microsimulation

sim = Microsimulation(dataset=str(h5))
for name, values in (overrides or {}).items():
sim.set_input(name, year, values)
return sim


def _difference(after: Any, before: Any) -> Any:
if isinstance(after, dict) and isinstance(before, dict):
return {
key: _difference(after[key], before.get(key))
for key in after
if key != "dwp_may_2025"
}
if isinstance(after, int | float) and isinstance(before, int | float):
return round(float(after) - float(before), 4)
return None


def main(argv: Iterable[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--h5", type=Path, required=True)
parser.add_argument("--pool", type=Path)
parser.add_argument("--control-h5", type=Path)
parser.add_argument("--year", type=int, default=2025)
parser.add_argument("--out", type=Path, required=True)
args = parser.parse_args(list(argv) if argv is not None else None)

# The report is licensed output: refused inside any git work tree before
# the simulations, not after them.
from microcosm.build.uk_runtime.receipt_counts import outside_work_trees

out = outside_work_trees(args.out, what="the engine report")
# The report measures the engine the build is pinned to (#1308's freeze),
# so it refuses any other policyengine-uk before it reads an H5.
from microcosm.build.uk_runtime.hmrc_uprating import (
assert_installed_engine_is_pinned,
)

engine = assert_installed_engine_is_pinned()
households = _households(args.h5)
dataset_year = _dataset_year(args.h5)
variants: dict[str, Mapping[str, np.ndarray] | None] = {"built": None}
if args.pool is not None:
with np.load(args.pool, allow_pickle=False) as pool:
spine = pd.DataFrame(
{"rent": pool["spine_rent"], "brma": pool["spine_brma"]},
index=pd.Index(pool["household_id"], name="household_id"),
).reindex(households.index)
if spine["rent"].isna().any():
raise ValueError("Some H5 households are not in the pool table.")
variants = {
"spine": {
"brma": spine["brma"].to_numpy(dtype=str),
"rent": spine["rent"].to_numpy(dtype=float),
},
"area_brma": {"rent": spine["rent"].to_numpy(dtype=float)},
"built": None,
}
report: dict[str, Any] = {
"year": args.year,
"dataset_year": dataset_year,
"engine": f"policyengine-uk {engine}",
"dwp_source": DWP_SOURCE,
"disclosure": (
"Weighted totals, means and shares over Great Britain or a nation; "
f"any carried by, or leaving out, fewer than {MIN_SOURCE_HOUSEHOLDS} "
"distinct source households reads <10."
),
"variants": {},
}
for name, overrides in variants.items():
sim = _simulation(args.h5, year=dataset_year, overrides=overrides)
report["variants"][name] = diagnostics(
sim, year=args.year, households=households
)
del sim
if "spine" in report["variants"]:
built = report["variants"]["built"]
report["changes"] = {
"area_brma_less_spine": _difference(
report["variants"]["area_brma"], report["variants"]["spine"]
),
"built_less_area_brma": _difference(built, report["variants"]["area_brma"]),
"built_less_spine": _difference(built, report["variants"]["spine"]),
}
if args.control_h5 is not None:
control_households = _households(args.control_h5)
sim = _simulation(
args.control_h5, year=_dataset_year(args.control_h5), overrides=None
)
report["control"] = diagnostics(
sim, year=args.year, households=control_households
)
report["changes_from_control"] = _difference(
report["variants"]["built"], report["control"]
)
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n")
print(f"wrote {args.out}")
return 0


if __name__ == "__main__":
raise SystemExit(main())
6 changes: 3 additions & 3 deletions docs/gate-battery-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -228,9 +228,9 @@ stretches on declaration alone:
| | BE | UK |
| --- | --- | --- |
| phases | `terminal` | `preflight`, `assembled`, `transferred`, `terminal` |
| entries | 9 | 43 (37 national-build entries plus 6 local-candidate entries) |
| entries | 9 | 73 (64 national-build entries, 7 local-candidate entries and 2 local diagnostics) |
| incumbent posture | none — incumbent-comparison gates deliberately not selected; external oracles replace self-parity | full — export/target parity against the pinned enhanced-FRS incumbent |
| criticality mix | 8 blocking + 1 diagnostic | 39 blocking + 4 local diagnostics |
| criticality mix | 8 blocking + 1 diagnostic | 71 blocking + 2 local diagnostics |

The differences are entirely in the two country inputs — the spec file
and the registry — which is the point. The UK national build is the
Expand All @@ -241,7 +241,7 @@ remains spec-only.

UK evaluates the declaration through four producer scopes: spine,
calibration seam, national release cut, and local candidate. The first three
compose the national release certification. The six local-candidate entries
compose the national release certification. The seven local-candidate entries
are explicitly classified as excluded from that certification until the
local publication work in #146; they are evaluated in their own signed
`local_candidate` report rather than silently disappearing from union
Expand Down
Loading
Loading