Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
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
9 changes: 9 additions & 0 deletions changelog.d/1705-shared-firm-mechanics.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
`microcosm.build.firms`: country-neutral mechanics for synthetic firm populations, taken out of the UK firm port so another country can reuse them (#1705). A country passes its band edges, band roles, registered counts, engine package and receipts as data:
- `draw_in_band` maps caller-drawn uniforms into a band, log-uniform for an open band, and keeps the input's type and dtype;
- `stratified_thin` thins a candidate draw by stratum, with exact base weights;
- a `RegistrationSpec` declares a register's bands as excluded, registrable or selected, which `registration_propensity` and `assign_scope_and_registration` use to reconcile a business register with a tax-registration count;
- `FirmRules`, `FirmRuleOutputs` and `align_rule_outputs` form the seam to a rule engine, with named outputs keyed by firm id, plus `weighted_totals`;
- `read_entity_variables` reads a policyengine-core package's entity variables from source with `ast`, and `input_status_problems` and `export_schema_problems` check a build's input-status record and its export against them;
- `firms.receipts` sets model totals beside sourced official receipts, without inventing a gap for an unset input or a missing figure.

The UK firm port (#1706) is to be rebuilt on these and will pin that its outputs are unchanged. The firm-only `Frame` is not included: it needs `EntitySchema` root populations.
7 changes: 7 additions & 0 deletions changelog.d/1705-uk-firm-attributes.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
UK firms gain region and legal status, and the policyengine-uk firm table gains the five inputs that depend on them (microcosm#1705). `uk_runtime/firm_attributes.py` draws `ons_region_code` given SIC division × turnover band (ONS UK Business 2025, Table 8) and `ons_legal_status` given industry group × turnover band (Table 13), with seeded categorical draws per cell after calibration, falling back from the cell to the row total and then to the UK total. Legal status is also weighted by the employment band through Table 12 (see `1705-uk-firm-legal-status-employment.changed.md`). The two draws are independent given their cells. Table 15 (region × legal status) is held out: on the 20-iteration thinned 2024-25 test build (seed 42), the weighted in-frame joint distribution is 0.033 in total variation from it (0.035 once legal status is coupled to the employment band through Table 12). The tables are committed under `tests/fixtures/uk/firm_attributes_2025/` with workbook provenance, and `tools/extract_uk_firm_ons_attribute_tables.py --check` re-extracts them from the paper repository's workbook.

`to_policyengine_uk_firm_table` emits `firm_legal_form`, `firm_region`, `firm_in_england`, `firm_is_public_body` and `firm_is_charity` when both ONS columns are present, and the unchanged base table otherwise. It never falls back to policyengine-uk's defaults (`LONDON`, `COMPANY`). The legal-status mapping is in `1705-uk-firm-legal-status-mapping.changed.md`: statuses 5–7 map to `OTHER` (outside corporation tax), status 4 to `COMPANY`, statuses 4–6 set `firm_is_public_body` and status 7 sets `firm_is_charity`, all assumptions. `firm_in_england`, which policyengine-uk defines by the firm's property, comes from the enterprise's region. `UK_FIRM_POLICYENGINE_UK_INPUT_STATUS` records every one of policyengine-uk's formula-less firm inputs (71 at `0d1c25010`) as set, derived, assumed or not set; paybill, profit, capital expenditure, R&D, rateable value and the remaining flags stay unset, with no placeholder values, until sources arrive. The validator now refuses missing values in every column.

A committed snapshot of policyengine-uk's firm variables (`tests/fixtures/uk/policyengine_uk_firm_inputs.json`, from PolicyEngine/policyengine-uk#2940, refreshed with `tools/snapshot_policyengine_uk_firm_inputs.py`, which reads the source with `ast` and refuses a dirty checkout unless `--allow-dirty` is passed) lets an engine-free test check that every exported column is a policyengine-uk firm input and that every enum value is a member.

`uk_runtime/firm_target_candidates.py` declares value-free M2 target candidates: three ONS UK Business tables available as fixtures, and ONS UK Business Table 3, DBT business population estimates, ONS ABS, HMRC corporation tax (capital allowances included), R&D and PAYE RTI statistics, and MHCLG/VOA business rates pending Ledger sources. Each candidate names the policyengine-uk inputs it would inform. None is wired into the solver, and `uk/uk_firms_targets.json` is unchanged.
1 change: 1 addition & 0 deletions changelog.d/1705-uk-firm-export-layout.changed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
The UK firm export's layout is now a base table plus a registry of optional input groups (microcosm#1705). `uk_runtime/firm_table.py`'s `UK_FIRM_EXPORT_GROUPS` holds one `UKFirmExportGroup` per group, with the source columns that switch it on, the policyengine-uk and Microcosm-only columns it adds, the groups it extends, and how it fills and checks its columns; the first is `attributes` (the ONS region and legal status draws), and each later input group is one more entry. `to_policyengine_uk_firm_table` emits the base and every group whose source columns the rows carry, and `validate_uk_firm_table` accepts the base and each valid set of groups (`UK_FIRM_TABLE_LAYOUTS`) and runs each present group's checks. `uk_firm_table_columns` and `uk_firm_export_groups` give a set of groups' layout and the groups a population carries. The named layouts (`UK_FIRM_TABLE_COLUMNS`, `UK_FIRM_EXTENDED_TABLE_COLUMNS` and their policyengine-uk column constants) are now derived from the registry and unchanged, and a test pins that the same-seed test build exports the same columns, dtypes and values as before.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Condition the UK firm ONS legal status draw on employment as well as turnover (microcosm#1705), using ONS UK Business 2025 Table 12 (legal status by industry group and employment sizeband), so sole proprietors and partnerships no longer take large headcounts at their turnover cell's rate. The status-by-employment fit against Table 12 is in-sample, since Table 12 is now a draw input. About twice as much employment now sits in ONS legal statuses 4–7 (public corporations, central and local government, and non-profit bodies), which moves toward Table 12.
1 change: 1 addition & 0 deletions changelog.d/1705-uk-firm-legal-status-mapping.changed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
The UK firm export maps ONS legal status 4 (public corporation or nationalised body) to `COMPANY` and marks it `firm_is_public_body`, so policyengine-uk charges it corporation tax and excludes it from the Employment Allowance; it previously mapped to `OTHER` (microcosm#1705). Every status 7 body (non-profit body or mutual association) is now exported with `firm_is_charity`, an assumption since ONS does not split charities out, which gives it policyengine-uk's charitable rate relief. (Its Employment Allowance charity exception matters only for public bodies, and no status 7 body is one, so the allowance does not move.) Limited liability partnerships are not drawn apart: ONS does not name them and they most likely sit with companies (status 1), a caveat only. The build receipt's `data_years` now also records the year each input group's source describes (`ons_attributes` for the ONS UK Business 2025 tables), apart from `rule_period`.
5 changes: 5 additions & 0 deletions changelog.d/1705-uk-firm-local-build.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
A local UK firm build and a policyengine-uk rules adapter (microcosm#1705).

`tools/build_uk_firms.py` (`uk_runtime/firm_build.build_uk_firm_dataset`) runs generation and the policyengine-uk table export. It writes `uk_firms.parquet` and `uk_firms.receipt.json`. The receipt records the vintage, seed, rule period, configuration, input and output sha256s, accuracy, target diagnostics and rules provenance, with no timestamps or paths. `--rules` is required and has no default. The build has no publish or staging path.

`uk_runtime/firm_policyengine_uk_rules.PolicyEngineUKFirmRules` implements the `UKFirmRules` seam on policyengine-uk's firm entity (PolicyEngine/policyengine-uk#2940). It builds a firm dataset from the candidate table and reads `firm_vat_liability_if_registered` for the tax year's start year. It imports policyengine-uk only when run, and raises a clear error if the installed policyengine-uk has no firm entity, as released versions do not. CI tests it with a fake simulation. Locally, against #2940 at `efeb6f6de` (not reproducible exactly, because that checkout had uncommitted changes outside VAT), it matched the standard-rate formula computed in float32 exactly on a 295,271-row thinned 2024-25 table. Against a float64 computation the largest difference was £1.25 (relative 3.1e-6), at firms with £10m–£50m turnover, because policyengine-uk stores firm amounts as float32. Partial exemption was not exercised.
7 changes: 7 additions & 0 deletions changelog.d/1705-uk-firm-paper-parity.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
The UK firm generator (`uk_runtime/firm_generation.py`) now follows `PolicyEngine/firm-microsim-paper` (microcosm#1705). Employment is drawn per sector from the ONS sector-by-employment rows. Weights are calibrated on two declared universes: the ONS VAT/PAYE frame (a new population row and the employment rows count frame rows only), and the HMRC VAT-registered subset, whose trader-count and net-VAT rows weight each frame firm by its band's registration propensity (HMRC count over frame mass, paper issue #37). Zero-turnover HMRC traders join the solve as an out-of-frame stratum, with a new Negative_or_Zero trader-count row. HMRC sector counts are rescaled to the band total, as the paper does, because they include traders of unknown band. Turnover is drawn uniformly inside each ONS band (log-uniform in the open band), and the £1-to-threshold net-VAT band is no longer calibrated. Optional stratified thinning (`sample_window_fraction`, `sample_tail_fraction`, `UKFirmGenerationConfig.fast()`) keeps every SIC × band × window stratum's base-weighted total and passes base weights to the solver as initial weights. After calibration, `vat_scope` and `vat_registered` are assigned by seeded weighted selection per band. Rows gain `base_weight`, `in_frame` and `vat_scope`; `vat_liability_k` is now the liability if registered for registered rows and zero for the rest. Exported signatures change: `assign_employment` takes `sic_codes` instead of a firm count; `build_firm_target_matrix` takes `propensity`, `frame_mask` and `vat_liability_if_registered_k` and returns a SciPy CSR matrix and NumPy targets; `UKFirmTargetLayout.n_turnover` goes from 7 to 8 and `n_vat_bands` from 7 to 6; the unused `assign_vat_flags` and `calculate_vat_liability_values` are removed. `UKFirmGenerationConfig.with_vintage()` switches vintage and resets the threshold, which `dataclasses.replace` does not.

Three new modules sit beside it. `uk_runtime/firm_rules.py` is the rules seam: a `UKFirmRules` protocol whose outputs are keyed by `firm_id`, so a policyengine-uk firm-rules adapter can replace the Axiom VAT evaluator, which is now wrapped by `LegacyVATEvaluatorRules` and kept as an optional cross-check. `uk_runtime/firm_universe.py` holds thinning, propensity and scope/registration selection. `uk_runtime/firm_table.py` exports a firm table with policyengine-uk's firm column names in pounds (`to_policyengine_uk_firm_table`), with the input-VAT imputation named as a data assumption. `docs/firm-support-plan.md` now names policyengine-uk as the firm rules home.

A parity test (`test_uk_firm_paper_parity.py`) runs a thinned 2024-25 build on the paper's committed processed tables and checks it against golden numbers from paper runs at commit aa1ce07; `tools/uk_firm_paper_parity.py` prints the full comparison locally.

Rules are evaluated in the tax year's start year as the policyengine-uk period (`rule_period_for_vintage`: 2024-25 is period 2024), because policyengine-uk gives period Y the parameter values in force on 30 April Y.
10 changes: 10 additions & 0 deletions changelog.d/1705-uk-firm-shared-mechanics-rewire.changed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
The UK firm port now runs on the country-neutral `microcosm.build.firms` layer (#1705):
- `firm_universe` uses its thinning and the two-universe functions, with the HMRC VAT bands declared as `UK_VAT_REGISTRATION_SPEC`;
- `firm_rules.UKFirmRuleOutputs` is a `FirmRuleOutputs` carrying `vat_liability_if_registered`;
- band turnover is drawn with `draw_in_band`;
- the policyengine-uk snapshot tool reads with `read_entity_variables`;
- the receipts tool uses `firms.receipts`.

The same-seed thinned 2024-25 population is unchanged, compared exactly against the code before the rewire on the same `main`.

The build receipt now records the rule period apart from the years the source data describe (`data_years`). For 2024-25 the ONS frame's turnover is mostly from 2023-24 VAT returns (ONS UK Business 2025, note 4). The receipt also notes that a change dated later in the tax year, such as 1 January, is not apportioned unless the parameter is day-weighted.
1 change: 1 addition & 0 deletions changelog.d/1705-uk-firm-tax-adapter.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
`uk_runtime/firm_policyengine_uk_rules.evaluate_uk_firm_taxes` reads every policyengine-uk firm tax (VAT, employer NIC after the Employment Allowance, apprenticeship levy, corporation tax, bank surcharge and business rates, plus the Employment Allowance and automatic enrolment employer contribution as informational outputs) for an exported UK firm table, handing policyengine-uk only its firm inputs and keying each value by `firm_id`; `weighted_uk_firm_tax_totals` sums each output by `firm_weight` (microcosm#1705). It drops, with a warning, any other `firm_*` column that is not a known policyengine-uk input. Taxes whose inputs the export does not set yet come out as zero: corporation tax, the bank surcharge, business rates, employer NIC, the levy and auto-enrolment (no profit, rateable value, bank flag or paybill).
1 change: 1 addition & 0 deletions changelog.d/1705-uk-firm-tax-receipts.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
`tools/compare_uk_firm_taxes_to_receipts.py` compares weighted policyengine-uk firm tax totals for 2024-25 with official receipts (HMRC cash receipts for VAT, employer NICs, Apprenticeship Levy, onshore corporation tax and Bank Surcharge; MHCLG NNDR3 England business rates), committed with URL, edition and access date in `tests/fixtures/uk/firm_tax_receipts_2024_25.csv` (microcosm#1705). It refuses a tax total without an explicit `inputs_populated` flag, prints "input not populated" rather than a gap where a tax's inputs are unset, flags the VAT row as an in-sample check because the generator is calibrated to HMRC VAT liability, and flags the employer NICs and Apprenticeship Levy rows as resting on an assumed paybill once one is supplied, so they are not a validation. Each source in the fixture's provenance file records the SHA-256 of the downloaded data file (HMRC NS_Table.ods and MHCLG NNDR3 Table 1 ODS), and a test requires it.
1 change: 1 addition & 0 deletions changelog.d/258-uk-firm-input-ratio.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
The UK firm generator's input-cost ratio now matches the corrected paper imputation, `0.2 + Beta(4, 2) × 0.6` with sector shifts and noise, clamped to [0.1, 0.95], instead of `0.3 + Beta(4, 2)` clamped to [0.6, 1.5], a ratio centred near 0.97 that allowed inputs up to 1.5 times turnover (microcosm#258). The 0.20 VAT rate is applied by the rules engine, not the generator (the firm table's `firm_input_vat` imputation aside).
1 change: 1 addition & 0 deletions changelog.d/636-uk-firm-public-solver.changed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
The UK firm generator solves its weights with the public `microcosm.calibrate.solve.solve_constraint_system` on a float32 sparse matrix, instead of the solver's private `_optimize` (microcosm#636). A local check on the small test fixture, across three configurations, gave weights bit-identical to the old path; CI does not pin this, and a test now refuses any private import from `microcosm.calibrate`.
Loading
Loading