Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
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.
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`.
68 changes: 55 additions & 13 deletions docs/firm-support-plan.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,44 @@ Microcosm should support firms as a first-class population while keeping the
same boundary that now applies to person and household calibration:

- Ledger is the only source of calibration target values and target contracts.
- Axiom is the executable policy/rules surface for VAT liabilities.
- policyengine-uk is the executable policy/rules surface for firm taxes: VAT,
and later corporation tax, employer NICs, the apprenticeship levy and
business rates, through its `Firm` entity (PolicyEngine/policyengine-uk#2939).
Axiom's UK VAT RuleSpec stays available as an optional cross-check, not as
the rules home.
- Microcosm owns frame construction, model features, target activation, solver
inputs, diagnostics, and published population artifacts.

The firm microsim paper remains a reference implementation and validation
baseline. It should not become the long-term source of target values, policy
logic, or release artifacts.

## Status

Tracking issue: microcosm#1705. The first step brings
`uk_runtime/firm_generation.py` up to the paper (sector-conditional employment,
two-universe calibration with per-band registration propensity, stratified
thinning with base weights, `in_frame` and `vat_scope` flags), moves it onto the
public solver (microcosm#636) and fixes the input-ratio imputation
(microcosm#258). It adds the rules seam (`uk_runtime/firm_rules.py`: a
`UKFirmRules` protocol whose outputs are keyed by `firm_id`) and a firm table
export with policyengine-uk's firm column names (`uk_runtime/firm_table.py`).
The existing Axiom VAT evaluator is wrapped behind the seam.
`uk_runtime/firm_policyengine_uk_rules.py` adds `PolicyEngineUKFirmRules`, which
runs policyengine-uk's firm entity on the candidate table and reads
`firm_vat_liability_if_registered`. It is tested engine-free with a fake
simulation; the released policyengine-uk has no firm entity yet, so its only
real-engine check is local, against PolicyEngine/policyengine-uk#2940.
`tools/build_uk_firms.py` (`uk_runtime/firm_build.py`) runs a local UK firm
build: generation and export to `uk_firms.parquet` with a JSON receipt of
inputs, configuration, rule period, data years, accuracy and rules provenance.
It has no publish or staging path. The country-neutral pieces (band draws,
thinning, the two-universe calibration, the rules seam, the engine-input
checks and the receipts comparison) live in `microcosm.build.firms`. A parity test on the
paper's committed 2024-25 tables (`test_uk_firm_paper_parity.py`) checks the
generator against golden numbers from paper runs, and
`tools/uk_firm_paper_parity.py` prints the full comparison locally.

## External Prerequisites

The first integration should depend on these upstream artifacts:
Expand All @@ -21,7 +51,10 @@ The first integration should depend on these upstream artifacts:
- `hmrc-vat-firm-targets-2024-25`
- Ledger target profile:
- `uk_firms`
- Axiom UK RuleSpec:
- policyengine-uk firm variables (rules home), once the `Firm` entity merges:
- `firm_vat_liability_if_registered`, `firm_vat`, `firm_vat_registered`
- later: corporation tax, employer NICs, apprenticeship levy, business rates
- Axiom UK RuleSpec (optional cross-check only):
- `uk:policies/govuk/vat#firm_must_register_for_vat`
- `uk:policies/govuk/vat#firm_vat_registered`
- `uk:policies/govuk/vat#firm_treated_as_vat_registered`
Expand All @@ -30,7 +63,8 @@ The first integration should depend on these upstream artifacts:
- `uk:policies/govuk/vat#net_vat_liability`

Microcosm should reject a UK firm build if those Ledger packages/profile are not
available. It should not fall back to repo-local CSV targets.
available. A build needs one rules engine (policyengine-uk once its firm entity
is released; Axiom is accepted only as a cross-check or a stand-in until then). It should not fall back to repo-local CSV targets.

## Phase 1: Frame Contract

Expand Down Expand Up @@ -76,9 +110,16 @@ Acceptance gates:
- Diagnostics include source package ID, source record ID, aggregate fact key,
period, geography, and target activation status.

## Phase 3: Axiom VAT Metrics
## Phase 3: Rules-engine VAT Metrics

Firm metrics come through the `UKFirmRules` seam. The production adapter is
`PolicyEngineUKFirmRules` (M4; VAT only so far, verified locally against the
unreleased policyengine-uk firm entity), which builds a
policyengine-uk simulation from the firm table (policyengine-uk column names)
and reads its firm variables. The Axiom adapter below stays as an optional
cross-check, and builds will record any difference between the two.

Add an Axiom-backed `RulesEngine` adapter path for firm metrics:
For the Axiom cross-check:

- Convert firm entity rows into the Axiom input variables used by
`uk:policies/govuk/vat`.
Expand All @@ -100,9 +141,9 @@ Acceptance gates:

- Metric outputs are deterministic for a fixed input frame.
- `net_vat_liability` supports negative values for repayment positions.
- Axiom rule IDs appear in metric provenance.
- The rules engine and its variable or rule IDs appear in metric provenance.
- No handwritten TypeScript/Python VAT calculation is used as a substitute for
Axiom.
the rules engine.

## Phase 4: UK Firm Base Builder

Expand Down Expand Up @@ -140,21 +181,22 @@ person-household-firm calibration are implemented.
Acceptance gates:

- Solver diagnostics report absolute and relative error by Ledger fact key.
- Release trace contains the Ledger target profile ID and Axiom RuleSpec rule
IDs used for VAT metrics.
- Release trace contains the Ledger target profile ID and the rules engine
(policyengine-uk version and variables, or Axiom rule IDs for a cross-check)
used for VAT metrics.
- Static validation compares against the firm microsim paper's published target
groups, but those paper CSVs are validation inputs only.
- CI covers the target resolver, Axiom metric adapter, frame schema, and a small
- CI covers the target resolver, rules adapters, frame schema, and a small
synthetic firm calibration fixture.

## Open Design Questions

- Whether `firm` should remain a standalone entity or become an owned entity
linked to persons/households in the default UK frame.
- How to reconcile source-observed VAT registration with Axiom's mandatory and
voluntary registration rules.
- How to reconcile source-observed VAT registration with the rules engine's
mandatory and voluntary registration rules.
- How to represent sector mappings between SIC, HMRC trade sectors, and future
Axiom supply classifications.
supply classifications in policyengine-uk.
- Whether future local firm distributions should be calibrated from Ledger
targets, allocated from national targets, or both with explicit source
hierarchy rules.
18 changes: 14 additions & 4 deletions packages/microcosm-build/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,10 +102,20 @@ data.
This is not yet the production firm microsimulation path: Ledger currently
covers the current paper target surface used by the adapter, including ONS
SIC-by-turnover, ONS SIC-by-employment, HMRC VAT-registered firms by SIC, and
HMRC net VAT liability by SIC. VAT liability is now an explicit rule-evaluator
input to generation; production runs should provide an Axiom RuleSpec artifact
through `AxiomVATRuleEvaluator`. The processed-table reader remains only for
paper-repository migration comparisons.
HMRC net VAT liability by SIC. VAT liability comes from a rules engine through
the `UKFirmRules` seam in `uk_runtime/firm_rules.py`, whose outputs are keyed by
`firm_id`. The firm rules home is policyengine-uk: `PolicyEngineUKFirmRules`
(`uk_runtime/firm_policyengine_uk_rules.py`) reads its firm VAT liability once
the policyengine-uk firm entity is installed. An Axiom RuleSpec artifact can
still be passed through `AxiomVATRuleEvaluator`, which the seam wraps
(`LegacyVATEvaluatorRules`), as an optional cross-check. `tools/build_uk_firms.py`
runs a local build to `uk_firms.parquet` with a JSON receipt. Calibration uses the paper's two universes (ONS frame
rows, and HMRC registered-trader rows weighted by per-band registration
propensity), optional stratified thinning (`UKFirmGenerationConfig.fast()`), and
the public `solve_constraint_system`. `uk_runtime/firm_table.py` exports the
result with policyengine-uk's firm column names. The processed-table reader
remains for paper-repository migration comparisons; `tools/uk_firm_paper_parity.py`
runs that comparison locally.

Build the row-wise local-geography H5 from a compact Microcosm UK H5 with:

Expand Down
63 changes: 63 additions & 0 deletions packages/microcosm-build/src/microcosm/build/firms/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
"""Country-neutral mechanics for synthetic firm populations.

A country's firm build draws candidate firms from published band counts,
thins them for speed, calibrates them against a business register and a
tax-registration count, and hands them to a rule engine. The pieces here know
nothing about any country: band edges, band roles, registered counts and rule
engines all arrive as arguments. They come from the UK firm port in
PolicyEngine/microcosm#1706, which is to be rebuilt on them.

- :mod:`.bands`: values drawn inside a band from uniforms the caller supplies;
- :mod:`.thinning`: stratified thinning with exact base weights;
- :mod:`.registration`: the two-universe treatment of a register and a
tax-registration count, set by a :class:`RegistrationSpec`;
- :mod:`.rules`: the seam to a rule engine, with outputs keyed by firm id;
- :mod:`.engine_inputs`: a rule engine's entity inputs read from source, the
input-status record a build keeps, and checks of an export against both;
- :mod:`.receipts`: model totals beside sourced official receipts, as a
diagnostic table that never invents a gap.

The firm-only ``Frame`` is not here yet: it needs ``EntitySchema`` to allow a
root population with no person or group entities.
"""

from __future__ import annotations

from .bands import draw_in_band
from .engine_inputs import (
EXPORTED_INPUT_STATUSES,
INPUT_STATUSES,
EntityVariables,
export_schema_problems,
input_status_problems,
read_entity_variables,
)
from .registration import (
BAND_ROLES,
RegistrationSpec,
assign_scope_and_registration,
registration_propensity,
select_to_weighted_target,
)
from .rules import FirmRuleOutputs, FirmRules, align_rule_outputs, weighted_totals
from .thinning import stratified_thin

__all__ = [
"BAND_ROLES",
"EXPORTED_INPUT_STATUSES",
"INPUT_STATUSES",
"EntityVariables",
"FirmRuleOutputs",
"FirmRules",
"RegistrationSpec",
"align_rule_outputs",
"assign_scope_and_registration",
"draw_in_band",
"export_schema_problems",
"input_status_problems",
"read_entity_variables",
"registration_propensity",
"select_to_weighted_target",
"stratified_thin",
"weighted_totals",
]
Loading
Loading