diff --git a/changelog.d/1705-shared-firm-mechanics.added.md b/changelog.d/1705-shared-firm-mechanics.added.md new file mode 100644 index 0000000000..3eda6eba3e --- /dev/null +++ b/changelog.d/1705-shared-firm-mechanics.added.md @@ -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. diff --git a/changelog.d/1705-uk-firm-local-build.added.md b/changelog.d/1705-uk-firm-local-build.added.md new file mode 100644 index 0000000000..4df9e48f51 --- /dev/null +++ b/changelog.d/1705-uk-firm-local-build.added.md @@ -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. diff --git a/changelog.d/1705-uk-firm-paper-parity.added.md b/changelog.d/1705-uk-firm-paper-parity.added.md new file mode 100644 index 0000000000..03849e6094 --- /dev/null +++ b/changelog.d/1705-uk-firm-paper-parity.added.md @@ -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. diff --git a/changelog.d/1705-uk-firm-shared-mechanics-rewire.changed.md b/changelog.d/1705-uk-firm-shared-mechanics-rewire.changed.md new file mode 100644 index 0000000000..4928b19cfb --- /dev/null +++ b/changelog.d/1705-uk-firm-shared-mechanics-rewire.changed.md @@ -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. diff --git a/changelog.d/1705-uk-firm-tax-adapter.added.md b/changelog.d/1705-uk-firm-tax-adapter.added.md new file mode 100644 index 0000000000..724880c9e3 --- /dev/null +++ b/changelog.d/1705-uk-firm-tax-adapter.added.md @@ -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). diff --git a/changelog.d/1705-uk-firm-tax-receipts.added.md b/changelog.d/1705-uk-firm-tax-receipts.added.md new file mode 100644 index 0000000000..9aca775482 --- /dev/null +++ b/changelog.d/1705-uk-firm-tax-receipts.added.md @@ -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. diff --git a/changelog.d/258-uk-firm-input-ratio.fixed.md b/changelog.d/258-uk-firm-input-ratio.fixed.md new file mode 100644 index 0000000000..4bcf103899 --- /dev/null +++ b/changelog.d/258-uk-firm-input-ratio.fixed.md @@ -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). diff --git a/changelog.d/636-uk-firm-public-solver.changed.md b/changelog.d/636-uk-firm-public-solver.changed.md new file mode 100644 index 0000000000..389cc3c4c5 --- /dev/null +++ b/changelog.d/636-uk-firm-public-solver.changed.md @@ -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`. diff --git a/docs/firm-support-plan.md b/docs/firm-support-plan.md index ee26c8370e..eb6e779442 100644 --- a/docs/firm-support-plan.md +++ b/docs/firm-support-plan.md @@ -4,7 +4,11 @@ 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. @@ -12,6 +16,32 @@ 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: @@ -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` @@ -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 @@ -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`. @@ -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 @@ -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. diff --git a/packages/microcosm-build/README.md b/packages/microcosm-build/README.md index 1e34c75f78..c90305a14a 100644 --- a/packages/microcosm-build/README.md +++ b/packages/microcosm-build/README.md @@ -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: diff --git a/packages/microcosm-build/src/microcosm/build/firms/__init__.py b/packages/microcosm-build/src/microcosm/build/firms/__init__.py new file mode 100644 index 0000000000..59f09aab60 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/firms/__init__.py @@ -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", +] diff --git a/packages/microcosm-build/src/microcosm/build/firms/_arrays.py b/packages/microcosm-build/src/microcosm/build/firms/_arrays.py new file mode 100644 index 0000000000..629333700b --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/firms/_arrays.py @@ -0,0 +1,16 @@ +"""Array argument checks shared by the firm mechanics.""" + +from __future__ import annotations + +import numpy as np + + +def as_1d(name: str, values: object, length: int | None = None) -> np.ndarray: + """``values`` as a one-dimensional array, optionally of ``length`` entries.""" + + array = np.asarray(values) + if array.ndim != 1: + raise ValueError(f"{name} must be one-dimensional, got shape {array.shape}") + if length is not None and len(array) != length: + raise ValueError(f"{name} has {len(array)} entries; expected {length}") + return array diff --git a/packages/microcosm-build/src/microcosm/build/firms/bands.py b/packages/microcosm-build/src/microcosm/build/firms/bands.py new file mode 100644 index 0000000000..8539703093 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/firms/bands.py @@ -0,0 +1,58 @@ +"""Values drawn inside a published band. + +Business statistics publish counts by band (turnover, employment), not +values. A firm in band ``[lower, upper)`` gets a value inside its band: +uniform for closed bands, log-uniform for an open top band whose upper edge is +a declared cap. Both keep every value inside its source band. + +The caller draws the uniforms, so the random stream stays with the caller: +:func:`draw_in_band` is a pure transform. It works on NumPy arrays and on +torch tensors alike and returns the type and dtype it was given, so a caller +that draws float32 uniforms from torch gets the same float32 values it +computed before this module existed. +""" + +from __future__ import annotations + +import math +from typing import Any + +import numpy as np + +__all__ = ["draw_in_band"] + + +def draw_in_band( + unit: Any, + lower: float, + upper: float, + *, + log_uniform: bool = False, + floor: float = 0.0, +) -> Any: + """Map uniforms in ``[0, 1)`` to values in ``[max(lower, floor), upper)``. + + Args: + unit: Uniform draws in ``[0, 1)``, a NumPy array or a torch tensor. + lower: The band's lower edge. + upper: The band's upper edge (an open band's declared cap). + log_uniform: Draw log-uniformly, for an open top band. The low edge + must then be positive. + floor: The smallest value drawn, applied to ``lower``; a band whose + lower edge is zero draws from ``floor`` instead. + + Returns: + Values the same shape, type and dtype as ``unit``. + """ + + low = max(float(lower), float(floor)) + high = float(upper) + if high < low: + raise ValueError(f"band upper edge {high} lies below its low edge {low}") + if log_uniform: + if low <= 0: + raise ValueError(f"a log-uniform band needs a positive low edge, got {low}") + exponent = math.log(low) + unit * (math.log(high) - math.log(low)) + # torch tensors carry .exp(); NumPy arrays and scalars do not. + return exponent.exp() if hasattr(exponent, "exp") else np.exp(exponent) + return low + unit * (high - low) diff --git a/packages/microcosm-build/src/microcosm/build/firms/engine_inputs.py b/packages/microcosm-build/src/microcosm/build/firms/engine_inputs.py new file mode 100644 index 0000000000..94667b9086 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/firms/engine_inputs.py @@ -0,0 +1,408 @@ +"""A rule engine's entity inputs, read from source, and checks against them. + +A firm table loads into a country model only if every exported column is one +of the model's formula-less variables on the firm entity, with the right value +type and enum members. This module reads those variables from a +policyengine-core country package's source with ``ast`` (it never imports the +package), so engine-free tests can check an export against a committed +snapshot. It also holds the input-status vocabulary a build uses to record how +it fills each input, and the checks that keep that record complete. + +- :func:`read_entity_variables` reads every ``Variable`` subclass whose + ``entity`` is a given name: value type, unit, default, enum members (the + ``possible_values`` class resolved through the defining module's imports), + definition period, whether it has a formula (a ``formula`` or + ``formula_*`` method or attribute, ``adds`` or ``subtracts``) and its file. + A variable created at runtime is not in the source and so not read. +- :func:`input_status_problems` checks a build's input-status record against + the engine's inputs. +- :func:`export_schema_problems` checks an exported table's columns, dtypes + and enum values against the variables read. +""" + +from __future__ import annotations + +import ast +from collections.abc import Iterable, Mapping +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Final + +import pandas as pd + +__all__ = [ + "EXPORTED_INPUT_STATUSES", + "INPUT_STATUSES", + "EntityVariables", + "export_schema_problems", + "input_status_problems", + "read_entity_variables", +] + +#: How a build fills an engine input: +#: +#: - ``set``: mapped directly from a generator column or a source draw; +#: - ``derived``: computed from other columns by a rule; +#: - ``assumed``: carries a data assumption beyond the source; +#: - ``not_set``: not exported; the engine's default applies. +INPUT_STATUSES: Final[tuple[str, ...]] = ("set", "derived", "assumed", "not_set") + +#: The statuses of inputs a build exports. +EXPORTED_INPUT_STATUSES: Final[tuple[str, ...]] = ("set", "derived", "assumed") + +_DTYPE_KINDS: Final[Mapping[str, str]] = {"float": "f", "int": "i", "bool": "b"} + + +@dataclass(frozen=True) +class EntityVariables: + """The variables a country package defines, as read from its source. + + ``variables`` maps each variable on the entity to its record (see + :func:`read_entity_variables`); ``input_names`` lists the formula-less + ones, sorted; ``variable_names`` is every variable the package defines, + on any entity. + """ + + variables: dict[str, dict[str, Any]] + input_names: list[str] + variable_names: list[str] + + +@dataclass +class _Module: + name: str + path: Path + tree: ast.Module + #: Local name -> (module, attribute) for ``from module import attribute``. + imports: dict[str, tuple[str, str]] = field(default_factory=dict) + #: Local alias -> module for ``import module`` and ``import module as m``. + module_aliases: dict[str, str] = field(default_factory=dict) + classes: dict[str, ast.ClassDef] = field(default_factory=dict) + + +def _module_name(package_dir: Path, path: Path) -> str: + parts = list(path.relative_to(package_dir.parent).with_suffix("").parts) + if parts[-1] == "__init__": + parts.pop() + return ".".join(parts) + + +def _resolve_relative(module: _Module, node: ast.ImportFrom) -> str: + if not node.level: + return node.module or "" + package = module.name.split(".") + if module.path.name != "__init__.py": + package = package[:-1] + if node.level > 1: + package = package[: len(package) - (node.level - 1)] + return ".".join([*package, *([node.module] if node.module else [])]) + + +def _read_modules(package_dir: Path) -> dict[str, _Module]: + modules: dict[str, _Module] = {} + tests_dir = package_dir / "tests" + for path in sorted(package_dir.rglob("*.py")): + if tests_dir in path.parents: + continue + tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) + module = _Module(name=_module_name(package_dir, path), path=path, tree=tree) + for node in tree.body: + if isinstance(node, ast.ImportFrom): + source = _resolve_relative(module, node) + for alias in node.names: + if alias.name != "*": + module.imports[alias.asname or alias.name] = ( + source, + alias.name, + ) + elif isinstance(node, ast.Import): + for alias in node.names: + module.module_aliases[alias.asname or alias.name] = alias.name + elif isinstance(node, ast.ClassDef): + module.classes[node.name] = node + modules[module.name] = module + return modules + + +def _base_names(node: ast.ClassDef) -> list[str]: + names = [] + for base in node.bases: + if isinstance(base, ast.Name): + names.append(base.id) + elif isinstance(base, ast.Attribute): + names.append(base.attr) + return names + + +def _assignments(node: ast.ClassDef) -> dict[str, ast.expr]: + values: dict[str, ast.expr] = {} + for statement in node.body: + if isinstance(statement, ast.Assign): + for target in statement.targets: + if isinstance(target, ast.Name): + values[target.id] = statement.value + elif isinstance(statement, ast.AnnAssign) and statement.value is not None: + if isinstance(statement.target, ast.Name): + values[statement.target.id] = statement.value + return values + + +def _is_formula_name(name: str) -> bool: + return name == "formula" or name.startswith("formula_") + + +def _has_formula(node: ast.ClassDef) -> bool: + for statement in node.body: + if isinstance(statement, (ast.FunctionDef, ast.AsyncFunctionDef)): + if _is_formula_name(statement.name): + return True + return any( + _is_formula_name(name) or name in ("adds", "subtracts") + for name in _assignments(node) + ) + + +def _enum_members(node: ast.ClassDef) -> list[str]: + members = [] + for statement in node.body: + if isinstance(statement, ast.Assign): + for target in statement.targets: + if isinstance(target, ast.Name) and not target.id.startswith("_"): + members.append(target.id) + return members + + +def _resolve_class( + modules: dict[str, _Module], + module: _Module, + name: str, + seen: frozenset = frozenset(), +) -> tuple[_Module, ast.ClassDef]: + """The class ``name`` refers to in ``module``, following its imports.""" + + key = (module.name, name) + if key in seen: + raise ValueError(f"Import cycle resolving {name} in {module.name}.") + if name in module.classes: + return module, module.classes[name] + if name in module.imports: + source, attribute = module.imports[name] + if source in modules: + return _resolve_class(modules, modules[source], attribute, seen | {key}) + submodule = f"{source}.{attribute}" + if submodule in modules: + raise ValueError(f"{name} in {module.name} is a module, not a class.") + raise ValueError(f"Cannot resolve class {name} from {module.name}.") + + +def _resolve_enum( + modules: dict[str, _Module], module: _Module, expression: ast.expr +) -> tuple[str, str, list[str]]: + if isinstance(expression, ast.Name): + owner, node = _resolve_class(modules, module, expression.id) + elif isinstance(expression, ast.Attribute) and isinstance( + expression.value, ast.Name + ): + alias = module.module_aliases.get(expression.value.id) + target = modules.get(alias) if alias else None + if target is None: + source = module.imports.get(expression.value.id) + target = modules.get(".".join(source)) if source else None + if target is None: + raise ValueError(f"Cannot resolve {ast.unparse(expression)}.") + owner, node = _resolve_class(modules, target, expression.attr) + else: + raise ValueError(f"Cannot resolve possible_values {ast.unparse(expression)}.") + if "Enum" not in _base_names(node): + raise ValueError(f"{node.name} in {owner.name} is not an Enum.") + return node.name, owner.name, _enum_members(node) + + +def _literal_or_source(expression: ast.expr) -> Any: + try: + return ast.literal_eval(expression) + except ValueError: + return ast.unparse(expression) + + +def _definition_period(expression: ast.expr | None) -> str | None: + if expression is None: + return None + if isinstance(expression, ast.Name): + return expression.id.lower() + return _literal_or_source(expression) + + +def _variable_record( + modules: dict[str, _Module], + module: _Module, + node: ast.ClassDef, + package_dir: Path, +) -> dict[str, Any]: + values = _assignments(node) + enum = None + members: list[str] | None = None + if "possible_values" in values: + enum_name, enum_module, members = _resolve_enum( + modules, module, values["possible_values"] + ) + enum = {"name": enum_name, "module": enum_module} + default = values.get("default_value") + if default is None: + default_value = None + elif ( + members is not None + and isinstance(default, ast.Attribute) + and default.attr in members + ): + default_value = default.attr + else: + default_value = _literal_or_source(default) + unit = values.get("unit") + return { + "default_value": default_value, + "definition_period": _definition_period(values.get("definition_period")), + "enum": enum, + "enum_members": members, + "file": module.path.relative_to(package_dir).as_posix(), + "has_formula": _has_formula(node), + "name": node.name, + "unit": None if unit is None else _literal_or_source(unit), + "value_type": ast.unparse(values["value_type"]) + if "value_type" in values + else None, + } + + +def read_entity_variables(package_dir: Path, *, entity: str) -> EntityVariables: + """Read the variables on ``entity`` from a country package's source. + + ``package_dir`` is the package directory itself (for example + ``policyengine-uk/policyengine_uk``); its ``tests/`` directory is skipped. + ``entity`` is the entity class name the variables assign (for example + ``Firm``). Each record holds ``default_value``, ``definition_period``, + ``enum`` (``name`` and ``module``, or None), ``enum_members``, ``file`` + (relative to the package), ``has_formula``, ``name``, ``unit`` and + ``value_type``. + + Raises ``ValueError`` when the package defines no variable on the entity, + defines one twice, or names an enum it cannot resolve. + """ + + package_dir = Path(package_dir) + if not package_dir.is_dir(): + raise ValueError(f"{package_dir} is not a package directory.") + modules = _read_modules(package_dir) + variable_names: set[str] = set() + variables: dict[str, dict[str, Any]] = {} + for module in modules.values(): + for node in module.classes.values(): + if "Variable" not in _base_names(node): + continue + variable_names.add(node.name) + assigned = _assignments(node).get("entity") + if isinstance(assigned, ast.Name) and assigned.id == entity: + if node.name in variables: + raise ValueError(f"{entity} variable {node.name} is defined twice.") + variables[node.name] = _variable_record( + modules, module, node, package_dir + ) + if not variables: + raise ValueError(f"{package_dir} defines no {entity} variables.") + inputs = sorted( + name for name, variable in variables.items() if not variable["has_formula"] + ) + return EntityVariables( + variables=variables, + input_names=inputs, + variable_names=sorted(variable_names), + ) + + +def input_status_problems( + status: Mapping[str, str], + engine_inputs: Iterable[str], + *, + exported_columns: Iterable[str] | None = None, +) -> list[str]: + """What is wrong with a build's input-status record; empty when nothing. + + ``status`` maps every engine input to one of :data:`INPUT_STATUSES`. It + must cover exactly ``engine_inputs``. With ``exported_columns`` (the + engine inputs the fullest export writes), the inputs whose status is + exported (:data:`EXPORTED_INPUT_STATUSES`) must be exactly those columns. + """ + + problems = [] + unknown = sorted( + {value for value in status.values() if value not in INPUT_STATUSES} + ) + if unknown: + problems.append( + f"unknown input statuses {unknown}; choose from {INPUT_STATUSES}" + ) + inputs = set(engine_inputs) + missing = sorted(inputs - set(status)) + if missing: + problems.append(f"engine inputs without a status: {missing}") + extra = sorted(set(status) - inputs) + if extra: + problems.append(f"statuses for names that are not engine inputs: {extra}") + if exported_columns is not None: + exported = set(exported_columns) + claimed = { + name for name, value in status.items() if value in EXPORTED_INPUT_STATUSES + } + unexported = sorted(claimed - exported) + if unexported: + problems.append( + f"inputs marked exported that no export writes: {unexported}" + ) + unclaimed = sorted(exported - claimed) + if unclaimed: + problems.append(f"exported inputs marked not_set or missing: {unclaimed}") + return problems + + +def export_schema_problems( + table: pd.DataFrame, + variables: EntityVariables, + *, + columns: Iterable[str] | None = None, +) -> list[str]: + """What in ``table`` would not load as engine inputs; empty when nothing. + + Each checked column (``columns``, else every column of ``table``) must be + a formula-less variable in ``variables``. A float, int or bool variable + needs a column of that dtype kind; an enum variable needs string values + that are members of its enum. + """ + + inputs = set(variables.input_names) + problems = [] + for column in table.columns if columns is None else columns: + if column not in table.columns: + problems.append(f"{column}: not in the table") + continue + if column not in inputs: + problems.append(f"{column}: not a formula-less engine input") + continue + variable = variables.variables[column] + value_type = variable["value_type"] + if value_type == "Enum": + values = table[column].to_numpy() + if not all(isinstance(value, str) for value in values): + problems.append(f"{column}: enum values must be member names") + continue + outside = sorted(set(values) - set(variable["enum_members"] or ())) + if outside: + problems.append(f"{column}: values {outside[:5]} are not enum members") + elif value_type in _DTYPE_KINDS: + kind = table[column].dtype.kind + if kind != _DTYPE_KINDS[value_type]: + problems.append( + f"{column}: dtype {table[column].dtype} for value type {value_type}" + ) + else: + problems.append(f"{column}: unchecked value type {value_type!r}") + return problems diff --git a/packages/microcosm-build/src/microcosm/build/firms/receipts.py b/packages/microcosm-build/src/microcosm/build/firms/receipts.py new file mode 100644 index 0000000000..1008ab161b --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/firms/receipts.py @@ -0,0 +1,242 @@ +"""Model totals beside official receipts, as a sourced diagnostic table. + +A firm build's tax totals are compared with official receipts to see where +the data fall short. The comparison is a diagnostic, never a calibration +target, and it must not invent a gap: + +- a total whose inputs the build leaves unset prints :data:`INPUT_NOT_POPULATED` + rather than a -100% shortfall, so every total needs an explicit + ``populated`` flag; +- a name with no official figure prints :data:`NO_OFFICIAL_FIGURE`; +- every official figure carries its publisher, title, edition, URL and access + date, or the receipts file is refused. + +The country supplies the receipts file, how money is formatted, and the +reasons each model measure differs from the official one. +""" + +from __future__ import annotations + +import csv +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass +from pathlib import Path +from typing import Final + +__all__ = [ + "INPUT_NOT_POPULATED", + "NO_MODEL_TOTAL", + "NO_OFFICIAL_FIGURE", + "RECEIPT_SOURCE_COLUMNS", + "ComparisonRow", + "Receipt", + "build_comparison_rows", + "compare_total", + "read_receipts", + "render_comparison_markdown", +] + +INPUT_NOT_POPULATED: Final = "input not populated" +NO_OFFICIAL_FIGURE: Final = "no official figure fetched" +NO_MODEL_TOTAL: Final = "no model total supplied" + +#: Columns every row with an official figure must fill. +RECEIPT_SOURCE_COLUMNS: Final[tuple[str, ...]] = ( + "measure", + "source_publisher", + "source_title", + "edition", + "url", + "accessed", +) +#: Columns a receipts file carries besides the name and value columns. +_RECEIPT_TEXT_COLUMNS: Final[tuple[str, ...]] = ( + "period", + *RECEIPT_SOURCE_COLUMNS, + "note", +) + + +@dataclass(frozen=True) +class Receipt: + """One official figure and where it comes from.""" + + name: str + official_value: float | None + period: str + measure: str + source_publisher: str + source_title: str + edition: str + url: str + accessed: str + note: str + + +@dataclass(frozen=True) +class ComparisonRow: + """One row of the comparison table, already formatted.""" + + name: str + model: str + official: str + gap: str + ratio: str + reason: str + + +def read_receipts( + path: Path, *, name_column: str, value_column: str +) -> dict[str, Receipt]: + """Read a receipts CSV, refusing missing columns, repeats or unsourced figures. + + The file needs ``name_column``, ``value_column`` (blank when there is no + official figure), ``period``, the :data:`RECEIPT_SOURCE_COLUMNS` and + ``note``. Receipts keep the file's row order. + """ + + required = (name_column, value_column, *_RECEIPT_TEXT_COLUMNS) + with Path(path).open(newline="", encoding="utf-8") as handle: + reader = csv.DictReader(handle) + missing = [c for c in required if c not in (reader.fieldnames or ())] + if missing: + raise ValueError(f"{path}: missing columns {missing}") + receipts: dict[str, Receipt] = {} + for row in reader: + name = row[name_column].strip() + if name in receipts: + raise ValueError(f"{path}: duplicate {name_column} {name!r}") + raw = row[value_column].strip() + value = float(raw) if raw else None + if value is not None: + unsourced = [c for c in RECEIPT_SOURCE_COLUMNS if not row[c].strip()] + if unsourced: + raise ValueError(f"{path}: {name} has a figure but no {unsourced}") + receipts[name] = Receipt( + name=name, + official_value=value, + **{c: row[c].strip() for c in _RECEIPT_TEXT_COLUMNS}, + ) + return receipts + + +def compare_total( + name: str, + *, + model_total: float | None, + populated: bool, + official_value: float | None, + reasons: Sequence[str], + format_value: Callable[[float], str], +) -> ComparisonRow: + """One table row. No gap or ratio unless both sides are real figures. + + ``reasons`` are joined, in order, into the row's reason text. + """ + + official = ( + format_value(official_value) + if official_value is not None + else NO_OFFICIAL_FIGURE + ) + if not populated: + model = gap = ratio = INPUT_NOT_POPULATED + elif model_total is None: + model = gap = ratio = NO_MODEL_TOTAL + else: + model = format_value(model_total) + if official_value is None: + gap = ratio = NO_OFFICIAL_FIGURE + else: + difference = model_total - official_value + gap = format_value(difference) + if official_value: + gap += f" ({difference / official_value:+.1%})" + ratio = f"{model_total / official_value:.3f}" + else: + ratio = "official figure is zero" + return ComparisonRow(name, model, official, gap, ratio, " ".join(reasons)) + + +def build_comparison_rows( + totals: Mapping[str, float | None], + populated: Mapping[str, object], + receipts: Mapping[str, Receipt], + *, + reasons_for: Callable[[str, Receipt | None], Sequence[str]], + format_value: Callable[[float], str], +) -> list[ComparisonRow]: + """Rows in receipts order, then any names only the model has, sorted. + + Every name in ``totals`` needs a true/false ``populated`` flag; without + one an unset input would print as a -100% gap, so it is refused. A name + in the receipts that the model left out entirely reads + :data:`NO_MODEL_TOTAL`. + """ + + unflagged = sorted( + name for name in totals if not isinstance(populated.get(name), bool) + ) + if unflagged: + raise ValueError( + f"totals {unflagged} have no true/false populated flag; without it " + "an unset input would print as a -100% gap" + ) + names = list(receipts) + sorted(set(totals) - set(receipts)) + rows = [] + for name in names: + total = totals.get(name) + receipt = receipts.get(name) + rows.append( + compare_total( + name, + model_total=None if total is None else float(total), + populated=bool(populated.get(name, True)), + official_value=None if receipt is None else receipt.official_value, + reasons=reasons_for(name, receipt), + format_value=format_value, + ) + ) + return rows + + +def _cell(text: str) -> str: + return text.replace("|", "\\|").replace("\n", " ") + + +def render_comparison_markdown( + rows: Sequence[ComparisonRow], + receipts: Mapping[str, Receipt], + *, + title: str, + name_header: str, + note: str | None = None, +) -> str: + """The comparison as markdown: a table, then a source line per receipt.""" + + lines = [ + f"# {title}", + "", + "Gap is model less official (share of official); ratio is model / official.", + ] + if note: + lines += ["", f"Model run note: {note}"] + lines += [ + "", + f"| {name_header} | Model total | Official | Gap | Ratio | Reason / caveat |", + "| --- | --- | --- | --- | --- | --- |", + ] + for row in rows: + cells = (row.name, row.model, row.official, row.gap, row.ratio, row.reason) + lines.append("| " + " | ".join(_cell(v) for v in cells) + " |") + lines += ["", "## Sources", ""] + for receipt in receipts.values(): + if receipt.official_value is None: + lines.append(f"- `{receipt.name}`: {NO_OFFICIAL_FIGURE}. {receipt.note}") + else: + lines.append( + f"- `{receipt.name}`: {receipt.source_publisher}, " + f"{receipt.source_title}; {receipt.edition}; {receipt.url} " + f"(accessed {receipt.accessed}). {receipt.note}" + ) + return "\n".join(lines) + "\n" diff --git a/packages/microcosm-build/src/microcosm/build/firms/registration.py b/packages/microcosm-build/src/microcosm/build/firms/registration.py new file mode 100644 index 0000000000..5ba96dac47 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/firms/registration.py @@ -0,0 +1,251 @@ +"""Two universes: a business register and a tax-registration count. + +A firm build often calibrates to two populations that overlap but are not the +same. One is a business register (the frame), counted by band. The other is +a tax administration's count of registered traders by the same bands, which +includes traders outside the register and leaves out registered businesses +that are not registered for the tax. Each frame firm enters the calibration +with its band's registration propensity (registered traders divided by the +band's frame mass). After calibration, a weighted selection per band marks +which firms are in the tax's scope and which are registered. + +What differs by country is data, not code: the band labels and what each band +means for registration. A :class:`RegistrationSpec` declares them. Each band +has a role: + +- ``"excluded"``: frame firms in the band are neither in scope nor + registered, and their propensity is 0. Registered traders outside the frame + sit here (for example, traders with zero or negative turnover). +- ``"registrable"``: every frame firm in the band is in scope (it could + register), and a weighted selection reaching the band's registered count + is registered. This is the band below a registration threshold. +- ``"selected"``: a weighted selection reaching the band's registered count + is both in scope and registered; the rest of the band is out of scope. + These are the bands above a threshold, where an unregistered firm is + outside the tax (exempt, or registered for another tax only). + +Rows outside the frame (``frame_mask`` False) are registered traders by +construction: in scope, registered, with propensity 1. + +Registered counts arrive per call, aligned with the spec's bands. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Final + +import numpy as np + +from ._arrays import as_1d + +__all__ = [ + "BAND_ROLES", + "RegistrationSpec", + "assign_scope_and_registration", + "registration_propensity", + "select_to_weighted_target", +] + +#: The roles a band can take; see the module docstring. +BAND_ROLES: Final[tuple[str, ...]] = ("excluded", "registrable", "selected") + + +@dataclass(frozen=True) +class RegistrationSpec: + """A country's registration bands and the role each band plays. + + ``band_labels[b]`` names band ``b``; ``band_roles[b]`` is its role, one + of :data:`BAND_ROLES`. Band indices passed to the functions here index + these tuples. + """ + + band_labels: tuple[str, ...] + band_roles: tuple[str, ...] + + def __post_init__(self) -> None: + labels = tuple(str(label) for label in self.band_labels) + roles = tuple(str(role) for role in self.band_roles) + if not labels: + raise ValueError("a registration spec needs at least one band") + if len(labels) != len(roles): + raise ValueError( + f"a registration spec has {len(labels)} band labels " + f"and {len(roles)} band roles" + ) + if len(set(labels)) != len(labels): + raise ValueError("registration band labels must be unique") + unknown = sorted(set(roles) - set(BAND_ROLES)) + if unknown: + raise ValueError( + f"unknown registration band roles {unknown}; choose from {BAND_ROLES}" + ) + object.__setattr__(self, "band_labels", labels) + object.__setattr__(self, "band_roles", roles) + + @property + def n_bands(self) -> int: + return len(self.band_labels) + + def bands_with_role(self, role: str) -> tuple[int, ...]: + """The indices of the bands with ``role``, in index order.""" + + if role not in BAND_ROLES: + raise ValueError(f"unknown registration band role {role!r}") + return tuple(b for b, r in enumerate(self.band_roles) if r == role) + + +def _counts(spec: RegistrationSpec, registered_counts: object) -> np.ndarray: + counts = as_1d("registered_counts", registered_counts, spec.n_bands).astype( + np.float64 + ) + if not np.all(np.isfinite(counts)) or np.any(counts < 0): + raise ValueError("registered_counts must hold finite, non-negative counts") + return counts + + +def _band_indices( + spec: RegistrationSpec, band_idx: object, length: int | None = None +) -> np.ndarray: + bands = as_1d("band_idx", band_idx, length) + if not np.issubdtype(bands.dtype, np.integer): + raise TypeError("band_idx must be an integer array") + if bands.size and (bands.min() < 0 or bands.max() >= spec.n_bands): + raise ValueError(f"band_idx values must lie in [0, {spec.n_bands - 1}]") + return bands.astype(np.int64) + + +def registration_propensity( + spec: RegistrationSpec, + band_idx: np.ndarray, + frame_mask: np.ndarray, + base_weights: np.ndarray, + registered_counts: np.ndarray, +) -> np.ndarray: + """Each row's probability of being a registered trader. + + For each band that is not ``"excluded"``, the propensity of its frame + rows is the band's registered count divided by its base-weighted frame + mass, capped at 1.0 when the frame cannot hold the registered population. + A band with no frame mass leaves its rows at 0.0. Frame rows in an + ``"excluded"`` band get 0.0; rows outside the frame get 1.0. + + Args: + spec: The bands and their roles. + band_idx: Integer array, shape ``(n,)``: each row's band. + frame_mask: Boolean array, shape ``(n,)``: True for frame rows. + base_weights: Float array, shape ``(n,)``: each row's base weight. + registered_counts: Float array, shape ``(spec.n_bands,)``. + + Returns: + Float64 array, shape ``(n,)``, of propensities in ``[0, 1]``. + """ + + bands = _band_indices(spec, band_idx) + n = len(bands) + frame = as_1d("frame_mask", frame_mask, n).astype(bool) + weights = as_1d("base_weights", base_weights, n).astype(np.float64) + counts = _counts(spec, registered_counts) + + frame_mass = np.bincount( + bands[frame], weights=weights[frame], minlength=spec.n_bands + ) + per_band = np.zeros(spec.n_bands, dtype=np.float64) + positive = frame_mass > 0 + per_band[positive] = np.minimum(1.0, counts[positive] / frame_mass[positive]) + per_band[list(spec.bands_with_role("excluded"))] = 0.0 + + propensity = np.where(frame, per_band[bands], 1.0) + return propensity.astype(np.float64) + + +def select_to_weighted_target( + candidates: np.ndarray, + weights: np.ndarray, + target: float, + rng: np.random.Generator, +) -> np.ndarray: + """``candidates`` in a seeded random order until their weight reaches ``target``. + + The first row whose cumulative weight reaches the target is included, so + the selected weight overshoots the target by less than one row's weight. + If the candidates' total weight falls short, every candidate is selected. + With no candidates, or a target of zero or less, nothing is selected and + ``rng`` is not drawn from. + + Args: + candidates: Integer row positions to choose from. + weights: Float array indexed by row position. + target: The weight to reach. + rng: The generator that draws the permutation. + + Returns: + The selected row positions, in selection order. + """ + + if len(candidates) == 0 or target <= 0: + return candidates[:0] + order = candidates[rng.permutation(len(candidates))] + cumulative = np.cumsum(weights[order]) + cutoff = min(int(np.searchsorted(cumulative, target, side="left")), len(order) - 1) + return order[: cutoff + 1] + + +def assign_scope_and_registration( + spec: RegistrationSpec, + band_idx: np.ndarray, + frame_mask: np.ndarray, + weights: np.ndarray, + registered_counts: np.ndarray, + *, + seed: int, +) -> tuple[np.ndarray, np.ndarray]: + """Assign scope and registration flags that match the registered counts. + + Rows outside the frame are in scope and registered. Frame rows follow + their band's role (module docstring). In each band that is not + ``"excluded"``, the registered weight lies in ``[target, target + w)`` + for the weight ``w`` of the last selected row, unless the band's weight + falls short of the target, when every row in the band is selected. + + One ``np.random.default_rng(seed)`` generator draws one permutation per + band that is not ``"excluded"``, in band index order (none for a band + with no candidates or a zero target). + + Args: + spec: The bands and their roles. + band_idx: Integer array, shape ``(n,)``: each row's band. + frame_mask: Boolean array, shape ``(n,)``: True for frame rows. + weights: Float array, shape ``(n,)``: calibration (or base) weights. + registered_counts: Float array, shape ``(spec.n_bands,)``. + seed: Seed of the selection generator. + + Returns: + ``(scope, registered)``: boolean arrays of shape ``(n,)``. + """ + + bands = _band_indices(spec, band_idx) + n = len(bands) + frame = as_1d("frame_mask", frame_mask, n).astype(bool) + row_weights = as_1d("weights", weights, n).astype(np.float64) + counts = _counts(spec, registered_counts) + rng = np.random.default_rng(int(seed)) + + scope = np.zeros(n, dtype=bool) + registered = np.zeros(n, dtype=bool) + scope[~frame] = True + registered[~frame] = True + + for band, role in enumerate(spec.band_roles): + if role == "excluded": + continue + in_band = frame & (bands == band) + if role == "registrable": + scope[in_band] = True + chosen = select_to_weighted_target( + np.flatnonzero(in_band), row_weights, counts[band], rng + ) + scope[chosen] = True + registered[chosen] = True + + return scope, registered diff --git a/packages/microcosm-build/src/microcosm/build/firms/rules.py b/packages/microcosm-build/src/microcosm/build/firms/rules.py new file mode 100644 index 0000000000..97e98a7c52 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/firms/rules.py @@ -0,0 +1,134 @@ +"""The seam between a firm build and a rule engine. + +A firm build does not compute taxes itself. It hands a firm table to a rule +engine (a country model, or a cross-check) and reads back named per-firm +outputs, keyed by firm id. The seam is the same for every country: + +- a :class:`FirmRules` implementation's ``evaluate(firms, *, period)`` + returns :class:`FirmRuleOutputs`; +- :func:`align_rule_outputs` puts the outputs back in the build's row order, + refusing a missing, repeated or unrequested firm id; +- :func:`weighted_totals` sums a per-firm output table by firm weight. + +What the table's columns mean, which outputs are read and what ``period`` +stands for are the country's business. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from dataclasses import dataclass +from types import MappingProxyType +from typing import Protocol + +import numpy as np +import pandas as pd + +__all__ = [ + "FirmRuleOutputs", + "FirmRules", + "align_rule_outputs", + "weighted_totals", +] + + +@dataclass(frozen=True) +class FirmRuleOutputs: + """Named per-firm rule results, keyed by ``firm_id``. + + ``values`` maps each output's name to a float64 array aligned with + ``firm_id``; every value must be finite. ``provenance`` names the rules + that produced them. + """ + + firm_id: np.ndarray + values: Mapping[str, np.ndarray] + provenance: Mapping[str, str] + + def __post_init__(self) -> None: + firm_id = np.asarray(self.firm_id) + if firm_id.ndim != 1 or not np.issubdtype(firm_id.dtype, np.integer): + raise ValueError("firm rule outputs need a 1-D integer firm_id") + if not self.values: + raise ValueError("firm rule outputs need at least one named output") + values: dict[str, np.ndarray] = {} + for name, raw in self.values.items(): + name = str(name) + if not name or name == "firm_id": + raise ValueError(f"firm rule output name {name!r} is not allowed") + array = np.asarray(raw, dtype=np.float64) + if array.shape != firm_id.shape: + raise ValueError( + f"firm rule output {name} has shape {array.shape} for " + f"{firm_id.shape[0]} firm ids" + ) + if not np.all(np.isfinite(array)): + raise ValueError(f"firm rule output {name} must be finite") + values[name] = array + object.__setattr__(self, "firm_id", firm_id.astype(np.int64)) + object.__setattr__(self, "values", MappingProxyType(values)) + object.__setattr__( + self, + "provenance", + MappingProxyType({str(k): str(v) for k, v in self.provenance.items()}), + ) + + +class FirmRules(Protocol): + """Evaluate rules for a firm table in ``period``.""" + + def evaluate(self, firms: pd.DataFrame, *, period: int) -> FirmRuleOutputs: + """Return named per-firm outputs keyed by ``firm_id``.""" + + +def align_rule_outputs( + outputs: FirmRuleOutputs, + firm_id: np.ndarray | pd.Series, +) -> dict[str, np.ndarray]: + """Every output of ``outputs``, in the order of ``firm_id``. + + Raises ``ValueError`` when either side repeats a firm id, when a requested + firm has no output, or when the outputs hold a firm not requested. + """ + + requested = pd.Index(np.asarray(firm_id, dtype=np.int64)) + produced = pd.Index(outputs.firm_id) + if not requested.is_unique: + raise ValueError("requested firm ids repeat") + if not produced.is_unique: + raise ValueError("firm rule outputs repeat a firm id") + positions = produced.get_indexer(requested) + missing = requested[positions < 0] + if len(missing): + raise ValueError( + f"firm rule outputs miss {len(missing)} firm ids, " + f"e.g. {missing[:5].tolist()}" + ) + extra = produced[~produced.isin(requested)] + if len(extra): + raise ValueError( + f"firm rule outputs hold {len(extra)} unrequested firm ids, " + f"e.g. {extra[:5].tolist()}" + ) + return {name: values[positions] for name, values in outputs.values.items()} + + +def weighted_totals( + table: pd.DataFrame, + *, + weight_column: str = "firm_weight", + id_column: str = "firm_id", +) -> dict[str, float]: + """``sum(value * weight)`` for every column but the id and weight columns. + + Each total stands alone; the caller decides which ones add up. + """ + + if weight_column not in table.columns: + raise ValueError(f"firm output table misses column {weight_column}") + weight = table[weight_column].to_numpy(np.float64) + return { + str(column): float(np.dot(table[column].to_numpy(np.float64), weight)) + for column in table.columns + if column not in (id_column, weight_column) + } diff --git a/packages/microcosm-build/src/microcosm/build/firms/thinning.py b/packages/microcosm-build/src/microcosm/build/firms/thinning.py new file mode 100644 index 0000000000..7c023748b3 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/firms/thinning.py @@ -0,0 +1,108 @@ +"""Stratified thinning of a candidate firm draw, with exact base weights. + +A full firm census (millions of rows) is slow to calibrate. Thinning keeps +rows inside an analysis window (for example around a tax threshold) at one +rate and rows outside it at another, stratum by stratum, and gives each kept +row the base weight that restores its stratum's row count. Strata are the +caller's keys (for example industry and turnover band) crossed with the +window side. +""" + +from __future__ import annotations + +from collections.abc import Sequence + +import numpy as np + +from ._arrays import as_1d + +__all__ = ["stratified_thin"] + + +def stratified_thin( + window_values: np.ndarray, + strata: Sequence[np.ndarray], + *, + window_lo: float, + window_hi: float, + window_fraction: float, + tail_fraction: float, + cell_floor: int, + rng_seed: int, +) -> tuple[np.ndarray, np.ndarray]: + """Thin rows by stratum and return the kept rows and their base weights. + + Rows whose ``window_values`` lie inside ``[window_lo, window_hi]`` + (inclusive) are kept with probability ``window_fraction``; every other row + with probability ``tail_fraction``. A stratum (the ``strata`` keys crossed + with the window side) that keeps fewer than ``min(cell_floor, stratum + size)`` rows is topped up with its unkept rows of lowest uniform draw, so + small strata survive. Each kept row's base weight is its stratum's size + divided by its kept count, so the base-weighted count of every stratum + equals its row count (up to float64 rounding). + + One uniform draw per row comes from ``np.random.default_rng(rng_seed)``. + Draws lie in ``[0, 1)``, so fractions of 1.0 keep every row at weight 1.0. + + Args: + window_values: Float array, shape ``(n,)``: the value the window reads. + strata: Integer arrays, each shape ``(n,)``: the stratum keys. An + empty sequence stratifies by window side alone. + window_lo: Lower window edge (inclusive). + window_hi: Upper window edge (inclusive). + window_fraction: Keep probability inside the window, in ``[0, 1]``. + tail_fraction: Keep probability outside the window, in ``[0, 1]``. + cell_floor: Minimum kept rows per stratum (capped at stratum size). + rng_seed: Seed of the generator that draws the uniforms. + + Returns: + ``(keep_idx, base_weights)``: ascending int64 positions of the kept + rows and their float64 base weights. + """ + + values = as_1d("window_values", window_values).astype(np.float64) + n = len(values) + keys = [] + for position, key in enumerate(strata): + array = as_1d(f"strata[{position}]", key, n) + if not np.issubdtype(array.dtype, np.integer): + raise TypeError(f"strata[{position}] must be an integer array") + keys.append(array.astype(np.int64)) + for name, fraction in ( + ("window_fraction", window_fraction), + ("tail_fraction", tail_fraction), + ): + if not 0.0 <= float(fraction) <= 1.0: + raise ValueError(f"{name} must lie in [0, 1], got {fraction}") + if int(cell_floor) < 0: + raise ValueError(f"cell_floor must be non-negative, got {cell_floor}") + if n == 0: + return np.zeros(0, dtype=np.int64), np.zeros(0, dtype=np.float64) + + in_window = (values >= window_lo) & (values <= window_hi) + fraction = np.where(in_window, float(window_fraction), float(tail_fraction)) + rng = np.random.default_rng(int(rng_seed)) + u = rng.random(n) + keep = u < fraction + + stacked = np.stack([*keys, in_window.astype(np.int64)], axis=1) + _, stratum = np.unique(stacked, axis=0, return_inverse=True) + stratum = stratum.reshape(-1) + n_strata = int(stratum.max()) + 1 + sizes = np.bincount(stratum, minlength=n_strata) + kept = np.bincount(stratum, weights=keep, minlength=n_strata).astype(np.int64) + deficit = np.clip(np.minimum(int(cell_floor), sizes) - kept, 0, None) + + if deficit.any(): + # Top up each deficient stratum with its lowest-u unkept rows. + candidates = np.flatnonzero(~keep & (deficit[stratum] > 0)) + order = candidates[np.lexsort((u[candidates], stratum[candidates]))] + ordered_strata = stratum[order] + first = np.searchsorted(ordered_strata, ordered_strata, side="left") + rank = np.arange(len(order)) - first # 0-based rank within stratum + keep[order[rank < deficit[ordered_strata]]] = True + kept = np.bincount(stratum, weights=keep, minlength=n_strata).astype(np.int64) + + base = sizes / np.maximum(kept, 1) + keep_idx = np.flatnonzero(keep).astype(np.int64) + return keep_idx, base[stratum[keep_idx]].astype(np.float64) diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/__init__.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/__init__.py index 90411f338a..4fc8468d46 100644 --- a/packages/microcosm-build/src/microcosm/build/uk_runtime/__init__.py +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/__init__.py @@ -45,6 +45,9 @@ uk_zero_weight_strata, write_uk_calibration_diagnostics, ) +from microcosm.build.uk_runtime.firm_build import ( + build_uk_firm_dataset, +) from microcosm.build.uk_runtime.firm_generation import ( EMPLOYMENT_BANDS, HMRC_BAND_COLUMNS, @@ -60,7 +63,6 @@ UKFirmValidationReport, UKFirmVATRuleEvaluator, assign_employment, - assign_vat_flags, build_firm_target_matrix, employment_band_name, generate_base_firms, @@ -77,6 +79,33 @@ validate_uk_firm_population, write_uk_firm_population, ) +from microcosm.build.uk_runtime.firm_policyengine_uk_rules import ( + POLICYENGINE_UK_FIRM_TAX_VARIABLES, + PolicyEngineUKFirmRules, + evaluate_uk_firm_taxes, + weighted_uk_firm_tax_totals, +) +from microcosm.build.uk_runtime.firm_rules import ( + LegacyVATEvaluatorRules, + UKFirmRuleOutputs, + UKFirmRules, + align_rule_outputs, + data_years_for_vintage, + rule_period_for_vintage, +) +from microcosm.build.uk_runtime.firm_table import ( + ASSUMED_INPUT_VAT_RATE, + UK_FIRM_POLICYENGINE_UK_INPUT_STATUS, + UK_FIRM_TABLE_COLUMNS, + build_candidate_rules_table, + to_policyengine_uk_firm_table, + validate_uk_firm_table, +) +from microcosm.build.uk_runtime.firm_universe import ( + assign_vat_scope_and_registration, + registration_propensity, + stratified_thin, +) from microcosm.build.uk_runtime.fiscal_targets import ( UK_CGT_REQUIRED_COLUMNS, UK_CGT_TARGET_COVERAGE_REQUIREMENTS, @@ -820,7 +849,6 @@ "derive_hmrc_income_auxiliaries", "dense_reference_deltas", "assign_uk_geography_ladder", - "assign_vat_flags", "build_firm_target_matrix", "build_conservative_hmrc_replay_report", "build_uk_spi_support_channel", @@ -977,6 +1005,26 @@ "validate_geography_coverage", "write_geography_crosswalk", "write_uk_firm_population", + "LegacyVATEvaluatorRules", + "UKFirmRuleOutputs", + "UKFirmRules", + "build_uk_firm_dataset", + "PolicyEngineUKFirmRules", + "POLICYENGINE_UK_FIRM_TAX_VARIABLES", + "evaluate_uk_firm_taxes", + "weighted_uk_firm_tax_totals", + "UK_FIRM_POLICYENGINE_UK_INPUT_STATUS", + "align_rule_outputs", + "rule_period_for_vintage", + "data_years_for_vintage", + "ASSUMED_INPUT_VAT_RATE", + "UK_FIRM_TABLE_COLUMNS", + "build_candidate_rules_table", + "to_policyengine_uk_firm_table", + "validate_uk_firm_table", + "assign_vat_scope_and_registration", + "registration_propensity", + "stratified_thin", "write_uk_calibration_diagnostics", "load_bound_spine_sidecar", "spine_provenance_from_sidecar", diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_build.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_build.py new file mode 100644 index 0000000000..232aa746ec --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_build.py @@ -0,0 +1,209 @@ +"""A local UK firm build: generated firms to a policyengine-uk table on disk. + +``build_uk_firm_dataset`` runs the experimental firm pipeline end to end: + +1. ``read_uk_firm_source_data`` reads the processed ONS/HMRC tables; +2. ``generate_uk_firm_population`` draws and calibrates the firms, with VAT + liability from the ``rules`` it is given; +3. ``to_policyengine_uk_firm_table`` exports policyengine-uk firm columns; +4. ``validate_uk_firm_table`` checks the table. + +It writes ``uk_firms.parquet`` and ``uk_firms.receipt.json`` to the output +directory and nothing else: there is no publication, staging or upload path. +The receipt holds the inputs' hashes keyed by role and file name, the rule +period with a note on how it treats mid-year changes, the years the source +data describe (``data_years``, which can lag the rule period), the +configuration's JSON-safe fields, the output's hash and shape, the +calibration's accuracy figures and the provenance the rules reported. +It holds no timestamp, hostname or absolute path, so two builds from the same inputs write the same receipt. +""" + +from __future__ import annotations + +import dataclasses +import hashlib +import json +import math +from collections.abc import Mapping +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any + +import numpy as np +import pandas as pd + +from microcosm.build.uk_runtime.firm_generation import ( + UKFirmGenerationConfig, + generate_uk_firm_population, + read_uk_firm_source_data, +) +from microcosm.build.uk_runtime.firm_rules import ( + UK_FIRM_RULE_PERIOD_NOTE, + UKFirmRuleOutputs, + UKFirmRules, + data_years_for_vintage, + rule_period_for_vintage, +) +from microcosm.build.uk_runtime.firm_table import ( + to_policyengine_uk_firm_table, + validate_uk_firm_table, +) + +#: Version of the ``uk_firms.receipt.json`` layout. +UK_FIRM_BUILD_RECEIPT_SCHEMA_VERSION = 1 +UK_FIRM_TABLE_FILE = "uk_firms.parquet" +UK_FIRM_RECEIPT_FILE = "uk_firms.receipt.json" + +#: Configuration fields holding rule objects, which the receipt leaves out. +_RULE_CONFIG_FIELDS = frozenset({"firm_rules", "vat_rule_evaluator"}) + + +@dataclass +class _RecordingRules: + """``UKFirmRules`` that passes every call through and keeps its provenance.""" + + rules: UKFirmRules + provenance: list[dict[str, str]] = field(default_factory=list) + + def evaluate(self, firms: pd.DataFrame, *, period: int) -> UKFirmRuleOutputs: + outputs = self.rules.evaluate(firms, period=period) + self.provenance.append( + {str(key): str(value) for key, value in outputs.provenance.items()} + ) + return outputs + + +def build_uk_firm_dataset( + *, + processed_dir: str | Path, + output_dir: str | Path, + rules: UKFirmRules, + config: UKFirmGenerationConfig, +) -> dict[str, Any]: + """Build the UK firm table and its receipt into ``output_dir``. + + ``config`` is run with ``firm_rules`` set to ``rules`` (wrapped so the + receipt can record the provenance it reports); a ``config`` that already + carries other firm rules raises ``ValueError``. Returns ``table`` (the + validated policyengine-uk firm table), ``receipt`` (the dict written as + JSON), ``result`` (the ``UKFirmGenerationResult``), ``table_path`` and + ``receipt_path``. + """ + + if config.firm_rules is not None and config.firm_rules is not rules: + raise ValueError( + "config.firm_rules differs from rules; pass the rules once, as rules." + ) + processed = Path(processed_dir) + output = Path(output_dir) + + recorder = _RecordingRules(rules) + run_config = dataclasses.replace(config, firm_rules=recorder) + source = read_uk_firm_source_data(processed, input_files=run_config.input_files) + result = generate_uk_firm_population(source, run_config) + if not recorder.provenance: + raise RuntimeError("The UK firm rules were never evaluated.") + + table = to_policyengine_uk_firm_table( + result.firms, threshold_k=float(result.config.vat_threshold) + ) + validate_uk_firm_table(table) + + output.mkdir(parents=True, exist_ok=True) + table_path = output / UK_FIRM_TABLE_FILE + table.to_parquet(table_path, index=False, engine="pyarrow") + written = pd.read_parquet(table_path, engine="pyarrow") + validate_uk_firm_table(written) + + validation = result.validation + receipt: dict[str, Any] = { + "schema_version": UK_FIRM_BUILD_RECEIPT_SCHEMA_VERSION, + "data_vintage": result.config.data_vintage, + "seed": int(result.config.seed), + "rule_period": rule_period_for_vintage(result.config.data_vintage), + "rule_period_note": UK_FIRM_RULE_PERIOD_NOTE, + "data_years": data_years_for_vintage(result.config.data_vintage), + "config": _config_record(result.config), + "inputs": { + "processed": _csv_hashes(processed), + }, + "output": { + "file": UK_FIRM_TABLE_FILE, + "sha256": _sha256(table_path), + "rows": len(table), + "columns": [str(column) for column in table.columns], + "weighted_firms": float(table["firm_weight"].sum()), + }, + "validation": { + **{ + key: float(value) + for key, value in dataclasses.asdict(validation).items() + }, + "overall": float(validation.overall), + }, + "calibration": { + "initial_loss": float(result.calibration.initial_loss), + "final_loss": float(result.calibration.final_loss), + }, + "target_diagnostics": _records(result.target_diagnostics), + "rules_provenance": recorder.provenance, + } + receipt = _json_safe(receipt) + receipt_path = output / UK_FIRM_RECEIPT_FILE + receipt_path.write_text( + json.dumps(receipt, sort_keys=True, indent=2, allow_nan=False) + "\n", + encoding="utf-8", + ) + return { + "table": table, + "receipt": receipt, + "result": result, + "table_path": table_path, + "receipt_path": receipt_path, + } + + +def _sha256(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def _csv_hashes(directory: Path) -> dict[str, str]: + """Every CSV directly in ``directory``, by file name, to its sha256.""" + + return {path.name: _sha256(path) for path in sorted(directory.glob("*.csv"))} + + +def _config_record(config: UKFirmGenerationConfig) -> dict[str, Any]: + record = {} + for item in dataclasses.fields(config): + if item.name in _RULE_CONFIG_FIELDS: + continue + value = getattr(config, item.name) + if isinstance(value, Mapping): + value = {str(key): str(entry) for key, entry in value.items()} + record[item.name] = value + record["thinned"] = config.thinned + return record + + +def _records(frame: pd.DataFrame) -> list[dict[str, Any]]: + return [ + {str(key): value for key, value in row.items()} + for row in frame.to_dict(orient="records") + ] + + +def _json_safe(value: Any) -> Any: + """``value`` with numpy scalars made native and non-finite floats None.""" + + if isinstance(value, Mapping): + return {str(key): _json_safe(entry) for key, entry in value.items()} + if isinstance(value, list | tuple): + return [_json_safe(entry) for entry in value] + if isinstance(value, np.generic): + value = value.item() + if isinstance(value, float) and not math.isfinite(value): + return None + if value is None or isinstance(value, bool | int | float | str): + return value + raise TypeError(f"UK firm receipt value {value!r} is not JSON-safe.") diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_generation.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_generation.py index 7df3399c8e..59a4076753 100644 --- a/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_generation.py +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_generation.py @@ -9,9 +9,26 @@ Scope is intentionally narrow and labelled experimental. Microcosm production calibration targets must be materialized from Ledger target profiles; the processed ONS/HMRC tables accepted here are a migration harness only, not a -production target source. VAT liability must be supplied by a configured rule -evaluator; the production path is an Axiom RuleSpec artifact, so this module -does not claim production firm microsimulation support without that artifact. +production target source. VAT liability must be supplied by configured rules +(:class:`~microcosm.build.uk_runtime.firm_rules.UKFirmRules`, or a legacy +:class:`UKFirmVATRuleEvaluator` such as the Axiom RuleSpec evaluator), so this +module does not claim production firm microsimulation support without them. + +The pipeline follows the paper generator (``firm_microsim.generate`` at paper +commit aa1ce07): + +1. draw ONS-frame firms by sector and turnover band, then input costs and, + when a sampling fraction is below one, stratified thinning whose base + weights become the solve's initial weights; +2. append the HMRC negative/zero-turnover traders *before* calibration, as an + out-of-frame stratum (``in_frame`` False, base weight one); +3. draw sector-conditional employment for every row; +4. evaluate VAT liability-if-registered through the rules seam; +5. calibrate on two universes (paper issue #37): ONS-frame rows (population, + employment) count frame rows only; HMRC registered-trader rows (counts by + band and sector, net VAT by band) weight every row by its band's + registration propensity; +6. assign VAT scope and registration from the calibrated weights. """ from __future__ import annotations @@ -31,15 +48,26 @@ from scipy import sparse from torch import Tensor -from microcosm.calibrate.solve import ( - _optimize as _calibrate_optimize, +from microcosm.build.firms import draw_in_band +from microcosm.build.uk_runtime.firm_rules import ( + LegacyVATEvaluatorRules, + UKFirmRules, + align_rule_outputs, + rule_period_for_vintage, ) -from microcosm.calibrate.solve import ( - _torch_constraint_matrix as _calibrate_torch_constraint_matrix, +from microcosm.build.uk_runtime.firm_table import build_candidate_rules_table +from microcosm.build.uk_runtime.firm_universe import ( + HMRC_BAND_NAMES, + assign_vat_scope_and_registration, + registration_propensity, + stratified_thin, ) from microcosm.calibrate.solve import ( + CONSERVE_MASS, + FREE_MASS, default_target_loss_scales, relative_error_loss, + solve_constraint_system, ) logger = logging.getLogger(__name__) @@ -169,17 +197,16 @@ class UKFirmLedgerTargetProfile: CHRONICLE_ONS_EMPLOYMENT_BANDS = LEDGER_ONS_EMPLOYMENT_BANDS CHRONICLE_HMRC_BANDS = LEDGER_HMRC_BANDS -HMRC_BAND_COLUMNS: tuple[str, ...] = ( - "Negative_or_Zero", - "£1_to_Threshold", - "£Threshold_to_£150k", - "£150k_to_£300k", - "£300k_to_£500k", - "£500k_to_£1m", - "£1m_to_£10m", - "Greater_than_£10m", -) +#: HMRC VAT turnover bands, in ``band_idx`` order; defined once in +#: :mod:`~microcosm.build.uk_runtime.firm_universe`. +HMRC_BAND_COLUMNS: tuple[str, ...] = HMRC_BAND_NAMES VAT_LIABILITY_BANDS: tuple[str, ...] = HMRC_BAND_COLUMNS[1:] +#: Net-VAT bands that enter the calibration. ``£1_to_Threshold`` is reported +#: but not calibrated, as in the paper: its HMRC total is remitted by voluntary +#: registrants whose input-reclaim-driven net remittances the +#: liability-if-registered model does not represent, and imposing it crushes +#: weights just below the threshold. +VAT_LIABILITY_BANDS_CALIBRATED: tuple[str, ...] = VAT_LIABILITY_BANDS[1:] EMPLOYMENT_BANDS: tuple[str, ...] = ( "0-4", "5-9", @@ -190,15 +217,24 @@ class UKFirmLedgerTargetProfile: "250+", ) +#: ONS turnover bands as ``(inclusive lower, exclusive upper, midpoint)`` in +#: thousands of pounds. The published integer labels are contiguous +#: continuous intervals: "50-99" is [50, 100), as in the paper generator. ONS_TURNOVER_BANDS: dict[str, tuple[float, float, float]] = { - "0-49": (0.0, 49.0, 24.5), - "50-99": (50.0, 99.0, 74.5), - "100-249": (100.0, 249.0, 174.5), - "250-499": (250.0, 499.0, 374.5), - "500-999": (500.0, 999.0, 749.5), - "1000-4999": (1000.0, 4999.0, 2999.5), + "0-49": (0.0, 50.0, 25.0), + "50-99": (50.0, 100.0, 75.0), + "100-249": (100.0, 250.0, 175.0), + "250-499": (250.0, 500.0, 375.0), + "500-999": (500.0, 1000.0, 750.0), + "1000-4999": (1000.0, 5000.0, 3000.0), "5000+": (5000.0, 50000.0, 15000.0), } +#: The open "5000+" band is drawn log-uniform on [5m, 50m) (paper issue #40): +#: a uniform draw put more enterprises above 10m than HMRC counts traders. +ONS_OPEN_TURNOVER_BAND = "5000+" +#: Floor for drawn turnover in thousands of pounds, so frame firms always have +#: positive turnover (the appended HMRC traders alone carry zero). +MIN_DRAWN_TURNOVER_K = 0.1 ONS_EMPLOYMENT_BANDS: dict[str, tuple[float, float, float]] = { "0-4": (1.0, 4.0, 2.5), "5-9": (5.0, 9.0, 7.0), @@ -230,6 +266,28 @@ class UKFirmLedgerTargetProfile: } HIGH_LIABILITY_SECTORS = {11, 12, 69, 70, 78} +#: Input/output ratio draw (microcosm#258, paper #21): ``offset + Beta(a, b) * +#: scale`` plus sector shifts and noise, clamped to ``[lower, upper]``. The +#: mean ratio is about 0.6, so value added is about 40% of turnover and always +#: strictly positive. +INPUT_RATIO_BETA_A = 4.0 +INPUT_RATIO_BETA_B = 2.0 +INPUT_RATIO_OFFSET = 0.2 +INPUT_RATIO_SCALE = 0.6 +INPUT_RATIO_LOWER = 0.1 +INPUT_RATIO_UPPER = 0.95 + +#: The paper's ``--fast`` sampling preset (``firm_microsim.generate``). +FAST_SAMPLE_WINDOW_FRACTION = 0.30 +FAST_SAMPLE_TAIL_FRACTION = 0.05 + +#: Upper edges of the ONS employment bands below the open top band, in +#: :data:`EMPLOYMENT_BANDS` order, for vectorised band lookup. +_EMPLOYMENT_BAND_UPPER_EDGES: np.ndarray = np.asarray( + [upper for _, upper, _ in ONS_EMPLOYMENT_BANDS.values()][:-1], + dtype=np.float64, +) + AXIOM_UK_VAT_NET_LIABILITY_OUTPUT = ( "uk:statutes/ukpga/1994/23/25#net_vat_liability_after_input_tax_credit" ) @@ -363,7 +421,27 @@ def net_liability_k( @dataclass(frozen=True) class UKFirmGenerationConfig: - """Configuration for the experimental UK firm generator.""" + """Configuration for the experimental UK firm generator. + + VAT liability comes from ``firm_rules`` (a + :class:`~microcosm.build.uk_runtime.firm_rules.UKFirmRules`). When it is + absent, a legacy ``vat_rule_evaluator`` is wrapped in + :class:`~microcosm.build.uk_runtime.firm_rules.LegacyVATEvaluatorRules`. + + Stratified thinning runs when ``sample_window_fraction`` or + ``sample_tail_fraction`` is below one: rows with turnover inside + ``[sample_window_lo_k, sample_window_hi_k]`` are kept at the window + fraction, others at the tail fraction, with at least ``sample_cell_floor`` + rows per sector x HMRC band x window-side stratum. The defaults keep every + row; :meth:`fast` is the paper's fast-iteration preset. + + ``vat_threshold`` defaults to the ``data_vintage``'s threshold, resolved + once at construction. ``dataclasses.replace(config, data_vintage=...)`` + therefore keeps the old vintage's threshold (it is passed back in as an + explicit value); use :meth:`with_vintage` to switch vintage and threshold + together. An explicit ``vat_threshold`` that differs from the vintage's + (a counterfactual threshold) is allowed. + """ data_vintage: str = DEFAULT_VINTAGE vat_threshold: float | None = None @@ -375,6 +453,7 @@ class UKFirmGenerationConfig: max_weight_ratio: float | None = None conserve_mass: bool = False turnover_importance: float = 5.0 + population_importance: float = 1.0 sector_importance: float = 1.0 employment_importance: float = 1.0 vat_liability_sector_importance: float = 1.0 @@ -382,6 +461,52 @@ class UKFirmGenerationConfig: calibrate_vat_liability_sector: bool = False input_files: dict[str, str] = field(default_factory=lambda: dict(INPUT_FILES)) vat_rule_evaluator: UKFirmVATRuleEvaluator | None = None + sample_tail_fraction: float = 1.0 + sample_window_fraction: float = 1.0 + sample_window_lo_k: float = 15.0 + sample_window_hi_k: float = 150.0 + sample_cell_floor: int = 40 + firm_rules: UKFirmRules | None = None + + @classmethod + def fast(cls, **overrides: Any) -> UKFirmGenerationConfig: + """The paper's fast-iteration preset: window 0.30, tails 0.05. + + Mirrors ``firm_microsim.generate(fast=True)``. Base weights keep every + calibration target a true population total, so a fast build solves + the same problem around a rescaled prior. + """ + + values: dict[str, Any] = { + "sample_window_fraction": FAST_SAMPLE_WINDOW_FRACTION, + "sample_tail_fraction": FAST_SAMPLE_TAIL_FRACTION, + } + values.update(overrides) + return cls(**values) + + def with_vintage(self, data_vintage: str) -> UKFirmGenerationConfig: + """This configuration for ``data_vintage`` at that vintage's threshold. + + Every other field is kept. Unlike ``dataclasses.replace(config, + data_vintage=...)``, the VAT threshold follows the new vintage. + """ + + if data_vintage not in VINTAGES: + raise ValueError( + f"Unknown UK firm vintage {data_vintage!r}; " + f"choose from {sorted(VINTAGES)}." + ) + return replace( + self, + data_vintage=data_vintage, + vat_threshold=float(VINTAGES[data_vintage]["threshold"]), + ) + + @property + def thinned(self) -> bool: + """Whether this configuration thins the candidate draw.""" + + return self.sample_window_fraction < 1.0 or self.sample_tail_fraction < 1.0 def __post_init__(self) -> None: if self.data_vintage not in VINTAGES: @@ -399,6 +524,14 @@ def __post_init__(self) -> None: raise ValueError("vat_threshold must be positive.") if self.n_iterations <= 0: raise ValueError("n_iterations must be positive.") + for name in ("sample_tail_fraction", "sample_window_fraction"): + fraction = float(getattr(self, name)) + if not 0.0 < fraction <= 1.0: + raise ValueError(f"{name} must lie in (0, 1], got {fraction}.") + if self.sample_window_lo_k > self.sample_window_hi_k: + raise ValueError("sample_window_lo_k must not exceed sample_window_hi_k.") + if self.sample_cell_floor < 0: + raise ValueError("sample_cell_floor must be non-negative.") def _vat_rule_period(data_vintage: str) -> dict[str, str]: @@ -446,14 +579,24 @@ class UKFirmSourceData: @dataclass(frozen=True) class UKFirmTargetLayout: - """Target row layout in the generated calibration matrix.""" + """Target row layout in the generated calibration matrix. + + Rows run: HMRC registered-trader counts for all eight HMRC turnover bands + (``Negative_or_Zero`` included, since its traders enter the solve), the + ONS frame population, HMRC registered traders by sector, ONS employment + bands, optional net VAT by sector, then net VAT by calibrated band. + """ n_sectors: int n_vat_sectors: int @property def n_turnover(self) -> int: - return 7 + return len(HMRC_BAND_COLUMNS) + + @property + def n_population(self) -> int: + return 1 @property def n_employment(self) -> int: @@ -461,16 +604,20 @@ def n_employment(self) -> int: @property def n_vat_bands(self) -> int: - return len(VAT_LIABILITY_BANDS) + return len(VAT_LIABILITY_BANDS_CALIBRATED) @property def turnover_start(self) -> int: return 0 @property - def sector_start(self) -> int: + def population_start(self) -> int: return self.turnover_start + self.n_turnover + @property + def sector_start(self) -> int: + return self.population_start + self.n_population + @property def employment_start(self) -> int: return self.sector_start + self.n_sectors @@ -515,7 +662,13 @@ def overall(self) -> float: @dataclass(frozen=True) class UKFirmCalibrationResult: - """Core Microcosm calibration result for pre-zero-turnover base firms.""" + """Core Microcosm calibration result for every generated row. + + ``weights`` and ``initial_weights`` cover the ONS-frame rows and the + appended HMRC negative/zero-turnover traders, in output row order. + ``initial_weights`` are the stratified-thinning base weights (one for + every row in an unthinned build). + """ weights: Tensor loss_trajectory: np.ndarray @@ -523,6 +676,7 @@ class UKFirmCalibrationResult: final_loss: float target_loss_weights: np.ndarray target_loss_scales: np.ndarray + initial_weights: np.ndarray | None = None @dataclass(frozen=True) @@ -729,6 +883,7 @@ def generate_uk_firm_population( """ cfg = _resolve_config(config, vintage=vintage, threshold=threshold, seed=seed) + rules = resolve_uk_firm_rules(cfg) torch.manual_seed(cfg.seed) np.random.seed(cfg.seed) @@ -736,81 +891,124 @@ def generate_uk_firm_population( data.hmrc_population_band, cfg.data_vintage, ) - base_sic, base_turnover = generate_base_firms(data.ons_turnover, cfg.device) - if len(base_sic) == 0: + hmrc_counts = np.asarray( + [hmrc_bands[band] for band in HMRC_BAND_COLUMNS], + dtype=np.float64, + ) + threshold_k = float(cfg.vat_threshold) + + frame_sic, frame_turnover = generate_base_firms(data.ons_turnover, cfg.device) + if len(frame_sic) == 0: raise ValueError("UK firm generation requires at least one ONS firm row.") - base_input = generate_input_values(base_turnover, base_sic, cfg.device) - base_employment = assign_employment( - len(base_sic), - data.ons_employment, - cfg.device, - ) - base_vat_registered = assign_vat_flags(base_turnover, hmrc_bands, cfg) - base_vat_liability = calculate_vat_liability_values( - cfg, - base_turnover, - base_input, - base_vat_registered, + frame_input = generate_input_values(frame_turnover, frame_sic, cfg.device) + frame_base_weights = np.ones(len(frame_sic), dtype=np.float64) + if cfg.thinned: + keep_idx, frame_base_weights = stratified_thin( + frame_turnover.detach().cpu().numpy(), + frame_sic.detach().cpu().numpy(), + map_to_hmrc_band_indices(frame_turnover, threshold_k).cpu().numpy(), + window_lo_k=cfg.sample_window_lo_k, + window_hi_k=cfg.sample_window_hi_k, + window_fraction=cfg.sample_window_fraction, + tail_fraction=cfg.sample_tail_fraction, + cell_floor=cfg.sample_cell_floor, + seed=cfg.seed, + ) + keep = torch.as_tensor(keep_idx, dtype=torch.long, device=cfg.device) + frame_sic = frame_sic[keep] + frame_turnover = frame_turnover[keep] + frame_input = frame_input[keep] + + # HMRC negative/zero-turnover traders join BEFORE calibration (paper + # issue #37): every target row sees the same rows, they sit outside the + # ONS frame, and they count toward the HMRC registered-trader rows. + sic_codes, turnover, input_values, base_weights, frame_mask = ( + _add_zero_turnover_firms( + frame_sic, + frame_turnover, + frame_input, + frame_base_weights, + hmrc_bands, + cfg.device, + ) ) - employment_band_indices = torch.tensor( - [_employment_band_index(value.item()) for value in base_employment], - dtype=torch.long, - device=cfg.device, + # Employment is drawn once, for every row, and kept: the employment + # target rows and the output describe the same firms. + employment = assign_employment(sic_codes, data.ons_employment, cfg.device) + employment_np = employment.detach().cpu().numpy() + employment_band_indices = employment_band_index_array(employment_np) + band_idx = map_to_hmrc_band_indices(turnover, threshold_k).cpu().numpy() + firm_ids = np.arange(1, len(sic_codes) + 1, dtype=np.int64) + sic_np = sic_codes.detach().cpu().numpy().astype(np.int64) + turnover_np = turnover.detach().cpu().numpy().astype(np.float64) + input_np = input_values.detach().cpu().numpy().astype(np.float64) + + liability_if_registered_k = evaluate_vat_liability_if_registered_k( + rules, + pd.DataFrame( + { + "firm_id": firm_ids, + "sic_code": sic_np, + "annual_turnover_k": turnover_np, + "annual_input_k": input_np, + "employment": employment_np, + } + ), + cfg.data_vintage, + ) + propensity = registration_propensity( + band_idx, + frame_mask, + base_weights, + hmrc_counts, ) target_matrix, target_values, layout, target_names = build_firm_target_matrix( cfg, - base_turnover, - base_sic, - base_input, + turnover_np, + sic_np, employment_band_indices, - base_vat_registered, data, - vat_liability_values=base_vat_liability, - ) - calibration = solve_firm_weights(cfg, target_matrix, target_values, layout) - weights = calibration.weights - - ( - final_sic, - final_turnover, - final_input, - final_employment, - final_weights, - final_vat_registered, - ) = _add_zero_turnover_firms( - base_sic, - base_turnover, - base_input, - base_employment, - weights, - base_vat_registered, - hmrc_bands, - data.ons_employment, - cfg.device, - ) - final_vat_liability = calculate_vat_liability_values( + propensity=propensity, + frame_mask=frame_mask, + vat_liability_if_registered_k=liability_if_registered_k, + ) + calibration = solve_firm_weights( cfg, - final_turnover, - final_input, - final_vat_registered, + target_matrix, + target_values, + layout, + initial_weights=base_weights, + ) + weights_np = calibration.weights.detach().cpu().numpy().astype(np.float64) + vat_scope, vat_registered = assign_vat_scope_and_registration( + band_idx, + frame_mask, + weights_np, + hmrc_counts, + seed=cfg.seed, ) firms = _assemble_firm_rows( - final_sic, - final_turnover, - final_input, - final_vat_liability, - final_employment, - final_weights, - final_vat_registered, + firm_ids, + sic_np, + turnover_np, + input_np, + np.where(vat_registered, liability_if_registered_k, 0.0), + employment_np, + weights_np, + base_weights, + frame_mask, + vat_scope, + vat_registered, cfg, ) validation = validate_uk_firm_population(firms, data, cfg) diagnostics = target_diagnostics( target_matrix, target_values, - weights, + weights_np, target_names, + initial_weights=base_weights, ) return UKFirmGenerationResult( firms=firms, @@ -852,7 +1050,15 @@ def generate_base_firms( count = int(row[band]) sic_codes.extend([sic_int] * count) turnovers.append( - _draw_band_turnover(count, lower, upper, device).cpu().numpy() + _draw_band_turnover( + count, + lower, + upper, + device, + log_uniform=band == ONS_OPEN_TURNOVER_BAND, + ) + .cpu() + .numpy() ) turnover_values = ( @@ -871,14 +1077,23 @@ def generate_input_values( sic_codes: Tensor, device: str = "cpu", ) -> Tensor: - """Draw annual input expenditure in thousands of pounds.""" + """Draw annual input expenditure in thousands of pounds. + + The input/output ratio is ``0.2 + Beta(4, 2) * 0.6`` (mean about 0.6) + with sector shifts and noise, clamped to ``[0.1, 0.95]`` so value added is + always strictly positive (microcosm#258, ported from the paper's #21). + """ n_firms = len(turnover_values) if n_firms == 0: return torch.empty(0, dtype=torch.float32, device=device) - ratios = torch.distributions.Beta(4.0, 2.0).sample((n_firms,)).to(device) - scaled = 0.3 + ratios * 1.0 + ratios = ( + torch.distributions.Beta(INPUT_RATIO_BETA_A, INPUT_RATIO_BETA_B) + .sample((n_firms,)) + .to(device) + ) + scaled = INPUT_RATIO_OFFSET + ratios * INPUT_RATIO_SCALE sector_noise = torch.randn(n_firms, device=device) * 0.15 sic_np = sic_codes.detach().cpu().numpy() neg_mask = np.isin(sic_np, list(NEGATIVE_LIABILITY_SECTORS)) @@ -887,7 +1102,11 @@ def generate_input_values( high_t = torch.tensor(high_mask, device=device) scaled = scaled + neg_t.float() * (torch.rand(n_firms, device=device) * 0.3) scaled = scaled - high_t.float() * (torch.rand(n_firms, device=device) * 0.2) - final_ratios = torch.clamp(scaled + sector_noise, 0.6, 1.5) + final_ratios = torch.clamp( + scaled + sector_noise, + INPUT_RATIO_LOWER, + INPUT_RATIO_UPPER, + ) return torch.where( turnover_values > 0, turnover_values * final_ratios, @@ -896,85 +1115,131 @@ def generate_input_values( def assign_employment( - n_firms: int, + sic_codes: Tensor, ons_employment: pd.DataFrame, device: str = "cpu", ) -> Tensor: - """Assign firm employment counts from ONS employment-band shares.""" + """Assign firm employment counts conditional on each firm's ONS sector. + Ported from the paper's ``generate.assign_employment``: each sector's + rows draw an employment band from that sector's ONS band shares (the + national shares when the sector has no ONS employment row or no firms), + then a count inside the band. Draws use torch's global generator. + """ + + sic_codes = torch.as_tensor(sic_codes, dtype=torch.int64, device=device) + n_firms = len(sic_codes) if n_firms == 0: return torch.empty(0, dtype=torch.float32, device=device) sector_rows = ons_employment[ ~ons_employment["Description"].astype(str).str.contains("Total", na=False) ] - band_counts = { - band: int(sector_rows[band].fillna(0).sum()) if band in sector_rows else 0 - for band in EMPLOYMENT_BANDS - } - total = sum(band_counts.values()) or 1 - values: list[float] = [] - for band in EMPLOYMENT_BANDS: - target = int(round(n_firms * band_counts[band] / total)) - if target <= 0: + national = torch.tensor( + [ + float(sector_rows[band].fillna(0).sum()) if band in sector_rows else 0.0 + for band in EMPLOYMENT_BANDS + ], + dtype=torch.float32, + device=device, + ) + if float(national.sum().item()) <= 0: + national = torch.ones(len(EMPLOYMENT_BANDS), dtype=torch.float32, device=device) + national = national / national.sum() + counts_by_sic: dict[int, Tensor] = {} + for _, row in sector_rows.iterrows(): + sic = row.get("SIC Code") + if pd.isna(sic) or str(sic) in {"", "Total"}: continue - lower, upper, midpoint = ONS_EMPLOYMENT_BANDS[band] - if band == "0-4": - draws = torch.randint(1, 5, (target,), device=device).float() - elif band == "250+": - log_mean = torch.log(torch.tensor(float(midpoint), device=device)) - draws = torch.normal(log_mean, 0.8, (target,), device=device).exp() - draws = torch.clamp(draws, lower, upper).round() - else: - u = torch.rand(target, device=device) - beta_approx = u.pow(0.5) * (1 - u).pow(2.0) - draws = (lower + beta_approx * (upper - lower)).round() - values.extend(draws.cpu().numpy()) - - np.random.shuffle(values) - if len(values) < n_firms: - values.extend([1] * (n_firms - len(values))) - else: - values = values[:n_firms] - return torch.tensor(values, dtype=torch.float32, device=device) - + counts_by_sic[int(sic)] = torch.tensor( + [ + float(row[band]) if band in row and pd.notna(row[band]) else 0.0 + for band in EMPLOYMENT_BANDS + ], + dtype=torch.float32, + device=device, + ) -def assign_vat_flags( - turnover_values: Tensor, - hmrc_bands: dict[str, float], - config: UKFirmGenerationConfig, -) -> Tensor: - """Assign VAT-registration flags.""" + result = torch.empty(n_firms, dtype=torch.float32, device=device) + for sic in torch.unique(sic_codes).tolist(): + idx = torch.where(sic_codes == int(sic))[0] + counts = counts_by_sic.get(int(sic)) + if counts is None or float(counts.sum().item()) <= 0: + probs = national + else: + probs = counts / counts.sum() + band_ids = torch.multinomial(probs, len(idx), replacement=True) + for band_id, band in enumerate(EMPLOYMENT_BANDS): + out_idx = idx[band_ids == band_id] + if len(out_idx) == 0: + continue + lower, upper, midpoint = ONS_EMPLOYMENT_BANDS[band] + if band == "0-4": + values = torch.randint(1, 5, (len(out_idx),), device=device).float() + elif band == "250+": + log_mean = torch.log(torch.tensor(float(midpoint), device=device)) + values = torch.normal( + log_mean, 0.8, (len(out_idx),), device=device + ).exp() + values = torch.clamp(values, lower, upper).round() + else: + values = torch.randint( + int(lower), int(upper) + 1, (len(out_idx),), device=device + ).float() + result[out_idx] = values + return result + + +def employment_band_index_array(employment: np.ndarray) -> np.ndarray: + """Vectorised ONS employment-band index (0-6) for employment counts. + + Agrees with :func:`employment_band_name` and the scalar band index. + """ - threshold = float(config.vat_threshold) - device = turnover_values.device - below = (turnover_values > 0) & (turnover_values <= threshold) - flags = turnover_values > threshold - below_indices = below.nonzero(as_tuple=False).flatten() - if len(below_indices) == 0: - return flags - target_below = int(round(max(0.0, float(hmrc_bands["£1_to_Threshold"])))) - n_select = min(len(below_indices), target_below) - if n_select > 0: - selected = below_indices[ - torch.randperm(len(below_indices), device=device)[:n_select] - ] - flags[selected] = True - return flags + values = np.asarray(employment, dtype=np.float64) + return np.searchsorted(_EMPLOYMENT_BAND_UPPER_EDGES, values, side="left").astype( + np.int64 + ) def build_firm_target_matrix( config: UKFirmGenerationConfig, - turnover_values: Tensor, - sic_codes: Tensor, - input_values: Tensor, - employment_band_indices: Tensor, - vat_registered: Tensor, + turnover_values: np.ndarray | Tensor, + sic_codes: np.ndarray | Tensor, + employment_band_indices: np.ndarray | Tensor, data: UKFirmSourceData, - vat_liability_values: Tensor | None = None, -) -> tuple[Tensor, Tensor, UKFirmTargetLayout, tuple[str, ...]]: - """Construct the firm calibration target matrix and target vector.""" + *, + propensity: np.ndarray, + frame_mask: np.ndarray, + vat_liability_if_registered_k: np.ndarray, +) -> tuple[sparse.csr_array, np.ndarray, UKFirmTargetLayout, tuple[str, ...]]: + """Construct the firm calibration matrix (float32 CSR) and target vector. + + Two universes (paper issue #37). ONS-frame rows (population, employment + bands) give frame rows a one and appended HMRC traders a zero. HMRC + registered-trader rows (counts by band and sector, net VAT by sector and + calibrated band) give every row its registration ``propensity``; net-VAT + rows multiply it by the row's liability-if-registered in thousands of + pounds. The matrix is assembled from COO triples, never densified. + """ threshold = float(config.vat_threshold) + turnover = _as_numpy(turnover_values, np.float64) + sic = _as_numpy(sic_codes, np.int64) + employment_band = _as_numpy(employment_band_indices, np.int64) + frame = np.asarray(frame_mask, dtype=bool) + prop = np.asarray(propensity, dtype=np.float64) + liability = np.asarray(vat_liability_if_registered_k, dtype=np.float64) + n_firms = len(turnover) + for name, values in ( + ("sic_codes", sic), + ("employment_band_indices", employment_band), + ("frame_mask", frame), + ("propensity", prop), + ("vat_liability_if_registered_k", liability), + ): + if values.shape != (n_firms,): + raise ValueError(f"{name} has shape {values.shape}; expected ({n_firms},).") + hmrc_bands = _hmrc_band_targets_for_vintage( data.hmrc_population_band, config.data_vintage, @@ -983,10 +1248,7 @@ def build_firm_target_matrix( data.hmrc_liability_band, config.data_vintage, ) - n_firms = len(turnover_values) - sector_rows = data.hmrc_population_sector[ - data.hmrc_population_sector["Trade_Sector"] != "Total" - ].copy() + sector_targets = hmrc_sector_targets(data, config.data_vintage) if config.calibrate_vat_liability_sector: vat_sector_rows = data.hmrc_liability_sector[ data.hmrc_liability_sector["Trade_Sector"] != "Total" @@ -995,120 +1257,151 @@ def build_firm_target_matrix( vat_sector_rows = data.hmrc_liability_sector.iloc[0:0].copy() layout = UKFirmTargetLayout( - n_sectors=len(sector_rows), + n_sectors=len(sector_targets), n_vat_sectors=len(vat_sector_rows), ) - matrix = torch.zeros(layout.n_targets, n_firms, device=config.device) - band_indices = map_to_hmrc_band_indices(turnover_values, threshold) - - target_names: list[str] = [] - for row, band_idx in enumerate(range(1, 8)): - matrix[row, (band_indices == band_idx) & vat_registered] = 1.0 - target_names.append(f"hmrc_vat_population/{HMRC_BAND_COLUMNS[band_idx]}") - - for offset, (_, sector_row) in enumerate(sector_rows.iterrows()): - row = layout.sector_start + offset - sic_code = int(sector_row["Trade_Sector"]) - matrix[row, (sic_codes == sic_code) & vat_registered] = 1.0 - target_names.append(f"hmrc_vat_population_sector/{sic_code}") - - for band_idx, band in enumerate(EMPLOYMENT_BANDS): - row = layout.employment_start + band_idx - matrix[row, employment_band_indices == band_idx] = 1.0 - target_names.append(f"ons_firm_employment/{band}") - - vat_liability = ( - vat_liability_values - if vat_liability_values is not None - else calculate_vat_liability_values( - config, - turnover_values, - input_values, - vat_registered, - ) + band_indices = map_to_hmrc_band_indices( + torch.as_tensor(turnover, dtype=torch.float32), + threshold, + ).numpy() + columns = np.arange(n_firms, dtype=np.int64) + row_blocks: list[np.ndarray] = [] + column_blocks: list[np.ndarray] = [] + value_blocks: list[np.ndarray] = [] + + def add(rows: np.ndarray, mask: np.ndarray, values: np.ndarray) -> None: + row_blocks.append(np.asarray(rows, dtype=np.int64)[mask]) + column_blocks.append(columns[mask]) + value_blocks.append(np.asarray(values, dtype=np.float32)[mask]) + + # HMRC registered-trader counts by turnover band: row b for band b. + add(layout.turnover_start + band_indices, prop != 0, prop) + target_names = [f"hmrc_vat_population/{band}" for band in HMRC_BAND_COLUMNS] + + # ONS frame population. + add( + np.full(n_firms, layout.population_start), + frame, + np.ones(n_firms), ) - for offset, (_, vat_row) in enumerate(vat_sector_rows.iterrows()): - row = layout.vat_sector_start + offset - sic_code = int(vat_row["Trade_Sector"]) - mask = (sic_codes == sic_code) & vat_registered - matrix[row, mask] = vat_liability[mask] - target_names.append(f"hmrc_vat_liability_sector/{sic_code}") - - for offset, band in enumerate(VAT_LIABILITY_BANDS): - row = layout.vat_band_start + offset - mask = _band_membership_mask(turnover_values, band, threshold) & vat_registered - matrix[row, mask] = vat_liability[mask] - target_names.append(f"hmrc_vat_liability/{band}") - - turnover_targets = [ - hmrc_bands[band] for band in HMRC_BAND_COLUMNS if band != "Negative_or_Zero" - ] - sector_targets = [ - _vintage_column_value(row, config.data_vintage, "HMRC population sectors") - for _, row in sector_rows.iterrows() - ] - ons_emp_rows = data.ons_employment[ - ~data.ons_employment["Description"].astype(str).str.contains("Total", na=False) - ] - employment_targets = [ - float(ons_emp_rows[band].fillna(0).sum()) if band in ons_emp_rows else 0.0 - for band in EMPLOYMENT_BANDS + target_names.append("ons_firm_population/total") + + sector_codes = list(sector_targets) + sector_row = _row_lookup(sic, sector_codes, layout.sector_start) + add(sector_row, (sector_row >= 0) & (prop != 0), prop) + target_names.extend(f"hmrc_vat_population_sector/{code}" for code in sector_codes) + + add( + layout.employment_start + employment_band, + frame, + np.ones(n_firms), + ) + target_names.extend(f"ons_firm_employment/{band}" for band in EMPLOYMENT_BANDS) + + weighted_liability = liability * prop + vat_sector_codes = [ + int(row["Trade_Sector"]) for _, row in vat_sector_rows.iterrows() ] + vat_sector_row = _row_lookup(sic, vat_sector_codes, layout.vat_sector_start) + add( + vat_sector_row, + (vat_sector_row >= 0) & (weighted_liability != 0), + weighted_liability, + ) + target_names.extend( + f"hmrc_vat_liability_sector/{code}" for code in vat_sector_codes + ) + + band_row = np.full(n_firms, -1, dtype=np.int64) + for offset, band in enumerate(VAT_LIABILITY_BANDS_CALIBRATED): + band_row[band_indices == HMRC_BAND_COLUMNS.index(band)] = ( + layout.vat_band_start + offset + ) + add(band_row, (band_row >= 0) & (weighted_liability != 0), weighted_liability) + target_names.extend( + f"hmrc_vat_liability/{band}" for band in VAT_LIABILITY_BANDS_CALIBRATED + ) + + rows = np.concatenate(row_blocks) + index_dtype = ( + np.int32 + if max(layout.n_targets, n_firms) < np.iinfo(np.int32).max + else np.int64 + ) + matrix = sparse.csr_array( + ( + np.concatenate(value_blocks), + ( + rows.astype(index_dtype), + np.concatenate(column_blocks).astype(index_dtype), + ), + ), + shape=(layout.n_targets, n_firms), + dtype=np.float32, + ) + + turnover_targets = [float(hmrc_bands[band]) for band in HMRC_BAND_COLUMNS] vat_sector_targets = [ _vintage_column_value(row, config.data_vintage, "HMRC liability sectors") * 1000.0 for _, row in vat_sector_rows.iterrows() ] vat_band_targets = [ - float(vat_liability_bands[band]) * 1000.0 for band in VAT_LIABILITY_BANDS + float(vat_liability_bands[band]) * 1000.0 + for band in VAT_LIABILITY_BANDS_CALIBRATED ] - targets = torch.tensor( + targets = np.asarray( turnover_targets - + sector_targets - + employment_targets + + [float(data.ons_total)] + + list(sector_targets.values()) + + list(_employment_targets(data.ons_employment).values()) + vat_sector_targets + vat_band_targets, - dtype=torch.float32, - device=config.device, + dtype=np.float64, ) return matrix, targets, layout, tuple(target_names) def solve_firm_weights( config: UKFirmGenerationConfig, - target_matrix: Tensor, - target_values: Tensor, + target_matrix: sparse.sparray | sparse.spmatrix | Tensor, + target_values: np.ndarray | Tensor, layout: UKFirmTargetLayout, + *, + initial_weights: np.ndarray | None = None, ) -> UKFirmCalibrationResult: - """Solve firm weights using Microcosm's shared calibration optimizer.""" + """Solve firm weights with Microcosm's public constraint-system solver. - _, n_firms = target_matrix.shape - initial_weights = np.ones(n_firms, dtype=np.float64) - matrix_np = target_matrix.detach().cpu().numpy().astype(np.float64, copy=False) - matrix = sparse.csr_array(matrix_np) - target_np = target_values.detach().cpu().numpy().astype(np.float64, copy=False) + ``initial_weights`` default to one per row; stratified builds pass their + base weights, so the solve starts from (and its result is reported + against) a draw whose base-weighted totals reproduce the full draw. + """ + + matrix = _as_float32_csr(target_matrix) + _, n_firms = matrix.shape + initial = ( + np.ones(n_firms, dtype=np.float64) + if initial_weights is None + else np.asarray(initial_weights, dtype=np.float64) + ) + target_np = _as_numpy(target_values, np.float64) loss_weights = _target_loss_weights(layout, config) loss_scales = default_target_loss_scales(target_np) - torch.manual_seed(config.seed) - weights, trajectory = _calibrate_optimize( - _calibrate_torch_constraint_matrix(matrix), - torch.tensor(target_np, dtype=torch.float32), - torch.tensor(loss_weights, dtype=torch.float32), - torch.tensor(loss_scales, dtype=torch.float32), - config.target_loss_cap, - initial_weights, + weights, trajectory = solve_constraint_system( + matrix, + target_np, + initial, + target_loss_weights=loss_weights, + target_loss_scales=loss_scales, + target_loss_cap=config.target_loss_cap, + mass=CONSERVE_MASS if config.conserve_mass else FREE_MASS, + max_weight_ratio=config.max_weight_ratio, epochs=config.n_iterations, learning_rate=config.learning_rate, - conserve_mass=config.conserve_mass, - max_weight_ratio=config.max_weight_ratio, - l0_lambda=0.0, - l2_lambda=0.0, - target_records=None, - init_mean=0.999, - temperature=0.25, + seed=config.seed, ) - initial_estimates = matrix @ initial_weights + initial_estimates = matrix @ initial final_estimates = matrix @ weights return UKFirmCalibrationResult( weights=torch.tensor(weights, dtype=torch.float32, device=config.device), @@ -1129,43 +1422,59 @@ def solve_firm_weights( ), target_loss_weights=loss_weights, target_loss_scales=loss_scales, + initial_weights=initial, ) def optimize_firm_weights( config: UKFirmGenerationConfig, - target_matrix: Tensor, - target_values: Tensor, + target_matrix: sparse.sparray | sparse.spmatrix | Tensor, + target_values: np.ndarray | Tensor, layout: UKFirmTargetLayout, + *, + initial_weights: np.ndarray | None = None, ) -> Tensor: """Return core-solved firm weights for callers that only need the vector.""" - return solve_firm_weights(config, target_matrix, target_values, layout).weights + return solve_firm_weights( + config, + target_matrix, + target_values, + layout, + initial_weights=initial_weights, + ).weights def target_diagnostics( - target_matrix: Tensor, - target_values: Tensor, - weights: Tensor, + target_matrix: sparse.sparray | sparse.spmatrix | Tensor, + target_values: np.ndarray | Tensor, + weights: np.ndarray | Tensor, names: tuple[str, ...], + *, + initial_weights: np.ndarray | None = None, ) -> pd.DataFrame: - """Return per-target diagnostics for the optimized weight vector.""" + """Return per-target diagnostics for the optimized weight vector. + + ``initial_estimate`` uses ``initial_weights`` (one per row by default). + """ - estimates = (target_matrix @ weights).detach().cpu().numpy() - targets = target_values.detach().cpu().numpy() + matrix = _as_float32_csr(target_matrix) + weight_np = _as_numpy(weights, np.float64) + initial = ( + np.ones_like(weight_np) + if initial_weights is None + else np.asarray(initial_weights, dtype=np.float64) + ) + estimates = np.asarray(matrix @ weight_np, dtype=np.float64) + targets = _as_numpy(target_values, np.float64) relative_error = np.divide( estimates - targets, np.where(np.abs(targets) < 1e-9, 1.0, targets), ) - initial = np.ones_like(weights.detach().cpu().numpy(), dtype=np.float64) - initial_estimates = (target_matrix.detach().cpu().numpy() @ initial).astype( - np.float64, - copy=False, - ) return pd.DataFrame( { "target_name": names, - "initial_estimate": initial_estimates, + "initial_estimate": np.asarray(matrix @ initial, dtype=np.float64), "estimate": estimates, "target": targets, "relative_error": relative_error, @@ -1173,38 +1482,73 @@ def target_diagnostics( ) -def calculate_vat_liability_values( - config: UKFirmGenerationConfig, - turnover_values: Tensor, - input_values: Tensor, - vat_registered: Tensor, -) -> Tensor: - """Evaluate net VAT liability for candidate firms via configured VAT rules.""" +def hmrc_sector_targets( + data: UKFirmSourceData, + data_vintage: str, +) -> dict[int, float]: + """HMRC registered-trader count targets by sector, on the band universe. + + HMRC sector counts include traders whose turnover band is "Unknown" + (159,300 in 2024-25), who cannot enter the turnover-band rows. As in the + paper, the sector counts are scaled so they sum to the eight HMRC band + counts, allocating the unknown-band traders proportionally; band and + sector rows then count the same registered universe. + """ - evaluator = config.vat_rule_evaluator - if evaluator is None: - raise ValueError( - "UK firm VAT liability requires a VAT rule evaluator. " - "Pass AxiomVATRuleEvaluator with a compiled UK VAT RuleSpec artifact." + sector_rows = data.hmrc_population_sector[ + data.hmrc_population_sector["Trade_Sector"] != "Total" + ] + raw = { + int(row["Trade_Sector"]): _vintage_column_value( + row, data_vintage, "HMRC population sectors" ) - turnover_np = turnover_values.detach().cpu().numpy() - input_np = input_values.detach().cpu().numpy() - registered_np = vat_registered.detach().cpu().numpy().astype(bool) - liability_np = np.asarray( - evaluator.net_liability_k( - turnover_k=turnover_np, - input_cost_k=input_np, - vat_registered=registered_np, - data_vintage=config.data_vintage, - ), - dtype=np.float32, + for _, row in sector_rows.iterrows() + } + hmrc_bands = _hmrc_band_targets_for_vintage( + data.hmrc_population_band, + data_vintage, ) - if liability_np.shape != turnover_np.shape: - raise ValueError( - "VAT rule evaluator returned shape " - f"{liability_np.shape}, expected {turnover_np.shape}." - ) - return torch.tensor(liability_np, dtype=torch.float32, device=config.device) + band_total = float(sum(hmrc_bands.values())) + sector_total = float(sum(raw.values())) + scale = band_total / sector_total if sector_total > 0 else 1.0 + return {sic_code: value * scale for sic_code, value in raw.items()} + + +def resolve_uk_firm_rules(config: UKFirmGenerationConfig) -> UKFirmRules: + """The VAT rules a configuration evaluates candidate firms with. + + ``firm_rules`` wins; otherwise a legacy ``vat_rule_evaluator`` is wrapped + in :class:`~microcosm.build.uk_runtime.firm_rules.LegacyVATEvaluatorRules`. + """ + + if config.firm_rules is not None: + return config.firm_rules + if config.vat_rule_evaluator is not None: + return LegacyVATEvaluatorRules(config.vat_rule_evaluator) + raise ValueError( + "UK firm VAT liability requires a VAT rule evaluator. " + "Pass firm_rules (a UKFirmRules), or AxiomVATRuleEvaluator with a " + "compiled UK VAT RuleSpec artifact." + ) + + +def evaluate_vat_liability_if_registered_k( + rules: UKFirmRules, + firms: pd.DataFrame, + data_vintage: str, +) -> np.ndarray: + """Each candidate firm's VAT liability if registered, in thousands of pounds. + + ``firms`` holds ``firm_id``, ``sic_code``, ``annual_turnover_k``, + ``annual_input_k`` and ``employment``. The rules see the pre-calibration + candidate table (policyengine-uk names, pounds) and their outputs are + aligned back to ``firms`` by ``firm_id``. + """ + + candidates = build_candidate_rules_table(firms) + outputs = rules.evaluate(candidates, period=rule_period_for_vintage(data_vintage)) + liability_gbp = align_rule_outputs(outputs, firms["firm_id"].to_numpy(np.int64)) + return np.asarray(liability_gbp, dtype=np.float64) / 1000.0 def validate_uk_firm_population( @@ -1230,29 +1574,29 @@ def validate_uk_firm_population( df["weighted_liability_m"] = df["vat_liability_k"] * df["firm_weight"] / 1000.0 df["sic_numeric"] = df["sic_code"].astype(int) registered = df[df["vat_registered"]] + # Two universes: HMRC margins score registered rows, ONS margins score + # ONS-frame rows (appended negative/zero-turnover traders are outside it). + frame = df[df["in_frame"].astype(bool)] if "in_frame" in df else df weighted_bands = registered.groupby("hmrc_band")["firm_weight"].sum() hmrc_accs = [] for band_name, target in hmrc_bands.items(): hmrc_accs.append(_accuracy(float(weighted_bands.get(band_name, 0.0)), target)) employment_targets = _employment_targets(data.ons_employment) - df["employment_band"] = df["employment"].apply(employment_band_name) - weighted_employment = df.groupby("employment_band")["firm_weight"].sum() + weighted_employment = ( + frame.assign(employment_band=frame["employment"].apply(employment_band_name)) + .groupby("employment_band")["firm_weight"] + .sum() + ) employment_accs = [ _accuracy(float(weighted_employment.get(band, 0.0)), target) for band, target in employment_targets.items() ] - sector_rows = data.hmrc_population_sector[ - data.hmrc_population_sector["Trade_Sector"] != "Total" - ] weighted_sector = registered.groupby("sic_numeric")["firm_weight"].sum() sector_accs = [ - _accuracy( - float(weighted_sector.get(int(row["Trade_Sector"]), 0.0)), - _vintage_column_value(row, config.data_vintage, "HMRC population sectors"), - ) - for _, row in sector_rows.iterrows() + _accuracy(float(weighted_sector.get(sic_code, 0.0)), target) + for sic_code, target in hmrc_sector_targets(data, config.data_vintage).items() ] liability_sector_rows = data.hmrc_liability_sector[ @@ -1278,12 +1622,15 @@ def validate_uk_firm_population( # HMRC liability targets are in millions; firm rows store thousands. float(vat_liability_bands[band]), ) - for band in VAT_LIABILITY_BANDS + for band in VAT_LIABILITY_BANDS_CALIBRATED ] return UKFirmValidationReport( hmrc_bands=float(np.mean(hmrc_accs)) if hmrc_accs else 0.0, - ons_population=_accuracy(float(df["firm_weight"].sum()), float(data.ons_total)), + ons_population=_accuracy( + float(frame["firm_weight"].sum()), + float(data.ons_total), + ), employment=float(np.mean(employment_accs)) if employment_accs else 0.0, sector=float(np.mean(sector_accs)) if sector_accs else 0.0, vat_liability_sector=( @@ -1401,61 +1748,65 @@ def _draw_band_turnover( lower: float, upper: float, device: str, + *, + log_uniform: bool = False, ) -> Tensor: - band_width = upper - lower - noise_std = max(25.0, band_width * 0.2) - base = lower + torch.rand(count, device=device) * band_width - noise = torch.normal(0, noise_std, (count,), device=device) - return torch.clamp(base + noise, min=0.1) + """Draw turnover inside the half-open band ``[lower, upper)``. + + Uniform (log-uniform for the open top band), as in the paper generator: + the maximum-entropy allocation given band membership, which keeps every + draw inside its source band. + """ + + unit = torch.rand(count, device=device) + return draw_in_band( + unit, lower, upper, log_uniform=log_uniform, floor=MIN_DRAWN_TURNOVER_K + ) def _add_zero_turnover_firms( sic_codes: Tensor, turnover: Tensor, input_values: Tensor, - employment: Tensor, - weights: Tensor, - vat_registered: Tensor, + base_weights: np.ndarray, hmrc_bands: dict[str, float], - ons_employment: pd.DataFrame, device: str, -) -> tuple[Tensor, Tensor, Tensor, Tensor, Tensor, Tensor]: +) -> tuple[Tensor, Tensor, Tensor, np.ndarray, np.ndarray]: + """Append HMRC Negative_or_Zero traders, allocated by sector share. + + Called before calibration. Appended rows carry zero turnover and input, + base weight one and ``frame_mask`` False. Returns ``(sic_codes, turnover, + input_values, base_weights, frame_mask)``. + """ + + n_frame = len(sic_codes) + frame_mask = np.ones(n_frame, dtype=bool) target = int(round(hmrc_bands["Negative_or_Zero"])) - if target <= 0 or len(sic_codes) == 0: - return sic_codes, turnover, input_values, employment, weights, vat_registered - add_sics = _allocate_zero_turnover_sics(sic_codes, target) + add_sics = _allocate_zero_turnover_sics(sic_codes, target) if target > 0 else [] if not add_sics: - return sic_codes, turnover, input_values, employment, weights, vat_registered + return sic_codes, turnover, input_values, base_weights, frame_mask n_add = len(add_sics) - zero_employment = assign_employment(n_add, ons_employment, device) + zeros = torch.zeros(n_add, dtype=torch.float32, device=device) return ( torch.cat( [sic_codes, torch.tensor(add_sics, dtype=torch.int64, device=device)] ), - torch.cat([turnover, torch.zeros(n_add, dtype=torch.float32, device=device)]), - torch.cat( - [input_values, torch.zeros(n_add, dtype=torch.float32, device=device)] - ), - torch.cat([employment, zero_employment]), - torch.cat([weights, torch.ones(n_add, dtype=torch.float32, device=device)]), - torch.cat( - [ - vat_registered, - torch.ones(n_add, dtype=torch.bool, device=device), - ] - ), + torch.cat([turnover, zeros]), + torch.cat([input_values, zeros]), + np.concatenate([base_weights, np.ones(n_add, dtype=np.float64)]), + np.concatenate([frame_mask, np.zeros(n_add, dtype=bool)]), ) def _allocate_zero_turnover_sics(sic_codes: Tensor, target: int) -> list[int]: unique_sics, counts = torch.unique(sic_codes, return_counts=True) total = len(sic_codes) - exact_allocations = target * counts.float() / total + exact_allocations = target * counts.double() / total allocations = torch.floor(exact_allocations).to(torch.int64) remainder = target - int(allocations.sum().item()) if remainder > 0: fractional_order = torch.argsort( - exact_allocations - allocations.float(), + exact_allocations - allocations.double(), descending=True, ) allocations[fractional_order[:remainder]] += 1 @@ -1466,20 +1817,19 @@ def _allocate_zero_turnover_sics(sic_codes: Tensor, target: int) -> list[int]: def _assemble_firm_rows( - sic_codes: Tensor, - turnover: Tensor, - input_values: Tensor, - vat_liability: Tensor, - employment: Tensor, - weights: Tensor, - vat_registered: Tensor, + firm_ids: np.ndarray, + sic_codes: np.ndarray, + turnover: np.ndarray, + input_values: np.ndarray, + vat_liability: np.ndarray, + employment: np.ndarray, + weights: np.ndarray, + base_weights: np.ndarray, + frame_mask: np.ndarray, + vat_scope: np.ndarray, + vat_registered: np.ndarray, config: UKFirmGenerationConfig, ) -> pd.DataFrame: - sic_np = sic_codes.detach().cpu().numpy().astype(int) - turnover_np = turnover.detach().cpu().numpy() - input_np = input_values.detach().cpu().numpy() - vat_liability_np = vat_liability.detach().cpu().numpy() - firm_ids = np.arange(1, len(sic_np) + 1, dtype=np.int64) return pd.DataFrame( { "firm_id": firm_ids, @@ -1489,13 +1839,16 @@ def _assemble_firm_rows( for firm_id in firm_ids ], "data_vintage": config.data_vintage, - "sic_code": [str(sic).zfill(5) for sic in sic_np], - "annual_turnover_k": turnover_np, - "annual_input_k": input_np, - "vat_liability_k": vat_liability_np, - "employment": employment.detach().cpu().numpy().astype(int), - "firm_weight": weights.detach().cpu().numpy(), - "vat_registered": vat_registered.detach().cpu().numpy().astype(bool), + "sic_code": [str(int(sic)).zfill(5) for sic in sic_codes], + "annual_turnover_k": np.asarray(turnover, dtype=np.float32), + "annual_input_k": np.asarray(input_values, dtype=np.float32), + "vat_liability_k": np.asarray(vat_liability, dtype=np.float32), + "employment": np.asarray(employment).astype(int), + "firm_weight": np.asarray(weights, dtype=np.float32), + "base_weight": np.asarray(base_weights, dtype=np.float64), + "in_frame": np.asarray(frame_mask, dtype=bool), + "vat_scope": np.asarray(vat_scope, dtype=bool), + "vat_registered": np.asarray(vat_registered, dtype=bool), "generation_status": "experimental", } ) @@ -1509,6 +1862,9 @@ def _target_loss_weights( weights[layout.turnover_start : layout.turnover_start + layout.n_turnover] = ( config.turnover_importance ) + weights[layout.population_start : layout.population_start + layout.n_population] = ( + config.population_importance + ) weights[layout.sector_start : layout.sector_start + layout.n_sectors] = ( config.sector_importance ) @@ -1869,3 +2225,33 @@ def _accuracy(synthetic: float, target: float) -> float: if abs(target) < 1e-9: return 1.0 if abs(synthetic) < 1e-9 else 0.0 return max(0.0, 1.0 - abs(synthetic - target) / abs(target)) + + +def _as_numpy(values: np.ndarray | Tensor, dtype: type) -> np.ndarray: + if isinstance(values, Tensor): + values = values.detach().cpu().numpy() + return np.asarray(values, dtype=dtype) + + +def _as_float32_csr( + matrix: sparse.sparray | sparse.spmatrix | Tensor, +) -> sparse.csr_array: + if isinstance(matrix, Tensor): + matrix = sparse.csr_array(matrix.detach().cpu().numpy().astype(np.float32)) + return sparse.csr_array(matrix, dtype=np.float32) + + +def _row_lookup(codes: np.ndarray, row_codes: list[int], start: int) -> np.ndarray: + """Target row per firm for its code among ``row_codes``; -1 when absent.""" + + rows = np.full(len(codes), -1, dtype=np.int64) + if not row_codes: + return rows + ordered = np.asarray(row_codes, dtype=np.int64) + order = np.argsort(ordered, kind="stable") + sorted_codes = ordered[order] + position = np.searchsorted(sorted_codes, codes) + position = np.clip(position, 0, len(sorted_codes) - 1) + found = sorted_codes[position] == codes + rows[found] = start + order[position[found]] + return rows diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_policyengine_uk_rules.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_policyengine_uk_rules.py new file mode 100644 index 0000000000..b91f218964 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_policyengine_uk_rules.py @@ -0,0 +1,526 @@ +"""policyengine-uk as the firm tax rules for the UK firm generator. + +policyengine-uk's firm entity is the rules home for Microcosm's UK firms. +``PolicyEngineUKFirmRules`` implements ``firm_rules.UKFirmRules``: it loads +the pre-calibration candidate table (``firm_table.build_candidate_rules_table``) +as a policyengine-uk firm table beside a one-person stub household, runs a +``Microsimulation`` and reads ``firm_vat_liability_if_registered`` for each +firm. The Axiom RuleSpec evaluator stays an optional cross-check through +``firm_rules.LegacyVATEvaluatorRules``; it is no longer the rules home. + +The generator's rules seam reads only VAT. ``POLICYENGINE_UK_FIRM_REGISTERED_VARIABLE`` +names ``firm_vat_registered``, which a later step reconciles with the +generator's registration flags; the seam does not read it yet. + +``evaluate_uk_firm_taxes`` reads every firm tax from the exported firm table +(``to_policyengine_uk_firm_table``, ``uk_firms.parquet``): +``POLICYENGINE_UK_FIRM_TAX_VARIABLES`` lists firm VAT, employer NIC (after the +Employment Allowance), the apprenticeship levy, corporation tax, the bank +surcharge and business rates, then two informational outputs that are not +additional taxes: the Employment Allowance (already netted out of +``firm_employer_ni``) and the employer's automatic enrolment minimum +contribution (an employment cost). It hands policyengine-uk only the table's +policyengine-uk firm inputs (keys of +``firm_table.UK_FIRM_POLICYENGINE_UK_INPUT_STATUS``), so microcosm-only +columns such as ``vat_registered`` are dropped and policyengine-uk applies its +own registration test; any other ``firm_*`` column that is not a known input +is dropped with a warning (an output, or an input newer than the committed +policyengine-uk snapshot). Inputs the export does not set (paybill, profit, +rateable value, capital expenditure, R&D, region, legal form, the bank flag) +take policyengine-uk's defaults, so corporation tax, the bank surcharge, +business rates, employer NIC, the levy and auto-enrolment are zero. +``weighted_uk_firm_tax_totals`` sums each output by ``firm_weight``. + +policyengine-uk is imported only inside the default simulation factory, so +importing this module needs no engine. The firm entity and its VAT variables +and the other firm taxes come with PolicyEngine/policyengine-uk#2940; a +policyengine-uk without them, +such as the release Microcosm's ``uk`` extra pins today, makes the default +factory raise a ``RuntimeError`` naming that pull request. + +Firm order: policyengine-uk builds its firm population from the firm table's +``firm_id`` column in the order the table gives its rows, and returns firm +variables in that order. The default factory hands over the candidate table in +its own order and reads ``firm_id`` back, refusing a simulation whose firm ids +differ from the table's, so each liability is keyed by the input ``firm_id``. + +Period convention. A firm data vintage is evaluated in the period +``firm_rules.rule_period_for_vintage`` gives it, the tax year's start year: +2024-25 is period 2024 and 2023-24 is period 2023. This adapter passes that +period through unchanged, as the dataset's ``fiscal_year`` and as the +simulation period. It matches how policyengine-uk labels a year, by its +financial year's start: + +- a dataset's ``fiscal_year`` is the year its financial year starts + (``UKSingleYearDataset`` warns that "FRS 2024/25 data is 2024"); +- ``CountryTaxBenefitSystem`` runs ``convert_to_fiscal_year_parameters`` over + ``gov``, which writes each year's 30 April value (or, for + ``fiscal_year_blend`` leaves, the 6 April to 5 April average) at 1 January + of that year. Period ``Y`` therefore reads the parameters of financial year + ``Y``-``Y+1``, not those in force on 1 January ``Y``: period 2023 reads the + £85,000 VAT registration threshold, period 2024 the £90,000 one that took + effect on 1 April 2024, and period 2025 the 2025-26 values. + +The VAT registration threshold parameter carries no +``preserve_calendar_dates``, so it is annualised this way too. Reading period +2025 for the 2024-25 vintage would give 2025-26 parameters: the same for VAT +(20% and £90,000 in both years), but not for employer NIC, whose rate and +threshold changed in April 2025, which is why the period is the start year. +""" + +from __future__ import annotations + +import importlib.metadata +import warnings +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass +from typing import Any, Protocol + +import numpy as np +import pandas as pd + +from microcosm.build.firms import weighted_totals +from microcosm.build.uk_runtime.firm_rules import UKFirmRuleOutputs +from microcosm.build.uk_runtime.firm_table import ( + UK_FIRM_CANDIDATE_RULES_COLUMNS, + UK_FIRM_MICROCOSM_ONLY_COLUMNS, + UK_FIRM_POLICYENGINE_UK_INPUT_STATUS, +) + +#: The firm variable the adapter reads: the VAT a firm would owe if +#: registered, in pounds per year (``firm_vat`` charges it when registered). +POLICYENGINE_UK_FIRM_LIABILITY_VARIABLE = "firm_vat_liability_if_registered" + +#: policyengine-uk's VAT registration test, for a later reconciliation with +#: the generator's registration flags. Not read yet. +POLICYENGINE_UK_FIRM_REGISTERED_VARIABLE = "firm_vat_registered" + +#: The pull request that adds the firm entity and its VAT variables. +POLICYENGINE_UK_FIRM_PULL_REQUEST = "PolicyEngine/policyengine-uk#2940" + +#: The policyengine-uk entity key of firms. +POLICYENGINE_UK_FIRM_ENTITY = "firm" + +#: Variables the adapter needs from policyengine-uk. +POLICYENGINE_UK_FIRM_REQUIRED_VARIABLES = ( + "firm_id", + POLICYENGINE_UK_FIRM_LIABILITY_VARIABLE, +) + +#: Firm taxes ``evaluate_uk_firm_taxes`` reads: Firm-entity GBP-per-year +#: formula variables of policyengine-uk (PolicyEngine/policyengine-uk#2940), +#: each with its file under ``policyengine_uk/variables/gov/``: +#: +#: - ``firm_vat``: hmrc/vat/firm/firm_vat.py, net VAT, zero when not +#: registered, negative for a repayment; +#: - ``firm_employer_ni``: hmrc/national_insurance/employer/firm/, secondary +#: Class 1 after the Employment Allowance; +#: - ``apprenticeship_levy``: hmrc/apprenticeship_levy/; +#: - ``corporation_tax``: hmrc/corporation_tax/, after the R&D expenditure +#: credit and without the bank surcharge; +#: - ``bank_surcharge``: hmrc/bank_surcharge/; +#: - ``firm_business_rates``: hmrc/business_rates/firm/, England only. +POLICYENGINE_UK_FIRM_TAXES: tuple[str, ...] = ( + "firm_vat", + "firm_employer_ni", + "apprenticeship_levy", + "corporation_tax", + "bank_surcharge", + "firm_business_rates", +) + +#: Firm-entity GBP outputs read beside the taxes for information. Not +#: additional taxes: ``employment_allowance`` +#: (hmrc/national_insurance/employment_allowance/) is already subtracted in +#: ``firm_employer_ni``, and ``firm_auto_enrolment_employer_contribution`` +#: (dwp/auto_enrolment/) is an employment cost. Do not add them to the taxes. +POLICYENGINE_UK_FIRM_INFORMATIONAL_VARIABLES: tuple[str, ...] = ( + "employment_allowance", + "firm_auto_enrolment_employer_contribution", +) + +#: Everything ``evaluate_uk_firm_taxes`` reads by default, taxes first. +POLICYENGINE_UK_FIRM_TAX_VARIABLES: tuple[str, ...] = ( + *POLICYENGINE_UK_FIRM_TAXES, + *POLICYENGINE_UK_FIRM_INFORMATIONAL_VARIABLES, +) + +#: Candidate-table columns handed to policyengine-uk as firm inputs, in order. +#: All are formula-less policyengine-uk firm variables; any other column of the +#: table is dropped, so it cannot override a rule. +POLICYENGINE_UK_FIRM_INPUT_COLUMNS: tuple[str, ...] = tuple( + UK_FIRM_CANDIDATE_RULES_COLUMNS +) + +#: The provenance version recorded when policyengine-uk is not installed (an +#: injected factory, for example). +POLICYENGINE_UK_VERSION_UNKNOWN = "not installed" + + +class UKFirmSimulation(Protocol): + """What the adapter reads from a simulation: a firm variable's values.""" + + def calculate(self, variable_name: str, period: int) -> Any: + """Values of ``variable_name`` in ``period``, one per firm.""" + + +#: Builds a simulation over a firm input table for a period. +UKFirmSimulationFactory = Callable[[pd.DataFrame, int], UKFirmSimulation] + + +def _missing_firm_support_message( + detail: str, + variables: Sequence[str] = POLICYENGINE_UK_FIRM_REQUIRED_VARIABLES, +) -> str: + needed = ", ".join(name for name in variables if name != "firm_id") + what = ( + "VAT" + if tuple(variables) == POLICYENGINE_UK_FIRM_REQUIRED_VARIABLES + else "taxes" + ) + return ( + f"The installed policyengine-uk cannot evaluate UK firm {what}: " + f"{detail}. It needs the firm entity and {needed} " + f"from {POLICYENGINE_UK_FIRM_PULL_REQUEST}; install a policyengine-uk " + "that includes it." + ) + + +def require_policyengine_uk_firm_rules( + tax_benefit_system: Any, + dataset_class: Any = None, + *, + variables: Sequence[str] = POLICYENGINE_UK_FIRM_REQUIRED_VARIABLES, +) -> None: + """Raise ``RuntimeError`` unless policyengine-uk can evaluate firm rules. + + Checks that ``tax_benefit_system`` has the firm entity and ``variables`` + (by default ``POLICYENGINE_UK_FIRM_REQUIRED_VARIABLES``, what the VAT path + reads) as firm variables and, when given, that ``dataset_class`` + (``UKSingleYearDataset``) takes a ``firm`` table. The error names the + missing variable and PolicyEngine/policyengine-uk#2940. + """ + + variables = tuple(variables) + + entity_keys = { + getattr(entity, "key", None) + for entity in getattr(tax_benefit_system, "entities", ()) + } + if POLICYENGINE_UK_FIRM_ENTITY not in entity_keys: + raise RuntimeError( + _missing_firm_support_message("it has no Firm entity", variables) + ) + system_variables = getattr(tax_benefit_system, "variables", {}) + for name in variables: + variable = system_variables.get(name) + if variable is None: + raise RuntimeError( + _missing_firm_support_message(f"it has no {name} variable", variables) + ) + if getattr(variable.entity, "key", None) != POLICYENGINE_UK_FIRM_ENTITY: + raise RuntimeError( + _missing_firm_support_message( + f"{name} is not a firm variable", variables + ) + ) + if dataset_class is not None: + import inspect + + try: + parameters = inspect.signature(dataset_class).parameters + except (TypeError, ValueError): + parameters = {} + if "firm" not in parameters: + raise RuntimeError( + _missing_firm_support_message( + f"{getattr(dataset_class, '__name__', dataset_class)} " + "takes no firm table", + variables, + ) + ) + + +def _stub_household_tables() -> dict[str, pd.DataFrame]: + """One adult in one benefit unit and one household, as policyengine-uk's + firm tests use. Firms are root entities with no members, so the household + side only has to load.""" + + return { + "person": pd.DataFrame( + { + "person_id": [1], + "person_benunit_id": [1], + "person_household_id": [1], + "age": [40], + "employment_income": [0.0], + } + ), + "benunit": pd.DataFrame({"benunit_id": [1]}), + "household": pd.DataFrame( + { + "household_id": [1], + "household_weight": [1.0], + "region": ["LONDON"], + "rent": [0.0], + "tenure_type": ["OWNED_OUTRIGHT"], + "council_tax": [0.0], + } + ), + } + + +def policyengine_uk_firm_simulation( + firm_table: pd.DataFrame, period: int +) -> UKFirmSimulation: + """A policyengine-uk ``Microsimulation`` over ``firm_table`` in ``period``. + + The default ``PolicyEngineUKFirmRules`` factory. Imports policyengine-uk + here, checks it has the firm rules (``require_policyengine_uk_firm_rules``) + and builds a ``UKSingleYearDataset`` labelled ``fiscal_year=period`` with + a one-person stub household and ``firm_table`` as its firm table. + """ + + return _policyengine_uk_firm_simulation( + firm_table, period, POLICYENGINE_UK_FIRM_REQUIRED_VARIABLES + ) + + +def _policyengine_uk_firm_simulation( + firm_table: pd.DataFrame, period: int, variables: Sequence[str] +) -> UKFirmSimulation: + variables = tuple(variables) + try: + from policyengine_uk import CountryTaxBenefitSystem, Microsimulation + from policyengine_uk.data import UKSingleYearDataset + except ImportError as error: + raise RuntimeError( + _missing_firm_support_message(f"importing it failed ({error})", variables) + ) from error + require_policyengine_uk_firm_rules( + CountryTaxBenefitSystem(), UKSingleYearDataset, variables=variables + ) + dataset = UKSingleYearDataset( + **_stub_household_tables(), + firm=firm_table, + fiscal_year=int(period), + ) + return Microsimulation(dataset=dataset) + + +def policyengine_uk_version() -> str: + """The installed policyengine-uk version, or a marker when absent.""" + + try: + return importlib.metadata.version("policyengine-uk") + except importlib.metadata.PackageNotFoundError: + return POLICYENGINE_UK_VERSION_UNKNOWN + + +def _firm_values( + simulation: UKFirmSimulation, variable: str, period: int, n_firms: int +) -> np.ndarray: + values = simulation.calculate(variable, period) + values = np.asarray(values) + if values.shape != (n_firms,): + raise ValueError( + f"policyengine-uk returned {variable} with shape {values.shape} " + f"for {n_firms} firms." + ) + return values + + +@dataclass(frozen=True) +class PolicyEngineUKFirmRules: + """``UKFirmRules`` that run policyengine-uk's firm entity. + + ``evaluate`` hands the candidate table's + ``POLICYENGINE_UK_FIRM_INPUT_COLUMNS`` to ``simulation_factory`` with the + period, reads ``firm_vat_liability_if_registered`` (pounds per year, + negative for a repayment) and keys it by the input ``firm_id``. The + simulation's own ``firm_id`` must match the input order. + + ``simulation_factory`` defaults to ``policyengine_uk_firm_simulation``; + tests inject their own. + """ + + simulation_factory: UKFirmSimulationFactory | None = None + name: str = "policyengine_uk" + + def evaluate(self, firms: pd.DataFrame, *, period: int) -> UKFirmRuleOutputs: + missing = [ + column + for column in POLICYENGINE_UK_FIRM_INPUT_COLUMNS + if column not in firms.columns + ] + if missing: + raise ValueError(f"UK firm candidate table misses columns {missing}.") + period = int(period) + firm_table = firms.loc[:, list(POLICYENGINE_UK_FIRM_INPUT_COLUMNS)].reset_index( + drop=True + ) + firm_id = firm_table["firm_id"].to_numpy(np.int64) + factory = self.simulation_factory or policyengine_uk_firm_simulation + simulation = factory(firm_table, period) + + liability = _firm_values( + simulation, POLICYENGINE_UK_FIRM_LIABILITY_VARIABLE, period, len(firm_id) + ).astype(np.float64) + if not np.all(np.isfinite(liability)): + raise ValueError( + f"policyengine-uk returned a non-finite " + f"{POLICYENGINE_UK_FIRM_LIABILITY_VARIABLE}." + ) + simulated_ids = _firm_values(simulation, "firm_id", period, len(firm_id)) + if not np.array_equal(simulated_ids.astype(np.int64), firm_id): + raise ValueError( + "policyengine-uk's firm_id order differs from the candidate " + "table's, so its liabilities cannot be keyed by firm_id." + ) + + return UKFirmRuleOutputs( + firm_id=firm_id, + vat_liability_if_registered=liability, + provenance=self._provenance(period), + ) + + def _provenance(self, period: int) -> Mapping[str, str]: + return { + "rules": self.name, + "policyengine_uk_version": policyengine_uk_version(), + "variable": POLICYENGINE_UK_FIRM_LIABILITY_VARIABLE, + "period": str(period), + "output": "vat_liability_if_registered", + } + + +#: Columns of a firm table ``evaluate_uk_firm_taxes`` may hand to +#: policyengine-uk: its formula-less firm inputs. +_POLICYENGINE_UK_FIRM_INPUTS = frozenset( + {"firm_id", "firm_weight", *UK_FIRM_POLICYENGINE_UK_INPUT_STATUS} +) + + +def _default_tax_simulation_factory( + variables: Sequence[str], +) -> UKFirmSimulationFactory: + required = ("firm_id", *variables) + + def factory(firm_table: pd.DataFrame, period: int) -> UKFirmSimulation: + return _policyengine_uk_firm_simulation(firm_table, period, required) + + return factory + + +def evaluate_uk_firm_taxes( + firm_table: pd.DataFrame, + *, + period: int, + simulation_factory: UKFirmSimulationFactory | None = None, + variables: Sequence[str] = POLICYENGINE_UK_FIRM_TAX_VARIABLES, +) -> pd.DataFrame: + """Each firm's policyengine-uk taxes in ``period``, keyed by ``firm_id``. + + ``firm_table`` is the policyengine-uk-named export + (``firm_table.to_policyengine_uk_firm_table``, ``uk_firms.parquet``). Its + columns that are policyengine-uk firm inputs (keys of + ``UK_FIRM_POLICYENGINE_UK_INPUT_STATUS``), in the table's column order, + go to ``simulation_factory`` with ``period``; every other column + (microcosm-only ones, or one named after an output) is dropped, so it + cannot override a rule. ``firm_id`` is required. + + Returns one row per input row, in input order: ``firm_id`` (int64), + ``firm_weight`` (float64) when the table has it, then one float64 column + per name in ``variables`` (pounds per year). Raises ``ValueError`` if a + variable comes back with the wrong shape or a non-finite value, or if the + simulation's ``firm_id`` order differs from the table's. + + ``simulation_factory`` defaults to a policyengine-uk ``Microsimulation`` + (as ``policyengine_uk_firm_simulation``) that first checks every name in + ``variables`` is a firm variable, raising a ``RuntimeError`` that names + the missing one and PolicyEngine/policyengine-uk#2940. + """ + + variables = tuple(variables) + if not variables: + raise ValueError("evaluate_uk_firm_taxes needs at least one variable.") + if len(set(variables)) != len(variables): + raise ValueError(f"UK firm tax variables {list(variables)} repeat a name.") + clashing = [name for name in variables if name in ("firm_id", "firm_weight")] + if clashing: + raise ValueError(f"UK firm tax variables cannot include {clashing}.") + if "firm_id" not in firm_table.columns: + raise ValueError("UK firm table misses column firm_id.") + + period = int(period) + inputs = [ + column + for column in firm_table.columns + if column in _POLICYENGINE_UK_FIRM_INPUTS + ] + unknown = [ + column + for column in firm_table.columns + if str(column).startswith("firm_") + and column not in _POLICYENGINE_UK_FIRM_INPUTS + and column not in UK_FIRM_MICROCOSM_ONLY_COLUMNS + ] + if unknown: + warnings.warn( + f"evaluate_uk_firm_taxes drops firm columns {unknown}: they are not " + "policyengine-uk firm inputs in UK_FIRM_POLICYENGINE_UK_INPUT_STATUS " + "(an output, or an input newer than the committed snapshot).", + stacklevel=2, + ) + handed = firm_table.loc[:, inputs].reset_index(drop=True) + firm_id = handed["firm_id"].to_numpy(np.int64) + factory = simulation_factory or _default_tax_simulation_factory(variables) + simulation = factory(handed, period) + + simulated_ids = _firm_values(simulation, "firm_id", period, len(firm_id)) + if not np.array_equal(simulated_ids.astype(np.int64), firm_id): + raise ValueError( + "policyengine-uk's firm_id order differs from the firm table's, " + "so its taxes cannot be keyed by firm_id." + ) + columns: dict[str, np.ndarray] = {"firm_id": firm_id} + if "firm_weight" in handed.columns: + columns["firm_weight"] = handed["firm_weight"].to_numpy(np.float64) + for name in variables: + values = _firm_values(simulation, name, period, len(firm_id)).astype(np.float64) + if not np.all(np.isfinite(values)): + raise ValueError(f"policyengine-uk returned a non-finite {name}.") + columns[name] = values + return pd.DataFrame(columns) + + +def weighted_uk_firm_tax_totals(taxes: pd.DataFrame) -> dict[str, float]: + """Weighted total of each output of ``evaluate_uk_firm_taxes``. + + Returns ``sum(value * firm_weight)`` for every column other than + ``firm_id`` and ``firm_weight``, in pounds per year. Each total stands + alone: the informational outputs + (``POLICYENGINE_UK_FIRM_INFORMATIONAL_VARIABLES``) are not taxes to add. + """ + + return weighted_totals(taxes) + + +__all__ = [ + "POLICYENGINE_UK_FIRM_INFORMATIONAL_VARIABLES", + "POLICYENGINE_UK_FIRM_INPUT_COLUMNS", + "POLICYENGINE_UK_FIRM_LIABILITY_VARIABLE", + "POLICYENGINE_UK_FIRM_PULL_REQUEST", + "POLICYENGINE_UK_FIRM_REGISTERED_VARIABLE", + "POLICYENGINE_UK_FIRM_REQUIRED_VARIABLES", + "POLICYENGINE_UK_FIRM_TAXES", + "POLICYENGINE_UK_FIRM_TAX_VARIABLES", + "PolicyEngineUKFirmRules", + "UKFirmSimulation", + "UKFirmSimulationFactory", + "evaluate_uk_firm_taxes", + "policyengine_uk_firm_simulation", + "policyengine_uk_version", + "require_policyengine_uk_firm_rules", + "weighted_uk_firm_tax_totals", +] diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_rules.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_rules.py new file mode 100644 index 0000000000..ff7ec0ffa1 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_rules.py @@ -0,0 +1,280 @@ +"""The rules seam between the UK firm generator and a VAT rule engine. + +The experimental UK firm generator (``firm_generation``) calibrates candidate +firms to HMRC net VAT liability. It does not compute VAT itself: it hands a +pre-calibration candidate table to a ``UKFirmRules`` implementation and reads +back each firm's VAT liability if it were registered. Target rows then weight +that liability by each firm's registration propensity. + +The candidate table uses policyengine-uk firm variable names in pounds +(``firm_table.build_candidate_rules_table``): all turnover standard-rated, no +VAT scope and no registration. The rules return +``vat_liability_if_registered`` in pounds, keyed by ``firm_id``; +``align_rule_outputs`` puts it back in the generator's row order. + +Two implementations live in source. ``PolicyEngineUKFirmRules`` +(``firm_policyengine_uk_rules``) runs policyengine-uk's firm entity on the +candidate table and reads ``firm_vat_liability_if_registered`` (the liability +``firm_vat`` charges a registered firm); reconciling ``firm_vat_registered`` +with the generator's registration flags is still to come. +``LegacyVATEvaluatorRules`` wraps an existing ``UKFirmVATRuleEvaluator`` such as +the Axiom RuleSpec evaluator, which stays an optional cross-check. No reference VAT +evaluator lives in source; tests bring their own doubles. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from dataclasses import dataclass +from types import MappingProxyType +from typing import TYPE_CHECKING, Protocol + +import numpy as np +import pandas as pd + +from microcosm.build.firms import FirmRuleOutputs +from microcosm.build.firms import align_rule_outputs as _align_rule_outputs + +if TYPE_CHECKING: + from microcosm.build.uk_runtime.firm_generation import UKFirmVATRuleEvaluator + +#: The policyengine-uk period (a year label) each firm data vintage (a tax +#: year) is evaluated in: the tax year's start year. policyengine-uk annualises +#: its ``gov`` parameters so that period Y takes the value in force on 30 April +#: Y (``convert_to_fiscal_year_parameters``), which is the Y-to-Y+1 tax year's +#: value. Period 2024 therefore reads the £90,000 VAT registration threshold +#: that took effect on 2024-04-01, and period 2023 the £85,000 one. +UK_FIRM_RULE_PERIOD_BY_VINTAGE: Mapping[str, int] = MappingProxyType( + { + "2023-24": 2023, + "2024-25": 2024, + } +) + +#: The inverse view, for adapters that need the vintage back from a period. +UK_FIRM_VINTAGE_BY_RULE_PERIOD: Mapping[int, str] = MappingProxyType( + {period: vintage for vintage, period in UK_FIRM_RULE_PERIOD_BY_VINTAGE.items()} +) + + +#: How the rule period treats a mid-year change, recorded in the build +#: receipt. policyengine-uk evaluates period Y with the parameter values in +#: force on 30 April Y, unless a parameter opts into day-weighting, so a +#: change dated 1 January (or any date after 30 April) is not apportioned +#: across the tax year. +UK_FIRM_RULE_PERIOD_NOTE = ( + "Rules for period Y take the parameter values in force on 30 April Y " + "(policyengine-uk convert_to_fiscal_year_parameters). A change dated " + "later in the tax year, such as 1 January, is not apportioned unless the " + "parameter is day-weighted." +) + +#: The years the source data describe, which can lag the rule period. The +#: ONS UK Business 2025 workbook (the 2024-25 frame) takes turnover for most +#: traders from VAT returns for the financial year 2023/24 (its note 4), so +#: the frame's turnover near the threshold predates the £90,000 threshold; +#: HMRC's VAT statistics are for 2024-25 itself. A vintage whose source +#: years have not been checked records ``None``. +UK_FIRM_DATA_YEARS_BY_VINTAGE: Mapping[str, Mapping[str, str] | None] = ( + MappingProxyType( + { + "2023-24": None, + "2024-25": MappingProxyType( + { + "ons_frame_turnover": "2023-24", + "ons_frame_turnover_note": ( + "ONS, UK business: activity, size and location, 2025 " + "(published 2025-09-24; https://www.ons.gov.uk/" + "businessindustryandtrade/business/activitysizeandlocation/" + "datasets/ukbusinessactivitysizeandlocation), note 4: " + "turnover for most traders is from VAT returns covering " + "the financial year 2023/2024." + ), + "hmrc_vat_statistics": "2024-25", + } + ), + } + ) +) + + +def data_years_for_vintage(data_vintage: str) -> dict[str, str] | None: + """The years a firm data vintage's sources describe, or ``None`` if unchecked. + + Keyed on the data vintage, not on the files a build reads: a build of + vintage ``"2024-25"`` records these years whatever its processed tables + hold. + """ + + if data_vintage not in UK_FIRM_DATA_YEARS_BY_VINTAGE: + raise ValueError( + f"No UK firm data years for vintage {data_vintage!r}; " + f"choose from {sorted(UK_FIRM_DATA_YEARS_BY_VINTAGE)}." + ) + years = UK_FIRM_DATA_YEARS_BY_VINTAGE[data_vintage] + return None if years is None else dict(years) + + +def rule_period_for_vintage(data_vintage: str) -> int: + """The policyengine-uk period a firm data vintage is evaluated in. + + ``"2024-25"`` gives 2024 and ``"2023-24"`` gives 2023: see + ``UK_FIRM_RULE_PERIOD_BY_VINTAGE`` for why the period is the tax year's + start year. Any other vintage raises ``ValueError``. + """ + + try: + return UK_FIRM_RULE_PERIOD_BY_VINTAGE[data_vintage] + except KeyError: + raise ValueError( + f"No UK firm rule period for vintage {data_vintage!r}; " + f"choose from {sorted(UK_FIRM_RULE_PERIOD_BY_VINTAGE)}." + ) from None + + +#: The output name the UK VAT seam carries in ``FirmRuleOutputs.values``. +UK_FIRM_VAT_OUTPUT = "vat_liability_if_registered" + + +class UKFirmRuleOutputs(FirmRuleOutputs): + """VAT rule results for candidate firms, keyed by ``firm_id``. + + A ``microcosm.build.firms.FirmRuleOutputs`` with one output, + :data:`UK_FIRM_VAT_OUTPUT`. ``vat_liability_if_registered`` is in pounds + per firm per year; negative values are repayments. ``provenance`` names + the rules that produced it. + """ + + def __init__( + self, + *, + firm_id: np.ndarray, + vat_liability_if_registered: np.ndarray, + provenance: Mapping[str, str], + ) -> None: + super().__init__( + firm_id=firm_id, + values={UK_FIRM_VAT_OUTPUT: vat_liability_if_registered}, + provenance=provenance, + ) + + @property + def vat_liability_if_registered(self) -> np.ndarray: + return self.values[UK_FIRM_VAT_OUTPUT] + + +class UKFirmRules(Protocol): + """Evaluate VAT rules for a pre-calibration UK firm candidate table.""" + + def evaluate(self, firms: pd.DataFrame, *, period: int) -> UKFirmRuleOutputs: + """Return each firm's VAT liability if registered, in pounds.""" + + +def align_rule_outputs( + outputs: FirmRuleOutputs, + firm_id: np.ndarray | pd.Series, +) -> np.ndarray: + """``outputs``' VAT liabilities in the order of ``firm_id``, in pounds. + + ``microcosm.build.firms.align_rule_outputs`` does the alignment: it raises + ``ValueError`` when either side repeats a firm id, when a requested firm + has no output, or when the outputs hold a firm not requested. + """ + + aligned = _align_rule_outputs(outputs, firm_id) + if UK_FIRM_VAT_OUTPUT not in aligned: + raise ValueError( + f"UK firm rule outputs lack {UK_FIRM_VAT_OUTPUT}; they hold {sorted(aligned)}." + ) + return aligned[UK_FIRM_VAT_OUTPUT] + + +#: Candidate-table columns ``LegacyVATEvaluatorRules`` reads. +LEGACY_VAT_EVALUATOR_INPUT_COLUMNS = ( + "firm_id", + "firm_standard_rated_supplies", + "firm_input_costs", +) + + +@dataclass(frozen=True) +class LegacyVATEvaluatorRules: + """``UKFirmRules`` over an existing ``UKFirmVATRuleEvaluator``. + + The evaluator works in thousands of pounds and by data vintage; this + adapter takes the candidate table in policyengine-uk names and pounds: + + - ``turnover_k`` is ``firm_standard_rated_supplies / 1000`` (the Axiom + evaluator reads it as standard-rated taxable supplies); + - ``input_cost_k`` is ``firm_input_costs / 1000`` (read as standard-rated + deductible purchases; the evaluator applies the VAT rate itself, so the + table's ``firm_input_vat`` is not read); + - ``vat_registered`` is all true, so the result is the liability if + registered; + - ``data_vintage`` is the vintage ``period`` stands for + (``UK_FIRM_VINTAGE_BY_RULE_PERIOD``). + + The evaluator's thousands of pounds come back multiplied by 1000. + """ + + evaluator: UKFirmVATRuleEvaluator + name: str = "legacy_vat_rule_evaluator" + + def evaluate(self, firms: pd.DataFrame, *, period: int) -> UKFirmRuleOutputs: + missing = [ + column + for column in LEGACY_VAT_EVALUATOR_INPUT_COLUMNS + if column not in firms.columns + ] + if missing: + raise ValueError(f"UK firm candidate table misses columns {missing}.") + try: + data_vintage = UK_FIRM_VINTAGE_BY_RULE_PERIOD[int(period)] + except KeyError: + raise ValueError( + f"No UK firm data vintage for rule period {period!r}; " + f"choose from {sorted(UK_FIRM_VINTAGE_BY_RULE_PERIOD)}." + ) from None + supplies_k = firms["firm_standard_rated_supplies"].to_numpy(np.float64) / 1000 + input_k = firms["firm_input_costs"].to_numpy(np.float64) / 1000 + liability_k = np.asarray( + self.evaluator.net_liability_k( + turnover_k=supplies_k, + input_cost_k=input_k, + vat_registered=np.ones(len(firms), dtype=bool), + data_vintage=data_vintage, + ), + dtype=np.float64, + ) + if liability_k.shape != supplies_k.shape: + raise ValueError( + "VAT rule evaluator returned shape " + f"{liability_k.shape}, expected {supplies_k.shape}." + ) + return UKFirmRuleOutputs( + firm_id=firms["firm_id"].to_numpy(np.int64), + vat_liability_if_registered=liability_k * 1000.0, + provenance={ + "rules": self.name, + "evaluator": type(self.evaluator).__name__, + "data_vintage": data_vintage, + "period": str(int(period)), + "output": "vat_liability_if_registered", + }, + ) + + +__all__ = [ + "LEGACY_VAT_EVALUATOR_INPUT_COLUMNS", + "UK_FIRM_DATA_YEARS_BY_VINTAGE", + "UK_FIRM_RULE_PERIOD_BY_VINTAGE", + "UK_FIRM_RULE_PERIOD_NOTE", + "UK_FIRM_VAT_OUTPUT", + "UK_FIRM_VINTAGE_BY_RULE_PERIOD", + "LegacyVATEvaluatorRules", + "UKFirmRuleOutputs", + "UKFirmRules", + "align_rule_outputs", + "data_years_for_vintage", + "rule_period_for_vintage", +] diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_table.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_table.py new file mode 100644 index 0000000000..1caae2bdb7 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_table.py @@ -0,0 +1,437 @@ +"""UK firm tables in policyengine-uk firm variable names, in pounds. + +Two views of the experimental UK firm generator's rows: + +- ``build_candidate_rules_table`` is the pre-calibration table the VAT rules + (``firm_rules.UKFirmRules``) evaluate: no weight, no VAT scope and no + registration, with all turnover standard-rated so the rules return each + firm's liability if registered. +- ``to_policyengine_uk_firm_table`` is the calibrated export, with + policyengine-uk's firm inputs followed by the Microcosm-only columns + (``UK_FIRM_TABLE_COLUMNS``), checked by ``validate_uk_firm_table``. + +``firm_region``, ``firm_legal_form`` and ``firm_paybill`` are not set: the +generator draws none of them. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from types import MappingProxyType + +import numpy as np +import pandas as pd + +from microcosm.build.firms import INPUT_STATUSES +from microcosm.build.uk_runtime.occupation_constants import ( + UK_SIC2007_SECTION_DIVISIONS, + uk_sic2007_sections, +) + +#: Share of a firm's input costs charged as VAT. A data assumption, not VAT +#: law: every purchase is taken to be standard-rated at 20%. Replace it with +#: sector purchase mixes (zero-rated, reduced-rated and exempt purchases) in +#: M3. +ASSUMED_INPUT_VAT_RATE = 0.20 + +#: policyengine-uk's ``SICSection`` member for a firm whose SIC 2007 division +#: lies in no section. +UK_FIRM_SIC_SECTION_UNKNOWN = "UNKNOWN" + +#: policyengine-uk's ``SICSection`` member names: the SIC 2007 sections A-U of +#: ``UK_SIC2007_SECTION_DIVISIONS`` and the unknown member. +UK_FIRM_SIC_SECTIONS: tuple[str, ...] = ( + UK_FIRM_SIC_SECTION_UNKNOWN, + *UK_SIC2007_SECTION_DIVISIONS, +) + +#: Generator columns ``build_candidate_rules_table`` reads. +UK_FIRM_CANDIDATE_SOURCE_COLUMNS = ( + "firm_id", + "sic_code", + "annual_turnover_k", + "annual_input_k", + "employment", +) + +#: The candidate table the VAT rules evaluate, in order. +UK_FIRM_CANDIDATE_RULES_COLUMNS = ( + "firm_id", + "firm_turnover", + "firm_input_costs", + "firm_employees", + "firm_sic_section", + "firm_standard_rated_supplies", + "firm_exempt_supplies", + "firm_input_vat", +) + +#: Generator columns ``to_policyengine_uk_firm_table`` reads. +UK_FIRM_EXPORT_SOURCE_COLUMNS = ( + *UK_FIRM_CANDIDATE_SOURCE_COLUMNS, + "firm_weight", + "vat_scope", + "vat_registered", + "in_frame", + "base_weight", + "data_vintage", + "source_firm_id", + "source_firm_key", +) + +#: policyengine-uk firm input variables in the export, in order. +UK_FIRM_POLICYENGINE_UK_COLUMNS = ( + "firm_id", + "firm_weight", + "firm_turnover", + "firm_input_costs", + "firm_employees", + "firm_sic_section", + "firm_standard_rated_supplies", + "firm_exempt_supplies", + "firm_vat_voluntarily_registered", + "firm_input_vat", +) + +#: Microcosm-only columns the export carries after the policyengine-uk ones. +UK_FIRM_MICROCOSM_COLUMNS = ( + "in_frame", + "vat_scope", + "vat_registered", + "base_weight", + "data_vintage", + "source_firm_id", + "source_firm_key", +) + +#: The export's columns, in order. +UK_FIRM_TABLE_COLUMNS = (*UK_FIRM_POLICYENGINE_UK_COLUMNS, *UK_FIRM_MICROCOSM_COLUMNS) + +#: Microcosm-only columns: none may share a name with a policyengine-uk variable, +#: or a dataset load would read it as one. +UK_FIRM_MICROCOSM_ONLY_COLUMNS = UK_FIRM_MICROCOSM_COLUMNS + +#: Values of ``UK_FIRM_POLICYENGINE_UK_INPUT_STATUS``: +#: +#: - ``set``: mapped directly from a generator column; +#: - ``derived``: computed from other columns by a rule; +#: - ``assumed``: carries a data assumption beyond the source; +#: - ``not_set``: not exported; policyengine-uk's default applies. +UK_FIRM_INPUT_STATUSES = INPUT_STATUSES + +#: Every formula-less policyengine-uk firm input (branch firm-entity-engine at +#: ``0d1c25010``, the committed snapshot) -> how this export fills it. The keys +#: with status other than ``not_set`` are exactly ``UK_FIRM_POLICYENGINE_UK_COLUMNS``. +#: ``firm_input_vat`` is ``ASSUMED_INPUT_VAT_RATE`` on all input costs. Every other +#: input waits for a source (region and legal status, paybill, profit, rateable +#: value, flags), so policyengine-uk applies its default. +UK_FIRM_POLICYENGINE_UK_INPUT_STATUS: Mapping[str, str] = MappingProxyType( + { + "firm_id": "set", + "firm_weight": "set", + "firm_turnover": "set", + "firm_input_costs": "set", + "firm_employees": "set", + "firm_sic_section": "set", + "firm_region": "not_set", + "firm_standard_rated_supplies": "derived", + "firm_exempt_supplies": "derived", + "firm_vat_voluntarily_registered": "derived", + "firm_in_england": "not_set", + "firm_input_vat": "assumed", + "firm_legal_form": "not_set", + "firm_is_public_body": "not_set", + "firm_paybill": "not_set", + "firm_taxable_trading_profit": "not_set", + "firm_rateable_value": "not_set", + "firm_n_associated_companies": "not_set", + "firm_small_profits_rate_excluded": "not_set", + "firm_is_bank": "not_set", + "firm_is_charity": "not_set", + "firm_is_single_director_company": "not_set", + "firm_in_freeport": "not_set", + "firm_zero_rated_supplies": "not_set", + "firm_reduced_rated_supplies": "not_set", + "firm_is_limited_cost_trader": "not_set", + "firm_uses_flat_rate_scheme": "not_set", + "firm_is_industrial_property": "not_set", + "firm_is_pub_or_live_music_venue": "not_set", + "firm_is_live_music_venue": "not_set", + "firm_is_rhl_property": "not_set", + "firm_is_wales_retail_property": "not_set", + "firm_is_wales_higher_multiplier_excluded": "not_set", + "firm_months_empty": "not_set", + "firm_n_properties": "not_set", + "firm_property_occupied": "not_set", + "firm_aia_share": "not_set", + "firm_capex_main_pool_new": "not_set", + "firm_capex_main_pool_new_for_leasing": "not_set", + "firm_capex_main_pool_used": "not_set", + "firm_capex_special_rate_new": "not_set", + "firm_capex_special_rate_used": "not_set", + "firm_capex_structures": "not_set", + "firm_disposal_proceeds_main_pool": "not_set", + "firm_disposal_proceeds_full_expensing": "not_set", + "firm_main_pool_brought_forward": "not_set", + "firm_sba_qualifying_cost_brought_forward": "not_set", + "firm_special_rate_pool_brought_forward": "not_set", + "firm_bank_surcharge_allowance_share": "not_set", + "firm_deductions_allowance_share": "not_set", + "firm_exempt_distributions": "not_set", + "firm_losses_brought_forward": "not_set", + "firm_non_trading_profits": "not_set", + "firm_apprenticeship_levy_allowance_share": "not_set", + "firm_claims_employment_allowance": "not_set", + "firm_zero_rated_class_1_earnings": "not_set", + "firm_class_1a_benefits": "not_set", + "firm_employees_above_auto_enrolment_upper_limit": "not_set", + "firm_employees_below_auto_enrolment_earnings_trigger": "not_set", + "firm_employees_below_secondary_threshold": "not_set", + "firm_paybill_above_auto_enrolment_upper_limit": "not_set", + "firm_paybill_below_auto_enrolment_earnings_trigger": "not_set", + "firm_paybill_below_secondary_threshold": "not_set", + "firm_low_paid_hours": "not_set", + "firm_low_paid_paybill": "not_set", + "firm_is_sme": "not_set", + "firm_qualifying_rd_expenditure": "not_set", + "firm_rdec_paye_nic_cap_supplied": "not_set", + "firm_rd_staff_paye_nic": "not_set", + "firm_relevant_paye_nic_liabilities": "not_set", + "firm_total_relevant_expenditure": "not_set", + } +) + +_BOOL_COLUMNS = ( + "firm_vat_voluntarily_registered", + "in_frame", + "vat_scope", + "vat_registered", +) +_NON_NEGATIVE_COLUMNS = ( + "firm_weight", + "base_weight", + "firm_turnover", + "firm_input_costs", + "firm_standard_rated_supplies", + "firm_exempt_supplies", + "firm_input_vat", +) + + +def _require(frame: pd.DataFrame, columns: tuple[str, ...], label: str) -> None: + missing = [column for column in columns if column not in frame.columns] + if missing: + raise ValueError(f"{label} misses columns {missing}.") + + +def _firm_ids(frame: pd.DataFrame) -> np.ndarray: + ids = frame["firm_id"] + if not pd.api.types.is_integer_dtype(ids): + raise ValueError("UK firm firm_id must be integers.") + if ids.duplicated().any(): + raise ValueError("UK firm firm_id repeats.") + return ids.to_numpy(np.int64) + + +def _gbp(frame: pd.DataFrame, column: str) -> np.ndarray: + values = frame[column].to_numpy(np.float64) * 1000.0 + if not np.all(np.isfinite(values)) or np.any(values < 0): + raise ValueError(f"UK firm {column} must be finite and non-negative.") + return values + + +def _employees(frame: pd.DataFrame) -> np.ndarray: + values = frame["employment"].to_numpy() + if not np.issubdtype(values.dtype, np.integer): + as_float = values.astype(np.float64) + if not np.all(np.isfinite(as_float)) or np.any(as_float != np.round(as_float)): + raise ValueError("UK firm employment must be whole numbers.") + values = values.astype(np.int64) + if np.any(values < 0): + raise ValueError("UK firm employment must be non-negative.") + return values + + +def uk_firm_sic_sections(sic_code: pd.Series | np.ndarray) -> np.ndarray: + """policyengine-uk ``SICSection`` member names for two-digit SIC divisions. + + ``sic_code`` holds a SIC 2007 division (01-99) as an integer or as the + generator's zero-padded string (``"00011"`` is division 11; it is not a + five-digit SIC class). A division in no section gives ``"UNKNOWN"``; a + value outside 0-99 or not a whole number raises ``ValueError``. + """ + + raw = pd.Series(np.asarray(sic_code, dtype=object)) + try: + numeric = pd.to_numeric(raw, errors="raise").to_numpy(np.float64) + except (TypeError, ValueError): + raise ValueError("UK firm sic_code must hold SIC 2007 divisions.") from None + if ( + not np.all(np.isfinite(numeric)) + or np.any(numeric != np.round(numeric)) + or np.any(numeric < 0) + or np.any(numeric > 99) + ): + raise ValueError( + "UK firm sic_code must hold two-digit SIC 2007 divisions (0-99)." + ) + sections = uk_sic2007_sections(numeric.astype(np.int64)) + sections[sections == ""] = UK_FIRM_SIC_SECTION_UNKNOWN + return sections + + +def build_candidate_rules_table(firms: pd.DataFrame) -> pd.DataFrame: + """The pre-calibration candidate table the VAT rules evaluate. + + Reads ``UK_FIRM_CANDIDATE_SOURCE_COLUMNS`` (thousands of pounds for + turnover and input costs) and returns ``UK_FIRM_CANDIDATE_RULES_COLUMNS`` + in pounds, ordered by ``firm_id``. All turnover is standard-rated and + nothing is exempt, so the rules' liability is the liability if + registered; VAT scope and registration come later. + """ + + _require(firms, UK_FIRM_CANDIDATE_SOURCE_COLUMNS, "UK firm candidates") + firm_id = _firm_ids(firms) + turnover = _gbp(firms, "annual_turnover_k") + input_costs = _gbp(firms, "annual_input_k") + table = pd.DataFrame( + { + "firm_id": firm_id, + "firm_turnover": turnover, + "firm_input_costs": input_costs, + "firm_employees": _employees(firms), + "firm_sic_section": uk_firm_sic_sections(firms["sic_code"]), + "firm_standard_rated_supplies": turnover, + "firm_exempt_supplies": np.zeros_like(turnover), + "firm_input_vat": ASSUMED_INPUT_VAT_RATE * input_costs, + }, + columns=list(UK_FIRM_CANDIDATE_RULES_COLUMNS), + ) + return table.sort_values("firm_id", kind="stable").reset_index(drop=True) + + +def to_policyengine_uk_firm_table( + firms: pd.DataFrame, + *, + threshold_k: float, +) -> pd.DataFrame: + """The calibrated firm table in policyengine-uk names and pounds. + + Reads ``UK_FIRM_EXPORT_SOURCE_COLUMNS`` and returns + ``UK_FIRM_TABLE_COLUMNS``, ordered by ``firm_id``: + + - turnover and input costs are the generator's thousands of pounds times + 1000; + - a firm in VAT scope has all turnover standard-rated, one out of scope + has it all exempt; + - ``firm_vat_voluntarily_registered`` is a registered firm whose turnover + does not exceed ``threshold_k`` (thousands of pounds); + - ``firm_input_vat`` is ``ASSUMED_INPUT_VAT_RATE`` times input costs for + every firm; policyengine-uk's partial exemption share restricts its + recovery. + + The result passes ``validate_uk_firm_table``. + """ + + _require(firms, UK_FIRM_EXPORT_SOURCE_COLUMNS, "UK firm population") + if not np.isfinite(threshold_k) or threshold_k <= 0: + raise ValueError("UK firm threshold_k must be positive.") + for column in ("vat_scope", "vat_registered", "in_frame"): + # A missing value would otherwise read as True. + if not pd.api.types.is_bool_dtype(firms[column]): + raise ValueError(f"UK firm {column} must be boolean.") + candidates = build_candidate_rules_table(firms) + ordered = firms.assign(_firm_id=_firm_ids(firms)).sort_values( + "_firm_id", kind="stable" + ) + scope = ordered["vat_scope"].to_numpy(bool) + registered = ordered["vat_registered"].to_numpy(bool) + turnover_k = ordered["annual_turnover_k"].to_numpy(np.float64) + turnover = candidates["firm_turnover"].to_numpy() + table = pd.DataFrame( + { + "firm_id": candidates["firm_id"].to_numpy(), + "firm_weight": ordered["firm_weight"].to_numpy(np.float64), + "firm_turnover": turnover, + "firm_input_costs": candidates["firm_input_costs"].to_numpy(), + "firm_employees": candidates["firm_employees"].to_numpy(), + "firm_sic_section": candidates["firm_sic_section"].to_numpy(), + "firm_standard_rated_supplies": np.where(scope, turnover, 0.0), + "firm_exempt_supplies": np.where(scope, 0.0, turnover), + "firm_vat_voluntarily_registered": registered & (turnover_k <= threshold_k), + "firm_input_vat": candidates["firm_input_vat"].to_numpy(), + "in_frame": ordered["in_frame"].to_numpy(bool), + "vat_scope": scope, + "vat_registered": registered, + "base_weight": ordered["base_weight"].to_numpy(np.float64), + "data_vintage": ordered["data_vintage"].astype(str).to_numpy(), + "source_firm_id": ordered["source_firm_id"].to_numpy(np.int64), + "source_firm_key": ordered["source_firm_key"].astype(str).to_numpy(), + }, + columns=list(UK_FIRM_TABLE_COLUMNS), + ) + validate_uk_firm_table(table) + return table + + +def validate_uk_firm_table(df: pd.DataFrame) -> None: + """Raise ``ValueError`` unless ``df`` meets the UK firm table contract. + + The contract: exactly ``UK_FIRM_TABLE_COLUMNS`` in order; integer + ``firm_id``, unique and ascending; finite non-negative weights and money; + non-negative integer employees; ``SICSection`` member names; boolean flags; + supplies that split turnover by VAT scope; and voluntary registration only + for registered firms. + """ + + if tuple(df.columns) != UK_FIRM_TABLE_COLUMNS: + raise ValueError( + f"UK firm table columns {list(df.columns)} are not " + f"{list(UK_FIRM_TABLE_COLUMNS)}." + ) + firm_id = _firm_ids(df) + if np.any(np.diff(firm_id) < 0): + raise ValueError("UK firm table must be ordered by firm_id.") + for column in _NON_NEGATIVE_COLUMNS: + values = df[column].to_numpy(np.float64) + if not np.all(np.isfinite(values)) or np.any(values < 0): + raise ValueError(f"UK firm {column} must be finite and non-negative.") + employees = df["firm_employees"] + if not pd.api.types.is_integer_dtype(employees) or (employees < 0).any(): + raise ValueError("UK firm firm_employees must be non-negative integers.") + if not df["firm_sic_section"].isin(UK_FIRM_SIC_SECTIONS).all(): + raise ValueError("UK firm firm_sic_section must be SICSection member names.") + for column in _BOOL_COLUMNS: + if not pd.api.types.is_bool_dtype(df[column]): + raise ValueError(f"UK firm {column} must be boolean.") + turnover = df["firm_turnover"].to_numpy(np.float64) + standard = df["firm_standard_rated_supplies"].to_numpy(np.float64) + exempt = df["firm_exempt_supplies"].to_numpy(np.float64) + scope = df["vat_scope"].to_numpy(bool) + if not np.allclose(standard + exempt, turnover, rtol=1e-9, atol=1e-6): + raise ValueError("UK firm supplies must add up to turnover.") + if np.any(exempt[scope] != 0) or np.any(standard[~scope] != 0): + raise ValueError("UK firm supplies must follow vat_scope.") + voluntary = df["firm_vat_voluntarily_registered"].to_numpy(bool) + if np.any(voluntary & ~df["vat_registered"].to_numpy(bool)): + raise ValueError("UK firm voluntary registration needs vat_registered.") + + +__all__ = [ + "ASSUMED_INPUT_VAT_RATE", + "UK_FIRM_CANDIDATE_RULES_COLUMNS", + "UK_FIRM_CANDIDATE_SOURCE_COLUMNS", + "UK_FIRM_EXPORT_SOURCE_COLUMNS", + "UK_FIRM_INPUT_STATUSES", + "UK_FIRM_MICROCOSM_COLUMNS", + "UK_FIRM_MICROCOSM_ONLY_COLUMNS", + "UK_FIRM_POLICYENGINE_UK_COLUMNS", + "UK_FIRM_POLICYENGINE_UK_INPUT_STATUS", + "UK_FIRM_SIC_SECTIONS", + "UK_FIRM_SIC_SECTION_UNKNOWN", + "UK_FIRM_TABLE_COLUMNS", + "build_candidate_rules_table", + "to_policyengine_uk_firm_table", + "uk_firm_sic_sections", + "validate_uk_firm_table", +] diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_universe.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_universe.py new file mode 100644 index 0000000000..b0d4c6123b --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_universe.py @@ -0,0 +1,259 @@ +"""UK firm universe: stratified thinning, registration propensity, VAT scope. + +The UK uses of three country-neutral mechanics in ``microcosm.build.firms``, +which mirror the firm-microsim-paper generator (``firm_microsim`` at paper +commit aa1ce07): + +* :func:`stratified_thin` mirrors ``generate.stratified_thin``; +* :func:`registration_propensity` mirrors ``calibration.registration_propensity``; +* :func:`assign_vat_scope_and_registration` mirrors ``generate.assign_vat_flags`` + together with its helper ``generate._select_to_weighted_target``. + +Shared conventions +------------------ +``band_idx`` is an integer array of HMRC VAT turnover-band indices, one per +row, using the paper's ``calibration.map_to_hmrc_bands`` layout:: + + 0 Negative_or_Zero 4 £300k_to_£500k + 1 £1_to_Threshold 5 £500k_to_£1m + 2 £Threshold_to_£150k 6 £1m_to_£10m + 3 £150k_to_£300k 7 Greater_than_£10m + +``hmrc_bands`` is a one-dimensional float array of HMRC registered-trader +counts aligned with that index: ``hmrc_bands[b]`` is the HMRC count for band +``b``, so it has exactly :data:`N_HMRC_BANDS` (8) entries. Index 0 is accepted +but unused here, because appended negative/zero-turnover rows are HMRC traders +by construction (the paper's treatment). + +``frame_mask`` is a boolean array, True for rows drawn from the ONS +VAT/PAYE enterprise frame and False for appended HMRC negative/zero-turnover +traders. + +The VAT bands enter the shared functions through +:data:`UK_VAT_REGISTRATION_SPEC`: ``Negative_or_Zero`` is excluded (appended +traders live there, outside the frame), ``£1_to_Threshold`` is registrable and +the six bands above the threshold are selected. + +The module does not depend on torch or on ``firm_generation``; callers convert +tensors to numpy before calling it. +""" + +from __future__ import annotations + +import numpy as np + +from microcosm.build.firms import ( + RegistrationSpec, + assign_scope_and_registration, +) +from microcosm.build.firms import ( + registration_propensity as _registration_propensity, +) +from microcosm.build.firms import ( + stratified_thin as _stratified_thin, +) + +__all__ = [ + "HMRC_BAND_NAMES", + "N_HMRC_BANDS", + "UK_VAT_REGISTRATION_SPEC", + "assign_vat_scope_and_registration", + "registration_propensity", + "stratified_thin", +] + +#: HMRC VAT turnover bands, in ``band_idx`` order (paper ``map_to_hmrc_bands``). +HMRC_BAND_NAMES: tuple[str, ...] = ( + "Negative_or_Zero", + "£1_to_Threshold", + "£Threshold_to_£150k", + "£150k_to_£300k", + "£300k_to_£500k", + "£500k_to_£1m", + "£1m_to_£10m", + "Greater_than_£10m", +) +N_HMRC_BANDS = len(HMRC_BAND_NAMES) + +#: The HMRC VAT bands' registration roles (``microcosm.build.firms.registration``). +UK_VAT_REGISTRATION_SPEC = RegistrationSpec( + HMRC_BAND_NAMES, + ("excluded", "registrable", *("selected",) * (N_HMRC_BANDS - 2)), +) + + +def _as_1d(name: str, values: object, length: int | None = None) -> np.ndarray: + array = np.asarray(values) + if array.ndim != 1: + raise ValueError(f"{name} must be one-dimensional, got shape {array.shape}") + if length is not None and len(array) != length: + raise ValueError(f"{name} has {len(array)} entries; expected {length}") + return array + + +def _hmrc_counts(hmrc_bands: object) -> np.ndarray: + counts = _as_1d("hmrc_bands", hmrc_bands, N_HMRC_BANDS).astype(np.float64) + if not np.all(np.isfinite(counts)) or np.any(counts < 0): + raise ValueError("hmrc_bands must hold finite, non-negative counts") + return counts + + +def _band_indices(band_idx: object, length: int | None = None) -> np.ndarray: + bands = _as_1d("band_idx", band_idx, length) + if not np.issubdtype(bands.dtype, np.integer): + raise TypeError("band_idx must be an integer array") + if bands.size and (bands.min() < 0 or bands.max() >= N_HMRC_BANDS): + raise ValueError(f"band_idx values must lie in [0, {N_HMRC_BANDS - 1}]") + return bands.astype(np.int64) + + +def stratified_thin( + turnover_k: np.ndarray, + sic: np.ndarray, + band_idx: np.ndarray, + *, + window_lo_k: float, + window_hi_k: float, + window_fraction: float, + tail_fraction: float, + cell_floor: int, + seed: int, +) -> tuple[np.ndarray, np.ndarray]: + """Thin a candidate firm draw by stratum and return exact base weights. + + Mirrors ``firm_microsim/generate.py::stratified_thin``. Rows whose + turnover lies inside the analysis window ``[window_lo_k, window_hi_k]`` + (inclusive, £ thousands) are kept with probability ``window_fraction``; + every other row is kept with probability ``tail_fraction``. Strata are + SIC code x HMRC band x window side. A stratum that keeps fewer rows than + ``min(cell_floor, stratum size)`` is topped up with its unkept rows of + lowest uniform draw until it reaches that floor, so small strata survive. + Each kept row's base weight is its stratum's size divided by its kept + count, so the base-weighted count of every stratum equals its original + row count (up to float64 rounding of ``kept * (size / kept)``). + + One uniform draw per row comes from ``np.random.default_rng(seed + 1)``, + the paper's generator and offset. Because draws lie in ``[0, 1)``, + fractions of 1.0 keep every row with base weight 1.0. + + Args: + turnover_k: Float array, shape ``(n,)``: turnover in £ thousands. + sic: Integer array, shape ``(n,)``: SIC code of each row. + band_idx: Integer array, shape ``(n,)``: HMRC band index (0-7), as + the paper computes from turnover and the VAT threshold. + window_lo_k: Lower window edge (£ thousands, inclusive). + window_hi_k: Upper window edge (£ thousands, inclusive). + window_fraction: Keep probability inside the window, in ``[0, 1]``. + tail_fraction: Keep probability outside the window, in ``[0, 1]``. + cell_floor: Minimum kept rows per stratum (capped at stratum size). + seed: Base seed; the generator is seeded with ``seed + 1``. + + Returns: + ``(keep_idx, base_weights)``: ``keep_idx`` is an ascending int64 array + of kept row positions; ``base_weights`` is a float64 array of the same + length giving each kept row's base weight. + """ + bands = _band_indices(band_idx, len(np.asarray(turnover_k))) + return _stratified_thin( + turnover_k, + [sic, bands], + window_lo=window_lo_k, + window_hi=window_hi_k, + window_fraction=window_fraction, + tail_fraction=tail_fraction, + cell_floor=cell_floor, + rng_seed=int(seed) + 1, + ) + + +def registration_propensity( + band_idx: np.ndarray, + frame_mask: np.ndarray, + base_weights: np.ndarray, + hmrc_bands: np.ndarray, +) -> np.ndarray: + """Per-row probability of being a VAT-registered trader, by HMRC band. + + Mirrors ``firm_microsim/calibration.py::registration_propensity``. For + each positive-turnover band ``b`` (1-7) the propensity of frame rows in + that band is ``hmrc_bands[b]`` divided by the band's base-weighted frame + mass, capped at 1.0 when the frame cannot hold the HMRC population. + + * A band with zero frame mass is skipped, as in the paper: its frame rows + (there are none with positive base weight) keep propensity 0.0. + * Frame rows in band 0 (non-positive turnover) are not covered by any + band loop in the paper and keep propensity 0.0. + * Out-of-frame rows (``frame_mask`` False, appended HMRC negative/zero + traders) receive propensity 1.0, as in the paper. + + Args: + band_idx: Integer array, shape ``(n,)``: HMRC band index (0-7). + frame_mask: Boolean array, shape ``(n,)``: True for ONS-frame rows. + base_weights: Float array, shape ``(n,)``: base weight of each row. + hmrc_bands: Float array, shape ``(8,)``: HMRC registered-trader count + per band, aligned with ``band_idx``. + + Returns: + Float64 array, shape ``(n,)``, of propensities in ``[0, 1]``. + """ + return _registration_propensity( + UK_VAT_REGISTRATION_SPEC, + _band_indices(band_idx), + frame_mask, + base_weights, + _hmrc_counts(hmrc_bands), + ) + + +def assign_vat_scope_and_registration( + band_idx: np.ndarray, + frame_mask: np.ndarray, + weights: np.ndarray, + hmrc_bands: np.ndarray, + *, + seed: int, +) -> tuple[np.ndarray, np.ndarray]: + """Assign VAT scope and registration flags matching HMRC trader counts. + + Mirrors ``firm_microsim/generate.py::assign_vat_flags``: + + * out-of-frame rows (``frame_mask`` False) are HMRC traders by + construction: in scope and registered; + * below the threshold (band 1), every frame row is in scope (registrable) + and a seeded weighted selection whose cumulative weight reaches + ``hmrc_bands[1]`` is registered; + * above the threshold (bands 2-7), a seeded weighted selection per band + reaching ``hmrc_bands[b]`` is in scope and registered; the rest of the + band is out of scope (PAYE-only or exempt-sector enterprises); + * frame rows in band 0 are neither in scope nor registered (the paper + does not assign them). + + Each band's registered weight lies in ``[target, target + w)`` for the + weight ``w`` of the last selected row, so it matches HMRC within one + weight, unless the band's total weight is below the target, in which case + every row in the band is selected. + + Selection uses one ``np.random.default_rng(seed)`` generator, drawing one + permutation for band 1 and then one per band 2-7 in order. The paper + draws with torch's global generator, so row-level selections differ from + the paper; weighted totals do not. + + Args: + band_idx: Integer array, shape ``(n,)``: HMRC band index (0-7). + frame_mask: Boolean array, shape ``(n,)``: True for ONS-frame rows. + weights: Float array, shape ``(n,)``: calibration (or base) weights. + hmrc_bands: Float array, shape ``(8,)``: HMRC registered-trader count + per band, aligned with ``band_idx``. + seed: Seed for the selection generator. + + Returns: + ``(scope, registered)``: boolean arrays of shape ``(n,)``. + """ + return assign_scope_and_registration( + UK_VAT_REGISTRATION_SPEC, + _band_indices(band_idx), + frame_mask, + weights, + _hmrc_counts(hmrc_bands), + seed=seed, + ) diff --git a/packages/microcosm-build/tests/engine_free/shared/test_firm_engine_inputs.py b/packages/microcosm-build/tests/engine_free/shared/test_firm_engine_inputs.py new file mode 100644 index 0000000000..1f02cced98 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/shared/test_firm_engine_inputs.py @@ -0,0 +1,225 @@ +"""Reading a country package's entity inputs from source, and checks against them. + +The package here is a toy written to ``tmp_path``; no country model is +imported. +""" + +from __future__ import annotations + +import textwrap +from pathlib import Path + +import numpy as np +import pandas as pd +import pytest + +from microcosm.build.firms import ( + EXPORTED_INPUT_STATUSES, + INPUT_STATUSES, + export_schema_problems, + input_status_problems, + read_entity_variables, +) + +_FILES = { + "__init__.py": "", + "enums.py": """ + from enum import Enum + + class Region(Enum): + NORTH = "North" + SOUTH = "South" + _PRIVATE = "hidden" + """, + "variables/__init__.py": "", + "variables/firm/__init__.py": "", + "variables/firm/inputs.py": """ + from toymodel.model_api import * + from toymodel.enums import Region + from toymodel import enums as e + + class firm_turnover(Variable): + entity = Firm + value_type = float + unit = GBP + definition_period = YEAR + default_value = 0 + + class firm_region(Variable): + entity = Firm + value_type = Enum + possible_values = Region + default_value = Region.SOUTH + definition_period = YEAR + + class firm_home_region(Variable): + entity = Firm + value_type = Enum + possible_values = e.Region + definition_period = YEAR + + class firm_is_bank(Variable): + entity = Firm + value_type = bool + definition_period = YEAR + """, + "variables/firm/outputs.py": """ + from toymodel.model_api import * + + class firm_tax(Variable): + entity = Firm + value_type = float + definition_period = YEAR + + def formula(firm, period, parameters): + return firm("firm_turnover", period) * 0.1 + + class firm_total(Variable): + entity = Firm + value_type = float + definition_period = YEAR + adds = ["firm_tax"] + + class person_age(Variable): + entity = Person + value_type = int + definition_period = YEAR + """, + "tests/test_ignored.py": """ + class firm_test_only(Variable): + entity = Firm + value_type = float + """, +} + + +@pytest.fixture +def toy_package(tmp_path: Path) -> Path: + package = tmp_path / "toymodel" + for name, source in _FILES.items(): + path = package / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(textwrap.dedent(source), encoding="utf-8") + return package + + +def test_reader_finds_entity_variables_and_their_inputs(toy_package) -> None: + read = read_entity_variables(toy_package, entity="Firm") + assert sorted(read.variables) == [ + "firm_home_region", + "firm_is_bank", + "firm_region", + "firm_tax", + "firm_total", + "firm_turnover", + ] + assert read.input_names == [ + "firm_home_region", + "firm_is_bank", + "firm_region", + "firm_turnover", + ] + assert "person_age" in read.variable_names + assert "firm_test_only" not in read.variable_names + + +def test_reader_records_types_units_defaults_and_enums(toy_package) -> None: + variables = read_entity_variables(toy_package, entity="Firm").variables + assert variables["firm_turnover"] == { + "default_value": 0, + "definition_period": "year", + "enum": None, + "enum_members": None, + "file": "variables/firm/inputs.py", + "has_formula": False, + "name": "firm_turnover", + "unit": "GBP", + "value_type": "float", + } + region = variables["firm_region"] + assert region["enum"] == {"name": "Region", "module": "toymodel.enums"} + assert region["enum_members"] == ["NORTH", "SOUTH"] + assert region["default_value"] == "SOUTH" + assert variables["firm_home_region"]["enum_members"] == ["NORTH", "SOUTH"] + assert variables["firm_tax"]["has_formula"] + assert variables["firm_total"]["has_formula"] + + +def test_reader_refuses_an_entity_with_no_variables(toy_package) -> None: + with pytest.raises(ValueError, match="defines no Household variables"): + read_entity_variables(toy_package, entity="Household") + + +def test_input_status_must_cover_exactly_the_inputs() -> None: + inputs = ["firm_turnover", "firm_region", "firm_is_bank"] + status = { + "firm_turnover": "set", + "firm_region": "assumed", + "firm_is_bank": "not_set", + } + assert input_status_problems(status, inputs) == [] + assert ( + input_status_problems( + status, inputs, exported_columns=["firm_turnover", "firm_region"] + ) + == [] + ) + problems = input_status_problems( + {**status, "firm_is_bank": "guessed", "firm_other": "set"}, + [*inputs, "firm_new"], + exported_columns=["firm_turnover"], + ) + assert problems == [ + f"unknown input statuses ['guessed']; choose from {INPUT_STATUSES}", + "engine inputs without a status: ['firm_new']", + "statuses for names that are not engine inputs: ['firm_other']", + "inputs marked exported that no export writes: ['firm_other', 'firm_region']", + ] + assert set(EXPORTED_INPUT_STATUSES) == set(INPUT_STATUSES) - {"not_set"} + + +def test_an_exported_column_marked_not_set_is_a_problem() -> None: + problems = input_status_problems( + {"firm_turnover": "not_set"}, + ["firm_turnover"], + exported_columns=["firm_turnover"], + ) + assert problems == ["exported inputs marked not_set or missing: ['firm_turnover']"] + + +def test_export_schema_accepts_a_loadable_table(toy_package) -> None: + read = read_entity_variables(toy_package, entity="Firm") + table = pd.DataFrame( + { + "firm_turnover": np.array([1.0, 2.0]), + "firm_region": ["NORTH", "SOUTH"], + "firm_is_bank": [False, True], + "in_frame": [True, True], + } + ) + columns = [c for c in table.columns if c.startswith("firm_")] + assert export_schema_problems(table, read, columns=columns) == [] + + +def test_export_schema_names_each_unloadable_column(toy_package) -> None: + read = read_entity_variables(toy_package, entity="Firm") + table = pd.DataFrame( + { + "firm_turnover": np.array([1, 2]), + "firm_region": ["NORTH", "EAST"], + "firm_home_region": [1, 2], + "firm_tax": [0.0, 0.0], + "in_frame": [True, True], + } + ) + problems = export_schema_problems( + table, read, columns=[*table.columns, "firm_gone"] + ) + assert problems == [ + "firm_turnover: dtype int64 for value type float", + "firm_region: values ['EAST'] are not enum members", + "firm_home_region: enum values must be member names", + "firm_tax: not a formula-less engine input", + "in_frame: not a formula-less engine input", + "firm_gone: not in the table", + ] diff --git a/packages/microcosm-build/tests/engine_free/shared/test_firm_receipts_comparison.py b/packages/microcosm-build/tests/engine_free/shared/test_firm_receipts_comparison.py new file mode 100644 index 0000000000..7897150b4c --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/shared/test_firm_receipts_comparison.py @@ -0,0 +1,189 @@ +"""The country-neutral comparison of model totals with official receipts.""" + +from __future__ import annotations + +import csv +from pathlib import Path + +import pytest + +from microcosm.build.firms.receipts import ( + INPUT_NOT_POPULATED, + NO_MODEL_TOTAL, + NO_OFFICIAL_FIGURE, + RECEIPT_SOURCE_COLUMNS, + Receipt, + build_comparison_rows, + compare_total, + read_receipts, + render_comparison_markdown, +) + +_COLUMNS = ("levy", "value_eur", "period", *RECEIPT_SOURCE_COLUMNS, "note") +_SOURCE = { + "measure": "cash receipts", + "source_publisher": "Tax Office", + "source_title": "Receipts bulletin", + "edition": "March 2026", + "url": "https://example.org/receipts", + "accessed": "2026-11-20", +} + + +def _write(path: Path, rows: list[dict[str, str]], columns=_COLUMNS) -> Path: + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=columns) + writer.writeheader() + for row in rows: + writer.writerow({c: row.get(c, "") for c in columns}) + return path + + +def _row(name: str, value: str, **overrides: str) -> dict[str, str]: + return { + "levy": name, + "value_eur": value, + "period": "2025", + **_SOURCE, + "note": "", + **overrides, + } + + +def _euros(value: float) -> str: + sign = "-" if value < 0 else "" + return f"{sign}€{abs(value) / 1e6:,.1f}m" + + +def _receipts(tmp_path: Path) -> dict[str, Receipt]: + path = _write( + tmp_path / "receipts.csv", + [ + _row("payroll_levy", "200000000"), + _row( + "site_levy", "", note="Not published yet.", **dict.fromkeys(_SOURCE, "") + ), + _row("profit_levy", "50000000"), + ], + ) + return read_receipts(path, name_column="levy", value_column="value_eur") + + +def test_reader_keeps_order_and_blank_figures(tmp_path) -> None: + receipts = _receipts(tmp_path) + assert list(receipts) == ["payroll_levy", "site_levy", "profit_levy"] + assert receipts["payroll_levy"].official_value == 200_000_000.0 + assert receipts["payroll_levy"].edition == "March 2026" + assert receipts["site_levy"].official_value is None + + +def test_reader_refuses_missing_columns_repeats_and_unsourced_figures( + tmp_path, +) -> None: + short = _write(tmp_path / "a.csv", [], columns=_COLUMNS[:-1]) + with pytest.raises(ValueError, match=r"missing columns \['note'\]"): + read_receipts(short, name_column="levy", value_column="value_eur") + repeated = _write(tmp_path / "b.csv", [_row("x", "1"), _row("x", "2")]) + with pytest.raises(ValueError, match="duplicate levy 'x'"): + read_receipts(repeated, name_column="levy", value_column="value_eur") + unsourced = _write(tmp_path / "c.csv", [_row("x", "1", url="")]) + with pytest.raises(ValueError, match=r"x has a figure but no \['url'\]"): + read_receipts(unsourced, name_column="levy", value_column="value_eur") + + +@pytest.mark.parametrize( + ("kwargs", "expected"), + [ + ( + {"model_total": 150e6, "populated": True, "official_value": 200e6}, + ("€150.0m", "€200.0m", "-€50.0m (-25.0%)", "0.750"), + ), + ( + {"model_total": 0.0, "populated": False, "official_value": 200e6}, + (INPUT_NOT_POPULATED, "€200.0m", INPUT_NOT_POPULATED, INPUT_NOT_POPULATED), + ), + ( + {"model_total": None, "populated": True, "official_value": 200e6}, + (NO_MODEL_TOTAL, "€200.0m", NO_MODEL_TOTAL, NO_MODEL_TOTAL), + ), + ( + {"model_total": 5e6, "populated": True, "official_value": None}, + ("€5.0m", NO_OFFICIAL_FIGURE, NO_OFFICIAL_FIGURE, NO_OFFICIAL_FIGURE), + ), + ( + {"model_total": 5e6, "populated": True, "official_value": 0.0}, + ("€5.0m", "€0.0m", "€5.0m", "official figure is zero"), + ), + ], +) +def test_compare_total_never_invents_a_gap(kwargs, expected) -> None: + row = compare_total("levy", reasons=["One.", "Two."], format_value=_euros, **kwargs) + assert (row.model, row.official, row.gap, row.ratio) == expected + assert row.reason == "One. Two." + + +def test_rows_follow_receipts_then_model_only_names(tmp_path) -> None: + receipts = _receipts(tmp_path) + seen = [] + + def reasons_for(name, receipt): + seen.append((name, receipt is not None)) + return [f"Official measure: {receipt.measure}."] if receipt else [] + + rows = build_comparison_rows( + {"payroll_levy": 180e6, "site_levy": 0.0, "extra_credit": 3e6}, + {"payroll_levy": True, "site_levy": False, "extra_credit": True}, + receipts, + reasons_for=reasons_for, + format_value=_euros, + ) + assert [r.name for r in rows] == [ + "payroll_levy", + "site_levy", + "profit_levy", + "extra_credit", + ] + assert rows[1].gap == INPUT_NOT_POPULATED + assert rows[2].model == NO_MODEL_TOTAL + assert rows[3].official == NO_OFFICIAL_FIGURE + assert rows[0].reason == "Official measure: cash receipts." + assert seen[-1] == ("extra_credit", False) + + +def test_rows_refuse_a_total_without_a_populated_flag(tmp_path) -> None: + with pytest.raises(ValueError, match=r"\['payroll_levy'\] have no true/false"): + build_comparison_rows( + {"payroll_levy": 1.0}, + {"payroll_levy": "yes"}, + _receipts(tmp_path), + reasons_for=lambda name, receipt: [], + format_value=_euros, + ) + + +def test_markdown_escapes_cells_and_lists_sources(tmp_path) -> None: + receipts = _receipts(tmp_path) + rows = build_comparison_rows( + {"payroll_levy": 180e6}, + {"payroll_levy": True}, + receipts, + reasons_for=lambda name, receipt: ["a | b"], + format_value=_euros, + ) + report = render_comparison_markdown( + rows, receipts, title="Firm levies, 2025", name_header="Levy", note="run 7" + ) + lines = report.splitlines() + assert lines[0] == "# Firm levies, 2025" + assert "Model run note: run 7" in lines + assert "| Levy | Model total | Official | Gap | Ratio | Reason / caveat |" in lines + assert ( + "| payroll_levy | €180.0m | €200.0m | -€20.0m (-10.0%) | 0.900 | a \\| b |" + in lines + ) + assert "- `site_levy`: no official figure fetched. Not published yet." in lines + assert ( + "- `payroll_levy`: Tax Office, Receipts bulletin; March 2026; " + "https://example.org/receipts (accessed 2026-11-20). " + ) in lines + assert report.endswith("\n") diff --git a/packages/microcosm-build/tests/engine_free/shared/test_firm_rules_seam.py b/packages/microcosm-build/tests/engine_free/shared/test_firm_rules_seam.py new file mode 100644 index 0000000000..9dd836adb0 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/shared/test_firm_rules_seam.py @@ -0,0 +1,119 @@ +"""The country-neutral firm rules seam: outputs, alignment and totals.""" + +from __future__ import annotations + +import numpy as np +import pandas as pd +import pytest + +from microcosm.build.firms import ( + FirmRuleOutputs, + FirmRules, + align_rule_outputs, + weighted_totals, +) + + +def _outputs(ids, **values) -> FirmRuleOutputs: + return FirmRuleOutputs( + firm_id=np.asarray(ids, dtype=np.int64), + values={name: np.asarray(v, dtype=np.float64) for name, v in values.items()}, + provenance={"rules": "test"}, + ) + + +class _FlatTax: + """A rules double: 10% of turnover, and a count of one per firm.""" + + def evaluate(self, firms: pd.DataFrame, *, period: int) -> FirmRuleOutputs: + return FirmRuleOutputs( + firm_id=firms["firm_id"].to_numpy(), + values={ + "tax": 0.1 * firms["turnover"].to_numpy(np.float64), + "payers": np.ones(len(firms)), + }, + provenance={"rules": "flat", "period": str(period)}, + ) + + +def test_outputs_coerce_and_freeze() -> None: + outputs = FirmRuleOutputs( + firm_id=np.array([1, 2], dtype=np.int32), + values={"tax": [1.5, -2.0]}, + provenance={"rules": "test"}, + ) + assert outputs.firm_id.dtype == np.int64 + assert outputs.values["tax"].dtype == np.float64 + with pytest.raises(TypeError): + outputs.provenance["rules"] = "other" # type: ignore[index] + with pytest.raises(TypeError): + outputs.values["tax"] = np.zeros(2) # type: ignore[index] + + +@pytest.mark.parametrize( + ("ids", "values", "match"), + [ + ([1.0, 2.0], {"tax": [1.0, 2.0]}, "integer"), + ([1, 2], {}, "at least one"), + ([1, 2], {"tax": [1.0]}, "shape"), + ([1, 2], {"tax": [1.0, np.nan]}, "finite"), + ([1, 2], {"firm_id": [1.0, 2.0]}, "not allowed"), + ([1, 2], {"": [1.0, 2.0]}, "not allowed"), + ], +) +def test_outputs_refuse_malformed_arrays(ids, values, match) -> None: + with pytest.raises(ValueError, match=match): + FirmRuleOutputs(firm_id=np.asarray(ids), values=values, provenance={}) + + +def test_align_reorders_every_output_by_firm_id() -> None: + outputs = _outputs([3, 1, 2], tax=[30.0, 10.0, 20.0], payers=[3.0, 1.0, 2.0]) + aligned = align_rule_outputs(outputs, np.array([1, 2, 3])) + assert list(aligned) == ["tax", "payers"] + np.testing.assert_array_equal(aligned["tax"], [10.0, 20.0, 30.0]) + np.testing.assert_array_equal(aligned["payers"], [1.0, 2.0, 3.0]) + by_series = align_rule_outputs(outputs, pd.Series([2, 3, 1])) + np.testing.assert_array_equal(by_series["tax"], [20.0, 30.0, 10.0]) + + +@pytest.mark.parametrize( + ("produced", "requested", "match"), + [ + ([1, 2], [1, 2, 3], "miss 1 firm ids"), + ([1, 2, 3], [1, 2], "unrequested"), + ([1, 1, 2], [1, 2], "outputs repeat"), + ([1, 2], [1, 1, 2], "requested firm ids repeat"), + ], +) +def test_align_refuses_mismatched_ids(produced, requested, match) -> None: + outputs = _outputs(produced, tax=np.zeros(len(produced))) + with pytest.raises(ValueError, match=match): + align_rule_outputs(outputs, np.asarray(requested)) + + +def test_a_rules_double_satisfies_the_protocol_and_aligns() -> None: + rules: FirmRules = _FlatTax() + firms = pd.DataFrame({"firm_id": [7, 5], "turnover": [100.0, 40.0]}) + outputs = rules.evaluate(firms, period=2024) + assert outputs.provenance["period"] == "2024" + aligned = align_rule_outputs(outputs, np.array([5, 7])) + np.testing.assert_allclose(aligned["tax"], [4.0, 10.0]) + + +def test_weighted_totals_sum_each_output_alone() -> None: + table = pd.DataFrame( + { + "firm_id": [1, 2], + "firm_weight": [2.0, 3.0], + "tax": [10.0, -1.0], + "payers": [1.0, 0.0], + } + ) + assert weighted_totals(table) == {"tax": 17.0, "payers": 2.0} + renamed = table.rename(columns={"firm_weight": "w", "firm_id": "id"}) + assert weighted_totals(renamed, weight_column="w", id_column="id") == { + "tax": 17.0, + "payers": 2.0, + } + with pytest.raises(ValueError, match="firm_weight"): + weighted_totals(table.drop(columns="firm_weight")) diff --git a/packages/microcosm-build/tests/engine_free/shared/test_firm_universe_mechanics.py b/packages/microcosm-build/tests/engine_free/shared/test_firm_universe_mechanics.py new file mode 100644 index 0000000000..8048cb1468 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/shared/test_firm_universe_mechanics.py @@ -0,0 +1,289 @@ +"""The country-neutral firm mechanics: band draws, thinning, registration. + +Two registration specs are used throughout. ``EIGHT_BANDS`` has the shape of +a VAT register with a threshold: an excluded band for traders outside the +frame, one registrable band below the threshold and six selected bands above +it. ``FOUR_BANDS`` has no registrable band and no excluded band, so the +functions are tested on a shape no current country uses. +""" + +from __future__ import annotations + +import numpy as np +import pytest + +from microcosm.build.firms import ( + BAND_ROLES, + RegistrationSpec, + assign_scope_and_registration, + draw_in_band, + registration_propensity, + select_to_weighted_target, + stratified_thin, +) + +EIGHT_BANDS = RegistrationSpec( + tuple(f"band_{b}" for b in range(8)), + ("excluded", "registrable", *("selected",) * 6), +) +FOUR_BANDS = RegistrationSpec(("a", "b", "c", "d"), ("selected",) * 4) + +THIN = { + "window_lo": 15.0, + "window_hi": 150.0, + "window_fraction": 0.3, + "tail_fraction": 0.05, + "cell_floor": 5, + "rng_seed": 43, +} + + +def _draw(n: int = 4000, seed: int = 0) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + rng = np.random.default_rng(seed) + turnover = rng.lognormal(mean=4.0, sigma=1.5, size=n) + sic = rng.choice( + np.array([1, 41, 47, 62, 86]), size=n, p=[0.05, 0.2, 0.4, 0.3, 0.05] + ) + bands = np.digitize( + turnover, [0.0, 90.0, 150.0, 300.0, 500.0, 1000.0, 10000.0], right=True + ) + return turnover, sic, bands.astype(np.int64) + + +def _strata(turnover, sic, bands) -> np.ndarray: + window = (turnover >= THIN["window_lo"]) & (turnover <= THIN["window_hi"]) + keys = np.stack([sic, bands, window.astype(np.int64)], axis=1) + return np.unique(keys, axis=0, return_inverse=True)[1].reshape(-1) + + +# Band draws. + + +def test_closed_band_draw_is_uniform_inside_the_band() -> None: + unit = np.array([0.0, 0.25, 0.5, 0.999]) + values = draw_in_band(unit, 10.0, 50.0) + np.testing.assert_allclose(values, [10.0, 20.0, 30.0, 49.96]) + + +def test_floor_lifts_a_zero_lower_edge() -> None: + values = draw_in_band(np.array([0.0, 0.5]), 0.0, 10.0, floor=2.0) + np.testing.assert_allclose(values, [2.0, 6.0]) + + +def test_open_band_draw_is_log_uniform_and_stays_below_the_cap() -> None: + unit = np.array([0.0, 0.5, 0.999999]) + values = draw_in_band(unit, 100.0, 10000.0, log_uniform=True) + np.testing.assert_allclose(values[:2], [100.0, 1000.0]) + assert values[2] < 10000.0 + + +def test_band_draw_keeps_torch_type_and_dtype() -> None: + torch = pytest.importorskip("torch") + unit = torch.tensor([0.0, 0.5], dtype=torch.float32) + for log_uniform in (False, True): + values = draw_in_band(unit, 1.0, 100.0, log_uniform=log_uniform) + assert isinstance(values, torch.Tensor) + assert values.dtype == torch.float32 + + +def test_band_draw_refuses_inverted_and_non_positive_log_bands() -> None: + with pytest.raises(ValueError, match="below its low edge"): + draw_in_band(np.array([0.5]), 10.0, 5.0) + with pytest.raises(ValueError, match="positive low edge"): + draw_in_band(np.array([0.5]), 0.0, 5.0, log_uniform=True) + + +# Thinning. + + +def test_full_fractions_return_every_row_at_unit_weight() -> None: + turnover, sic, bands = _draw() + params = {**THIN, "window_fraction": 1.0, "tail_fraction": 1.0} + keep, base = stratified_thin(turnover, [sic, bands], **params) + np.testing.assert_array_equal(keep, np.arange(len(turnover))) + np.testing.assert_array_equal(base, np.ones(len(turnover))) + + +def test_base_weighted_stratum_totals_reproduce_the_draw() -> None: + turnover, sic, bands = _draw() + keep, base = stratified_thin(turnover, [sic, bands], **THIN) + assert len(keep) < len(turnover) / 2 + strata = _strata(turnover, sic, bands) + original = np.bincount(strata) + weighted = np.bincount(strata[keep], weights=base, minlength=len(original)) + np.testing.assert_allclose(weighted, original, rtol=1e-12, atol=0.0) + + +def test_cell_floor_keeps_small_strata() -> None: + turnover, sic, bands = _draw() + keep, _ = stratified_thin(turnover, [sic, bands], **THIN) + strata = _strata(turnover, sic, bands) + sizes = np.bincount(strata) + kept = np.bincount(strata[keep], minlength=len(sizes)) + assert np.all(kept >= np.minimum(THIN["cell_floor"], sizes)) + params = {**THIN, "window_fraction": 0.0, "tail_fraction": 0.0} + keep, base = stratified_thin( + np.array([500.0, 600.0, 700.0]), [np.array([1, 1, 1])], **params + ) + np.testing.assert_array_equal(keep, [0, 1, 2]) + np.testing.assert_array_equal(base, [1.0, 1.0, 1.0]) + + +def test_floor_top_up_takes_lowest_draws_and_weights_by_ratio() -> None: + n = 12 + params = {**THIN, "tail_fraction": 0.0, "cell_floor": 4, "rng_seed": 8} + keep, base = stratified_thin( + np.full(n, 500.0), [np.ones(n, dtype=np.int64)], **params + ) + u = np.random.default_rng(8).random(n) + np.testing.assert_array_equal(keep, np.sort(np.argsort(u)[:4])) + np.testing.assert_array_equal(base, np.full(4, 3.0)) + + +def test_thinning_without_keys_stratifies_by_window_side() -> None: + values = np.array([10.0] * 6 + [100.0] * 4) + params = {**THIN, "window_fraction": 0.0, "tail_fraction": 0.0, "cell_floor": 2} + keep, base = stratified_thin(values, [], **params) + assert len(keep) == 4 + assert sorted(base.tolist()) == [2.0, 2.0, 3.0, 3.0] + + +def test_thinning_is_deterministic_by_seed() -> None: + turnover, sic, bands = _draw() + first = stratified_thin(turnover, [sic, bands], **THIN) + second = stratified_thin(turnover, [sic, bands], **THIN) + other = stratified_thin(turnover, [sic, bands], **{**THIN, "rng_seed": 44}) + np.testing.assert_array_equal(first[0], second[0]) + np.testing.assert_array_equal(first[1], second[1]) + assert not np.array_equal(first[0], other[0]) + + +def test_thinning_refuses_misaligned_or_non_integer_keys() -> None: + with pytest.raises(ValueError, match=r"strata\[0\]"): + stratified_thin(np.ones(3), [np.ones(2, dtype=np.int64)], **THIN) + with pytest.raises(TypeError, match="integer"): + stratified_thin(np.ones(3), [np.ones(3)], **THIN) + + +# Registration spec. + + +def test_spec_records_bands_by_role() -> None: + assert EIGHT_BANDS.n_bands == 8 + assert EIGHT_BANDS.bands_with_role("excluded") == (0,) + assert EIGHT_BANDS.bands_with_role("registrable") == (1,) + assert EIGHT_BANDS.bands_with_role("selected") == tuple(range(2, 8)) + assert set(BAND_ROLES) == {"excluded", "registrable", "selected"} + + +@pytest.mark.parametrize( + ("labels", "roles", "message"), + [ + ((), (), "at least one band"), + (("a", "b"), ("selected",), "2 band labels and 1 band roles"), + (("a", "a"), ("selected", "selected"), "unique"), + (("a",), ("threshold",), "unknown registration band roles"), + ], +) +def test_spec_refuses_malformed_declarations(labels, roles, message) -> None: + with pytest.raises(ValueError, match=message): + RegistrationSpec(labels, roles) + + +# Propensity. + + +def test_propensity_is_registered_count_over_frame_mass() -> None: + bands = np.array([0, 1, 1, 1, 2, 2, 3, 0, 7]) + frame = np.array([True, True, True, True, True, True, True, False, True]) + base = np.array([1.0, 10.0, 20.0, 30.0, 4.0, 6.0, 2.0, 1.0, 5.0]) + counts = np.array([99.0, 15.0, 5.0, 8.0, 0.0, 0.0, 0.0, 7.0]) + propensity = registration_propensity(EIGHT_BANDS, bands, frame, base, counts) + expected = [0.0, 0.25, 0.25, 0.25, 0.5, 0.5, 1.0, 1.0, 1.0] + np.testing.assert_allclose(propensity, expected, rtol=0, atol=1e-12) + + +def test_propensity_without_an_excluded_band_covers_every_band() -> None: + bands = np.array([0, 0, 1, 3]) + frame = np.array([True, True, True, False]) + base = np.array([2.0, 2.0, 5.0, 1.0]) + counts = np.array([1.0, 10.0, 0.0, 0.0]) + propensity = registration_propensity(FOUR_BANDS, bands, frame, base, counts) + np.testing.assert_allclose(propensity, [0.25, 0.25, 1.0, 1.0]) + + +def test_propensity_leaves_empty_bands_at_zero() -> None: + propensity = registration_propensity( + EIGHT_BANDS, + np.array([4, 4]), + np.array([True, True]), + np.zeros(2), + np.full(8, 5.0), + ) + np.testing.assert_array_equal(propensity, [0.0, 0.0]) + + +def test_registered_counts_must_align_with_the_spec() -> None: + with pytest.raises(ValueError, match="registered_counts"): + registration_propensity( + EIGHT_BANDS, np.array([1]), np.array([True]), np.ones(1), np.ones(7) + ) + with pytest.raises(ValueError, match="band_idx"): + registration_propensity( + FOUR_BANDS, np.array([4]), np.array([True]), np.ones(1), np.ones(4) + ) + + +# Scope and registration. + + +@pytest.mark.parametrize("spec", [EIGHT_BANDS, FOUR_BANDS]) +def test_registration_totals_match_counts_within_one_weight(spec) -> None: + rng = np.random.default_rng(3) + n = 5000 + bands = rng.integers(0, spec.n_bands, size=n) + frame = rng.random(n) > 0.05 + weights = rng.uniform(1.0, 20.0, size=n) + mass = np.bincount(bands[frame], weights=weights[frame], minlength=spec.n_bands) + counts = np.round(mass * rng.uniform(0.3, 0.95, size=spec.n_bands)) + scope, registered = assign_scope_and_registration( + spec, bands, frame, weights, counts, seed=42 + ) + assert scope[~frame].all() and registered[~frame].all() + assert not (registered & ~scope).any() + for band, role in enumerate(spec.band_roles): + rows = frame & (bands == band) + if role == "excluded": + assert not (scope | registered)[rows].any() + continue + if role == "registrable": + assert scope[rows].all() + else: + assert np.array_equal(scope[rows], registered[rows]) + total = weights[rows & registered].sum() + assert counts[band] <= total < counts[band] + weights[rows].max() + again = assign_scope_and_registration(spec, bands, frame, weights, counts, seed=42) + np.testing.assert_array_equal(again[1], registered) + + +def test_registration_selects_whole_band_when_count_exceeds_mass() -> None: + counts = np.zeros(8) + counts[2] = 100.0 + scope, registered = assign_scope_and_registration( + EIGHT_BANDS, + np.array([2, 2, 2]), + np.ones(3, dtype=bool), + np.ones(3), + counts, + seed=1, + ) + assert scope.all() and registered.all() + + +def test_weighted_selection_draws_nothing_for_an_empty_or_zero_target() -> None: + rng = np.random.default_rng(5) + state = rng.bit_generator.state + empty = select_to_weighted_target(np.zeros(0, dtype=np.int64), np.ones(3), 2.0, rng) + zero = select_to_weighted_target(np.arange(3), np.ones(3), 0.0, rng) + assert len(empty) == len(zero) == 0 + assert rng.bit_generator.state == state diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_build.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_build.py new file mode 100644 index 0000000000..eeb17cfcaf --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_build.py @@ -0,0 +1,277 @@ +"""The local UK firm build writes a valid table and a reproducible receipt. + +A thinned 2024-25 build on the paper-parity fixtures, with a test-only rules +double, runs twice into different directories: the parquet round-trips, the +receipt's hashes match the files, and the two builds agree exactly without a +committed golden hash. The tool is loaded from its path, refuses to run +without ``--rules`` and writes the same receipt as the library call. +""" + +from __future__ import annotations + +import dataclasses +import hashlib +import importlib.util +import json +import sys +from functools import cache +from pathlib import Path + +import numpy as np +import pandas as pd +import pytest + +from microcosm.build.uk_runtime.firm_build import ( + UK_FIRM_RECEIPT_FILE, + UK_FIRM_TABLE_FILE, + build_uk_firm_dataset, +) +from microcosm.build.uk_runtime.firm_generation import UKFirmGenerationConfig +from microcosm.build.uk_runtime.firm_rules import ( + UK_FIRM_RULE_PERIOD_NOTE, + UKFirmRuleOutputs, + rule_period_for_vintage, +) +from microcosm.build.uk_runtime.firm_table import ( + UK_FIRM_TABLE_COLUMNS, + validate_uk_firm_table, +) +from test_support.paths import paths_for + +PATHS = paths_for("microcosm-build") +FIXTURES = PATHS.tests / "fixtures" / "uk" +PROCESSED = FIXTURES / "firm_2024_25" +TOOL = PATHS.repository / "tools" / "build_uk_firms.py" +SEED = 42 +ITERATIONS = 20 +WINDOW_FRACTION = 0.02 +TAIL_FRACTION = 0.005 + + +class _StandardRateDouble: + """Test-only rules double, 0.20 x (turnover - inputs); not UK VAT law.""" + + def evaluate(self, firms: pd.DataFrame, *, period: int) -> UKFirmRuleOutputs: + del period + liability = 0.20 * ( + firms["firm_turnover"].to_numpy(dtype=np.float64) + - firms["firm_input_costs"].to_numpy(dtype=np.float64) + ) + return UKFirmRuleOutputs( + firm_id=firms["firm_id"].to_numpy(dtype=np.int64), + vat_liability_if_registered=liability, + provenance={"rules": "standard-rate test double"}, + ) + + +def _config(rules: _StandardRateDouble) -> UKFirmGenerationConfig: + return UKFirmGenerationConfig( + seed=SEED, + n_iterations=ITERATIONS, + sample_window_fraction=WINDOW_FRACTION, + sample_tail_fraction=TAIL_FRACTION, + firm_rules=rules, + ).with_vintage("2024-25") + + +def _build(output_dir: Path) -> dict: + rules = _StandardRateDouble() + return build_uk_firm_dataset( + processed_dir=PROCESSED, + output_dir=output_dir, + rules=rules, + config=_config(rules), + ) + + +@pytest.fixture(scope="module") +def builds(tmp_path_factory: pytest.TempPathFactory) -> tuple[dict, dict]: + return ( + _build(tmp_path_factory.mktemp("first") / "out"), + _build(tmp_path_factory.mktemp("second") / "out"), + ) + + +def _sha256(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +@cache +def _load_tool(): + # Registered before it runs, as the stock cell tool's test does. + if "build_uk_firms" in sys.modules: + return sys.modules["build_uk_firms"] + spec = importlib.util.spec_from_file_location("build_uk_firms", TOOL) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +def test_parquet_round_trips_and_validates(builds) -> None: + built, _ = builds + table_path = built["table_path"] + + assert table_path.name == UK_FIRM_TABLE_FILE + written = pd.read_parquet(table_path) + pd.testing.assert_frame_equal(written, built["table"]) + validate_uk_firm_table(written) + receipt = built["receipt"] + assert receipt["output"]["rows"] == len(written) + assert receipt["output"]["columns"] == list(written.columns) + assert receipt["output"]["weighted_firms"] == pytest.approx( + float(written["firm_weight"].sum()) + ) + + +def test_receipt_hashes_match_the_files(builds) -> None: + built, _ = builds + receipt = json.loads(built["receipt_path"].read_text(encoding="utf-8")) + + assert built["receipt_path"].name == UK_FIRM_RECEIPT_FILE + assert receipt == built["receipt"] + assert receipt["output"]["sha256"] == _sha256(built["table_path"]) + for role, directory in (("processed", PROCESSED),): + expected = {path.name: _sha256(path) for path in directory.glob("*.csv")} + assert expected + assert receipt["inputs"][role] == expected + + +def test_receipt_records_the_run(builds) -> None: + built, _ = builds + receipt = built["receipt"] + + assert receipt["schema_version"] == 1 + assert receipt["data_vintage"] == "2024-25" + assert receipt["seed"] == SEED + assert receipt["rule_period"] == rule_period_for_vintage("2024-25") + assert receipt["rule_period_note"] == UK_FIRM_RULE_PERIOD_NOTE + assert receipt["data_years"]["ons_frame_turnover"] == "2023-24" + assert receipt["data_years"]["hmrc_vat_statistics"] == "2024-25" + assert receipt["config"]["n_iterations"] == ITERATIONS + assert "firm_rules" not in receipt["config"] + assert "vat_rule_evaluator" not in receipt["config"] + assert receipt["rules_provenance"] == [{"rules": "standard-rate test double"}] + assert 0.0 < receipt["validation"]["overall"] <= 1.0 + assert receipt["target_diagnostics"] + assert receipt["output"]["columns"] == list(UK_FIRM_TABLE_COLUMNS) + assert set(receipt["inputs"]) == {"processed"} + + +def _comparable(receipt: dict) -> dict: + """A receipt without the parquet hash, floats rounded to 9 significant digits. + + Same-seed builds agree exactly on the machines tested so far; the + comparison tolerates last-digit float differences so a platform's + floating-point reductions cannot fail it. + """ + + def _round(value): + if isinstance(value, float): + return float(f"{value:.9g}") + if isinstance(value, dict): + return {key: _round(item) for key, item in value.items()} + if isinstance(value, list): + return [_round(item) for item in value] + return value + + trimmed = json.loads(json.dumps(receipt)) + trimmed["output"].pop("sha256") + return _round(trimmed) + + +def test_two_builds_agree(builds) -> None: + first, second = builds + + pd.testing.assert_frame_equal(first["table"], second["table"]) + assert _comparable(first["receipt"]) == _comparable(second["receipt"]) + + +def test_receipt_holds_no_absolute_path(builds, tmp_path_factory) -> None: + for built in builds: + text = built["receipt_path"].read_text(encoding="utf-8") + assert str(tmp_path_factory.getbasetemp()) not in text + assert str(built["table_path"].parent) not in text + assert str(PATHS.repository) not in text + + +def test_tool_needs_rules(tmp_path: Path) -> None: + tool = _load_tool() + with pytest.raises(SystemExit) as raised: + tool.main( + [ + "--processed-dir", + str(PROCESSED), + "--out-dir", + str(tmp_path), + ] + ) + assert raised.value.code != 0 + assert not any(tmp_path.iterdir()) + + +def test_tool_needs_an_artifact_for_axiom(tmp_path: Path) -> None: + tool = _load_tool() + with pytest.raises(SystemExit) as raised: + tool.main( + [ + "--processed-dir", + str(PROCESSED), + "--out-dir", + str(tmp_path), + "--rules", + "axiom", + ] + ) + assert raised.value.code != 0 + + +def test_tool_writes_the_library_build( + builds, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys +) -> None: + """The tool's flags reach the build: thinned to the test's fractions + after ``--fast`` is seen, it writes the library build's receipt.""" + + tool = _load_tool() + real_config = tool._config + seen: list[UKFirmGenerationConfig] = [] + + def thinned_config(args, rules): + config = real_config(args, rules) + seen.append(config) + return dataclasses.replace( + config, + sample_window_fraction=WINDOW_FRACTION, + sample_tail_fraction=TAIL_FRACTION, + ) + + monkeypatch.setattr(tool, "_rules", lambda args: _StandardRateDouble()) + monkeypatch.setattr(tool, "_config", thinned_config) + out = tmp_path / "tool" + code = tool.main( + [ + "--processed-dir", + str(PROCESSED), + "--out-dir", + str(out), + "--rules", + "policyengine-uk", + "--fast", + "--seed", + str(SEED), + "--n-iterations", + str(ITERATIONS), + ] + ) + + assert code == 0 + assert str(out / UK_FIRM_TABLE_FILE) in capsys.readouterr().out + (config,) = seen + fast = UKFirmGenerationConfig.fast() + assert config.sample_window_fraction == fast.sample_window_fraction + assert config.sample_tail_fraction == fast.sample_tail_fraction + assert config.n_iterations == ITERATIONS + assert config.data_vintage == "2024-25" + receipt = json.loads((out / UK_FIRM_RECEIPT_FILE).read_text(encoding="utf-8")) + assert _comparable(receipt) == _comparable(builds[0]["receipt"]) diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_generation.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_generation.py index 3430f7334b..f0edb43671 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_generation.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_generation.py @@ -1,32 +1,57 @@ from __future__ import annotations +import ast +import dataclasses from pathlib import Path import numpy as np import pandas as pd import pytest import torch +from scipy import sparse from microcosm.build.uk_runtime import ( AxiomVATRuleEvaluator as PublicAxiomVATRuleEvaluator, ) +from microcosm.build.uk_runtime import firm_generation from microcosm.build.uk_runtime.firm_generation import ( DEFAULT_UK_FIRM_TARGET_PROFILE, + FAST_SAMPLE_TAIL_FRACTION, + FAST_SAMPLE_WINDOW_FRACTION, HMRC_BAND_COLUMNS, INPUT_FILES, + INPUT_RATIO_LOWER, + INPUT_RATIO_UPPER, UK_FIRM_TARGET_IDS, + VAT_LIABILITY_BANDS_CALIBRATED, AxiomVATRuleEvaluator, UKFirmGenerationConfig, - calculate_vat_liability_values, + assign_employment, + build_firm_target_matrix, + employment_band_index_array, employment_band_name, + evaluate_vat_liability_if_registered_k, + generate_base_firms, + generate_input_values, generate_uk_firm_population, hmrc_band_name, read_uk_firm_source_data, + resolve_uk_firm_rules, uk_firm_source_data_from_frames, uk_firm_source_data_from_ledger_facts, uk_firm_target_profile_from_mapping, write_uk_firm_population, ) +from microcosm.build.uk_runtime.firm_rules import ( + UK_FIRM_RULE_PERIOD_BY_VINTAGE, + LegacyVATEvaluatorRules, + UKFirmRuleOutputs, +) +from microcosm.build.uk_runtime.firm_table import ( + to_policyengine_uk_firm_table, + validate_uk_firm_table, +) +from microcosm.build.uk_runtime.firm_universe import HMRC_BAND_NAMES def test_axiom_vat_rule_evaluator_is_public_uk_runtime_api() -> None: @@ -110,8 +135,10 @@ def test_generate_uk_firm_population_accepts_ledger_source_data() -> None: ) diagnostics = result.target_diagnostics.set_index("target_name") - assert diagnostics.loc["hmrc_vat_population_sector/11", "target"] == 3.0 - assert diagnostics.loc["hmrc_vat_population_sector/12", "target"] == 2.0 + # Ledger sector counts 3 and 2 are scaled onto the ten HMRC band traders, + # as the paper allocates unknown-band traders proportionally. + assert diagnostics.loc["hmrc_vat_population_sector/11", "target"] == 6.0 + assert diagnostics.loc["hmrc_vat_population_sector/12", "target"] == 4.0 assert len(result.firms[result.firms["annual_turnover_k"] == 0]) == 3 assert result.calibration.final_loss <= result.calibration.initial_loss @@ -154,6 +181,9 @@ def test_generate_uk_firm_population_returns_experimental_firm_rows() -> None: "vat_liability_k", "employment", "firm_weight", + "base_weight", + "in_frame", + "vat_scope", "vat_registered", "generation_status", ] @@ -162,13 +192,33 @@ def test_generate_uk_firm_population_returns_experimental_firm_rows() -> None: assert firms["source_firm_key"].is_unique assert set(firms["generation_status"]) == {"experimental"} assert (firms["firm_weight"] > 0).all() - assert firms.loc[ - firms["annual_turnover_k"] > config.vat_threshold, - "vat_registered", - ].all() + # An unthinned build starts every row from a unit base weight. + assert (firms["base_weight"] == 1.0).all() + + # The HMRC negative/zero-turnover traders are appended before calibration: + # they are the only out-of-frame rows and are registered, in-scope traders. zero_turnover = firms[firms["annual_turnover_k"] == 0] assert len(zero_turnover) == 3 + assert firms.index[~firms["in_frame"]].tolist() == zero_turnover.index.tolist() assert zero_turnover["vat_registered"].all() + assert zero_turnover["vat_scope"].all() + assert len(result.calibration.weights) == len(firms) + np.testing.assert_allclose( + result.calibration.weights.numpy(), + firms["firm_weight"].to_numpy(), + ) + + # Registration implies scope; every below-threshold frame firm is in scope. + assert not (firms["vat_registered"] & ~firms["vat_scope"]).any() + below = ( + firms["in_frame"] + & (firms["annual_turnover_k"] > 0) + & (firms["annual_turnover_k"] <= config.vat_threshold) + ) + assert firms.loc[below, "vat_scope"].all() + # Unregistered firms owe no VAT in the output. + assert (firms.loc[~firms["vat_registered"], "vat_liability_k"] == 0).all() + assert 0.0 <= result.validation.overall <= 1.0 assert result.calibration.final_loss <= result.calibration.initial_loss assert len(result.calibration.loss_trajectory) == config.n_iterations @@ -177,15 +227,28 @@ def test_generate_uk_firm_population_returns_experimental_firm_rows() -> None: ) assert "initial_estimate" in result.target_diagnostics.columns - base_firms = firms.iloc[: len(result.calibration.weights)].copy() - base_firms["employment_band"] = base_firms["employment"].apply(employment_band_name) - weighted_employment = base_firms.groupby("employment_band")["firm_weight"].sum() + # ONS-frame rows count frame firms only; the appended traders are outside. + frame = firms[firms["in_frame"]].copy() + frame["employment_band"] = frame["employment"].apply(employment_band_name) + weighted_employment = frame.groupby("employment_band")["firm_weight"].sum() diagnostics = result.target_diagnostics.set_index("target_name") for band in ("0-4", "5-9", "10-19", "20-49"): assert diagnostics.loc[ f"ons_firm_employment/{band}", "estimate", - ] == pytest.approx(float(weighted_employment.get(band, 0.0))) + ] == pytest.approx(float(weighted_employment.get(band, 0.0)), rel=1e-5) + assert diagnostics.loc["ons_firm_population/total", "target"] == 7.0 + assert diagnostics.loc["ons_firm_population/total", "estimate"] == pytest.approx( + float(frame["firm_weight"].sum()), rel=1e-5 + ) + assert diagnostics.loc[ + "ons_firm_population/total", "initial_estimate" + ] == pytest.approx(7.0) + # The appended traders enter the HMRC Negative_or_Zero row with propensity 1. + assert diagnostics.loc["hmrc_vat_population/Negative_or_Zero", "target"] == 3.0 + assert diagnostics.loc[ + "hmrc_vat_population/Negative_or_Zero", "estimate" + ] == pytest.approx(float(zero_turnover["firm_weight"].sum()), rel=1e-5) def test_generate_uk_firm_population_uses_configured_vintage_targets() -> None: @@ -204,8 +267,19 @@ def test_generate_uk_firm_population_uses_configured_vintage_targets() -> None: targets_2024 = result_2024.target_diagnostics.set_index("target_name")["target"] assert targets_2023["hmrc_vat_population/£Threshold_to_£150k"] == 4.0 assert targets_2024["hmrc_vat_population/£Threshold_to_£150k"] == 2.0 - assert targets_2023["hmrc_vat_population_sector/11"] == 2.0 - assert targets_2024["hmrc_vat_population_sector/11"] == 3.0 + # Sector counts are scaled to each vintage's HMRC band total. + frames = _source_frames() + for vintage, targets in (("2023-24", targets_2023), ("2024-25", targets_2024)): + bands = frames["hmrc_population_band"].set_index("Financial_Year") + band_total = float(bands.loc[vintage, list(HMRC_BAND_COLUMNS)].sum()) + sectors = frames["hmrc_population_sector"] + sectors = sectors[sectors["Trade_Sector"] != "Total"] + scale = band_total / float(sectors[vintage].sum()) + assert targets["hmrc_vat_population_sector/11"] == pytest.approx( + float(sectors.loc[sectors["Trade_Sector"] == 11, vintage].iloc[0]) * scale + ) + assert targets_2023["hmrc_vat_population_sector/11"] == pytest.approx(11 / 3) + assert targets_2024["hmrc_vat_population_sector/11"] == pytest.approx(6.0) def test_generate_uk_firm_population_requires_requested_hmrc_vintage() -> None: @@ -282,16 +356,361 @@ def test_generate_uk_firm_population_requires_vat_rule_evaluator() -> None: def test_vat_liability_uses_input_tax_credit_not_full_input_cost() -> None: - result = calculate_vat_liability_values( - _firm_config(), - torch.tensor([100.0, 100.0], dtype=torch.float32), - torch.tensor([40.0, 120.0], dtype=torch.float32), - torch.tensor([True, True], dtype=torch.bool), + result = evaluate_vat_liability_if_registered_k( + resolve_uk_firm_rules(_firm_config()), + pd.DataFrame( + { + "firm_id": [0, 1], + "sic_code": [11, 11], + "annual_turnover_k": [100.0, 100.0], + "annual_input_k": [40.0, 120.0], + "employment": [1.0, 1.0], + } + ), + "2023-24", ) assert result.tolist() == pytest.approx([12.0, -4.0]) +def test_firm_generation_uses_only_public_calibrate_names() -> None: + """microcosm#636: no private ``microcosm.calibrate.solve`` imports.""" + + tree = ast.parse(Path(firm_generation.__file__).read_text(encoding="utf-8")) + imported = [ + alias.name + for node in ast.walk(tree) + if isinstance(node, ast.ImportFrom) + and node.module is not None + and node.module.startswith("microcosm.calibrate") + for alias in node.names + ] + assert "solve_constraint_system" in imported + assert not [name for name in imported if name.startswith("_")] + + +def test_build_firm_target_matrix_is_float32_csr_with_two_universes() -> None: + data = _source_data() + config = _firm_config(data_vintage="2024-25") + turnover = np.array([30.0, 120.0, 400.0, 0.0]) + sic = np.array([11, 12, 11, 12]) + employment_band = np.array([0, 1, 3, 0]) + frame = np.array([True, True, True, False]) + propensity = np.array([0.5, 0.25, 1.0, 1.0]) + liability_k = np.array([2.0, 4.0, 8.0, 0.0]) + + matrix, targets, layout, names = build_firm_target_matrix( + config, + turnover, + sic, + employment_band, + data, + propensity=propensity, + frame_mask=frame, + vat_liability_if_registered_k=liability_k, + ) + + assert sparse.issparse(matrix) + assert matrix.format == "csr" + assert matrix.dtype == np.float32 + assert matrix.shape == (layout.n_targets, 4) + assert len(names) == len(targets) == layout.n_targets + dense = matrix.toarray() + row = {name: dense[index] for index, name in enumerate(names)} + # HMRC registered-trader rows carry the propensity. + np.testing.assert_allclose( + row["hmrc_vat_population/Negative_or_Zero"], [0, 0, 0, 1] + ) + np.testing.assert_allclose( + row["hmrc_vat_population/£1_to_Threshold"], [0.5, 0, 0, 0] + ) + np.testing.assert_allclose( + row["hmrc_vat_population/£Threshold_to_£150k"], [0, 0.25, 0, 0] + ) + np.testing.assert_allclose(row["hmrc_vat_population_sector/11"], [0.5, 0, 1, 0]) + np.testing.assert_allclose(row["hmrc_vat_population_sector/12"], [0, 0.25, 0, 1]) + # ONS-frame rows exclude the appended trader. + np.testing.assert_allclose(row["ons_firm_population/total"], [1, 1, 1, 0]) + np.testing.assert_allclose(row["ons_firm_employment/0-4"], [1, 0, 0, 0]) + np.testing.assert_allclose(row["ons_firm_employment/20-49"], [0, 0, 1, 0]) + # Net-VAT rows: liability-if-registered x propensity; the below-threshold + # band is reported, not calibrated. + assert "hmrc_vat_liability/£1_to_Threshold" not in row + assert [name for name in names if name.startswith("hmrc_vat_liability/")] == [ + f"hmrc_vat_liability/{band}" for band in VAT_LIABILITY_BANDS_CALIBRATED + ] + np.testing.assert_allclose( + row["hmrc_vat_liability/£Threshold_to_£150k"], [0, 1.0, 0, 0] + ) + np.testing.assert_allclose(row["hmrc_vat_liability/£300k_to_£500k"], [0, 0, 8.0, 0]) + target = dict(zip(names, targets, strict=True)) + assert target["ons_firm_population/total"] == 7.0 + assert target["hmrc_vat_population/Negative_or_Zero"] == 3.0 + assert target["hmrc_vat_liability/£500k_to_£1m"] == pytest.approx(2_000.0) + + +def test_registered_trader_rows_are_propensity_scaled() -> None: + result = generate_uk_firm_population( + _source_data(), + _firm_config(data_vintage="2024-25", n_iterations=2, seed=3), + ) + firms = result.firms + diagnostics = result.target_diagnostics.set_index("target_name") + threshold = result.config.vat_threshold + bands = firms["annual_turnover_k"].apply(lambda t: hmrc_band_name(t, threshold)) + # At unit base weights each band's expected registered count is its HMRC + # count, capped by the frame mass the band holds. + for band in HMRC_BAND_COLUMNS[1:]: + frame_mass = float(firms.loc[firms["in_frame"] & (bands == band)].shape[0]) + target = diagnostics.loc[f"hmrc_vat_population/{band}", "target"] + assert diagnostics.loc[ + f"hmrc_vat_population/{band}", "initial_estimate" + ] == pytest.approx(min(target, frame_mass), rel=1e-6) + + +def test_vat_liability_rows_align_rule_outputs_by_firm_id() -> None: + rules = _ShuffledFirmIdRules() + result = generate_uk_firm_population( + _source_data(), + UKFirmGenerationConfig( + data_vintage="2024-25", + firm_rules=rules, + n_iterations=2, + seed=5, + ), + ) + firms = result.firms + threshold = result.config.vat_threshold + hmrc = _source_frames()["hmrc_population_band"].iloc[1] + bands = firms["annual_turnover_k"].apply(lambda t: hmrc_band_name(t, threshold)) + diagnostics = result.target_diagnostics.set_index("target_name") + assert rules.periods == [2024] + for band in VAT_LIABILITY_BANDS_CALIBRATED: + members = firms["in_frame"] & (bands == band) + if not members.any(): + continue + propensity = min(1.0, float(hmrc[band]) / float(members.sum())) + # The double's liability is firm_id thousand pounds per firm. + expected = float(firms.loc[members, "firm_id"].sum()) * propensity + assert diagnostics.loc[ + f"hmrc_vat_liability/{band}", "initial_estimate" + ] == pytest.approx(expected, rel=1e-5) + registered = firms["vat_registered"] + np.testing.assert_allclose( + firms.loc[registered, "vat_liability_k"], + firms.loc[registered, "firm_id"].astype(float), + ) + + +def test_firm_rules_take_precedence_over_legacy_evaluator() -> None: + rules = _ShuffledFirmIdRules() + config = UKFirmGenerationConfig( + firm_rules=rules, + vat_rule_evaluator=_TestVATRuleEvaluator(), + ) + assert resolve_uk_firm_rules(config) is rules + + legacy = resolve_uk_firm_rules(_firm_config()) + assert isinstance(legacy, LegacyVATEvaluatorRules) + assert isinstance(legacy.evaluator, _TestVATRuleEvaluator) + + with pytest.raises(ValueError, match="requires a VAT rule evaluator"): + resolve_uk_firm_rules(UKFirmGenerationConfig()) + + +def test_generation_config_sampling_defaults_and_fast_preset() -> None: + config = UKFirmGenerationConfig() + assert config.sample_tail_fraction == 1.0 + assert config.sample_window_fraction == 1.0 + assert config.sample_window_lo_k == 15.0 + assert config.sample_window_hi_k == 150.0 + assert config.sample_cell_floor == 40 + assert config.firm_rules is None + assert not config.thinned + + fast = UKFirmGenerationConfig.fast(data_vintage="2024-25", seed=9) + assert fast.sample_window_fraction == FAST_SAMPLE_WINDOW_FRACTION == 0.30 + assert fast.sample_tail_fraction == FAST_SAMPLE_TAIL_FRACTION == 0.05 + assert fast.data_vintage == "2024-25" + assert fast.vat_threshold == 90.0 + assert fast.seed == 9 + assert fast.thinned + + with pytest.raises(ValueError, match="sample_tail_fraction"): + UKFirmGenerationConfig(sample_tail_fraction=0.0) + with pytest.raises(ValueError, match="sample_window_fraction"): + UKFirmGenerationConfig(sample_window_fraction=1.5) + with pytest.raises(ValueError, match="sample_window_lo_k"): + UKFirmGenerationConfig(sample_window_lo_k=200.0) + with pytest.raises(ValueError, match="sample_cell_floor"): + UKFirmGenerationConfig(sample_cell_floor=-1) + + +def test_hmrc_band_columns_are_the_firm_universe_band_names() -> None: + assert HMRC_BAND_COLUMNS is HMRC_BAND_NAMES + + +def test_every_generator_vintage_has_a_rule_period() -> None: + assert set(UK_FIRM_RULE_PERIOD_BY_VINTAGE) == set(firm_generation.VINTAGES) + + +def test_with_vintage_resolves_the_vintage_threshold() -> None: + default = UKFirmGenerationConfig(seed=7, n_iterations=5) + assert default.vat_threshold == 85.0 + + # The gotcha with_vintage exists for: replace() keeps the old threshold. + replaced = dataclasses.replace(default, data_vintage="2024-25") + assert replaced.vat_threshold == 85.0 + + switched = default.with_vintage("2024-25") + assert switched.data_vintage == "2024-25" + assert switched.vat_threshold == 90.0 + assert switched.seed == 7 + assert switched.n_iterations == 5 + assert switched.with_vintage("2023-24").vat_threshold == 85.0 + # An explicit counterfactual threshold is still accepted. + assert UKFirmGenerationConfig(vat_threshold=100.0).vat_threshold == 100.0 + + with pytest.raises(ValueError, match="Unknown UK firm vintage"): + default.with_vintage("1999-00") + + +def test_generated_firms_convert_to_a_policyengine_uk_firm_table() -> None: + result = generate_uk_firm_population( + _source_data(), + _firm_config(data_vintage="2024-25", n_iterations=5, seed=3), + ) + firms = result.firms + + table = to_policyengine_uk_firm_table( + firms, threshold_k=float(result.config.vat_threshold) + ) + + validate_uk_firm_table(table) + assert len(table) == len(firms) + assert "UNKNOWN" not in set(table["firm_sic_section"]) + by_id = firms.set_index("firm_id").loc[table["firm_id"]] + np.testing.assert_array_equal(table["firm_weight"], by_id["firm_weight"]) + np.testing.assert_array_equal(table["base_weight"], by_id["base_weight"]) + np.testing.assert_array_equal( + table["source_firm_id"], by_id["source_firm_id"].to_numpy(np.int64) + ) + assert set(table["firm_id"]) == set(firms["firm_id"]) + + +def test_thinned_generation_carries_base_weights_into_the_solve() -> None: + data = _source_data(scale=60) + config = UKFirmGenerationConfig.fast( + vat_rule_evaluator=_TestVATRuleEvaluator(), + data_vintage="2024-25", + sample_cell_floor=2, + n_iterations=3, + seed=13, + ) + + result = generate_uk_firm_population(data, config) + firms = result.firms + frame = firms[firms["in_frame"]] + drawn_rows = 7 * 60 + + assert len(frame) < drawn_rows + assert (frame["base_weight"] >= 1.0).all() + assert (frame["base_weight"] > 1.0).any() + # Base weights reproduce the full draw: the stratum base-weighted totals + # add up to every drawn frame row. + assert float(frame["base_weight"].sum()) == pytest.approx(drawn_rows) + assert (firms.loc[~firms["in_frame"], "base_weight"] == 1.0).all() + np.testing.assert_array_equal( + result.calibration.initial_weights, + firms["base_weight"].to_numpy(), + ) + # ``initial_weights`` is echoed back by ``solve_firm_weights``; prove the + # solver itself started from the base weights. Its own first-epoch loss is + # the loss at ``matrix @ base_weight`` ... + assert result.calibration.loss_trajectory[0] == pytest.approx( + result.calibration.initial_loss, rel=1e-5 + ) + # ... and a three-epoch solve stays at the base weights (up to 20 here), + # far from the all-ones start an unthinned solve uses. + assert firms["base_weight"].max() > 2.0 + np.testing.assert_allclose( + firms["firm_weight"].to_numpy(), + firms["base_weight"].to_numpy(), + rtol=1e-3, + ) + diagnostics = result.target_diagnostics.set_index("target_name") + assert diagnostics.loc[ + "ons_firm_population/total", "initial_estimate" + ] == pytest.approx(drawn_rows) + + again = generate_uk_firm_population(data, config).firms + pd.testing.assert_frame_equal(firms, again) + + +def test_generate_base_firms_draws_inside_half_open_source_bands() -> None: + torch.manual_seed(0) + ons_turnover = pd.DataFrame( + [ + {"SIC Code": 45, "Description": "Retail", "50-99": 500, "5000+": 500}, + ] + ) + + sic, turnover = generate_base_firms(ons_turnover) + + values = turnover.numpy() + assert sic.tolist() == [45] * 1_000 + assert ((values[:500] >= 50.0) & (values[:500] < 100.0)).all() + assert ((values[500:] >= 5_000.0) & (values[500:] < 50_000.0)).all() + # The open top band is log-uniform: its median sits near sqrt(5m x 50m). + assert np.median(values[500:]) == pytest.approx(15_811.0, rel=0.15) + + +def test_generate_input_values_uses_recentred_input_ratio() -> None: + torch.manual_seed(0) + n_firms = 20_000 + turnover = torch.full((n_firms,), 100.0) + sic = torch.full((n_firms,), 45, dtype=torch.int64) # no sector shift + + ratios = (generate_input_values(turnover, sic) / turnover).numpy() + + assert ratios.min() >= INPUT_RATIO_LOWER - 1e-6 + assert ratios.max() <= INPUT_RATIO_UPPER + 1e-6 + # 0.2 + Beta(4, 2) * 0.6 has mean 0.6; value added is always positive. + assert ratios.mean() == pytest.approx(0.6, abs=0.02) + zero = generate_input_values(torch.tensor([0.0]), torch.tensor([50])) + assert zero.tolist() == [0.0] + + +def test_assign_employment_is_sector_conditional() -> None: + ons_employment = pd.DataFrame( + [ + {"SIC Code": 1, "Description": "Small", "0-4": 5, "250+": 0}, + {"SIC Code": 2, "Description": "Large", "0-4": 0, "250+": 5}, + {"SIC Code": "", "Description": "Total", "0-4": 5, "250+": 5}, + ] + ) + torch.manual_seed(0) + sic = torch.tensor([1] * 50 + [2] * 50 + [3] * 200, dtype=torch.int64) + + employment = assign_employment(sic, ons_employment).numpy() + + assert employment.shape == (300,) + assert ((employment[:50] >= 1) & (employment[:50] <= 4)).all() + assert (employment[50:100] >= 250).all() + # A sector without an ONS row draws from the national shares. + unknown = employment[100:] + assert (unknown <= 4).any() and (unknown >= 250).any() + assert assign_employment(sic[:0], ons_employment).shape == (0,) + + +def test_employment_band_index_array_matches_band_names() -> None: + employment = np.arange(1, 3_001) + indices = employment_band_index_array(employment) + names = [employment_band_name(value) for value in employment] + order = ["0-4", "5-9", "10-19", "20-49", "50-99", "100-249", "250+"] + assert [order[index] for index in indices] == names + + class _TestVATRuleEvaluator: def net_liability_k( self, @@ -305,6 +724,22 @@ def net_liability_k( return np.where(vat_registered, 0.2 * (turnover_k - input_cost_k), 0.0) +class _ShuffledFirmIdRules: + """Rules double: liability is firm_id thousand pounds, returned reversed.""" + + def __init__(self) -> None: + self.periods: list[int] = [] + + def evaluate(self, firms: pd.DataFrame, *, period: int) -> UKFirmRuleOutputs: + self.periods.append(period) + firm_id = firms["firm_id"].to_numpy(np.int64)[::-1] + return UKFirmRuleOutputs( + firm_id=firm_id, + vat_liability_if_registered=firm_id.astype(np.float64) * 1000.0, + provenance={"rules": "test-double"}, + ) + + def _firm_config(**overrides) -> UKFirmGenerationConfig: return UKFirmGenerationConfig( vat_rule_evaluator=_TestVATRuleEvaluator(), @@ -312,8 +747,18 @@ def _firm_config(**overrides) -> UKFirmGenerationConfig: ) -def _source_data(): - return uk_firm_source_data_from_frames(**_source_frames()) +def _source_data(scale: int = 1): + frames = _source_frames() + if scale != 1: + for key in ("ons_turnover", "ons_employment"): + frame = frames[key] + numeric = [ + column + for column in frame.columns + if column not in {"SIC Code", "Description"} + ] + frames[key] = frame.assign(**{c: frame[c] * scale for c in numeric}) + return uk_firm_source_data_from_frames(**frames) def _ledger_target_profile_mapping(**overrides: str) -> dict[str, object]: diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_paper_parity.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_paper_parity.py new file mode 100644 index 0000000000..b2d4fc1b07 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_paper_parity.py @@ -0,0 +1,438 @@ +"""Paper parity for the experimental UK firm generator (2024-25 vintage). + +The committed fixture ``tests/fixtures/uk/firm_2024_25`` holds the six +processed ONS/HMRC tables from PolicyEngine/firm-microsim-paper at aa1ce07 and +``paper_reference_2024_25.json``, golden numbers from local paper runs (see +``tools/uk_firm_paper_parity.py``). Parity is distributional, not row or weight +identity: the generators use different random streams and calibration losses. + +The CI run here is thinned (window fraction 0.05, tail fraction 0.01) and +uses the generator's default 1,000 epochs, as the paper does. At 300 epochs +the net-VAT-by-band mean accuracy was 0.938, below the 0.96 bar; at 1,000 it +is 0.994. It is compared with the paper's full-census golden numbers at the +thinned tolerances of the scoping decision. Seed reproducibility uses a +separate short run pair; the main thinned solve takes about 30 seconds. +""" + +from __future__ import annotations + +import hashlib +import json +from dataclasses import fields +from functools import cache +from typing import Any + +import numpy as np +import pandas as pd +import pytest + +from microcosm.build.uk_runtime.firm_generation import ( + UKFirmGenerationConfig, + generate_uk_firm_population, + read_uk_firm_source_data, +) +from microcosm.build.uk_runtime.firm_rules import UKFirmRuleOutputs +from microcosm.build.uk_runtime.firm_universe import HMRC_BAND_NAMES +from test_support.paths import paths_for + +FIXTURE_DIR = paths_for("microcosm-build").tests / "fixtures" / "uk" / "firm_2024_25" +THRESHOLD_K = 90.0 +SEED = 42 +CI_WINDOW_FRACTION = 0.05 +CI_TAIL_FRACTION = 0.01 +CI_EPOCHS = 1_000 +REPRODUCIBILITY_EPOCHS = 50 +PAPER_FORMULA_RATE = 0.20 + +HMRC_BANDS = HMRC_BAND_NAMES +CALIBRATED_VAT_BANDS = HMRC_BANDS[2:] +EMPLOYMENT_BANDS = ("0-4", "5-9", "10-19", "20-49", "50-99", "100-249", "250+") + + +class PaperFormulaRules: + """Test-only rules double: the paper's 0.20 x (turnover - inputs), in GBP. + + Not UK VAT law; it lets the parity run compare draws and weights with the + paper, whose liability model is this standard-rate approximation. + """ + + def evaluate(self, firms: pd.DataFrame, *, period: int) -> UKFirmRuleOutputs: + del period + liability = PAPER_FORMULA_RATE * ( + firms["firm_turnover"].to_numpy(dtype=np.float64) + - firms["firm_input_costs"].to_numpy(dtype=np.float64) + ) + return UKFirmRuleOutputs( + firm_id=firms["firm_id"].to_numpy(dtype=np.int64), + vat_liability_if_registered=liability, + provenance={"rules": "paper-formula test double"}, + ) + + +def _ci_config(seed: int = SEED, epochs: int = CI_EPOCHS) -> UKFirmGenerationConfig: + names = {field.name for field in fields(UKFirmGenerationConfig)} + missing = { + "firm_rules", + "sample_window_fraction", + "sample_tail_fraction", + } - names + assert not missing, f"generator config lacks paper-parity fields: {missing}" + # Build directly: replace() on a default (2023-24) config would keep the + # £85k threshold its __post_init__ already resolved. + return UKFirmGenerationConfig( + data_vintage="2024-25", + seed=seed, + n_iterations=epochs, + sample_window_fraction=CI_WINDOW_FRACTION, + sample_tail_fraction=CI_TAIL_FRACTION, + firm_rules=PaperFormulaRules(), + ) + + +@cache +def _run(seed: int = SEED) -> Any: + data = read_uk_firm_source_data(FIXTURE_DIR) + return generate_uk_firm_population(data, _ci_config(seed)) + + +@cache +def _reference() -> dict[str, Any]: + return json.loads( + (FIXTURE_DIR / "paper_reference_2024_25.json").read_text(encoding="utf-8") + ) + + +@cache +def _tables() -> dict[str, pd.DataFrame]: + return { + "turnover": pd.read_csv(FIXTURE_DIR / "ons_firm_turnover.csv"), + "employment": pd.read_csv(FIXTURE_DIR / "ons_firm_employment.csv"), + "pop_band": pd.read_csv( + FIXTURE_DIR / "hmrc_vat_population_by_turnover_band.csv" + ), + "pop_sector": pd.read_csv( + FIXTURE_DIR / "hmrc_vat_population_by_sector.csv", + dtype={"Trade_Sector": str}, + ), + "liab_band": pd.read_csv( + FIXTURE_DIR / "hmrc_vat_liability_by_turnover_band.csv" + ), + } + + +def _hmrc_counts() -> dict[str, float]: + row = _tables()["pop_band"].iloc[-1] + return {band: float(row[band]) for band in HMRC_BANDS} + + +def _ons_sector_rows() -> pd.DataFrame: + turnover = _tables()["turnover"] + sic = turnover["SIC Code"] + rows = turnover[sic.notna() & (sic.astype(str) != "")] + return rows[~rows["Description"].str.contains("Total", na=False)] + + +def _ons_band_columns() -> list[str]: + return [ + column + for column in _tables()["turnover"].columns + if column not in {"SIC Code", "Description", "Total"} + ] + + +def _ons_draw_rows_by_sic() -> dict[int, int]: + columns = _ons_band_columns() + return { + int(row["SIC Code"]): int(row[columns].fillna(0).astype(int).sum()) + for _, row in _ons_sector_rows().iterrows() + } + + +def _expected_targets() -> dict[str, float]: + """The paper's 2024-25 target vector derived from the fixture tables.""" + + tables = _tables() + hmrc = _hmrc_counts() + expected = {f"hmrc_vat_population/{band}": hmrc[band] for band in HMRC_BANDS} + sectors = tables["pop_sector"][tables["pop_sector"]["Trade_Sector"] != "Total"] + raw = { + int(row["Trade_Sector"]): float(row.iloc[-1]) for _, row in sectors.iterrows() + } + scale = sum(hmrc.values()) / sum(raw.values()) + expected.update( + { + f"hmrc_vat_population_sector/{sic}": value * scale + for sic, value in raw.items() + } + ) + employment = tables["employment"] + employment = employment[~employment["Description"].str.contains("Total", na=False)] + expected.update( + { + f"ons_firm_employment/{band}": float(employment[band].fillna(0).sum()) + for band in EMPLOYMENT_BANDS + } + ) + liability = tables["liab_band"].iloc[-1] + expected.update( + { + f"hmrc_vat_liability/{band}": float(liability[band]) * 1000.0 + for band in CALIBRATED_VAT_BANDS + } + ) + return expected + + +def _ons_total() -> float: + turnover = _tables()["turnover"] + sic = turnover["SIC Code"] + total_row = turnover[sic.isna() | (sic.astype(str) == "")] + if len(total_row): + return float(total_row.iloc[0]["Total"]) + return float(_ons_sector_rows()["Total"].sum()) + + +def _band_index(turnover_k: np.ndarray) -> np.ndarray: + edges = np.array([0.0, THRESHOLD_K, 150, 300, 500, 1000, 10000]) + return np.searchsorted(edges, turnover_k.astype(np.float64), side="left") + + +def _employment_index(employment: np.ndarray) -> np.ndarray: + edges = np.array([4, 9, 19, 49, 99, 249]) + return np.searchsorted(edges, employment.astype(np.float64), side="left") + + +def _accuracy(estimate: float, target: float) -> float: + return max(0.0, 1.0 - abs(estimate - target) / abs(target)) + + +@cache +def _summary() -> dict[str, Any]: + firms = _run().firms + weight = firms["firm_weight"].to_numpy(dtype=np.float64) + turnover = firms["annual_turnover_k"].to_numpy(dtype=np.float64) + inputs = firms["annual_input_k"].to_numpy(dtype=np.float64) + registered = firms["vat_registered"].to_numpy(dtype=bool) + frame = firms["in_frame"].to_numpy(dtype=bool) + band = _band_index(turnover) + employment = _employment_index(firms["employment"].to_numpy()) + sic = firms["sic_code"].astype(int).to_numpy() + liability_m = PAPER_FORMULA_RATE * (turnover - inputs) * weight / 1000.0 + reg_band = np.bincount(band[registered], weights=weight[registered], minlength=8) + reg_vat = np.bincount( + band[registered], weights=liability_m[registered], minlength=8 + ) + emp = np.bincount(employment[frame], weights=weight[frame], minlength=7) + window = frame & (turnover > 80.0) & (turnover <= 100.0) + return { + "weighted_frame_population": float(weight[frame].sum()), + "registered_traders": float(weight[registered].sum()), + "hmrc_band_registered": dict(zip(HMRC_BANDS, reg_band.tolist(), strict=True)), + "net_vat_by_band_m": dict(zip(HMRC_BANDS, reg_vat.tolist(), strict=True)), + "employment_band_frame": dict(zip(EMPLOYMENT_BANDS, emp.tolist(), strict=True)), + "sector_registered": pd.Series(weight[registered]) + .groupby(sic[registered]) + .sum() + .to_dict(), + "frame_mass_80_100k": float(weight[window].sum()), + } + + +def _paper_full() -> dict[str, Any]: + return _reference()["runs"]["full"]["summary"] + + +# --- fixture integrity ------------------------------------------------------ + + +def test_fixture_matches_recorded_paper_provenance() -> None: + provenance = json.loads( + (FIXTURE_DIR / ".provenance.json").read_text(encoding="utf-8") + ) + + assert provenance["paper_commit"].startswith("aa1ce07") + for name, entry in provenance["files"].items(): + digest = hashlib.sha256((FIXTURE_DIR / name).read_bytes()).hexdigest() + assert digest == entry["sha256"], name + assert len(provenance["files"]) == 6 + reference_digest = hashlib.sha256( + (FIXTURE_DIR / "paper_reference_2024_25.json").read_bytes() + ).hexdigest() + assert reference_digest == provenance["reference"]["sha256"] + + +def test_golden_full_run_reproduces_the_published_paper_headline() -> None: + reference = json.loads( + (FIXTURE_DIR / "paper_reference_2024_25.json").read_text(encoding="utf-8") + ) + provenance = json.loads( + (FIXTURE_DIR / ".provenance.json").read_text(encoding="utf-8") + ) + headline = reference["paper_published_headline"] + full = reference["runs"]["full"]["summary"] + + assert reference["paper_commit"] == provenance["paper_commit"] + assert ( + round(full["weighted_frame_population"]) + == headline["weighted_frame_population"] + ) + assert round(full["registered_traders"]) == headline["registered_traders"] + assert full["pre_thinning_rows"] == headline["rows"] + + +def test_pre_thinning_row_count_matches_paper() -> None: + draw_rows = sum(_ons_draw_rows_by_sic().values()) + appended = int(round(_hmrc_counts()["Negative_or_Zero"])) + + assert draw_rows + appended == 2_946_015 + assert _paper_full()["pre_thinning_rows"] == 2_946_015 + + +# --- exact checks on the thinned run ---------------------------------------- + + +def test_target_vector_matches_fixture_tables() -> None: + diagnostics = _run().target_diagnostics + expected = _expected_targets() + actual = dict( + zip( + diagnostics["target_name"], diagnostics["target"].astype(float), strict=True + ) + ) + unmatched = sorted(set(actual) - set(expected)) + + # The one row outside the named families is the ONS frame population. + assert len(unmatched) == 1, unmatched + np.testing.assert_allclose(actual[unmatched[0]], _ons_total(), rtol=1e-6) + assert set(expected) <= set(actual) + for name, value in expected.items(): + np.testing.assert_allclose(actual[name], value, rtol=1e-6, err_msg=name) + + +def test_thinning_preserves_pre_thinning_totals_per_sector() -> None: + firms = _run().firms + frame = firms[firms["in_frame"].to_numpy(dtype=bool)] + base_by_sic = frame.groupby(frame["sic_code"].astype(int))["base_weight"].sum() + expected = _ons_draw_rows_by_sic() + + assert len(frame) < 0.05 * sum(expected.values()) + assert sorted(base_by_sic.index) == sorted(k for k, v in expected.items() if v) + for sic, rows in expected.items(): + if rows: + np.testing.assert_allclose(base_by_sic[sic], rows, rtol=1e-6, err_msg=sic) + appended = int((~firms["in_frame"].to_numpy(dtype=bool)).sum()) + pre_thinning = round(float(frame["base_weight"].sum())) + appended + assert pre_thinning == 2_946_015 + + +def test_propensity_scaled_band_rows_hit_hmrc_counts_at_base_weights() -> None: + """Row b holds p_b on band-b frame rows, so at base weights it equals HMRC_b. + + ``initial_estimate`` is the target matrix applied to the base weights, so + this checks the propensities the generator actually used, to 1e-6. + """ + + diagnostics = _run().target_diagnostics.set_index("target_name") + hmrc = _hmrc_counts() + + for band in HMRC_BANDS: + row = diagnostics.loc[f"hmrc_vat_population/{band}"] + np.testing.assert_allclose( + row["initial_estimate"], hmrc[band], rtol=1e-6, err_msg=band + ) + + +def test_registration_propensities_are_hmrc_count_over_frame_mass() -> None: + from microcosm.build.uk_runtime.firm_universe import registration_propensity + + firms = _run().firms + frame = firms["in_frame"].to_numpy(dtype=bool) + band = _band_index(firms["annual_turnover_k"].to_numpy()) + base = firms["base_weight"].to_numpy(dtype=np.float64) + hmrc = _hmrc_counts() + propensity = np.asarray( + registration_propensity( + band, frame, base, np.array([hmrc[b] for b in HMRC_BANDS]) + ) + ) + + for index, name in enumerate(HMRC_BANDS[1:], start=1): + mask = frame & (band == index) + expected = min(1.0, hmrc[name] / base[mask].sum()) + np.testing.assert_allclose(propensity[mask], expected, atol=1e-6, err_msg=name) + np.testing.assert_allclose(propensity[~frame], 1.0, atol=1e-6) + + +# --- distributional parity with the paper (thinned tolerances) -------------- + + +def test_weighted_frame_population_and_registered_traders() -> None: + summary, paper = _summary(), _paper_full() + + assert summary["weighted_frame_population"] == pytest.approx( + paper["weighted_frame_population"], rel=0.005 + ) + assert summary["registered_traders"] == pytest.approx( + paper["registered_traders"], rel=0.005 + ) + + +@pytest.mark.parametrize("band", HMRC_BANDS) +def test_hmrc_band_counts_within_thinned_tolerance(band: str) -> None: + assert _summary()["hmrc_band_registered"][band] == pytest.approx( + _paper_full()["hmrc_band_registered"][band], rel=0.03 + ) + + +@pytest.mark.parametrize("band", EMPLOYMENT_BANDS) +def test_employment_bands_within_tolerance(band: str) -> None: + assert _summary()["employment_band_frame"][band] == pytest.approx( + _paper_full()["employment_band_frame"][band], rel=0.02 + ) + + +def test_net_vat_by_calibrated_band_mean_accuracy() -> None: + liability = _tables()["liab_band"].iloc[-1] + accuracies = [ + _accuracy(_summary()["net_vat_by_band_m"][band], float(liability[band])) + for band in CALIBRATED_VAT_BANDS + ] + + assert np.mean(accuracies) >= 0.96 + + +def test_sector_counts_mean_accuracy() -> None: + expected = { + int(name.rsplit("/", 1)[1]): value + for name, value in _expected_targets().items() + if name.startswith("hmrc_vat_population_sector/") + } + synthetic = _summary()["sector_registered"] + accuracies = [_accuracy(synthetic.get(sic, 0.0), v) for sic, v in expected.items()] + + assert np.mean(accuracies) >= 0.90 + + +def test_frame_mass_near_threshold_within_thinned_tolerance() -> None: + assert _summary()["frame_mass_80_100k"] == pytest.approx( + _paper_full()["frame_mass_80_100k"], rel=0.10 + ) + + +# --- reproducibility -------------------------------------------------------- + + +def test_same_seed_reproduces_the_thinned_population() -> None: + data = read_uk_firm_source_data(FIXTURE_DIR) + config = _ci_config(epochs=REPRODUCIBILITY_EPOCHS) + first = generate_uk_firm_population(data, config).firms + second = generate_uk_firm_population(data, config).firms + other_seed = generate_uk_firm_population( + data, _ci_config(seed=SEED + 1, epochs=REPRODUCIBILITY_EPOCHS) + ).firms + + pd.testing.assert_frame_equal(first, second) + assert not np.array_equal( + first["annual_turnover_k"].to_numpy(), + other_seed["annual_turnover_k"].to_numpy(), + ) diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_policyengine_uk_rules.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_policyengine_uk_rules.py new file mode 100644 index 0000000000..95e406bb9a --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_policyengine_uk_rules.py @@ -0,0 +1,573 @@ +"""The policyengine-uk firm rules adapter, with an injected simulation factory. + +No test imports policyengine-uk: a fake factory stands in for the +``Microsimulation`` and records what the adapter hands it. The schema snapshot +(``tests/fixtures/uk/policyengine_uk_firm_inputs.json``) says which firm +variables policyengine-uk has and which carry a formula. +""" + +from __future__ import annotations + +import json +import subprocess +import sys +from dataclasses import dataclass, field +from functools import cache +from types import SimpleNamespace + +import numpy as np +import pandas as pd +import pytest + +from microcosm.build.uk_runtime.firm_policyengine_uk_rules import ( + POLICYENGINE_UK_FIRM_INFORMATIONAL_VARIABLES, + POLICYENGINE_UK_FIRM_INPUT_COLUMNS, + POLICYENGINE_UK_FIRM_LIABILITY_VARIABLE, + POLICYENGINE_UK_FIRM_PULL_REQUEST, + POLICYENGINE_UK_FIRM_REGISTERED_VARIABLE, + POLICYENGINE_UK_FIRM_TAX_VARIABLES, + POLICYENGINE_UK_FIRM_TAXES, + PolicyEngineUKFirmRules, + evaluate_uk_firm_taxes, + require_policyengine_uk_firm_rules, + weighted_uk_firm_tax_totals, +) +from microcosm.build.uk_runtime.firm_rules import ( + UKFirmRuleOutputs, + align_rule_outputs, + rule_period_for_vintage, +) +from microcosm.build.uk_runtime.firm_table import ( + UK_FIRM_MICROCOSM_ONLY_COLUMNS, + UK_FIRM_POLICYENGINE_UK_INPUT_STATUS, + build_candidate_rules_table, +) +from test_support.paths import paths_for + +SNAPSHOT = ( + paths_for("microcosm-build").tests + / "fixtures" + / "uk" + / "policyengine_uk_firm_inputs.json" +) + +MODULE = "microcosm.build.uk_runtime.firm_policyengine_uk_rules" + + +@cache +def snapshot() -> dict: + return json.loads(SNAPSHOT.read_text(encoding="utf-8")) + + +def candidates() -> pd.DataFrame: + firms = pd.DataFrame( + { + "firm_id": [70, 3, 512, 44, 8], + "sic_code": [47, 62, 1, 86, 64], + "annual_turnover_k": [120.0, 2_500.0, 30.0, 0.0, 61_000.0], + "annual_input_k": [70.0, 3_100.0, 12.0, 4.0, 20_000.0], + "employment": [3, 20, 0, 1, 450], + } + ) + return build_candidate_rules_table(firms) + + +def paper_liability(table: pd.DataFrame) -> np.ndarray: + return 0.20 * table["firm_standard_rated_supplies"].to_numpy(np.float64) - table[ + "firm_input_vat" + ].to_numpy(np.float64) + + +@dataclass +class FakeSimulation: + table: pd.DataFrame + liability: np.ndarray + firm_id: np.ndarray + reads: list = field(default_factory=list) + + def calculate(self, variable_name: str, period: int): + self.reads.append((variable_name, period)) + if variable_name == POLICYENGINE_UK_FIRM_LIABILITY_VARIABLE: + return self.liability + if variable_name == "firm_id": + return self.firm_id + raise KeyError(variable_name) + + +@dataclass +class FakeFactory: + """Records each call and answers with the paper formula unless told to + return something else.""" + + liability: np.ndarray | None = None + firm_id: np.ndarray | None = None + calls: list = field(default_factory=list) + + def __call__(self, table: pd.DataFrame, period: int) -> FakeSimulation: + simulation = FakeSimulation( + table=table, + liability=( + paper_liability(table) if self.liability is None else self.liability + ), + firm_id=( + table["firm_id"].to_numpy() if self.firm_id is None else self.firm_id + ), + ) + self.calls.append((table, period, simulation)) + return simulation + + +def test_the_variables_it_reads_are_policyengine_uk_firm_formulas() -> None: + variables = snapshot()["firm_variables"] + for name in ( + POLICYENGINE_UK_FIRM_LIABILITY_VARIABLE, + POLICYENGINE_UK_FIRM_REGISTERED_VARIABLE, + ): + assert name in variables + assert variables[name]["has_formula"] is True + assert POLICYENGINE_UK_FIRM_LIABILITY_VARIABLE == "firm_vat_liability_if_registered" + assert POLICYENGINE_UK_FIRM_REGISTERED_VARIABLE == "firm_vat_registered" + + +def test_the_factory_gets_only_formula_less_firm_inputs() -> None: + factory = FakeFactory() + table = candidates().assign( + firm_weight=1.0, **{POLICYENGINE_UK_FIRM_LIABILITY_VARIABLE: 0.0} + ) + PolicyEngineUKFirmRules(simulation_factory=factory).evaluate(table, period=2024) + + (handed, _, _), *rest = factory.calls + assert not rest + inputs = set(snapshot()["firm_input_names"]) + assert tuple(handed.columns) == POLICYENGINE_UK_FIRM_INPUT_COLUMNS + assert set(handed.columns) <= inputs + # A column naming a formula variable would override the rule it reads. + assert POLICYENGINE_UK_FIRM_LIABILITY_VARIABLE not in handed.columns + + +def test_the_period_is_forwarded_and_firm_ids_keep_their_rows() -> None: + factory = FakeFactory() + table = candidates().iloc[[3, 0, 4, 1, 2]] + period = rule_period_for_vintage("2024-25") + outputs = PolicyEngineUKFirmRules(simulation_factory=factory).evaluate( + table, period=period + ) + + handed, handed_period, simulation = factory.calls[0] + # The tax year's start year, passed through unchanged. + assert handed_period == period == 2024 + assert handed["firm_id"].tolist() == table["firm_id"].tolist() + assert {read for read, _ in simulation.reads} == { + POLICYENGINE_UK_FIRM_LIABILITY_VARIABLE, + "firm_id", + } + assert {at for _, at in simulation.reads} == {period} + + assert isinstance(outputs, UKFirmRuleOutputs) + assert outputs.firm_id.tolist() == table["firm_id"].tolist() + np.testing.assert_allclose( + outputs.vat_liability_if_registered, paper_liability(table) + ) + by_id = align_rule_outputs(outputs, candidates()["firm_id"]) + np.testing.assert_allclose(by_id, paper_liability(candidates())) + + +def test_provenance_names_the_rules_version_variable_and_period() -> None: + outputs = PolicyEngineUKFirmRules(simulation_factory=FakeFactory()).evaluate( + candidates(), period=2024 + ) + provenance = dict(outputs.provenance) + assert provenance["rules"] == "policyengine_uk" + assert provenance["variable"] == POLICYENGINE_UK_FIRM_LIABILITY_VARIABLE + assert provenance["period"] == "2024" + assert provenance["policyengine_uk_version"] + + +@pytest.mark.parametrize( + "liability", + [ + np.zeros(4), + np.zeros(6), + np.array([1.0, np.nan, 3.0, 4.0, 5.0]), + np.array([1.0, 2.0, np.inf, 4.0, 5.0]), + ], + ids=["short", "long", "nan", "inf"], +) +def test_a_bad_liability_from_the_factory_raises(liability) -> None: + rules = PolicyEngineUKFirmRules(simulation_factory=FakeFactory(liability=liability)) + with pytest.raises(ValueError, match=POLICYENGINE_UK_FIRM_LIABILITY_VARIABLE): + rules.evaluate(candidates(), period=2024) + + +def test_firm_ids_out_of_order_in_the_simulation_raise() -> None: + table = candidates() + rules = PolicyEngineUKFirmRules( + simulation_factory=FakeFactory(firm_id=table["firm_id"].to_numpy()[::-1]) + ) + with pytest.raises(ValueError, match="firm_id order"): + rules.evaluate(table, period=2024) + + +def test_a_table_without_a_candidate_column_raises() -> None: + rules = PolicyEngineUKFirmRules(simulation_factory=FakeFactory()) + with pytest.raises(ValueError, match="firm_input_vat"): + rules.evaluate(candidates().drop(columns="firm_input_vat"), period=2024) + + +def fake_system(*, entities=("person", "benunit", "household", "firm"), variables=()): + firm = SimpleNamespace(key="firm") + return SimpleNamespace( + entities=[SimpleNamespace(key=key) for key in entities], + variables={name: SimpleNamespace(entity=firm) for name in variables}, + ) + + +@pytest.mark.parametrize( + ("system", "detail"), + [ + ( + fake_system(entities=("person", "benunit", "household")), + "no Firm entity", + ), + ( + fake_system(variables=("firm_id",)), + f"no {POLICYENGINE_UK_FIRM_LIABILITY_VARIABLE} variable", + ), + ], + ids=["no-firm-entity", "no-liability-variable"], +) +def test_a_policyengine_uk_without_firm_rules_names_the_pull_request( + system, detail +) -> None: + with pytest.raises(RuntimeError) as error: + require_policyengine_uk_firm_rules(system) + message = str(error.value) + assert detail in message + assert POLICYENGINE_UK_FIRM_PULL_REQUEST in message + assert POLICYENGINE_UK_FIRM_PULL_REQUEST == "PolicyEngine/policyengine-uk#2940" + + +def test_a_dataset_without_a_firm_table_names_the_pull_request() -> None: + system = fake_system(variables=("firm_id", POLICYENGINE_UK_FIRM_LIABILITY_VARIABLE)) + require_policyengine_uk_firm_rules(system) + + def old_dataset(person, benunit, household, fiscal_year=None): + del person, benunit, household, fiscal_year + + def new_dataset(person, benunit, household, firm=None, fiscal_year=None): + del person, benunit, household, firm, fiscal_year + + require_policyengine_uk_firm_rules(system, new_dataset) + with pytest.raises(RuntimeError, match="takes no firm table.*#2940"): + require_policyengine_uk_firm_rules(system, old_dataset) + + +def test_importing_the_adapter_leaves_policyengine_uk_unimported() -> None: + script = ( + "import sys\n" + f"import {MODULE}\n" + "from microcosm.build.uk_runtime.firm_policyengine_uk_rules import " + "PolicyEngineUKFirmRules\n" + "PolicyEngineUKFirmRules()\n" + "leaked = sorted(m for m in sys.modules " + "if m.split('.')[0] in ('policyengine_uk', 'policyengine_core'))\n" + "assert not leaked, leaked\n" + ) + completed = subprocess.run( + [sys.executable, "-c", script], + capture_output=True, + text=True, + check=False, + ) + assert completed.returncode == 0, completed.stderr + + +# evaluate_uk_firm_taxes: every firm tax from the exported firm table. + + +def export_table() -> pd.DataFrame: + """Rows shaped like the extended ``uk_firms.parquet`` export, with + microcosm-only columns after the policyengine-uk ones.""" + + return pd.DataFrame( + { + "firm_id": [5, 2, 9], + "firm_weight": [10.0, 2.5, 1.0], + "firm_turnover": [100_000.0, 2_000_000.0, 50_000.0], + "firm_input_costs": [40_000.0, 900_000.0, 10_000.0], + "firm_employees": [2, 30, 0], + "firm_sic_section": ["G", "J", "A"], + "firm_standard_rated_supplies": [100_000.0, 2_000_000.0, 0.0], + "firm_exempt_supplies": [0.0, 0.0, 50_000.0], + "firm_vat_voluntarily_registered": [False, False, False], + "firm_input_vat": [8_000.0, 180_000.0, 2_000.0], + "firm_legal_form": ["COMPANY", "COMPANY", "SOLE_TRADER"], + "firm_region": ["LONDON", "NORTH_WEST", "WALES"], + "firm_in_england": [True, True, False], + "firm_is_public_body": [False, False, False], + "in_frame": [True, True, True], + "vat_scope": [True, True, False], + "vat_registered": [True, True, False], + "base_weight": [9.0, 3.0, 1.0], + "data_vintage": ["2024-25"] * 3, + "source_firm_id": [1, 2, 3], + "source_firm_key": ["a", "b", "c"], + "ons_legal_status": [1, 1, 2], + "ons_region_code": ["E12000007", "E12000002", "W92000004"], + } + ) + + +def tax_value(name: str, firm_id: np.ndarray) -> np.ndarray: + """A distinct, deterministic value per variable and firm.""" + + offset = 1_000.0 * (1 + POLICYENGINE_UK_FIRM_TAX_VARIABLES.index(name)) + return offset + firm_id.astype(np.float64) + + +@dataclass +class FakeTaxSimulation: + table: pd.DataFrame + overrides: dict + reads: list = field(default_factory=list) + + def calculate(self, variable_name: str, period: int): + self.reads.append((variable_name, period)) + if variable_name in self.overrides: + return self.overrides[variable_name] + firm_id = self.table["firm_id"].to_numpy() + if variable_name == "firm_id": + return firm_id + if variable_name in POLICYENGINE_UK_FIRM_TAX_VARIABLES: + # float32, as policyengine-uk stores firm amounts. + return tax_value(variable_name, firm_id).astype(np.float32) + raise KeyError(variable_name) + + +@dataclass +class FakeTaxFactory: + overrides: dict = field(default_factory=dict) + calls: list = field(default_factory=list) + + def __call__(self, table: pd.DataFrame, period: int) -> FakeTaxSimulation: + simulation = FakeTaxSimulation(table=table, overrides=self.overrides) + self.calls.append((table, period, simulation)) + return simulation + + +def test_the_tax_variables_are_policyengine_uk_firm_gbp_formulas() -> None: + assert POLICYENGINE_UK_FIRM_TAXES == ( + "firm_vat", + "firm_employer_ni", + "apprenticeship_levy", + "corporation_tax", + "bank_surcharge", + "firm_business_rates", + ) + assert POLICYENGINE_UK_FIRM_INFORMATIONAL_VARIABLES == ( + "employment_allowance", + "firm_auto_enrolment_employer_contribution", + ) + assert POLICYENGINE_UK_FIRM_TAX_VARIABLES == ( + *POLICYENGINE_UK_FIRM_TAXES, + *POLICYENGINE_UK_FIRM_INFORMATIONAL_VARIABLES, + ) + variables = snapshot()["firm_variables"] + for name in POLICYENGINE_UK_FIRM_TAX_VARIABLES: + assert variables[name]["has_formula"] is True, name + assert variables[name]["unit"] == "GBP", name + assert variables[name]["value_type"] == "float", name + assert variables[name]["definition_period"] == "year", name + + +def test_only_policyengine_uk_firm_inputs_reach_the_factory() -> None: + factory = FakeTaxFactory() + # A column named after an output would override the rule that computes it. + table = export_table().assign(firm_vat=0.0, corporation_tax=0.0) + with pytest.warns(UserWarning, match=r"drops firm columns \['firm_vat'\]"): + evaluate_uk_firm_taxes(table, period=2024, simulation_factory=factory) + + (handed, period, simulation), *rest = factory.calls + assert not rest + assert period == 2024 + inputs = set(UK_FIRM_POLICYENGINE_UK_INPUT_STATUS) + assert set(handed.columns) <= inputs + assert set(handed.columns) <= set(snapshot()["firm_input_names"]) + assert not set(handed.columns) & set(UK_FIRM_MICROCOSM_ONLY_COLUMNS) + assert not set(handed.columns) & set(POLICYENGINE_UK_FIRM_TAX_VARIABLES) + # Every policyengine-uk input in the table is kept, in the table's order. + assert list(handed.columns) == [c for c in table.columns if c in inputs] + assert "firm_region" in handed.columns + assert "firm_legal_form" in handed.columns + assert list(handed.index) == list(range(len(table))) + assert {at for _, at in simulation.reads} == {2024} + assert {read for read, _ in simulation.reads} == { + "firm_id", + *POLICYENGINE_UK_FIRM_TAX_VARIABLES, + } + + +def test_an_input_the_export_leaves_unset_passes_through_when_given() -> None: + table = export_table() + unset = sorted( + name + for name, status in UK_FIRM_POLICYENGINE_UK_INPUT_STATUS.items() + if status == "not_set" and name not in table.columns + ) + assert unset + factory = FakeTaxFactory() + table = table.assign(**{unset[0]: [0.0, 1.0, 0.0]}) + evaluate_uk_firm_taxes(table, period=2024, simulation_factory=factory) + handed = factory.calls[0][0] + assert handed[unset[0]].tolist() == [0.0, 1.0, 0.0] + + +def test_taxes_are_keyed_by_firm_id_in_input_order() -> None: + table = export_table().iloc[[2, 0, 1]].set_axis([7, 3, 11]) + taxes = evaluate_uk_firm_taxes( + table, period=2024, simulation_factory=FakeTaxFactory() + ) + + assert list(taxes.columns) == [ + "firm_id", + "firm_weight", + *POLICYENGINE_UK_FIRM_TAX_VARIABLES, + ] + assert list(taxes.index) == [0, 1, 2] + assert taxes["firm_id"].dtype == np.int64 + assert taxes["firm_id"].tolist() == [9, 5, 2] + assert taxes["firm_weight"].tolist() == [1.0, 10.0, 2.5] + for name in POLICYENGINE_UK_FIRM_TAX_VARIABLES: + assert taxes[name].dtype == np.float64 + np.testing.assert_array_equal( + taxes[name].to_numpy(), tax_value(name, np.array([9, 5, 2])) + ) + + +def test_a_table_without_weights_returns_no_weight_column() -> None: + taxes = evaluate_uk_firm_taxes( + export_table().drop(columns="firm_weight"), + period=2024, + simulation_factory=FakeTaxFactory(), + variables=("firm_vat", "corporation_tax"), + ) + assert list(taxes.columns) == ["firm_id", "firm_vat", "corporation_tax"] + with pytest.raises(ValueError, match="firm_weight"): + weighted_uk_firm_tax_totals(taxes) + + +def test_a_table_without_firm_id_raises() -> None: + with pytest.raises(ValueError, match="firm_id"): + evaluate_uk_firm_taxes( + export_table().drop(columns="firm_id"), + period=2024, + simulation_factory=FakeTaxFactory(), + ) + + +@pytest.mark.parametrize( + "variables", + [(), ("firm_vat", "firm_vat"), ("firm_vat", "firm_weight"), ("firm_id",)], + ids=["empty", "repeated", "weight", "id"], +) +def test_bad_variable_lists_raise(variables) -> None: + with pytest.raises(ValueError): + evaluate_uk_firm_taxes( + export_table(), + period=2024, + simulation_factory=FakeTaxFactory(), + variables=variables, + ) + + +def test_firm_ids_out_of_order_in_the_tax_simulation_raise() -> None: + reversed_ids = export_table()["firm_id"].to_numpy()[::-1] + factory = FakeTaxFactory(overrides={"firm_id": reversed_ids}) + with pytest.raises(ValueError, match="firm_id order"): + evaluate_uk_firm_taxes(export_table(), period=2024, simulation_factory=factory) + + +@pytest.mark.parametrize( + "values", + [ + np.zeros(2), + np.zeros(4), + np.zeros((3, 1)), + np.array([1.0, np.nan, 3.0]), + np.array([1.0, 2.0, -np.inf]), + ], + ids=["short", "long", "2d", "nan", "inf"], +) +def test_a_bad_tax_from_the_factory_raises(values) -> None: + factory = FakeTaxFactory(overrides={"corporation_tax": values}) + with pytest.raises(ValueError, match="corporation_tax"): + evaluate_uk_firm_taxes(export_table(), period=2024, simulation_factory=factory) + + +def test_weighted_totals_multiply_by_firm_weight() -> None: + taxes = pd.DataFrame( + { + "firm_id": np.array([1, 2, 3], dtype=np.int64), + "firm_weight": [2.0, 0.5, 10.0], + "firm_vat": [100.0, -40.0, 3.0], + "corporation_tax": [0.0, 1_000.0, 25.0], + } + ) + totals = weighted_uk_firm_tax_totals(taxes) + assert list(totals) == ["firm_vat", "corporation_tax"] + assert totals["firm_vat"] == pytest.approx(2.0 * 100 - 0.5 * 40 + 10.0 * 3) + assert totals["corporation_tax"] == pytest.approx(0.5 * 1_000 + 10.0 * 25) + assert all(isinstance(value, float) for value in totals.values()) + + +def test_weighted_totals_of_evaluated_taxes() -> None: + table = export_table() + taxes = evaluate_uk_firm_taxes( + table, period=2024, simulation_factory=FakeTaxFactory() + ) + totals = weighted_uk_firm_tax_totals(taxes) + assert list(totals) == list(POLICYENGINE_UK_FIRM_TAX_VARIABLES) + weight = table["firm_weight"].to_numpy() + for name, total in totals.items(): + expected = float(tax_value(name, table["firm_id"].to_numpy()) @ weight) + assert total == pytest.approx(expected) + + +def test_a_policyengine_uk_without_a_tax_variable_names_it_and_the_pull_request() -> ( + None +): + system = fake_system( + variables=("firm_id", *POLICYENGINE_UK_FIRM_TAX_VARIABLES[:-1]) + ) + # The VAT-only check is unchanged. + with pytest.raises(RuntimeError, match=POLICYENGINE_UK_FIRM_LIABILITY_VARIABLE): + require_policyengine_uk_firm_rules(system) + missing = POLICYENGINE_UK_FIRM_TAX_VARIABLES[-1] + with pytest.raises(RuntimeError) as error: + require_policyengine_uk_firm_rules( + system, variables=("firm_id", *POLICYENGINE_UK_FIRM_TAX_VARIABLES) + ) + message = str(error.value) + assert f"no {missing} variable" in message + assert POLICYENGINE_UK_FIRM_PULL_REQUEST in message + require_policyengine_uk_firm_rules( + system, variables=("firm_id", *POLICYENGINE_UK_FIRM_TAX_VARIABLES[:-1]) + ) + + +def test_importing_the_tax_reader_leaves_policyengine_uk_unimported() -> None: + script = ( + "import sys\n" + "from microcosm.build.uk_runtime.firm_policyengine_uk_rules import " + "evaluate_uk_firm_taxes, weighted_uk_firm_tax_totals\n" + "leaked = sorted(m for m in sys.modules " + "if m.split('.')[0] in ('policyengine_uk', 'policyengine_core'))\n" + "assert not leaked, leaked\n" + ) + completed = subprocess.run( + [sys.executable, "-c", script], + capture_output=True, + text=True, + check=False, + ) + assert completed.returncode == 0, completed.stderr diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_policyengine_uk_schema.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_policyengine_uk_schema.py new file mode 100644 index 0000000000..4221b1e5c3 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_policyengine_uk_schema.py @@ -0,0 +1,135 @@ +"""The UK firm export against the policyengine-uk firm schema snapshot. + +``tests/fixtures/uk/policyengine_uk_firm_inputs.json`` is policyengine-uk's +firm variables as ``tools/snapshot_policyengine_uk_firm_inputs.py`` read them +from source (PolicyEngine/policyengine-uk#2940). These tests hold the export +to that snapshot without importing policyengine-uk: refresh the snapshot with +the tool when policyengine-uk's firm variables change. +""" + +from __future__ import annotations + +import json +from functools import cache + +import numpy as np +import pandas as pd + +from microcosm.build.firms import ( + EntityVariables, + export_schema_problems, + input_status_problems, +) +from microcosm.build.uk_runtime.firm_table import ( + UK_FIRM_INPUT_STATUSES, + UK_FIRM_MICROCOSM_ONLY_COLUMNS, + UK_FIRM_POLICYENGINE_UK_COLUMNS, + UK_FIRM_POLICYENGINE_UK_INPUT_STATUS, + UK_FIRM_SIC_SECTIONS, + UK_FIRM_TABLE_COLUMNS, + to_policyengine_uk_firm_table, +) +from test_support.paths import paths_for + +SNAPSHOT = ( + paths_for("microcosm-build").tests + / "fixtures" + / "uk" + / "policyengine_uk_firm_inputs.json" +) + + +@cache +def _snapshot() -> dict: + return json.loads(SNAPSHOT.read_text(encoding="utf-8")) + + +def _variables() -> EntityVariables: + snapshot = _snapshot() + return EntityVariables( + variables=snapshot["firm_variables"], + input_names=snapshot["firm_input_names"], + variable_names=snapshot["policyengine_uk_variable_names"], + ) + + +def _variable(name: str) -> dict: + return _snapshot()["firm_variables"][name] + + +def _firms() -> pd.DataFrame: + return pd.DataFrame( + { + "firm_id": np.array([4, 2, 1, 3], dtype=np.int64), + "source_firm_id": np.array([4, 2, 1, 3], dtype=np.int64), + "source_firm_key": [ + f"2024-25:experimental_uk_firm:{i}" for i in (4, 2, 1, 3) + ], + "data_vintage": "2024-25", + "sic_code": ["00011", "00047", "00004", "00086"], + "annual_turnover_k": np.array([120.0, 90.0, 0.0, 40.0]), + "annual_input_k": np.array([80.0, 30.0, 0.0, 10.0]), + "employment": np.array([12, 3, 0, 1]), + "firm_weight": [2.5, 10.0, 0.0, 4.0], + "vat_scope": [True, True, False, False], + "vat_registered": [True, True, False, True], + "in_frame": [True, True, False, True], + "base_weight": [1.0, 2.0, 1.0, 1.0], + } + ) + + +def test_snapshot_records_the_policyengine_uk_checkout() -> None: + snapshot = _snapshot() + source = snapshot["policyengine_uk"] + + assert source["pull_request"] == "PolicyEngine/policyengine-uk#2940" + assert len(source["head_commit"]) == 40 + # A dirty checkout's HEAD does not identify the source it was read from. + assert source["dirty"] is False + assert snapshot["firm_input_names"] == sorted( + name + for name, variable in snapshot["firm_variables"].items() + if not variable["has_formula"] + ) + assert set(snapshot["firm_variables"]) <= set( + snapshot["policyengine_uk_variable_names"] + ) + + +def test_input_status_covers_exactly_the_snapshot_inputs() -> None: + assert UK_FIRM_INPUT_STATUSES == ("set", "derived", "assumed", "not_set") + assert ( + input_status_problems( + UK_FIRM_POLICYENGINE_UK_INPUT_STATUS, + _snapshot()["firm_input_names"], + exported_columns=UK_FIRM_POLICYENGINE_UK_COLUMNS, + ) + == [] + ) + + +def test_sic_sections_are_the_sic_section_members() -> None: + assert _variable("firm_sic_section")["enum"]["name"] == "SICSection" + assert UK_FIRM_SIC_SECTIONS == tuple(_variable("firm_sic_section")["enum_members"]) + + +def test_microcosm_only_columns_collide_with_no_policyengine_uk_variable() -> None: + snapshot = _snapshot() + microcosm_only = set(UK_FIRM_MICROCOSM_ONLY_COLUMNS) + + assert snapshot["collisions"] == [] + assert microcosm_only <= set(snapshot["microcosm_only_columns_checked"]) + assert microcosm_only.isdisjoint(snapshot["policyengine_uk_variable_names"]) + assert not any(column.startswith("firm_") for column in microcosm_only) + + +def test_export_loads_as_policyengine_uk_firm_inputs() -> None: + table = to_policyengine_uk_firm_table(_firms(), threshold_k=90.0) + assert tuple(table.columns) == UK_FIRM_TABLE_COLUMNS + assert ( + export_schema_problems( + table, _variables(), columns=UK_FIRM_POLICYENGINE_UK_COLUMNS + ) + == [] + ) diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_rules.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_rules.py new file mode 100644 index 0000000000..c5ec2b6fa5 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_rules.py @@ -0,0 +1,211 @@ +"""The UK firm rules seam: outputs, alignment, periods and the legacy adapter.""" + +from __future__ import annotations + +import numpy as np +import pandas as pd +import pytest + +from microcosm.build.firms import FirmRuleOutputs +from microcosm.build.uk_runtime.firm_rules import ( + UK_FIRM_DATA_YEARS_BY_VINTAGE, + UK_FIRM_RULE_PERIOD_BY_VINTAGE, + UK_FIRM_RULE_PERIOD_NOTE, + UK_FIRM_VINTAGE_BY_RULE_PERIOD, + LegacyVATEvaluatorRules, + UKFirmRuleOutputs, + align_rule_outputs, + data_years_for_vintage, + rule_period_for_vintage, +) +from microcosm.build.uk_runtime.firm_table import ( + ASSUMED_INPUT_VAT_RATE, + build_candidate_rules_table, +) + + +class _RecordingEvaluator: + """A VAT double: 20% of supplies less 20% of purchases, in £k.""" + + def __init__(self) -> None: + self.calls: list[dict[str, object]] = [] + + def net_liability_k( + self, *, turnover_k, input_cost_k, vat_registered, data_vintage + ): + self.calls.append( + { + "turnover_k": np.asarray(turnover_k), + "input_cost_k": np.asarray(input_cost_k), + "vat_registered": np.asarray(vat_registered), + "data_vintage": data_vintage, + } + ) + liability = 0.2 * np.asarray(turnover_k) - 0.2 * np.asarray(input_cost_k) + return np.where(vat_registered, liability, 0.0).astype(np.float32) + + +def _outputs(ids, values) -> UKFirmRuleOutputs: + return UKFirmRuleOutputs( + firm_id=np.asarray(ids, dtype=np.int64), + vat_liability_if_registered=np.asarray(values, dtype=np.float64), + provenance={"rules": "test"}, + ) + + +def _candidates() -> pd.DataFrame: + return build_candidate_rules_table( + pd.DataFrame( + { + "firm_id": [3, 1, 2], + "sic_code": ["00011", "00047", "00086"], + "annual_turnover_k": [100.0, 50.0, 2000.0], + "annual_input_k": [60.0, 10.0, 1500.0], + "employment": [4, 1, 30], + } + ) + ) + + +@pytest.mark.parametrize(("vintage", "period"), [("2024-25", 2024), ("2023-24", 2023)]) +def test_rule_period_is_the_tax_years_start_year(vintage, period) -> None: + assert rule_period_for_vintage(vintage) == period + assert UK_FIRM_VINTAGE_BY_RULE_PERIOD[period] == vintage + + +def test_the_inverse_period_view_is_derived_from_the_vintages() -> None: + assert dict(UK_FIRM_VINTAGE_BY_RULE_PERIOD) == { + period: vintage for vintage, period in UK_FIRM_RULE_PERIOD_BY_VINTAGE.items() + } + + +def test_an_unknown_vintage_has_no_rule_period() -> None: + with pytest.raises(ValueError, match="2025-26"): + rule_period_for_vintage("2025-26") + + +def test_outputs_coerce_and_freeze() -> None: + outputs = UKFirmRuleOutputs( + firm_id=np.array([1, 2], dtype=np.int32), + vat_liability_if_registered=[1.5, -2.0], + provenance={"rules": "test"}, + ) + assert outputs.firm_id.dtype == np.int64 + assert outputs.vat_liability_if_registered.dtype == np.float64 + with pytest.raises(TypeError): + outputs.provenance["rules"] = "other" # type: ignore[index] + + +@pytest.mark.parametrize( + ("ids", "values", "match"), + [ + ([1.0, 2.0], [1.0, 2.0], "integer"), + ([1, 2], [1.0], "shape"), + ([1, 2], [1.0, np.nan], "finite"), + ], +) +def test_outputs_refuse_malformed_arrays(ids, values, match) -> None: + with pytest.raises(ValueError, match=match): + UKFirmRuleOutputs( + firm_id=np.asarray(ids), + vat_liability_if_registered=np.asarray(values), + provenance={}, + ) + + +def test_align_reorders_by_firm_id() -> None: + outputs = _outputs([3, 1, 2], [30.0, 10.0, 20.0]) + np.testing.assert_array_equal( + align_rule_outputs(outputs, np.array([1, 2, 3])), [10.0, 20.0, 30.0] + ) + np.testing.assert_array_equal( + align_rule_outputs(outputs, pd.Series([2, 3, 1])), [20.0, 30.0, 10.0] + ) + + +@pytest.mark.parametrize( + ("produced", "requested", "match"), + [ + ([1, 2], [1, 2, 3], "miss 1 firm ids"), + ([1, 2, 3], [1, 2], "unrequested"), + ([1, 1, 2], [1, 2], "outputs repeat"), + ([1, 2], [1, 1, 2], "requested firm ids repeat"), + ], +) +def test_align_refuses_mismatched_ids(produced, requested, match) -> None: + outputs = _outputs(produced, np.zeros(len(produced))) + with pytest.raises(ValueError, match=match): + align_rule_outputs(outputs, np.asarray(requested)) + + +def test_legacy_adapter_converts_units_and_registers_every_firm() -> None: + evaluator = _RecordingEvaluator() + candidates = _candidates() + outputs = LegacyVATEvaluatorRules(evaluator).evaluate(candidates, period=2024) + + (call,) = evaluator.calls + assert call["data_vintage"] == "2024-25" + assert call["vat_registered"].all() + np.testing.assert_allclose(call["turnover_k"], [50.0, 2000.0, 100.0]) + np.testing.assert_allclose(call["input_cost_k"], [10.0, 1500.0, 60.0]) + np.testing.assert_array_equal(outputs.firm_id, [1, 2, 3]) + np.testing.assert_allclose( + outputs.vat_liability_if_registered, [8_000.0, 100_000.0, 8_000.0], rtol=1e-6 + ) + assert outputs.provenance["evaluator"] == "_RecordingEvaluator" + assert outputs.provenance["data_vintage"] == "2024-25" + assert outputs.provenance["period"] == "2024" + + +def test_legacy_adapter_agrees_with_the_tables_input_vat() -> None: + """The legacy double's liability equals output VAT less ``firm_input_vat``.""" + + candidates = _candidates() + outputs = LegacyVATEvaluatorRules(_RecordingEvaluator()).evaluate( + candidates, period=2023 + ) + expected = ( + ASSUMED_INPUT_VAT_RATE * candidates["firm_standard_rated_supplies"] + - candidates["firm_input_vat"] + ).to_numpy() + np.testing.assert_allclose( + align_rule_outputs(outputs, candidates["firm_id"]), expected, rtol=1e-6 + ) + + +def test_legacy_adapter_refuses_an_unknown_period_and_missing_columns() -> None: + rules = LegacyVATEvaluatorRules(_RecordingEvaluator()) + with pytest.raises(ValueError, match="rule period 2026"): + rules.evaluate(_candidates(), period=2026) + with pytest.raises(ValueError, match="firm_input_costs"): + rules.evaluate(_candidates().drop(columns="firm_input_costs"), period=2024) + + +def test_legacy_adapter_refuses_a_wrong_shape() -> None: + class _Short: + def net_liability_k(self, **_kwargs): + return np.zeros(1) + + with pytest.raises(ValueError, match="returned shape"): + LegacyVATEvaluatorRules(_Short()).evaluate(_candidates(), period=2024) + + +def test_data_years_are_recorded_apart_from_the_rule_period() -> None: + years = data_years_for_vintage("2024-25") + assert rule_period_for_vintage("2024-25") == 2024 + assert years["ons_frame_turnover"] == "2023-24" + assert "note 4" in years["ons_frame_turnover_note"] + assert years["hmrc_vat_statistics"] == "2024-25" + assert data_years_for_vintage("2023-24") is None + assert set(UK_FIRM_DATA_YEARS_BY_VINTAGE) == set(UK_FIRM_RULE_PERIOD_BY_VINTAGE) + with pytest.raises(ValueError, match="2025-26"): + data_years_for_vintage("2025-26") + assert "1 January" in UK_FIRM_RULE_PERIOD_NOTE + + +def test_align_refuses_outputs_without_the_vat_output() -> None: + outputs = FirmRuleOutputs( + firm_id=np.array([1, 2]), values={"other": [1.0, 2.0]}, provenance={} + ) + with pytest.raises(ValueError, match="vat_liability_if_registered"): + align_rule_outputs(outputs, np.array([1, 2])) diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_table.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_table.py new file mode 100644 index 0000000000..db016459da --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_table.py @@ -0,0 +1,226 @@ +"""UK firm tables in policyengine-uk names: candidates, export and contract.""" + +from __future__ import annotations + +import numpy as np +import pandas as pd +import pytest + +from microcosm.build.uk_runtime.firm_table import ( + ASSUMED_INPUT_VAT_RATE, + UK_FIRM_CANDIDATE_RULES_COLUMNS, + UK_FIRM_MICROCOSM_COLUMNS, + UK_FIRM_POLICYENGINE_UK_COLUMNS, + UK_FIRM_SIC_SECTIONS, + UK_FIRM_TABLE_COLUMNS, + build_candidate_rules_table, + to_policyengine_uk_firm_table, + uk_firm_sic_sections, + validate_uk_firm_table, +) +from microcosm.build.uk_runtime.occupation_constants import ( + UK_SIC2007_SECTION_DIVISIONS, +) + +#: policyengine-uk ``SICSection`` member names (branch firm-entity-engine, +#: policyengine_uk/variables/firm/firm_sic_section.py), in declaration order. +_POLICYENGINE_UK_SIC_SECTION_MEMBERS = ("UNKNOWN", *"ABCDEFGHIJKLMNOPQRSTU") + + +def _firms() -> pd.DataFrame: + return pd.DataFrame( + { + "firm_id": np.array([4, 2, 1, 3], dtype=np.int64), + "source_firm_id": np.array([4, 2, 1, 3], dtype=np.int64), + "source_firm_key": [ + f"2024-25:experimental_uk_firm:{i}" for i in (4, 2, 1, 3) + ], + "data_vintage": "2024-25", + "sic_code": ["00011", "00047", "00004", "00086"], + "annual_turnover_k": np.array([120.0, 90.0, 0.0, 40.0], dtype=np.float32), + "annual_input_k": np.array([80.0, 30.0, 0.0, 10.0], dtype=np.float32), + "employment": np.array([12, 3, 0, 1]), + "firm_weight": [2.5, 10.0, 0.0, 4.0], + "vat_scope": [True, True, False, False], + "vat_registered": [True, True, False, True], + "in_frame": [True, True, False, True], + "base_weight": [1.0, 2.0, 1.0, 1.0], + "generation_status": "experimental", + } + ) + + +def test_sic_sections_match_policyengine_uk_members() -> None: + assert UK_FIRM_SIC_SECTIONS == _POLICYENGINE_UK_SIC_SECTION_MEMBERS + assert UK_FIRM_SIC_SECTIONS[1:] == tuple(UK_SIC2007_SECTION_DIVISIONS) + + +def test_sic_sections_read_divisions_as_ints_or_padded_strings() -> None: + assert list(uk_firm_sic_sections(["00001", "00011", "00047", "00099"])) == [ + "A", + "C", + "G", + "U", + ] + assert list(uk_firm_sic_sections(np.array([4, 35, 68, 86]))) == [ + "UNKNOWN", + "D", + "L", + "Q", + ] + + +@pytest.mark.parametrize("bad", [["47110"], [100], [-1], ["x"], [11.5]]) +def test_sic_sections_refuse_values_that_are_not_divisions(bad) -> None: + with pytest.raises(ValueError, match="SIC 2007 divisions"): + uk_firm_sic_sections(bad) + + +def test_candidate_table_is_pounds_all_standard_rated_ordered_by_id() -> None: + table = build_candidate_rules_table(_firms()) + assert tuple(table.columns) == UK_FIRM_CANDIDATE_RULES_COLUMNS + assert table["firm_id"].tolist() == [1, 2, 3, 4] + assert table["firm_turnover"].tolist() == [0.0, 90_000.0, 40_000.0, 120_000.0] + assert table["firm_input_costs"].tolist() == [0.0, 30_000.0, 10_000.0, 80_000.0] + assert table["firm_employees"].tolist() == [0, 3, 1, 12] + assert table["firm_sic_section"].tolist() == ["UNKNOWN", "G", "Q", "C"] + pd.testing.assert_series_equal( + table["firm_standard_rated_supplies"], + table["firm_turnover"], + check_names=False, + ) + assert (table["firm_exempt_supplies"] == 0).all() + np.testing.assert_allclose( + table["firm_input_vat"], ASSUMED_INPUT_VAT_RATE * table["firm_input_costs"] + ) + assert ASSUMED_INPUT_VAT_RATE == 0.20 + + +def test_candidate_table_needs_only_the_pre_calibration_columns() -> None: + firms = _firms()[ + ["firm_id", "sic_code", "annual_turnover_k", "annual_input_k", "employment"] + ] + assert len(build_candidate_rules_table(firms)) == 4 + with pytest.raises(ValueError, match="firm_id"): + build_candidate_rules_table(firms.drop(columns="firm_id")) + + +@pytest.mark.parametrize( + ("column", "value", "match"), + [ + ("annual_turnover_k", -1.0, "annual_turnover_k"), + ("annual_input_k", np.nan, "annual_input_k"), + ("employment", 1.5, "whole numbers"), + ("firm_id", 2, "repeats"), + ], +) +def test_candidate_table_refuses_bad_rows(column, value, match) -> None: + firms = _firms() + if column == "employment": + firms[column] = firms[column].astype(float) + firms.loc[0, column] = value + with pytest.raises(ValueError, match=match): + build_candidate_rules_table(firms) + + +def test_export_follows_the_contract() -> None: + table = to_policyengine_uk_firm_table(_firms(), threshold_k=90.0) + assert tuple(table.columns) == UK_FIRM_TABLE_COLUMNS + assert UK_FIRM_TABLE_COLUMNS == ( + *UK_FIRM_POLICYENGINE_UK_COLUMNS, + *UK_FIRM_MICROCOSM_COLUMNS, + ) + for absent in ("firm_region", "firm_legal_form", "firm_paybill"): + assert absent not in table.columns + assert table["firm_id"].tolist() == [1, 2, 3, 4] + assert table["firm_weight"].tolist() == [0.0, 10.0, 4.0, 2.5] + assert table["source_firm_key"].tolist() == [ + f"2024-25:experimental_uk_firm:{i}" for i in (1, 2, 3, 4) + ] + validate_uk_firm_table(table) + + +def test_export_splits_supplies_by_scope_and_flags_voluntary_registration() -> None: + table = to_policyengine_uk_firm_table(_firms(), threshold_k=90.0).set_index( + "firm_id" + ) + assert table["firm_standard_rated_supplies"].tolist() == [ + 0.0, + 90_000.0, + 0.0, + 120_000.0, + ] + assert table["firm_exempt_supplies"].tolist() == [0.0, 0.0, 40_000.0, 0.0] + # Firm 2 sits on the threshold, which registration must exceed; firm 3 is + # registered below it; firm 4 is above it. + assert table["firm_vat_voluntarily_registered"].tolist() == [ + False, + True, + True, + False, + ] + np.testing.assert_allclose( + table["firm_input_vat"], [0.0, 6_000.0, 2_000.0, 16_000.0] + ) + + +def test_export_threshold_moves_the_voluntary_flag() -> None: + table = to_policyengine_uk_firm_table(_firms(), threshold_k=85.0) + assert table["firm_vat_voluntarily_registered"].tolist() == [ + False, + False, + True, + False, + ] + with pytest.raises(ValueError, match="threshold_k"): + to_policyengine_uk_firm_table(_firms(), threshold_k=0.0) + + +def test_export_needs_the_calibrated_columns() -> None: + with pytest.raises(ValueError, match="vat_scope"): + to_policyengine_uk_firm_table( + _firms().drop(columns="vat_scope"), threshold_k=90.0 + ) + + +def test_export_refuses_flags_that_are_not_boolean() -> None: + firms = _firms().astype({"vat_registered": object}) + firms.loc[0, "vat_registered"] = np.nan + with pytest.raises(ValueError, match="vat_registered must be boolean"): + to_policyengine_uk_firm_table(firms, threshold_k=90.0) + + +@pytest.mark.parametrize( + ("mutate", "match"), + [ + (lambda t: t.assign(firm_weight=[-1.0, 1.0, 1.0, 1.0]), "firm_weight"), + (lambda t: t.assign(firm_weight=[np.inf, 1.0, 1.0, 1.0]), "firm_weight"), + (lambda t: t.assign(firm_id=[1, 1, 3, 4]), "repeats"), + (lambda t: t.assign(firm_id=[2, 1, 3, 4]), "ordered"), + (lambda t: t.drop(columns="base_weight"), "columns"), + (lambda t: t[list(reversed(t.columns))], "columns"), + (lambda t: t.assign(firm_sic_section=["Z", "A", "A", "A"]), "SICSection"), + (lambda t: t.assign(vat_scope=[1, 1, 0, 1]), "boolean"), + (lambda t: t.assign(firm_exempt_supplies=[0.0, 1.0, 40_000.0, 0.0]), "add up"), + ( + lambda t: t.assign( + firm_vat_voluntarily_registered=[True, True, True, False] + ), + "needs vat_registered", + ), + ], +) +def test_validation_refuses_tables_outside_the_contract(mutate, match) -> None: + table = to_policyengine_uk_firm_table(_firms(), threshold_k=90.0) + with pytest.raises(ValueError, match=match): + validate_uk_firm_table(mutate(table)) + + +def test_validation_refuses_supplies_against_scope() -> None: + table = to_policyengine_uk_firm_table(_firms(), threshold_k=90.0) + swapped = table.assign( + firm_standard_rated_supplies=table["firm_exempt_supplies"], + firm_exempt_supplies=table["firm_standard_rated_supplies"], + ) + with pytest.raises(ValueError, match="vat_scope"): + validate_uk_firm_table(swapped) diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_tax_receipts.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_tax_receipts.py new file mode 100644 index 0000000000..677de934ab --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_tax_receipts.py @@ -0,0 +1,209 @@ +"""The UK firm tax receipts comparison tool and its official-figure fixture.""" + +from __future__ import annotations + +import csv +import importlib.util +import json +import re +import sys +from functools import cache + +import pytest + +from test_support.paths import paths_for + +PATHS = paths_for("microcosm-build") +TOOL = PATHS.repository / "tools" / "compare_uk_firm_taxes_to_receipts.py" +RECEIPTS = PATHS.tests / "fixtures" / "uk" / "firm_tax_receipts_2024_25.csv" +TAXES = ( + "firm_vat", + "firm_employer_ni", + "apprenticeship_levy", + "corporation_tax", + "bank_surcharge", + "firm_business_rates", +) + + +@cache +def _load_tool(): + name = "compare_uk_firm_taxes_to_receipts" + if name in sys.modules: + return sys.modules[name] + spec = importlib.util.spec_from_file_location(name, TOOL) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +def _receipt(tool, tax: str, value: float | None): + return tool.Receipt( + name=tax, + official_value=value, + period="2024-25", + measure="test measure", + source_publisher="p", + source_title="t", + edition="e", + url="https://example.org", + accessed="2026-11-22", + note="", + ) + + +def test_fixture_has_required_columns_and_sourced_figures() -> None: + tool = _load_tool() + with RECEIPTS.open(newline="", encoding="utf-8") as handle: + reader = csv.DictReader(handle) + assert set(tool.REQUIRED_COLUMNS) <= set(reader.fieldnames or ()) + rows = list(reader) + assert [row["tax"] for row in rows] == list(TAXES) + for row in rows: + assert row["period"] == "2024-25" + if row["official_value_gbp"].strip(): + assert float(row["official_value_gbp"]) > 0 + for column in ("url", "edition", "accessed", "measure", "source_title"): + assert row[column].strip(), (row["tax"], column) + assert row["url"].startswith("https://") + else: + # A blank figure must say why it was not fetched. + assert row["note"].strip(), row["tax"] + # The reader enforces the same rule. + assert set(tool.read_receipts(RECEIPTS)) == set(TAXES) + + +def test_every_provenance_source_has_a_content_hash() -> None: + provenance = json.loads( + RECEIPTS.with_name(RECEIPTS.name + ".provenance.json").read_text( + encoding="utf-8" + ) + ) + sources = provenance["sources"] + assert sources + covered = set() + for name, source in sources.items(): + digest = source.get("sha256", "") + assert re.fullmatch(r"[0-9a-f]{64}", digest), name + assert source["url"].startswith("https://assets.publishing.service.gov.uk/") + covered.update(source["taxes"]) + assert covered == set(TAXES) + + +def test_reader_refuses_a_figure_without_a_source(tmp_path) -> None: + tool = _load_tool() + path = tmp_path / "receipts.csv" + header = ",".join(tool.REQUIRED_COLUMNS) + path.write_text(f"{header}\nfirm_vat,1,2024-25,m,p,t,,https://x,2026-11-22,\n") + with pytest.raises(ValueError, match="edition"): + tool.read_receipts(path) + + +def test_gap_arithmetic() -> None: + tool = _load_tool() + row = tool.compare_tax( + "corporation_tax", + model_total=80e9, + populated=True, + receipt=_receipt(tool, "corporation_tax", 100e9), + ) + assert row.model == "£80.00bn" + assert row.official == "£100.00bn" + assert row.gap == "-£20.00bn (-20.0%)" + assert row.ratio == "0.800" + + +def test_blank_official_figure_prints_message() -> None: + tool = _load_tool() + row = tool.compare_tax( + "firm_employer_ni", + model_total=50e9, + populated=True, + receipt=_receipt(tool, "firm_employer_ni", None), + ) + assert row.official == tool.NO_OFFICIAL_FIGURE == "no official figure fetched" + assert row.gap == row.ratio == "no official figure fetched" + assert "%" not in row.gap + + +def test_unpopulated_input_prints_no_gap_or_percentage() -> None: + tool = _load_tool() + row = tool.compare_tax( + "firm_business_rates", + model_total=0.0, + populated=False, + receipt=_receipt(tool, "firm_business_rates", 26e9), + ) + assert row.model == row.gap == row.ratio == "input not populated" + assert all("%" not in cell for cell in (row.model, row.gap, row.ratio, row.reason)) + + +def test_report_end_to_end(tmp_path) -> None: + tool = _load_tool() + taxes = { + "period": 2024, + "totals": {tax: 1e9 for tax in TAXES}, + "inputs_populated": {tax: tax == "firm_vat" for tax in TAXES}, + "note": "synthetic", + } + path = tmp_path / "taxes.json" + path.write_text(json.dumps(taxes)) + out = tmp_path / "report.md" + assert tool.main(["--taxes-json", str(path), "--out", str(out)]) == 0 + report = out.read_text(encoding="utf-8") + lines = {line.split(" | ")[0].strip("| "): line for line in report.splitlines()} + assert "in-sample" in lines["firm_vat"].lower() + assert "does not validate the model" in lines["firm_vat"] + for tax in TAXES[1:]: + assert "input not populated" in lines[tax] + assert "%" not in lines[tax] + assert "England only" in lines["firm_business_rates"] + for tax in ("firm_employer_ni", "apprenticeship_levy"): + assert "not a validation" in lines[tax] + assert "does not set it" in lines[tax] + assert "public sector" not in lines[tax] + assert "firm_paybill_below_secondary_threshold" in lines["firm_employer_ni"] + assert "firm_is_single_director_company" in lines["firm_employer_ni"] + assert "cash" in lines["firm_vat"] + # Only the populated VAT row carries a percentage gap. + assert "%" in lines["firm_vat"] + + +def test_tax_missing_from_the_model_json_is_not_called_unpopulated() -> None: + tool = _load_tool() + receipts = tool.read_receipts(RECEIPTS) + rows = { + row.name: row + for row in tool.build_rows({"period": 2024, "totals": {}}, receipts) + } + assert rows["bank_surcharge"].model == "no model total supplied" + assert "%" not in rows["bank_surcharge"].gap + + +def test_paybill_caveat_survives_without_receipt_or_caveat_entry() -> None: + tool = _load_tool() + for tax in tool.PAYBILL_TAXES: + row = tool.compare_tax(tax, model_total=1e9, populated=True, receipt=None) + assert row.reason.startswith(tool.PAYBILL_ASSUMED_CAVEAT) + + +@pytest.mark.parametrize( + "inputs_populated", [None, {}, {"firm_employer_ni": "yes"}, {"firm_vat": True}] +) +def test_total_without_explicit_populated_flag_is_refused(inputs_populated) -> None: + tool = _load_tool() + receipts = tool.read_receipts(RECEIPTS) + taxes = {"period": 2024, "totals": {"firm_employer_ni": 0.0}} + if inputs_populated is not None: + taxes["inputs_populated"] = inputs_populated + with pytest.raises(ValueError, match="firm_employer_ni"): + tool.compare(taxes, receipts) + + +def test_period_mismatch_is_refused() -> None: + tool = _load_tool() + receipts = tool.read_receipts(RECEIPTS) + with pytest.raises(ValueError, match="2025-26"): + tool.compare({"period": 2025, "totals": {}}, receipts) diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_universe.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_universe.py new file mode 100644 index 0000000000..e3f793f15f --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_universe.py @@ -0,0 +1,155 @@ +from __future__ import annotations + +import numpy as np +import pytest + +from microcosm.build.uk_runtime.firm_universe import ( + N_HMRC_BANDS, + assign_vat_scope_and_registration, + registration_propensity, + stratified_thin, +) + +THIN = { + "window_lo_k": 15.0, + "window_hi_k": 150.0, + "window_fraction": 0.3, + "tail_fraction": 0.05, + "cell_floor": 5, + "seed": 42, +} + + +def _draw(n: int = 4000, seed: int = 0) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + rng = np.random.default_rng(seed) + turnover = rng.lognormal(mean=4.0, sigma=1.5, size=n) + sic = rng.choice( + np.array([1, 41, 47, 62, 86]), size=n, p=[0.05, 0.2, 0.4, 0.3, 0.05] + ) + bands = np.digitize( + turnover, [0.0, 90.0, 150.0, 300.0, 500.0, 1000.0, 10000.0], right=True + ) + return turnover, sic, bands.astype(np.int64) + + +def _strata(turnover, sic, bands) -> np.ndarray: + window = (turnover >= THIN["window_lo_k"]) & (turnover <= THIN["window_hi_k"]) + keys = np.stack([sic, bands, window.astype(np.int64)], axis=1) + return np.unique(keys, axis=0, return_inverse=True)[1].reshape(-1) + + +def test_full_fractions_return_every_row_at_unit_weight() -> None: + turnover, sic, bands = _draw() + params = {**THIN, "window_fraction": 1.0, "tail_fraction": 1.0} + keep, base = stratified_thin(turnover, sic, bands, **params) + np.testing.assert_array_equal(keep, np.arange(len(turnover))) + np.testing.assert_array_equal(base, np.ones(len(turnover))) + + +def test_base_weighted_stratum_totals_reproduce_the_draw() -> None: + turnover, sic, bands = _draw() + keep, base = stratified_thin(turnover, sic, bands, **THIN) + assert len(keep) < len(turnover) / 2 + strata = _strata(turnover, sic, bands) + original = np.bincount(strata) + weighted = np.bincount(strata[keep], weights=base, minlength=len(original)) + np.testing.assert_allclose(weighted, original, rtol=1e-12, atol=0.0) + assert np.round(weighted).astype(np.int64).tolist() == original.tolist() + + +def test_cell_floor_keeps_small_strata() -> None: + turnover, sic, bands = _draw() + keep, _ = stratified_thin(turnover, sic, bands, **THIN) + strata = _strata(turnover, sic, bands) + sizes = np.bincount(strata) + kept = np.bincount(strata[keep], minlength=len(sizes)) + assert np.all(kept >= np.minimum(THIN["cell_floor"], sizes)) + # Three-row stratum, zero tail fraction: the floor keeps all three. + params = {**THIN, "window_fraction": 0.0, "tail_fraction": 0.0} + keep, base = stratified_thin( + np.array([500.0, 600.0, 700.0]), + np.array([1, 1, 1]), + np.array([5, 5, 5]), + **params, + ) + np.testing.assert_array_equal(keep, [0, 1, 2]) + np.testing.assert_array_equal(base, [1.0, 1.0, 1.0]) + + +def test_floor_top_up_takes_lowest_draws_and_weights_by_ratio() -> None: + n = 12 + turnover = np.full(n, 500.0) + params = {**THIN, "tail_fraction": 0.0, "cell_floor": 4, "seed": 7} + keep, base = stratified_thin( + turnover, np.ones(n, dtype=np.int64), np.full(n, 4), **params + ) + u = np.random.default_rng(8).random(n) + np.testing.assert_array_equal(keep, np.sort(np.argsort(u)[:4])) + np.testing.assert_array_equal(base, np.full(4, 3.0)) + + +def test_thinning_is_deterministic_by_seed() -> None: + turnover, sic, bands = _draw() + first = stratified_thin(turnover, sic, bands, **THIN) + second = stratified_thin(turnover, sic, bands, **THIN) + other = stratified_thin(turnover, sic, bands, **{**THIN, "seed": 43}) + np.testing.assert_array_equal(first[0], second[0]) + np.testing.assert_array_equal(first[1], second[1]) + assert not np.array_equal(first[0], other[0]) + + +def test_propensity_is_hmrc_count_over_frame_mass() -> None: + bands = np.array([0, 1, 1, 1, 2, 2, 3, 0, 7]) + frame = np.array([True, True, True, True, True, True, True, False, True]) + base = np.array([1.0, 10.0, 20.0, 30.0, 4.0, 6.0, 2.0, 1.0, 5.0]) + hmrc = np.array([99.0, 15.0, 5.0, 8.0, 0.0, 0.0, 0.0, 7.0]) + propensity = registration_propensity(bands, frame, base, hmrc) + expected = [0.0, 0.25, 0.25, 0.25, 0.5, 0.5, 1.0, 1.0, 1.0] + np.testing.assert_allclose(propensity, expected, rtol=0, atol=1e-12) + + +def test_propensity_leaves_empty_bands_at_zero() -> None: + bands = np.array([4, 4]) + propensity = registration_propensity( + bands, np.array([True, True]), np.zeros(2), np.full(N_HMRC_BANDS, 5.0) + ) + np.testing.assert_array_equal(propensity, [0.0, 0.0]) + + +def test_registration_totals_match_hmrc_within_one_weight() -> None: + rng = np.random.default_rng(3) + n = 5000 + bands = rng.integers(0, N_HMRC_BANDS, size=n) + frame = rng.random(n) > 0.05 + weights = rng.uniform(1.0, 20.0, size=n) + mass = np.bincount(bands[frame], weights=weights[frame], minlength=N_HMRC_BANDS) + hmrc = np.round(mass * np.array([0.0, 0.4, 0.9, 0.8, 0.7, 0.6, 0.5, 0.95])) + scope, registered = assign_vat_scope_and_registration( + bands, frame, weights, hmrc, seed=42 + ) + assert scope[~frame].all() and registered[~frame].all() + assert not (scope | registered)[frame & (bands == 0)].any() + assert scope[frame & (bands == 1)].all() + assert np.array_equal(scope[frame & (bands >= 2)], registered[frame & (bands >= 2)]) + assert not (registered & ~scope).any() + for band in range(1, N_HMRC_BANDS): + rows = frame & (bands == band) + total = weights[rows & registered].sum() + assert hmrc[band] <= total < hmrc[band] + weights[rows].max() + again = assign_vat_scope_and_registration(bands, frame, weights, hmrc, seed=42) + np.testing.assert_array_equal(again[1], registered) + + +def test_registration_selects_whole_band_when_target_exceeds_mass() -> None: + bands = np.array([2, 2, 2]) + hmrc = np.zeros(N_HMRC_BANDS) + hmrc[2] = 100.0 + scope, registered = assign_vat_scope_and_registration( + bands, np.ones(3, dtype=bool), np.ones(3), hmrc, seed=1 + ) + assert scope.all() and registered.all() + + +def test_hmrc_bands_must_align_with_band_index() -> None: + with pytest.raises(ValueError, match="hmrc_bands"): + registration_propensity(np.array([1]), np.array([True]), np.ones(1), np.ones(7)) diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_2024_25/.provenance.json b/packages/microcosm-build/tests/fixtures/uk/firm_2024_25/.provenance.json new file mode 100644 index 0000000000..9ee24fa112 --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_2024_25/.provenance.json @@ -0,0 +1,49 @@ +{ + "source_repository": "PolicyEngine/firm-microsim-paper", + "paper_commit": "aa1ce07045255b0ddc9942894810259be86b747f", + "paper_commit_short": "aa1ce07", + "vintage": "2024-25", + "description": "Processed ONS (2025) and HMRC (2024-25) firm tables copied verbatim from the paper repository for the paper-parity test.", + "files": { + "hmrc_vat_liability_by_sector.csv": { + "sha256": "abe6a8330eedd19fe893c38901cacc336dad28d5b63ceeaad937e4e4a41afed3", + "source_path": "data/processed/2024-25/hmrc_vat_liability_by_sector.csv", + "bytes": 4856 + }, + "hmrc_vat_liability_by_turnover_band.csv": { + "sha256": "a650a867c30c0d7d08b1c979f93275261cbfe641c6c859f0aa21833122767f76", + "source_path": "data/processed/2024-25/hmrc_vat_liability_by_turnover_band.csv", + "bytes": 218 + }, + "hmrc_vat_population_by_sector.csv": { + "sha256": "b5c47c47cae0f4162f905235b5d8999fddc9bdc7d5d8435ad0474a7b005374d7", + "source_path": "data/processed/2024-25/hmrc_vat_population_by_sector.csv", + "bytes": 4920 + }, + "hmrc_vat_population_by_turnover_band.csv": { + "sha256": "b4350c5ba51a8cbfc5114878144606aedf9c2ef07fa2dac56d52743b2604cb61", + "source_path": "data/processed/2024-25/hmrc_vat_population_by_turnover_band.csv", + "bytes": 245 + }, + "ons_firm_employment.csv": { + "sha256": "423caf9003eecec7ec83810006c418d0a220bac71b155ac4489eb5562945ec3c", + "source_path": "data/processed/2024-25/ons_firm_employment.csv", + "bytes": 7171 + }, + "ons_firm_turnover.csv": { + "sha256": "a3908d4e88395e8e35633ee7dd315b4edec56b72a1d119f7e062a31db73c5814", + "source_path": "data/processed/2024-25/ons_firm_turnover.csv", + "bytes": 7452 + } + }, + "reference": { + "file": "paper_reference_2024_25.json", + "sha256": "cfac6e8258a2f2ed4a3774fd1ccc91bd77d6bcc8356e0328c14fce29d80024fa", + "commands": { + "full": "python tools/uk_firm_paper_parity.py paper-extract --mode full (paper generate(write=False))", + "fast": "python tools/uk_firm_paper_parity.py paper-extract --mode fast (paper generate(write=False))", + "ci": "python tools/uk_firm_paper_parity.py paper-extract --mode ci (paper generate(write=False))" + }, + "note": "Assembled by hand from one `tools/uk_firm_paper_parity.py paper-extract` run per mode (full, fast, ci) in the paper environment at aa1ce07, plus targets derived from the fixture tables and the published headline in results/calibration_accuracy.txt." + } +} diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_2024_25/hmrc_vat_liability_by_sector.csv b/packages/microcosm-build/tests/fixtures/uk/firm_2024_25/hmrc_vat_liability_by_sector.csv new file mode 100644 index 0000000000..36288907e1 --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_2024_25/hmrc_vat_liability_by_sector.csv @@ -0,0 +1,89 @@ +Trade_Sector,Trade_Sub_Sector,2024-25 +00001,"Crop and animal production, hunting and related service activities",-2300 +00002,Forestry and logging,110 +00003,Fishing and aquaculture,-100 +00005,Mining of coal and lignite,0 +00006,Extraction of crude petroleum and natural gas,-460 +00007,Mining of metal ores,-10 +00008,Other mining and quarrying,290 +00009,Mining and support service activities,-320 +00010,Manufacture of food products,-2060 +00011,Manufacture of beverages,1840 +00012,Manufacture of tobacco products,1700 +00013,Manufacture of textiles,440 +00014,Manufacture of wearing apparel,290 +00015,Manufacture of leather and related products,130 +00016,"Manufacture of wood and of products of wood and cork, except furniture; manufacture of articles of straw and plaiting materials",620 +00017,Manufacture of paper and paper products,870 +00018,Printing and reproduction of recorded media,500 +00019,Manufacture of coke and refined petroleum products,7550 +00020,Manufacture of chemicals and chemical products,1570 +00021,Manufacture of basic pharmaceutical products and pharmaceutical preparations,600 +00022,Manufacture of rubber and rubber products,1470 +00023,Manufacture of other non-metallic mineral products,1150 +00024,Manufacture of basic metals,-780 +00025,"Manufacture of fabricated metal products, except machinery and equipment",1990 +00026,"Manufacture of computer, electronic and optical products",1130 +00027,Manufacture of electrical equipment,840 +00028,Manufacture of machinery and equipment n.e.c,1320 +00029,"Manufacture of motor vehicles, trailers and semi-trailers",1390 +00030,Manufacture of other transport equipment,-1250 +00031,Manufacture of furniture,720 +00032,Other manufacturing,1200 +00033,Repair and installation of machinery and equipment,1050 +00035,"Electricity, gas, steam and air conditioning supply",3940 +00036,"Water collection, treatment and supply",-2490 +00037,Sewerage,-10 +00038,"Waste collection, treatment and disposal activities; materials recovery",600 +00039,Remediation activities and other waste management services,350 +00041,Construction of buildings,2630 +00042,Civil engineering,4490 +00043,Specialised construction activities,5000 +00045,Wholesale and retail trade and repair of motor vehicles and motorcycles,14000 +00046,"Wholesale trade, except of motor vehicles and motorcycles",25900 +00047,Retail trade except of motor vehicles and motorcycles,16800 +00049,Land transport and transport via pipelines,-310 +00050,Water transport,-90 +00051,Air transport,-1340 +00052,Warehousing and support activities for transportation,1190 +00053,Postal and courier activities,1250 +00055,Accommodation,2860 +00056,Food and beverage service activities,8800 +00058,Publishing activities,800 +00059,"Motion picture, video and television programme production, sound recording and music publishing activities",470 +00060,Programming and broadcasting activities,-20 +00061,Telecommunications,4250 +00062,"Computer programming, consultancy and related activities",15700 +00063,Information service activities,430 +00064,"Financial service activities, except insurance and pension funding",90 +00065,"Insurance, reinsurance and pension funding, except compulsory social security",290 +00066,Activities auxiliary to financial services and insurance activities,1060 +00068,Real estate activities,4840 +00069,Legal and accounting services,9590 +00070,Activities of head offices; management consultancy services,9410 +00071,Architectural and engineering activities; technical testing and analysis,5080 +00072,Scientific research and development,30 +00073,Advertising and market research,2010 +00074,"Other professional, scientific and technical activities",1710 +00075,Veterinary activities,810 +00077,Rental and leasing activities,1690 +00078,Employment activities,5870 +00079,"Travel agency, tour operator and other reservation service and related activities",170 +00080,Security and investigation activities,1160 +00081,Services to buildings and landscape activities,2500 +00082,Office administrative and support activities,6250 +00084,Public administration and defence; compulsory social security,-11600 +00085,Education,960 +00086,Human health activities,40 +00087,Residential care activities,320 +00088,Social work activities without accommodation,420 +00090,"Creative, arts and entertainment activities",1750 +00091,"Libraries, archives, museums and other cultural activities",30 +00092,Gambling and betting activities,70 +00093,Sports activities and amusement and recreation activities,1910 +00094,Activities of membership organisations,590 +00095,Repair of computers and personal and household goods,300 +00096,Other personal service activities,3210 +00097,Activities of households as employers of domestic personnel,0 +00098,Undifferentiated goods- and services-producing activities of private households for own use,0 +00099,Activities of extraterritorial organisations and bodies,40 diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_2024_25/hmrc_vat_liability_by_turnover_band.csv b/packages/microcosm-build/tests/fixtures/uk/firm_2024_25/hmrc_vat_liability_by_turnover_band.csv new file mode 100644 index 0000000000..f0298fecb0 --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_2024_25/hmrc_vat_liability_by_turnover_band.csv @@ -0,0 +1,2 @@ +Financial_Year,Negative_or_Zero,£1_to_Threshold,£Threshold_to_£150k,£150k_to_£300k,£300k_to_£500k,£500k_to_£1m,£1m_to_£10m,Greater_than_£10m,Total +2024-25,-2910,-300,2420,4830,3970,6840,29520,132800,177170 diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_2024_25/hmrc_vat_population_by_sector.csv b/packages/microcosm-build/tests/fixtures/uk/firm_2024_25/hmrc_vat_population_by_sector.csv new file mode 100644 index 0000000000..1c193717c4 --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_2024_25/hmrc_vat_population_by_sector.csv @@ -0,0 +1,89 @@ +Trade_Sector,Trade_Sub_Sector,2024-25 +00001,"Crop and animal production, hunting and related service activities",128900 +00002,Forestry and logging,5480 +00003,Fishing and aquaculture,4540 +00005,Mining of coal and lignite,30 +00006,Extraction of crude petroleum and natural gas,220 +00007,Mining of metal ores,90 +00008,Other mining and quarrying,790 +00009,Mining and support service activities,1470 +00010,Manufacture of food products,10200 +00011,Manufacture of beverages,3230 +00012,Manufacture of tobacco products,60 +00013,Manufacture of textiles,4170 +00014,Manufacture of wearing apparel,3450 +00015,Manufacture of leather and related products,820 +00016,"Manufacture of wood and of products of wood and cork, except furniture; manufacture of articles of straw and plaiting materials",8240 +00017,Manufacture of paper and paper products,1610 +00018,Printing and reproduction of recorded media,9630 +00019,Manufacture of coke and refined petroleum products,180 +00020,Manufacture of chemicals and chemical products,3680 +00021,Manufacture of basic pharmaceutical products and pharmaceutical preparations,840 +00022,Manufacture of rubber and rubber products,4730 +00023,Manufacture of other non-metallic mineral products,4420 +00024,Manufacture of basic metals,2350 +00025,"Manufacture of fabricated metal products, except machinery and equipment",19300 +00026,"Manufacture of computer, electronic and optical products",5900 +00027,Manufacture of electrical equipment,2900 +00028,Manufacture of machinery and equipment n.e.c,7710 +00029,"Manufacture of motor vehicles, trailers and semi-trailers",3100 +00030,Manufacture of other transport equipment,2040 +00031,Manufacture of furniture,5720 +00032,Other manufacturing,10400 +00033,Repair and installation of machinery and equipment,13500 +00035,"Electricity, gas, steam and air conditioning supply",7530 +00036,"Water collection, treatment and supply",650 +00037,Sewerage,920 +00038,"Waste collection, treatment and disposal activities; materials recovery",5240 +00039,Remediation activities and other waste management services,1260 +00041,Construction of buildings,117600 +00042,Civil engineering,22300 +00043,Specialised construction activities,209800 +00045,Wholesale and retail trade and repair of motor vehicles and motorcycles,71400 +00046,"Wholesale trade, except of motor vehicles and motorcycles",104400 +00047,Retail trade except of motor vehicles and motorcycles,335600 +00049,Land transport and transport via pipelines,50400 +00050,Water transport,1530 +00051,Air transport,1170 +00052,Warehousing and support activities for transportation,12300 +00053,Postal and courier activities,33200 +00055,Accommodation,18000 +00056,Food and beverage service activities,110400 +00058,Publishing activities,11900 +00059,"Motion picture, video and television programme production, sound recording and music publishing activities",30900 +00060,Programming and broadcasting activities,1470 +00061,Telecommunications,6900 +00062,"Computer programming, consultancy and related activities",118800 +00063,Information service activities,7040 +00064,"Financial service activities, except insurance and pension funding",14000 +00065,"Insurance, reinsurance and pension funding, except compulsory social security",2970 +00066,Activities auxiliary to financial services and insurance activities,6240 +00068,Real estate activities,112800 +00069,Legal and accounting services,58700 +00070,Activities of head offices; management consultancy services,136100 +00071,Architectural and engineering activities; technical testing and analysis,63900 +00072,Scientific research and development,5800 +00073,Advertising and market research,20000 +00074,"Other professional, scientific and technical activities",48100 +00075,Veterinary activities,3680 +00077,Rental and leasing activities,18200 +00078,Employment activities,25500 +00079,"Travel agency, tour operator and other reservation service and related activities",7320 +00080,Security and investigation activities,8690 +00081,Services to buildings and landscape activities,37700 +00082,Office administrative and support activities,48700 +00084,Public administration and defence; compulsory social security,3760 +00085,Education,23600 +00086,Human health activities,10300 +00087,Residential care activities,1820 +00088,Social work activities without accommodation,3160 +00090,"Creative, arts and entertainment activities",28800 +00091,"Libraries, archives, museums and other cultural activities",1120 +00092,Gambling and betting activities,360 +00093,Sports activities and amusement and recreation activities,33400 +00094,Activities of membership organisations,8610 +00095,Repair of computers and personal and household goods,4860 +00096,Other personal service activities,41300 +00097,Activities of households as employers of domestic personnel,140 +00098,Undifferentiated goods- and services-producing activities of private households for own use,130 +00099,Activities of extraterritorial organisations and bodies,60 diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_2024_25/hmrc_vat_population_by_turnover_band.csv b/packages/microcosm-build/tests/fixtures/uk/firm_2024_25/hmrc_vat_population_by_turnover_band.csv new file mode 100644 index 0000000000..25f1d8f893 --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_2024_25/hmrc_vat_population_by_turnover_band.csv @@ -0,0 +1,2 @@ +Financial_Year,Negative_or_Zero,£1_to_Threshold,£Threshold_to_£150k,£150k_to_£300k,£300k_to_£500k,£500k_to_£1m,£1m_to_£10m,Greater_than_£10m,Unknown,Total +2024-25,211400,683700,280400,338600,186700,184100,240500,45800,159300,2330500 diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_2024_25/ons_firm_employment.csv b/packages/microcosm-build/tests/fixtures/uk/firm_2024_25/ons_firm_employment.csv new file mode 100644 index 0000000000..27f56336c8 --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_2024_25/ons_firm_employment.csv @@ -0,0 +1,90 @@ +SIC Code,Description,0-4,5-9,10-19,20-49,50-99,100-249,250+,Total +01,Crop and animal production; hunting and related service activities,116525,10565,3155,1090,360,150,100,131945 +02,Forestry and logging,4235,470,175,65,15,5,5,4970 +03,Fishing and aquaculture,3535,255,105,15,5,5,5,3925 +05,Mining of coal and lignite,5,0,0,0,0,0,0,5 +06,Extraction of crude petroleum and natural gas,70,10,5,5,0,10,15,115 +07,Mining of metal ores,0,0,0,0,0,0,0,0 +08,Other mining and quarrying,375,120,85,55,25,15,10,685 +09,Mining support service activities,250,35,15,25,15,5,10,355 +10,Manufacture of food products,5070,1480,1095,870,370,300,250,9435 +11,Manufacture of beverages,1780,385,260,145,65,25,35,2695 +12,Manufacture of tobacco products,0,5,0,0,0,0,0,5 +13,Manufacture of textiles,2725,690,405,275,110,45,20,4270 +14,Manufacture of wearing apparel,2655,455,215,130,45,10,5,3515 +15,Manufacture of leather and related products,370,75,40,30,15,5,5,540 +16,Manufacture of wood and of products of wood and cork; except furniture; manufacture of articles of straw and plaiting materials,7795,1280,655,415,145,50,25,10365 +17,Manufacture of paper and paper products,645,160,165,180,105,70,30,1355 +18,Printing and reproduction of recorded media,6905,1415,615,385,120,70,30,9540 +19,Manufacture of coke and refined petroleum products,30,10,0,15,10,5,10,80 +20,Manufacture of chemicals and chemical products,1885,415,275,295,190,125,70,3255 +21,Manufacture of basic pharmaceutical products and pharmaceutical preparations,370,60,30,45,35,35,55,630 +22,Manufacture of rubber and plastic products,2250,935,665,630,355,225,90,5150 +23,Manufacture of other non-metallic mineral products,2270,705,450,325,125,80,40,3995 +24,Manufacture of basic metals,1035,230,180,200,85,60,35,1825 +25,Manufacture of fabricated metal products; except machinery and equipment,12895,3535,2490,1810,635,255,80,21700 +26,Manufacture of computer; electronic and optical products,3165,740,465,480,225,145,60,5280 +27,Manufacture of electrical equipment,1565,430,345,355,175,90,50,3010 +28,Manufacture of machinery and equipment n.e.c.,3920,1065,720,705,345,195,100,7050 +29,Manufacture of motor vehicles; trailers and semi-trailers,2400,420,235,190,135,105,70,3555 +30,Manufacture of other transport equipment,1320,215,95,80,65,50,65,1890 +31,Manufacture of furniture,4370,995,585,380,160,85,25,6600 +32,Other manufacturing,6855,1430,595,320,140,80,35,9455 +33,Repair and installation of machinery and equipment,12045,1505,800,380,125,80,60,14995 +35,Electricity; gas; steam and air conditioning supply,5845,550,275,90,35,25,40,6860 +36,Water collection; treatment and supply,45,15,5,15,10,5,20,115 +37,Sewerage,850,200,100,90,20,5,0,1265 +38,Waste collection; treatment and disposal activities; materials recovery,3915,905,620,445,165,90,70,6210 +39,Remediation activities and other waste management services,845,180,110,70,20,0,0,1225 +41,Construction of buildings,109235,8145,3165,1180,400,185,100,122410 +42,Civil engineering,18095,2200,1015,640,235,120,80,22385 +43,Specialised construction activities,206260,20775,8120,3605,820,330,125,240035 +45,Wholesale and retail trade and repair of motor vehicles and motorcycles,63025,13245,4155,1530,445,255,210,82865 +46,Wholesale trade; except of motor vehicles and motorcycles,68380,14600,9140,5375,1865,855,510,100725 +47,Retail trade; except of motor vehicles and motorcycles,159695,32800,12910,5295,1265,480,455,212900 +49,Land transport and transport via pipelines,50575,5240,2910,1755,620,265,185,61550 +50,Water transport,1130,170,75,55,20,10,10,1470 +51,Air transport,810,50,30,25,15,20,15,965 +52,Warehousing and support activities for transportation,12595,1775,1015,805,400,240,190,17020 +53,Postal and courier activities,31630,1095,365,170,60,30,25,33375 +55,Accommodation,12500,2935,2240,2150,960,445,210,21440 +56,Food and beverage service activities,81960,37485,23170,10110,1515,520,490,155250 +58,Publishing activities,9940,1160,675,440,155,75,55,12500 +59,Motion picture; video and television programme production; sound recording and music publishing activities,31550,1380,750,380,165,85,40,34350 +60,Programming and broadcasting activities,1930,130,45,35,10,10,20,2180 +61,Telecommunications,6240,595,360,330,140,105,75,7845 +62,Computer programming; consultancy and related activities,105525,7495,4525,3090,1170,510,320,122635 +63,Information service activities,6510,740,495,250,100,50,45,8190 +64,Financial service activities; except insurance and pension funding,19900,1225,465,340,175,105,160,22370 +65,Insurance; reinsurance and pension funding; except compulsory social security,5010,135,85,60,20,25,55,5390 +66,Activities auxiliary to financial services and insurance activities,21885,3435,1630,820,465,260,230,28725 +68,Real estate activities,104180,11490,4580,1245,350,220,245,122310 +69,Legal and accounting activities,57555,8080,4210,2190,755,425,305,73520 +70,Activities of head offices; management consultancy activities,142800,8175,4385,2245,805,340,195,158945 +71,Architectural and engineering activities; technical testing and analysis,66970,6200,3265,1935,685,310,185,79550 +72,Scientific research and development,3875,730,530,395,165,95,105,5895 +73,Advertising and market research,19870,1820,1110,755,310,130,105,24100 +74,Other professional; scientific and technical activities,65785,4775,2135,885,235,70,30,73915 +75,Veterinary activities,2060,610,565,275,75,30,15,3630 +77,Rental and leasing activities,13720,2270,1250,660,235,115,70,18320 +78,Employment activities,21820,3270,2665,1790,1115,660,445,31765 +79,Travel agency; tour operator and other reservation service and related activities,7400,975,425,265,120,70,35,9290 +80,Security and investigation activities,8235,1070,720,505,240,160,90,11020 +81,Services to buildings and landscape activities,40950,6675,3300,1550,610,325,315,53725 +82,Office administrative; office support and other business support activities,83560,7815,3850,1590,615,290,230,97950 +84,Public administration and defence; compulsory social security,6535,555,210,135,45,55,430,7965 +85,Education,30860,6175,4350,2795,1640,1575,1705,49100 +86,Human health activities,47900,7860,6480,4210,1285,415,500,68650 +87,Residential care activities,3295,1295,1970,2920,1605,700,435,12220 +88,Social work activities without accommodation,15180,7615,6850,4200,1520,640,350,36355 +90,Creative; arts and entertainment activities,30325,1650,740,340,135,85,30,33305 +91,Libraries; archives; museums and other cultural activities,930,310,230,215,130,90,55,1960 +92,Gambling and betting activities,380,175,120,90,35,30,30,860 +93,Sports activities and amusement and recreation activities,27415,5435,3450,2300,610,290,235,39735 +94,Activities of membership organisations,15295,4025,1770,900,290,145,100,22525 +95,Repair of computers and personal and household goods,8260,805,285,150,40,15,15,9570 +96,Other personal service activities,66855,12040,3775,1010,215,70,35,84000 +97,Activities of households as employers of domestic personnel,0,0,0,0,0,0,0,0 +98,Undifferentiated goods- and services-producing activities of private households for own use,0,0,0,0,0,0,0,0 +99,Activities of extraterritorial organisations and bodies,0,0,0,0,0,0,0,0 +,Total,2137205,300645,156590,84595,29335,14835,11415,2734620 diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_2024_25/ons_firm_turnover.csv b/packages/microcosm-build/tests/fixtures/uk/firm_2024_25/ons_firm_turnover.csv new file mode 100644 index 0000000000..4fd13a0a90 --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_2024_25/ons_firm_turnover.csv @@ -0,0 +1,90 @@ +SIC Code,Description,0-49,50-99,100-249,250-499,500-999,1000-4999,5000+,Total +01,Crop and animal production; hunting and related service activities,41615,24105,29875,16355,10675,8245,1085,131955 +02,Forestry and logging,850,1065,1705,680,345,270,50,4965 +03,Fishing and aquaculture,1180,750,1015,490,215,220,50,3920 +05,Mining of coal and lignite,0,0,0,0,0,0,0,0 +06,Extraction of crude petroleum and natural gas,20,10,20,10,5,10,40,115 +07,Mining of metal ores,0,0,0,0,0,0,0,0 +08,Other mining and quarrying,85,55,125,85,75,150,110,685 +09,Mining support service activities,55,25,120,25,15,40,75,355 +10,Manufacture of food products,1475,1215,2180,1220,890,1235,1220,9435 +11,Manufacture of beverages,630,405,640,315,270,275,155,2690 +12,Manufacture of tobacco products,0,0,0,0,0,0,0,0 +13,Manufacture of textiles,470,810,1250,600,415,510,215,4270 +14,Manufacture of wearing apparel,550,675,1310,405,260,240,75,3515 +15,Manufacture of leather and related products,105,120,130,60,40,60,30,545 +16,Manufacture of wood and of products of wood and cork; except furniture; manufacture of articles of straw and plaiting materials,715,2490,3515,1305,950,1030,360,10365 +17,Manufacture of paper and paper products,160,170,220,115,115,260,315,1355 +18,Printing and reproduction of recorded media,1620,1980,2685,1255,805,900,290,9535 +19,Manufacture of coke and refined petroleum products,5,0,10,5,5,5,45,75 +20,Manufacture of chemicals and chemical products,480,450,600,330,275,500,625,3260 +21,Manufacture of basic pharmaceutical products and pharmaceutical preparations,90,65,125,75,45,80,150,630 +22,Manufacture of rubber and plastic products,395,425,865,650,675,1260,880,5150 +23,Manufacture of other non-metallic mineral products,265,540,1010,560,475,725,415,3990 +24,Manufacture of basic metals,160,230,425,205,190,325,285,1820 +25,Manufacture of fabricated metal products; except machinery and equipment,1880,3970,4940,2955,2535,3915,1505,21700 +26,Manufacture of computer; electronic and optical products,845,675,1190,560,480,890,640,5280 +27,Manufacture of electrical equipment,355,305,595,330,305,640,480,3010 +28,Manufacture of machinery and equipment n.e.c.,780,775,1505,845,760,1395,995,7055 +29,Manufacture of motor vehicles; trailers and semi-trailers,315,480,1140,485,300,445,385,3550 +30,Manufacture of other transport equipment,270,425,455,215,130,195,205,1895 +31,Manufacture of furniture,485,1150,2050,960,765,870,315,6595 +32,Other manufacturing,1520,1845,2650,1240,925,920,360,9460 +33,Repair and installation of machinery and equipment,1495,3650,4790,1895,1280,1425,465,15000 +35,Electricity; gas; steam and air conditioning supply,2015,615,1260,820,720,965,460,6855 +36,Water collection; treatment and supply,10,5,10,10,10,25,40,110 +37,Sewerage,95,205,340,220,175,170,55,1260 +38,Waste collection; treatment and disposal activities; materials recovery,490,610,1615,960,720,1130,690,6215 +39,Remediation activities and other waste management services,120,185,310,165,155,235,70,1240 +41,Construction of buildings,15220,13910,27845,29020,20730,12540,3140,122405 +42,Civil engineering,2240,2990,7795,3265,2205,2605,1285,22385 +43,Specialised construction activities,16145,53410,92715,35415,19975,18240,4135,240035 +45,Wholesale and retail trade and repair of motor vehicles and motorcycles,5635,12715,26180,16065,9815,9265,3190,82865 +46,Wholesale trade; except of motor vehicles and motorcycles,12430,9890,18865,14190,12825,20465,12055,100720 +47,Retail trade; except of motor vehicles and motorcycles,20890,28235,65610,42860,28430,22340,4535,212900 +49,Land transport and transport via pipelines,9220,14180,21460,6170,4185,4800,1530,61545 +50,Water transport,400,235,300,135,110,160,140,1480 +51,Air transport,165,75,110,270,130,105,115,970 +52,Warehousing and support activities for transportation,2025,3290,3625,1845,2080,2575,1575,17015 +53,Postal and courier activities,19705,6480,4305,1290,715,680,200,33375 +55,Accommodation,1950,3180,6520,3040,2390,3250,1115,21445 +56,Food and beverage service activities,9870,26495,63775,30000,15630,8195,1280,155245 +58,Publishing activities,2660,2450,3630,1505,855,980,420,12500 +59,Motion picture; video and television programme production; sound recording and music publishing activities,5970,9015,12450,2890,1460,1760,800,34345 +60,Programming and broadcasting activities,330,485,825,240,120,105,70,2175 +61,Telecommunications,1110,1065,1900,1430,870,925,550,7850 +62,Computer programming; consultancy and related activities,20255,32990,44450,9100,5625,7045,3170,122635 +63,Information service activities,1450,2380,2150,725,580,600,305,8190 +64,Financial service activities; except insurance and pension funding,12700,1050,3135,2365,1095,1065,965,22375 +65,Insurance; reinsurance and pension funding; except compulsory social security,4515,25,125,185,140,190,210,5390 +66,Activities auxiliary to financial services and insurance activities,5950,1095,10520,4060,2820,2625,1655,28725 +68,Real estate activities,25260,29645,35000,15550,8450,6530,1875,122310 +69,Legal and accounting activities,9300,15735,26315,10070,5595,4980,1530,73525 +70,Activities of head offices; management consultancy activities,26200,27730,67425,18780,8715,7500,2605,158955 +71,Architectural and engineering activities; technical testing and analysis,8765,21490,29510,8060,4575,5180,1960,79540 +72,Scientific research and development,1470,905,1445,620,425,595,430,5890 +73,Advertising and market research,3305,3690,9300,3055,1770,2060,930,24110 +74,Other professional; scientific and technical activities,9535,18980,31535,6620,3510,3000,740,73920 +75,Veterinary activities,285,780,815,400,510,740,105,3635 +77,Rental and leasing activities,3025,2605,4200,2820,2100,2565,1005,18320 +78,Employment activities,3385,4210,9300,4535,3325,4855,2155,31765 +79,Travel agency; tour operator and other reservation service and related activities,1555,930,2015,1870,1165,1170,580,9285 +80,Security and investigation activities,965,1775,4365,1470,955,1155,330,11015 +81,Services to buildings and landscape activities,7300,10965,21375,7380,3290,2715,695,53720 +82,Office administrative; office support and other business support activities,9780,12010,33365,20965,10715,9030,2085,97950 +84,Public administration and defence; compulsory social security,300,4960,1325,545,225,185,415,7955 +85,Education,4325,12145,13335,6640,4770,4930,2950,49095 +86,Human health activities,1780,25625,18630,8240,6070,7070,1240,68655 +87,Residential care activities,1285,1170,1280,1420,1755,4215,1105,12230 +88,Social work activities without accommodation,1740,6055,8970,7470,6125,5190,810,36360 +90,Creative; arts and entertainment activities,5725,6700,11720,4385,2400,1950,425,33305 +91,Libraries; archives; museums and other cultural activities,260,290,500,270,235,270,130,1955 +92,Gambling and betting activities,55,100,200,160,120,140,95,870 +93,Sports activities and amusement and recreation activities,9000,5650,12905,5360,3385,2770,655,39725 +94,Activities of membership organisations,4670,4340,6820,3335,1680,1335,350,22530 +95,Repair of computers and personal and household goods,940,1795,4875,1005,445,395,120,9575 +96,Other personal service activities,14640,28825,28215,6560,3130,2195,430,83995 +97,Activities of households as employers of domestic personnel,0,0,0,0,0,0,0,0 +98,Undifferentiated goods- and services-producing activities of private households for own use,0,0,0,0,0,0,0,0 +99,Activities of extraterritorial organisations and bodies,0,0,0,0,0,0,0,0 +,Total,387285,525225,873705,390055,244225,232795,81325,2734615 diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_2024_25/paper_reference_2024_25.json b/packages/microcosm-build/tests/fixtures/uk/firm_2024_25/paper_reference_2024_25.json new file mode 100644 index 0000000000..07f609f723 --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_2024_25/paper_reference_2024_25.json @@ -0,0 +1,796 @@ +{ + "description": "Golden numbers from local runs of the firm-microsim-paper generator, generate(vintage='2024-25', write=False), seed 42, captured by tools/uk_firm_paper_parity.py paper-extract. 'full' is the full synthetic census (paper release mode); 'fast' is the paper fast preset (window 0.30, tails 0.05); 'ci' is the thinning used by the Microcosm CI parity test (window 0.05, tails 0.01, paper's 1000 epochs). Net VAT uses the paper formula 0.20 x (turnover - inputs), GBP millions; counts are weighted firms.", + "paper_repository": "PolicyEngine/firm-microsim-paper", + "paper_commit": "aa1ce07045255b0ddc9942894810259be86b747f", + "vintage": "2024-25", + "vat_threshold_k": 90.0, + "seed": 42, + "paper_published_headline": { + "source": "results/calibration_accuracy.txt at aa1ce07, vintage 2024-25 section", + "rows": 2946015, + "weighted_frame_population": 2731034, + "registered_traders": 2170760, + "accuracy": { + "hmrc_bands": 1.0, + "ons_population": 0.999, + "employment": 0.999, + "sector": 0.925, + "vat_liability_band": 0.981, + "overall": 0.981, + "vat_liability_sector_diagnostic": 0.442, + "vat_liability_below_threshold_diagnostic": 0.0 + }, + "effective_sample_size": 180070 + }, + "targets": { + "employment_bands": { + "0-4": 2137205.0, + "10-19": 156590.0, + "100-249": 14835.0, + "20-49": 84595.0, + "250+": 11415.0, + "5-9": 300645.0, + "50-99": 29335.0 + }, + "hmrc_bands": { + "Greater_than_£10m": 45800.0, + "Negative_or_Zero": 211400.0, + "£150k_to_£300k": 338600.0, + "£1_to_Threshold": 683700.0, + "£1m_to_£10m": 240500.0, + "£300k_to_£500k": 186700.0, + "£500k_to_£1m": 184100.0, + "£Threshold_to_£150k": 280400.0 + }, + "ons_draw_rows": 2734615, + "ons_draw_rows_by_sic": { + "1": 131955, + "10": 9435, + "11": 2690, + "12": 0, + "13": 4270, + "14": 3515, + "15": 545, + "16": 10365, + "17": 1355, + "18": 9535, + "19": 75, + "2": 4965, + "20": 3260, + "21": 630, + "22": 5150, + "23": 3990, + "24": 1820, + "25": 21700, + "26": 5280, + "27": 3010, + "28": 7055, + "29": 3550, + "3": 3920, + "30": 1895, + "31": 6595, + "32": 9460, + "33": 15000, + "35": 6855, + "36": 110, + "37": 1260, + "38": 6215, + "39": 1240, + "41": 122405, + "42": 22385, + "43": 240035, + "45": 82865, + "46": 100720, + "47": 212900, + "49": 61545, + "5": 0, + "50": 1480, + "51": 970, + "52": 17015, + "53": 33375, + "55": 21445, + "56": 155245, + "58": 12500, + "59": 34345, + "6": 115, + "60": 2175, + "61": 7850, + "62": 122635, + "63": 8190, + "64": 22375, + "65": 5390, + "66": 28725, + "68": 122310, + "69": 73525, + "7": 0, + "70": 158955, + "71": 79540, + "72": 5890, + "73": 24110, + "74": 73920, + "75": 3635, + "77": 18320, + "78": 31765, + "79": 9285, + "8": 685, + "80": 11015, + "81": 53720, + "82": 97950, + "84": 7955, + "85": 49095, + "86": 68655, + "87": 12230, + "88": 36360, + "9": 355, + "90": 33305, + "91": 1955, + "92": 870, + "93": 39725, + "94": 22530, + "95": 9575, + "96": 83995, + "97": 0, + "98": 0, + "99": 0 + }, + "ons_total": 2734615, + "pre_thinning_rows": 2946015, + "sector_registered_scaled": { + "1": 120103.02845641845, + "10": 9503.885882509452, + "11": 3009.5638627946596, + "12": 55.90521107358501, + "13": 3885.4121696141583, + "14": 3214.549636731138, + "15": 764.0378846723285, + "16": 7677.648987439008, + "17": 1500.1231638078643, + "18": 8972.786377310395, + "19": 167.71563322075502, + "2": 5106.009278054097, + "20": 3428.8529458465473, + "21": 782.6729550301901, + "22": 4407.1941396342845, + "23": 4118.350549087429, + "24": 2189.620767048746, + "25": 17982.84289533651, + "26": 5497.345755569192, + "27": 2702.0852018899423, + "28": 7183.819622955673, + "29": 2888.4359054685588, + "3": 4230.160971234599, + "30": 1900.7771765018904, + "31": 5329.630122348438, + "32": 9690.236586088067, + "33": 12578.672491556626, + "35": 7016.103989734918, + "36": 605.6397866305042, + "37": 857.2132364616368, + "38": 4882.388433759757, + "39": 1174.009432545285, + "41": 109574.21370422661, + "42": 20778.10344901576, + "43": 195481.8880539689, + "45": 66527.20117756617, + "46": 97275.06726803792, + "47": 312696.4806049188, + "49": 46960.37730181141, + "5": 27.952605536792504, + "50": 1425.5828823764177, + "51": 1090.1516159349076, + "52": 11460.568270084927, + "53": 30934.21679405037, + "55": 16771.5633220755, + "56": 102865.58837539642, + "58": 11087.866862927693, + "59": 28791.18370289628, + "6": 204.98577393647835, + "60": 1369.6776713028328, + "61": 6429.099273462276, + "62": 110692.31792569831, + "63": 6559.544765967307, + "64": 13044.549250503169, + "65": 2767.307948142458, + "66": 5814.141951652841, + "68": 105101.79681833982, + "69": 54693.931500324, + "7": 83.85781661037751, + "70": 126811.65378524867, + "71": 59539.04979336803, + "72": 5404.1704037798845, + "73": 18635.07035786167, + "74": 44817.34421065731, + "75": 3428.8529458465473, + "77": 16957.914025654118, + "78": 23759.71470627363, + "79": 6820.435750977371, + "8": 736.085279135536, + "80": 8096.938070490895, + "81": 35127.107624569246, + "82": 45376.396321393164, + "84": 3503.393227277994, + "85": 21989.38302227677, + "86": 9597.06123429876, + "87": 1695.791402565412, + "88": 2944.341116542144, + "9": 1369.6776713028328, + "90": 26834.501315320806, + "91": 1043.5639400402536, + "92": 335.43126644151005, + "93": 31120.56749762899, + "94": 8022.397789059449, + "95": 4528.322096960385, + "96": 38481.42028898435, + "97": 130.4454925050317, + "98": 121.12795732610086, + "99": 55.90521107358501 + }, + "sector_scale": 0.9317535178930835, + "vat_liability_bands_m": { + "Greater_than_£10m": 132800.0, + "£150k_to_£300k": 4830.0, + "£1_to_Threshold": -300.0, + "£1m_to_£10m": 29520.0, + "£300k_to_£500k": 3970.0, + "£500k_to_£1m": 6840.0, + "£Threshold_to_£150k": 2420.0 + } + }, + "runs": { + "full": { + "metadata": { + "command": "python tools/uk_firm_paper_parity.py paper-extract --mode full (paper generate(write=False))", + "mode": "full", + "n_iterations": 1000, + "paper_commit": "aa1ce07045255b0ddc9942894810259be86b747f", + "paper_package_version": "1.0.0", + "runtime_seconds": 46.6, + "sample_tail_fraction": 1.0, + "sample_window_fraction": 1.0, + "seed": 42, + "vat_threshold_k": 90.0, + "vintage": "2024-25" + }, + "summary": { + "accuracy_paper_report": { + "employment": 0.9992796020673834, + "hmrc_bands": 0.9997201439731548, + "ons_population": 0.9986906749213326, + "overall": 0.9808146121550967, + "sector": 0.9249665671950983, + "vat_liability_band": 0.9814160726185147, + "vat_liability_below_threshold_diagnostic": 0.0, + "vat_liability_sector_diagnostic": 0.44164980771030726 + }, + "accuracy_recomputed": { + "employment": 0.9992796048899785, + "hmrc_bands": 0.9997201515517684, + "ons_population": 0.9986906694385108, + "sector": 0.924966568899712, + "vat_liability_band": 0.981416084608603 + }, + "base_weighted_frame_by_band": { + "Greater_than_£10m": 56745.0, + "Negative_or_Zero": 0.0, + "£150k_to_£300k": 660275.0, + "£1_to_Threshold": 807289.0, + "£1m_to_£10m": 257375.0, + "£300k_to_£500k": 312029.0, + "£500k_to_£1m": 244225.0, + "£Threshold_to_£150k": 396677.0 + }, + "employment_band_frame": { + "0-4": 2133365.0900074914, + "10-19": 156637.464300178, + "100-249": 14838.186019144952, + "20-49": 84662.56577096134, + "250+": 11410.530124753714, + "5-9": 300750.8634629026, + "50-99": 29369.78532116115 + }, + "frame_mass_80_100k": 211319.2237438038, + "hmrc_band_frame": { + "Greater_than_£10m": 56915.13736882806, + "Negative_or_Zero": 0.0, + "£150k_to_£300k": 660727.4202410579, + "£1_to_Threshold": 801559.2276893631, + "£1m_to_£10m": 257943.28568785638, + "£300k_to_£500k": 312570.47510578483, + "£500k_to_£1m": 244137.74237342924, + "£Threshold_to_£150k": 397181.1965402737 + }, + "hmrc_band_registered": { + "Greater_than_£10m": 45800.221564002335, + "Negative_or_Zero": 210944.29118078947, + "£150k_to_£300k": 338600.60811205953, + "£1_to_Threshold": 683700.3797336593, + "£1m_to_£10m": 240500.11716318876, + "£300k_to_£500k": 186713.39923953265, + "£500k_to_£1m": 184100.11112336814, + "£Threshold_to_£150k": 280400.8603019938 + }, + "net_vat_by_band_m": { + "Greater_than_£10m": 132752.69021068668, + "Negative_or_Zero": 0.0, + "£150k_to_£300k": 4984.489439303038, + "£1_to_Threshold": 2598.167296055077, + "£1m_to_£10m": 30232.605164427692, + "£300k_to_£500k": 4099.530396439564, + "£500k_to_£1m": 6986.117275950915, + "£Threshold_to_£150k": 2422.4989711261196 + }, + "pre_thinning_frame_rows": 2734615, + "pre_thinning_rows": 2946015, + "propensities": { + "Greater_than_£10m": 0.8071195483207703, + "£150k_to_£300k": 0.5128166079521179, + "£1_to_Threshold": 0.8469086289405823, + "£1m_to_£10m": 0.934434175491333, + "£300k_to_£500k": 0.5983418226242065, + "£500k_to_£1m": 0.7538130879402161, + "£Threshold_to_£150k": 0.7068723440170288 + }, + "registered_traders": 2170759.988418594, + "rows_appended": 211400, + "rows_in_frame": 2734615, + "rows_total": 2946015, + "sector_registered": { + "1": 119964.19608929753, + "10": 9436.825319096446, + "11": 3022.8109404444695, + "13": 3895.240386426449, + "14": 3254.6370813548565, + "15": 788.9549102783203, + "16": 7672.805732131004, + "17": 1482.1220144331455, + "18": 8979.993964150548, + "19": 167.83168244361877, + "2": 5098.877266466618, + "20": 3464.14872212708, + "21": 794.6988846063614, + "22": 4445.629419028759, + "23": 4059.8553403019905, + "24": 2223.720085501671, + "25": 17855.35631969571, + "26": 5474.011161670089, + "27": 2694.547403395176, + "28": 7215.657854616642, + "29": 2875.21913908422, + "3": 4286.891459822655, + "30": 1894.9566146731377, + "31": 5347.037402048707, + "32": 9707.879584893584, + "33": 12524.32934486866, + "35": 7046.882777303457, + "36": 608.0567445755005, + "37": 845.9034920036793, + "38": 4806.333894923329, + "39": 1166.8951407670975, + "41": 109352.3524210453, + "42": 20946.35791133344, + "43": 194447.46947316825, + "45": 66259.9855902642, + "46": 97656.53514458239, + "47": 311891.2404678017, + "49": 46983.4171487391, + "50": 1423.95148524642, + "51": 1092.6758102178574, + "52": 11445.308537572622, + "53": 31139.06213864684, + "55": 16763.953387007117, + "56": 103558.78631170094, + "58": 11022.832382321358, + "59": 28673.051029518247, + "6": 212.84801697731018, + "60": 1339.091271609068, + "61": 6328.096106991172, + "62": 110576.78934559226, + "63": 6556.516412422061, + "64": 13220.959186971188, + "65": 2800.529340803623, + "66": 5840.813328370452, + "68": 105265.8801612556, + "69": 54842.42610022426, + "70": 124953.63828089833, + "71": 59645.11747227609, + "72": 5446.323996081948, + "73": 18697.653755262494, + "74": 45352.271729812026, + "75": 3424.1196042746305, + "77": 16922.58749845624, + "78": 23595.00766901672, + "79": 6860.799726977944, + "8": 735.3637803792953, + "80": 8070.256181806326, + "81": 35486.94546067715, + "82": 46219.182913184166, + "84": 3535.118015408516, + "85": 22153.028830468655, + "86": 9752.18581239134, + "87": 1714.5700703710318, + "88": 2967.248104430735, + "9": 1351.8572874069214, + "90": 26813.784154072404, + "91": 1037.8420244455338, + "92": 340.9195793867111, + "93": 31158.13204434514, + "94": 8082.883896738291, + "95": 4525.196432977915, + "96": 39174.71941423416 + }, + "weighted_all_rows": 2941978.7761873826, + "weighted_frame_population": 2731034.485006593 + } + }, + "fast": { + "metadata": { + "command": "python tools/uk_firm_paper_parity.py paper-extract --mode fast (paper generate(write=False))", + "mode": "fast", + "n_iterations": 1000, + "paper_commit": "aa1ce07045255b0ddc9942894810259be86b747f", + "paper_package_version": "1.0.0", + "runtime_seconds": 11.9, + "sample_tail_fraction": 0.05, + "sample_window_fraction": 0.3, + "seed": 42, + "vat_threshold_k": 90.0, + "vintage": "2024-25" + }, + "summary": { + "accuracy_paper_report": { + "employment": 0.9976360609447799, + "hmrc_bands": 0.9997428315309259, + "ons_population": 0.999218171479349, + "overall": 0.9795266335681276, + "sector": 0.9152128475849305, + "vat_liability_band": 0.9858232563006523, + "vat_liability_below_threshold_diagnostic": 0.0, + "vat_liability_sector_diagnostic": 0.4436226173973186 + }, + "accuracy_recomputed": { + "employment": 0.9976360634547458, + "hmrc_bands": 0.9997428419805229, + "ons_population": 0.9992181334639304, + "sector": 0.9152128515229836, + "vat_liability_band": 0.9858232706704313 + }, + "base_weighted_frame_by_band": { + "Greater_than_£10m": 56744.99994182587, + "Negative_or_Zero": 0.0, + "£150k_to_£300k": 660275.0012540817, + "£1_to_Threshold": 807288.995570898, + "£1m_to_£10m": 257375.00056648254, + "£300k_to_£500k": 312029.0003080368, + "£500k_to_£1m": 244225.0004348755, + "£Threshold_to_£150k": 396677.0003185272 + }, + "employment_band_frame": { + "0-4": 2135103.870435357, + "10-19": 156177.5261270404, + "100-249": 14883.566627502441, + "20-49": 84954.1526632607, + "250+": 11451.898360222578, + "5-9": 300633.68555665016, + "50-99": 29272.196272432804 + }, + "frame_mass_80_100k": 205283.36257779598, + "hmrc_band_frame": { + "Greater_than_£10m": 56906.68916261196, + "Negative_or_Zero": 0.0, + "£150k_to_£300k": 657928.5314950943, + "£1_to_Threshold": 807930.0717658699, + "£1m_to_£10m": 258858.10786354542, + "£300k_to_£500k": 312067.9549868107, + "£500k_to_£1m": 243101.61582517624, + "£Threshold_to_£150k": 395683.9249433577 + }, + "hmrc_band_registered": { + "Greater_than_£10m": 45808.15448731184, + "Negative_or_Zero": 211633.57290643454, + "£150k_to_£300k": 338629.92483377457, + "£1_to_Threshold": 683699.9876717627, + "£1m_to_£10m": 240504.19484233856, + "£300k_to_£500k": 186753.26077628136, + "£500k_to_£1m": 184168.50583565235, + "£Threshold_to_£150k": 280403.11453953385 + }, + "net_vat_by_band_m": { + "Greater_than_£10m": 130936.20723211003, + "Negative_or_Zero": 0.0, + "£150k_to_£300k": 4934.834878643151, + "£1_to_Threshold": 2439.9758355685144, + "£1m_to_£10m": 29422.11792988876, + "£300k_to_£500k": 4062.6440952736552, + "£500k_to_£1m": 6911.409846018982, + "£Threshold_to_£150k": 2449.594130785122 + }, + "pre_thinning_frame_rows": 2734615, + "pre_thinning_rows": 2946015, + "propensities": { + "Greater_than_£10m": 0.8071194291114807, + "£150k_to_£300k": 0.5128166079521179, + "£1_to_Threshold": 0.8469086289405823, + "£1m_to_£10m": 0.934434175491333, + "£300k_to_£500k": 0.5983417630195618, + "£500k_to_£1m": 0.7538130879402161, + "£Threshold_to_£150k": 0.7068724036216736 + }, + "registered_traders": 2171600.71589309, + "rows_appended": 211400, + "rows_in_frame": 414883, + "rows_total": 626283, + "sector_registered": { + "1": 119411.96590214968, + "10": 9723.357931256294, + "11": 2994.826173901558, + "13": 3786.053709626198, + "14": 3233.7380092144012, + "15": 734.7865303754807, + "16": 7652.158621251583, + "17": 1519.7203660011292, + "18": 9509.211738526821, + "19": 175.49820816516876, + "2": 5253.909435689449, + "20": 3544.1249166727066, + "21": 767.7686570882797, + "22": 4529.836126327515, + "23": 4223.077932536602, + "24": 2107.4992567300797, + "25": 17871.303397536278, + "26": 5387.064121127129, + "27": 2711.4367249011993, + "28": 7186.4552174806595, + "29": 3074.279161453247, + "3": 3990.727827012539, + "30": 1797.5810302495956, + "31": 5227.288194298744, + "32": 9269.210405290127, + "33": 12753.418346762657, + "35": 6641.606627821922, + "36": 620.4683179855347, + "37": 858.4745876193047, + "38": 4926.286958515644, + "39": 1172.758105456829, + "41": 110618.18405401707, + "42": 19888.03439593315, + "43": 192838.07758367062, + "45": 65200.90012431145, + "46": 99093.45688939095, + "47": 316093.65796136856, + "49": 46257.35612612963, + "50": 1373.8693815469742, + "51": 1150.910875916481, + "52": 11456.373620152473, + "53": 30396.91821461916, + "55": 16688.60404074192, + "56": 103427.85897046328, + "58": 11217.508732676506, + "59": 29597.021784186363, + "6": 201.0714076757431, + "60": 1318.5502353310585, + "61": 6293.977297842503, + "62": 110944.33502429724, + "63": 6540.093919336796, + "64": 13157.202590823174, + "65": 2782.9401773810387, + "66": 5792.925646543503, + "68": 104237.94009333849, + "69": 55305.35066562891, + "70": 125729.33487743139, + "71": 59475.773442626, + "72": 5542.768952488899, + "73": 18502.439553141594, + "74": 45091.88890969753, + "75": 3487.288051724434, + "77": 16638.87414598465, + "78": 23718.101908624172, + "79": 6774.5889738202095, + "8": 735.3180112838745, + "80": 8179.551505446434, + "81": 34712.183336138725, + "82": 46136.08576589823, + "84": 3568.6851347088814, + "85": 22376.37254714966, + "86": 9816.196328222752, + "87": 1704.976273804903, + "88": 2951.2622604370117, + "9": 1357.3758707046509, + "90": 26640.736464321613, + "91": 1020.6158734560013, + "92": 335.6709485948086, + "93": 30844.134862422943, + "94": 8018.460329592228, + "95": 4606.67216360569, + "96": 39106.34704941511 + }, + "weighted_all_rows": 2944110.4689489007, + "weighted_frame_population": 2732476.896042466 + } + }, + "ci": { + "metadata": { + "command": "python tools/uk_firm_paper_parity.py paper-extract --mode ci (paper generate(write=False))", + "mode": "ci", + "n_iterations": 1000, + "paper_commit": "aa1ce07045255b0ddc9942894810259be86b747f", + "paper_package_version": "1.0.0", + "runtime_seconds": 8.1, + "sample_tail_fraction": 0.01, + "sample_window_fraction": 0.05, + "seed": 42, + "vat_threshold_k": 90.0, + "vintage": "2024-25" + }, + "summary": { + "accuracy_paper_report": { + "employment": 0.9975441165532369, + "hmrc_bands": 0.9975473703127989, + "ons_population": 0.9991196201293417, + "overall": 0.9794400851280528, + "sector": 0.9168777093227329, + "vat_liability_band": 0.9861116093221535, + "vat_liability_below_threshold_diagnostic": 0.0, + "vat_liability_sector_diagnostic": 0.421978015513833 + }, + "accuracy_recomputed": { + "employment": 0.9975440902512792, + "hmrc_bands": 0.9975473570572899, + "ons_population": 0.9991196157396318, + "sector": 0.916877713613306, + "vat_liability_band": 0.986111634134133 + }, + "base_weighted_frame_by_band": { + "Greater_than_£10m": 56745.000014305115, + "Negative_or_Zero": 0.0, + "£150k_to_£300k": 660275.0028057098, + "£1_to_Threshold": 807288.9969472885, + "£1m_to_£10m": 257375.00214004517, + "£300k_to_£500k": 312029.0027551651, + "£500k_to_£1m": 244225.00114440918, + "£Threshold_to_£150k": 396677.0013618469 + }, + "employment_band_frame": { + "0-4": 2139209.119071603, + "10-19": 156390.83732274175, + "100-249": 14848.321364820004, + "20-49": 84817.07354360819, + "250+": 11525.231386780739, + "5-9": 300922.69381320477, + "50-99": 29309.235501408577 + }, + "frame_mass_80_100k": 204658.09104776382, + "hmrc_band_frame": { + "Greater_than_£10m": 56555.826705247164, + "Negative_or_Zero": 0.0, + "£150k_to_£300k": 660597.7991147637, + "£1_to_Threshold": 808812.9786997437, + "£1m_to_£10m": 257790.1677660346, + "£300k_to_£500k": 313010.1510490775, + "£500k_to_£1m": 243656.47523593903, + "£Threshold_to_£150k": 396599.11343336105 + }, + "hmrc_band_registered": { + "Greater_than_£10m": 45910.30438107252, + "Negative_or_Zero": 208275.8249926269, + "£150k_to_£300k": 338664.67499423027, + "£1_to_Threshold": 683711.0054327548, + "£1m_to_£10m": 240678.8206601739, + "£300k_to_£500k": 186879.56739717722, + "£500k_to_£1m": 184192.42455112934, + "£Threshold_to_£150k": 280405.5458892584 + }, + "net_vat_by_band_m": { + "Greater_than_£10m": 131787.9731104, + "Negative_or_Zero": 0.0, + "£150k_to_£300k": 4924.08472312402, + "£1_to_Threshold": 2407.1616228845223, + "£1m_to_£10m": 29655.750737985803, + "£300k_to_£500k": 3926.0286551930867, + "£500k_to_£1m": 6990.308871425455, + "£Threshold_to_£150k": 2464.9654951328844 + }, + "pre_thinning_frame_rows": 2734615, + "pre_thinning_rows": 2946015, + "propensities": { + "Greater_than_£10m": 0.8071195483207703, + "£150k_to_£300k": 0.5128166079521179, + "£1_to_Threshold": 0.8469086289405823, + "£1m_to_£10m": 0.9344340562820435, + "£300k_to_£500k": 0.5983418226242065, + "£500k_to_£1m": 0.7538130879402161, + "£Threshold_to_£150k": 0.7068723440170288 + }, + "registered_traders": 2168718.1682984233, + "rows_appended": 211400, + "rows_in_frame": 83871, + "rows_total": 295271, + "sector_registered": { + "1": 120203.21258962154, + "10": 9589.240319311619, + "11": 2985.464300751686, + "13": 3909.8133143782616, + "14": 3264.3695616722107, + "15": 756.3511484265327, + "16": 7358.059962749481, + "17": 1525.8046830892563, + "18": 9254.508373379707, + "19": 167.1140952706337, + "2": 5168.323067367077, + "20": 3313.179394185543, + "21": 785.6329906582832, + "22": 4295.445243835449, + "23": 4050.3090683817863, + "24": 2214.943606674671, + "25": 17319.013136208057, + "26": 5589.812849283218, + "27": 2726.037388622761, + "28": 6984.42305123806, + "29": 2887.3712748885155, + "3": 4084.3912047743797, + "30": 1883.275464117527, + "31": 5215.75959020853, + "32": 9443.830440580845, + "33": 13031.292599856853, + "35": 7210.7526433467865, + "36": 609.7097059488297, + "37": 836.1121672987938, + "38": 4660.516917288303, + "39": 1210.1906185746193, + "41": 112137.12744563818, + "42": 21406.10072362423, + "43": 192570.05619072914, + "45": 68274.08201527596, + "46": 96418.41523307562, + "47": 311940.22880345583, + "49": 47405.35372340679, + "50": 1403.1352739930153, + "51": 1094.3093605041504, + "52": 11481.722654759884, + "53": 30360.783470392227, + "55": 15801.685593664646, + "56": 102784.14784020185, + "58": 11387.250971257687, + "59": 28510.143669307232, + "6": 204.465358376503, + "60": 1397.1976575255394, + "61": 6553.785117924213, + "62": 110981.50515049696, + "63": 6632.1104036569595, + "64": 12820.3187135458, + "65": 2794.926446020603, + "66": 5907.918754935265, + "68": 105309.73614090681, + "69": 56534.01371490955, + "70": 123961.49080705643, + "71": 59949.72519373894, + "72": 5307.79555785656, + "73": 18589.813453555107, + "74": 45114.108233869076, + "75": 3474.22380143404, + "77": 16912.339772999287, + "78": 24095.92184203863, + "79": 6720.692761957645, + "8": 746.7289262413979, + "80": 7746.74538475275, + "81": 35374.28318786621, + "82": 45725.8654769063, + "84": 3467.5612616539, + "85": 21447.156668543816, + "86": 9602.6638276577, + "87": 1710.7446040809155, + "88": 2989.261797964573, + "9": 1378.169525563717, + "90": 25888.119412899017, + "91": 1066.590378344059, + "92": 332.055389970541, + "93": 31079.9824847579, + "94": 8025.881462991238, + "95": 4476.627516269684, + "96": 38888.83836787939 + }, + "weighted_all_rows": 2945298.3369967937, + "weighted_frame_population": 2737022.512004167 + } + } + } +} diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_tax_receipts_2024_25.csv b/packages/microcosm-build/tests/fixtures/uk/firm_tax_receipts_2024_25.csv new file mode 100644 index 0000000000..20115100e6 --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_tax_receipts_2024_25.csv @@ -0,0 +1,7 @@ +tax,official_value_gbp,period,measure,geography,basis,source_publisher,source_title,edition,url,accessed,note +firm_vat,170994000000,2024-25,VAT cash receipts as recorded by HMRC (UK),UK,cash,HM Revenue and Customs,"HMRC tax receipts and National Insurance contributions for the UK: Table 2 HMRC Receipts (Annually), sheet Receipts_Annually",NS_Table.ods published 0700 20 November 2026 (data to October 2026),https://assets.publishing.service.gov.uk/media/6af706889be17c68c69ca800/NS_Table.ods,2026-11-22,"Column 'Value Added Tax', row '2024 to 2025': 170994 GBP million." +firm_employer_ni,116070000000,2024-25,"PAYE NIC1 (employer) cash receipts, UK: employer Class 1 secondary plus Class 1A, excluding Class 1B",UK,cash,HM Revenue and Customs,"HMRC tax receipts and National Insurance contributions for the UK: Table 2 HMRC Receipts (Annually), sheet Receipts_Annually",NS_Table.ods published 0700 20 November 2026 (data to October 2026),https://assets.publishing.service.gov.uk/media/6af706889be17c68c69ca800/NS_Table.ods,2026-11-22,"Column ""PAYE NIC1 (EMP'er)"", row '2024 to 2025': 116070 GBP million. Table notes: includes class 1 NICs paid by employers and class 1A NICs; excludes NIC1B. Total NICs (all classes) were 172518 GBP million." +apprenticeship_levy,4100000000,2024-25,"Apprenticeship Levy cash receipts, UK",UK,cash,HM Revenue and Customs,"HMRC tax receipts and National Insurance contributions for the UK: Table 2 HMRC Receipts (Annually), sheet Receipts_Annually",NS_Table.ods published 0700 20 November 2026 (data to October 2026),https://assets.publishing.service.gov.uk/media/6af706889be17c68c69ca800/NS_Table.ods,2026-11-22,"Column 'Apprenticeship Levy', row '2024 to 2025': 4100 GBP million." +corporation_tax,88953000000,2024-25,"Onshore Corporation Tax cash receipts, UK, gross of provisional tax credits, excluding Bank Surcharge and Bank Levy",UK,cash,HM Revenue and Customs,"HMRC tax receipts and National Insurance contributions for the UK: Table 2 HMRC Receipts (Annually), sheet Receipts_Annually",NS_Table.ods published 0700 20 November 2026 (data to October 2026),https://assets.publishing.service.gov.uk/media/6af706889be17c68c69ca800/NS_Table.ods,2026-11-22,"Derived: column 'Corporation Tax' 90915 less 'Offshore (included within Corporation Tax)' 1962 = 88953 GBP million, row '2024 to 2025'. Table notes: CT receipts are gross of provisional tax credits; Bank Levy and Bank Surcharge are shown separately (not in CT)." +bank_surcharge,974000000,2024-25,"Bank Surcharge cash receipts, UK",UK,cash,HM Revenue and Customs,"HMRC tax receipts and National Insurance contributions for the UK: Table 2 HMRC Receipts (Annually), sheet Receipts_Annually",NS_Table.ods published 0700 20 November 2026 (data to October 2026),https://assets.publishing.service.gov.uk/media/6af706889be17c68c69ca800/NS_Table.ods,2026-11-22,"Column 'Bank Surcharge', row '2024 to 2025': 974 GBP million. Bank Levy (1320 GBP million) is a separate balance-sheet levy and is not included." +firm_business_rates,26852000000,2024-25,"Gross rates payable in year less total cost of reliefs, England (NNDR3)",England,collectable (accrued to year),"Ministry of Housing, Communities and Local Government","National non-domestic rates collected by local authorities in England 2025 to 2026, Table 1","Published 22 July 2026 (2024-25 column, NNDR3 returns)",https://www.gov.uk/government/statistics/national-non-domestic-rates-collected-by-councils-in-england-2025-to-2026/national-non-domestic-rates-collected-by-local-authorities-in-england-2025-to-2026,2026-11-22,"Row 'Gross Rates Payable in year less total cost of reliefs', column '2024 to 2025': 26852 GBP million (gross 35439 less reliefs 8588; same value in the 27 January 2026 update of the 2024-25 release). Before transitional arrangements and collection adjustments; non-domestic rating income was 26397 GBP million. England only; Scotland, Wales and Northern Ireland are excluded." diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_tax_receipts_2024_25.csv.provenance.json b/packages/microcosm-build/tests/fixtures/uk/firm_tax_receipts_2024_25.csv.provenance.json new file mode 100644 index 0000000000..99cbab0500 --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_tax_receipts_2024_25.csv.provenance.json @@ -0,0 +1,28 @@ +{ + "kind": "uk_firm_tax_receipts_fixture", + "schema_version": 1, + "period": "2024-25", + "accessed": "2026-11-22", + "method": "Figures were read from the downloaded publications on the access date and multiplied from GBP million to GBP; none was filled from memory. corporation_tax is onshore CT, derived as Corporation Tax less its Offshore component.", + "sources": { + "hmrc_receipts": { + "landing_page": "https://www.gov.uk/government/statistics/hmrc-tax-and-nics-receipts-for-the-uk", + "url": "https://assets.publishing.service.gov.uk/media/6af706889be17c68c69ca800/NS_Table.ods", + "edition": "Published 0700 20 November 2026; next update 22 December 2026", + "sheet": "Receipts_Annually (Table 2, cash basis, GBP million), row '2024 to 2025'", + "sha256": "485a2fef86fbdc1339547253e401029e49a9cae781210affdebd1fa87caddc22", + "taxes": ["firm_vat", "firm_employer_ni", "apprenticeship_levy", "corporation_tax", "bank_surcharge"] + }, + "mhclg_nndr3": { + "landing_page": "https://www.gov.uk/government/statistics/national-non-domestic-rates-collected-by-councils-in-england-2025-to-2026", + "release_page": "https://www.gov.uk/government/statistics/national-non-domestic-rates-collected-by-councils-in-england-2025-to-2026/national-non-domestic-rates-collected-by-local-authorities-in-england-2025-to-2026", + "url": "https://assets.publishing.service.gov.uk/media/6a5f99e734dfb74772f96c93/NNDR3_2025-26_Stats_release_Tables_Values_only.ods", + "edition": "Published 22 July 2026 (landing page public-updated-at 2026-07-22T09:30:07+01:00 on the retrieval date, so no later edition); the 2024-25 column agrees with the 2024-25 release updated 27 January 2026", + "retrieved": "2026-11-22", + "size_bytes": 32147, + "sha256": "2337ca62c997c7c1717dd9ec1f4df422752e99194ad2702116062a2eba62f8fe", + "table": "Sheet Table_1, column E '2024 to 2025' (GBP million): E5 'Gross rates payable in year' 35439.3077; E6 'Total cost of reliefs' 8587.7403; E9 'Gross Rates Payable in year less total cost of reliefs' 26851.5674, rounded to 26852 GBP million in the fixture", + "taxes": ["firm_business_rates"] + } + } +} diff --git a/packages/microcosm-build/tests/fixtures/uk/policyengine_uk_firm_inputs.json b/packages/microcosm-build/tests/fixtures/uk/policyengine_uk_firm_inputs.json new file mode 100644 index 0000000000..65cbc4a85d --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/policyengine_uk_firm_inputs.json @@ -0,0 +1,3444 @@ +{ + "collisions": [], + "firm_input_names": [ + "firm_aia_share", + "firm_apprenticeship_levy_allowance_share", + "firm_bank_surcharge_allowance_share", + "firm_capex_main_pool_new", + "firm_capex_main_pool_new_for_leasing", + "firm_capex_main_pool_used", + "firm_capex_special_rate_new", + "firm_capex_special_rate_used", + "firm_capex_structures", + "firm_claims_employment_allowance", + "firm_class_1a_benefits", + "firm_deductions_allowance_share", + "firm_disposal_proceeds_full_expensing", + "firm_disposal_proceeds_main_pool", + "firm_employees", + "firm_employees_above_auto_enrolment_upper_limit", + "firm_employees_below_auto_enrolment_earnings_trigger", + "firm_employees_below_secondary_threshold", + "firm_exempt_distributions", + "firm_exempt_supplies", + "firm_id", + "firm_in_england", + "firm_in_freeport", + "firm_input_costs", + "firm_input_vat", + "firm_is_bank", + "firm_is_charity", + "firm_is_industrial_property", + "firm_is_limited_cost_trader", + "firm_is_live_music_venue", + "firm_is_pub_or_live_music_venue", + "firm_is_public_body", + "firm_is_rhl_property", + "firm_is_single_director_company", + "firm_is_sme", + "firm_is_wales_higher_multiplier_excluded", + "firm_is_wales_retail_property", + "firm_legal_form", + "firm_losses_brought_forward", + "firm_low_paid_hours", + "firm_low_paid_paybill", + "firm_main_pool_brought_forward", + "firm_months_empty", + "firm_n_associated_companies", + "firm_n_properties", + "firm_non_trading_profits", + "firm_paybill", + "firm_paybill_above_auto_enrolment_upper_limit", + "firm_paybill_below_auto_enrolment_earnings_trigger", + "firm_paybill_below_secondary_threshold", + "firm_property_occupied", + "firm_qualifying_rd_expenditure", + "firm_rateable_value", + "firm_rd_staff_paye_nic", + "firm_rdec_paye_nic_cap_supplied", + "firm_reduced_rated_supplies", + "firm_region", + "firm_relevant_paye_nic_liabilities", + "firm_sba_qualifying_cost_brought_forward", + "firm_sic_section", + "firm_small_profits_rate_excluded", + "firm_special_rate_pool_brought_forward", + "firm_standard_rated_supplies", + "firm_taxable_trading_profit", + "firm_total_relevant_expenditure", + "firm_turnover", + "firm_uses_flat_rate_scheme", + "firm_vat_voluntarily_registered", + "firm_weight", + "firm_zero_rated_class_1_earnings", + "firm_zero_rated_supplies" + ], + "firm_variables": { + "apprenticeship_levy": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/apprenticeship_levy/apprenticeship_levy.py", + "has_formula": true, + "name": "apprenticeship_levy", + "unit": "GBP", + "value_type": "float" + }, + "bank_surcharge": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/bank_surcharge/bank_surcharge.py", + "has_formula": true, + "name": "bank_surcharge", + "unit": "GBP", + "value_type": "float" + }, + "corporation_tax": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/corporation_tax/corporation_tax.py", + "has_formula": true, + "name": "corporation_tax", + "unit": "GBP", + "value_type": "float" + }, + "corporation_tax_before_credits": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/corporation_tax/corporation_tax_before_credits.py", + "has_formula": true, + "name": "corporation_tax_before_credits", + "unit": "GBP", + "value_type": "float" + }, + "employment_allowance": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/national_insurance/employment_allowance/employment_allowance.py", + "has_formula": true, + "name": "employment_allowance", + "unit": "GBP", + "value_type": "float" + }, + "employment_allowance_eligible": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/national_insurance/employment_allowance/employment_allowance_eligible.py", + "has_formula": true, + "name": "employment_allowance_eligible", + "unit": null, + "value_type": "bool" + }, + "firm_aia_main_pool_new": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/corporation_tax/capital_allowances/firm_aia_main_pool_new.py", + "has_formula": true, + "name": "firm_aia_main_pool_new", + "unit": "GBP", + "value_type": "float" + }, + "firm_aia_main_pool_used": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/corporation_tax/capital_allowances/firm_aia_main_pool_used.py", + "has_formula": true, + "name": "firm_aia_main_pool_used", + "unit": "GBP", + "value_type": "float" + }, + "firm_aia_share": { + "default_value": 1, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/capital_allowances/firm_aia_share.py", + "has_formula": false, + "name": "firm_aia_share", + "unit": "/1", + "value_type": "float" + }, + "firm_aia_special_rate_new": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/corporation_tax/capital_allowances/firm_aia_special_rate_new.py", + "has_formula": true, + "name": "firm_aia_special_rate_new", + "unit": "GBP", + "value_type": "float" + }, + "firm_aia_special_rate_used": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/corporation_tax/capital_allowances/firm_aia_special_rate_used.py", + "has_formula": true, + "name": "firm_aia_special_rate_used", + "unit": "GBP", + "value_type": "float" + }, + "firm_annual_investment_allowance": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/corporation_tax/capital_allowances/firm_annual_investment_allowance.py", + "has_formula": true, + "name": "firm_annual_investment_allowance", + "unit": "GBP", + "value_type": "float" + }, + "firm_annual_investment_allowance_limit": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/corporation_tax/capital_allowances/firm_annual_investment_allowance_limit.py", + "has_formula": true, + "name": "firm_annual_investment_allowance_limit", + "unit": "GBP", + "value_type": "float" + }, + "firm_apprenticeship_levy_allowance_share": { + "default_value": 1, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/employer_costs/firm_apprenticeship_levy_allowance_share.py", + "has_formula": false, + "name": "firm_apprenticeship_levy_allowance_share", + "unit": "/1", + "value_type": "float" + }, + "firm_augmented_profits": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/corporation_tax/firm_augmented_profits.py", + "has_formula": true, + "name": "firm_augmented_profits", + "unit": "GBP", + "value_type": "float" + }, + "firm_auto_enrolment_employer_contribution": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/dwp/auto_enrolment/firm_auto_enrolment_employer_contribution.py", + "has_formula": true, + "name": "firm_auto_enrolment_employer_contribution", + "unit": "GBP", + "value_type": "float" + }, + "firm_auto_enrolment_qualifying_earnings": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/dwp/auto_enrolment/firm_auto_enrolment_qualifying_earnings.py", + "has_formula": true, + "name": "firm_auto_enrolment_qualifying_earnings", + "unit": "GBP", + "value_type": "float" + }, + "firm_bank_surcharge_allowance_share": { + "default_value": 1, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/corporation_tax/firm_bank_surcharge_allowance_share.py", + "has_formula": false, + "name": "firm_bank_surcharge_allowance_share", + "unit": "/1", + "value_type": "float" + }, + "firm_business_rates": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/business_rates/firm/firm_business_rates.py", + "has_formula": true, + "name": "firm_business_rates", + "unit": "GBP", + "value_type": "float" + }, + "firm_business_rates_multiplier": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/business_rates/firm/firm_business_rates_multiplier.py", + "has_formula": true, + "name": "firm_business_rates_multiplier", + "unit": "/1", + "value_type": "float" + }, + "firm_business_rates_reliefs": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/business_rates/firm/firm_business_rates_reliefs.py", + "has_formula": true, + "name": "firm_business_rates_reliefs", + "unit": "GBP", + "value_type": "float" + }, + "firm_capex_main_pool_new": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/capital_allowances/firm_capex_main_pool_new.py", + "has_formula": false, + "name": "firm_capex_main_pool_new", + "unit": "GBP", + "value_type": "float" + }, + "firm_capex_main_pool_new_for_leasing": { + "default_value": 0, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/capital_allowances/firm_capex_main_pool_new_for_leasing.py", + "has_formula": false, + "name": "firm_capex_main_pool_new_for_leasing", + "unit": "GBP", + "value_type": "float" + }, + "firm_capex_main_pool_used": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/capital_allowances/firm_capex_main_pool_used.py", + "has_formula": false, + "name": "firm_capex_main_pool_used", + "unit": "GBP", + "value_type": "float" + }, + "firm_capex_special_rate_new": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/capital_allowances/firm_capex_special_rate_new.py", + "has_formula": false, + "name": "firm_capex_special_rate_new", + "unit": "GBP", + "value_type": "float" + }, + "firm_capex_special_rate_used": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/capital_allowances/firm_capex_special_rate_used.py", + "has_formula": false, + "name": "firm_capex_special_rate_used", + "unit": "GBP", + "value_type": "float" + }, + "firm_capex_structures": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/capital_allowances/firm_capex_structures.py", + "has_formula": false, + "name": "firm_capex_structures", + "unit": "GBP", + "value_type": "float" + }, + "firm_capital_allowances": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/corporation_tax/capital_allowances/firm_capital_allowances.py", + "has_formula": true, + "name": "firm_capital_allowances", + "unit": "GBP", + "value_type": "float" + }, + "firm_charitable_rate_relief": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/business_rates/firm/firm_charitable_rate_relief.py", + "has_formula": true, + "name": "firm_charitable_rate_relief", + "unit": "GBP", + "value_type": "float" + }, + "firm_claims_employment_allowance": { + "default_value": true, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/employer_costs/firm_claims_employment_allowance.py", + "has_formula": false, + "name": "firm_claims_employment_allowance", + "unit": null, + "value_type": "bool" + }, + "firm_claims_rd_sme_relief": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/corporation_tax/rd_relief/firm_claims_rd_sme_relief.py", + "has_formula": true, + "name": "firm_claims_rd_sme_relief", + "unit": null, + "value_type": "bool" + }, + "firm_class_1_earnings_above_secondary_threshold": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/national_insurance/employer/firm/firm_class_1_earnings_above_secondary_threshold.py", + "has_formula": true, + "name": "firm_class_1_earnings_above_secondary_threshold", + "unit": "GBP", + "value_type": "float" + }, + "firm_class_1a_benefits": { + "default_value": 0, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/firm_class_1a_benefits.py", + "has_formula": false, + "name": "firm_class_1a_benefits", + "unit": "GBP", + "value_type": "float" + }, + "firm_class_1a_ni": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/national_insurance/employer/firm/firm_class_1a_ni.py", + "has_formula": true, + "name": "firm_class_1a_ni", + "unit": "GBP", + "value_type": "float" + }, + "firm_corporation_tax_lower_limit": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/corporation_tax/firm_corporation_tax_lower_limit.py", + "has_formula": true, + "name": "firm_corporation_tax_lower_limit", + "unit": "GBP", + "value_type": "float" + }, + "firm_corporation_tax_upper_limit": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/corporation_tax/firm_corporation_tax_upper_limit.py", + "has_formula": true, + "name": "firm_corporation_tax_upper_limit", + "unit": "GBP", + "value_type": "float" + }, + "firm_deductions_allowance_share": { + "default_value": 1, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/corporation_tax/firm_deductions_allowance_share.py", + "has_formula": false, + "name": "firm_deductions_allowance_share", + "unit": "/1", + "value_type": "float" + }, + "firm_disposal_proceeds_full_expensing": { + "default_value": 0, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/capital_allowances/firm_disposal_proceeds_full_expensing.py", + "has_formula": false, + "name": "firm_disposal_proceeds_full_expensing", + "unit": "GBP", + "value_type": "float" + }, + "firm_disposal_proceeds_main_pool": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/capital_allowances/firm_disposal_proceeds_main_pool.py", + "has_formula": false, + "name": "firm_disposal_proceeds_main_pool", + "unit": "GBP", + "value_type": "float" + }, + "firm_employees": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/firm_employees.py", + "has_formula": false, + "name": "firm_employees", + "unit": "person", + "value_type": "int" + }, + "firm_employees_above_auto_enrolment_upper_limit": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/employer_costs/firm_employees_above_auto_enrolment_upper_limit.py", + "has_formula": false, + "name": "firm_employees_above_auto_enrolment_upper_limit", + "unit": "person", + "value_type": "int" + }, + "firm_employees_below_auto_enrolment_earnings_trigger": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/employer_costs/firm_employees_below_auto_enrolment_earnings_trigger.py", + "has_formula": false, + "name": "firm_employees_below_auto_enrolment_earnings_trigger", + "unit": "person", + "value_type": "int" + }, + "firm_employees_below_secondary_threshold": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/employer_costs/firm_employees_below_secondary_threshold.py", + "has_formula": false, + "name": "firm_employees_below_secondary_threshold", + "unit": "person", + "value_type": "int" + }, + "firm_employer_ni": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/national_insurance/employer/firm/firm_employer_ni.py", + "has_formula": true, + "name": "firm_employer_ni", + "unit": "GBP", + "value_type": "float" + }, + "firm_employer_ni_before_allowance": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/national_insurance/employer/firm/firm_employer_ni_before_allowance.py", + "has_formula": true, + "name": "firm_employer_ni_before_allowance", + "unit": "GBP", + "value_type": "float" + }, + "firm_empty_property_rates_exemption": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/business_rates/firm/firm_empty_property_rates_exemption.py", + "has_formula": true, + "name": "firm_empty_property_rates_exemption", + "unit": "GBP", + "value_type": "float" + }, + "firm_exempt_distributions": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/corporation_tax/firm_exempt_distributions.py", + "has_formula": false, + "name": "firm_exempt_distributions", + "unit": "GBP", + "value_type": "float" + }, + "firm_exempt_supplies": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/vat/firm_exempt_supplies.py", + "has_formula": false, + "name": "firm_exempt_supplies", + "unit": "GBP", + "value_type": "float" + }, + "firm_flat_rate_percentage": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/vat/firm/firm_flat_rate_percentage.py", + "has_formula": true, + "name": "firm_flat_rate_percentage", + "unit": "/1", + "value_type": "float" + }, + "firm_flat_rate_scheme_eligible": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/vat/firm/firm_flat_rate_scheme_eligible.py", + "has_formula": true, + "name": "firm_flat_rate_scheme_eligible", + "unit": null, + "value_type": "bool" + }, + "firm_flat_rate_sector_percentage": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/vat/firm/firm_flat_rate_sector_percentage.py", + "has_formula": true, + "name": "firm_flat_rate_sector_percentage", + "unit": "/1", + "value_type": "float" + }, + "firm_flat_rate_turnover": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/vat/firm/firm_flat_rate_turnover.py", + "has_formula": true, + "name": "firm_flat_rate_turnover", + "unit": "GBP", + "value_type": "float" + }, + "firm_full_expensing_allowance": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/corporation_tax/capital_allowances/firm_full_expensing_allowance.py", + "has_formula": true, + "name": "firm_full_expensing_allowance", + "unit": "GBP", + "value_type": "float" + }, + "firm_full_expensing_balancing_charge": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/corporation_tax/capital_allowances/firm_full_expensing_balancing_charge.py", + "has_formula": true, + "name": "firm_full_expensing_balancing_charge", + "unit": "GBP", + "value_type": "float" + }, + "firm_gross_business_rates": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/business_rates/firm/firm_gross_business_rates.py", + "has_formula": true, + "name": "firm_gross_business_rates", + "unit": "GBP", + "value_type": "float" + }, + "firm_id": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/firm_id.py", + "has_formula": false, + "name": "firm_id", + "unit": null, + "value_type": "int" + }, + "firm_in_england": { + "default_value": true, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/business_rates/firm_in_england.py", + "has_formula": false, + "name": "firm_in_england", + "unit": null, + "value_type": "bool" + }, + "firm_in_freeport": { + "default_value": false, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/firm_in_freeport.py", + "has_formula": false, + "name": "firm_in_freeport", + "unit": null, + "value_type": "bool" + }, + "firm_input_costs": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/firm_input_costs.py", + "has_formula": false, + "name": "firm_input_costs", + "unit": "GBP", + "value_type": "float" + }, + "firm_input_vat": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/vat/firm_input_vat.py", + "has_formula": false, + "name": "firm_input_vat", + "unit": "GBP", + "value_type": "float" + }, + "firm_is_bank": { + "default_value": false, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/firm_is_bank.py", + "has_formula": false, + "name": "firm_is_bank", + "unit": null, + "value_type": "bool" + }, + "firm_is_charity": { + "default_value": false, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/firm_is_charity.py", + "has_formula": false, + "name": "firm_is_charity", + "unit": null, + "value_type": "bool" + }, + "firm_is_industrial_property": { + "default_value": false, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/business_rates/firm_is_industrial_property.py", + "has_formula": false, + "name": "firm_is_industrial_property", + "unit": null, + "value_type": "bool" + }, + "firm_is_limited_cost_trader": { + "default_value": false, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/vat/firm_is_limited_cost_trader.py", + "has_formula": false, + "name": "firm_is_limited_cost_trader", + "unit": null, + "value_type": "bool" + }, + "firm_is_live_music_venue": { + "default_value": false, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/business_rates/firm_is_live_music_venue.py", + "has_formula": false, + "name": "firm_is_live_music_venue", + "unit": null, + "value_type": "bool" + }, + "firm_is_pub_or_live_music_venue": { + "default_value": false, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/business_rates/firm_is_pub_or_live_music_venue.py", + "has_formula": false, + "name": "firm_is_pub_or_live_music_venue", + "unit": null, + "value_type": "bool" + }, + "firm_is_public_body": { + "default_value": false, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/employer_costs/firm_is_public_body.py", + "has_formula": false, + "name": "firm_is_public_body", + "unit": null, + "value_type": "bool" + }, + "firm_is_rd_intensive": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/corporation_tax/rd_relief/firm_is_rd_intensive.py", + "has_formula": true, + "name": "firm_is_rd_intensive", + "unit": null, + "value_type": "bool" + }, + "firm_is_rhl_property": { + "default_value": false, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/business_rates/firm_is_rhl_property.py", + "has_formula": false, + "name": "firm_is_rhl_property", + "unit": null, + "value_type": "bool" + }, + "firm_is_single_director_company": { + "default_value": false, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/firm_is_single_director_company.py", + "has_formula": false, + "name": "firm_is_single_director_company", + "unit": null, + "value_type": "bool" + }, + "firm_is_sme": { + "default_value": false, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/rd/firm_is_sme.py", + "has_formula": false, + "name": "firm_is_sme", + "unit": null, + "value_type": "bool" + }, + "firm_is_wales_higher_multiplier_excluded": { + "default_value": false, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/business_rates/firm_is_wales_higher_multiplier_excluded.py", + "has_formula": false, + "name": "firm_is_wales_higher_multiplier_excluded", + "unit": null, + "value_type": "bool" + }, + "firm_is_wales_retail_property": { + "default_value": false, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/business_rates/firm_is_wales_retail_property.py", + "has_formula": false, + "name": "firm_is_wales_retail_property", + "unit": null, + "value_type": "bool" + }, + "firm_legal_form": { + "default_value": "COMPANY", + "definition_period": "year", + "enum": { + "module": "policyengine_uk.variables.firm.firm_legal_form", + "name": "FirmLegalForm" + }, + "enum_members": [ + "COMPANY", + "SOLE_TRADER", + "PARTNERSHIP", + "OTHER" + ], + "file": "variables/firm/firm_legal_form.py", + "has_formula": false, + "name": "firm_legal_form", + "unit": null, + "value_type": "Enum" + }, + "firm_liable_to_corporation_tax": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/corporation_tax/firm_liable_to_corporation_tax.py", + "has_formula": true, + "name": "firm_liable_to_corporation_tax", + "unit": null, + "value_type": "bool" + }, + "firm_losses_brought_forward": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/corporation_tax/firm_losses_brought_forward.py", + "has_formula": false, + "name": "firm_losses_brought_forward", + "unit": "GBP", + "value_type": "float" + }, + "firm_losses_used": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/corporation_tax/firm_losses_used.py", + "has_formula": true, + "name": "firm_losses_used", + "unit": "GBP", + "value_type": "float" + }, + "firm_low_paid_hours": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/firm_low_paid_hours.py", + "has_formula": false, + "name": "firm_low_paid_hours", + "unit": "hour", + "value_type": "float" + }, + "firm_low_paid_paybill": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/firm_low_paid_paybill.py", + "has_formula": false, + "name": "firm_low_paid_paybill", + "unit": "GBP", + "value_type": "float" + }, + "firm_main_pool_balance": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/corporation_tax/capital_allowances/firm_main_pool_balance.py", + "has_formula": true, + "name": "firm_main_pool_balance", + "unit": "GBP", + "value_type": "float" + }, + "firm_main_pool_balancing_charge": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/corporation_tax/capital_allowances/firm_main_pool_balancing_charge.py", + "has_formula": true, + "name": "firm_main_pool_balancing_charge", + "unit": "GBP", + "value_type": "float" + }, + "firm_main_pool_brought_forward": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/capital_allowances/firm_main_pool_brought_forward.py", + "has_formula": false, + "name": "firm_main_pool_brought_forward", + "unit": "GBP", + "value_type": "float" + }, + "firm_main_pool_carried_forward": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/corporation_tax/capital_allowances/firm_main_pool_carried_forward.py", + "has_formula": true, + "name": "firm_main_pool_carried_forward", + "unit": "GBP", + "value_type": "float" + }, + "firm_main_pool_new_expenditure_after_full_expensing": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/corporation_tax/capital_allowances/firm_main_pool_new_expenditure_after_full_expensing.py", + "has_formula": true, + "name": "firm_main_pool_new_expenditure_after_full_expensing", + "unit": "GBP", + "value_type": "float" + }, + "firm_main_pool_writing_down_allowance": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/corporation_tax/capital_allowances/firm_main_pool_writing_down_allowance.py", + "has_formula": true, + "name": "firm_main_pool_writing_down_allowance", + "unit": "GBP", + "value_type": "float" + }, + "firm_main_rate_first_year_allowance": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/corporation_tax/capital_allowances/firm_main_rate_first_year_allowance.py", + "has_formula": true, + "name": "firm_main_rate_first_year_allowance", + "unit": "GBP", + "value_type": "float" + }, + "firm_marginal_relief": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/corporation_tax/firm_marginal_relief.py", + "has_formula": true, + "name": "firm_marginal_relief", + "unit": "GBP", + "value_type": "float" + }, + "firm_minimum_wage_cost": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/minimum_wage/firm/firm_minimum_wage_cost.py", + "has_formula": true, + "name": "firm_minimum_wage_cost", + "unit": "GBP", + "value_type": "float" + }, + "firm_months_empty": { + "default_value": 0, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/business_rates/firm_months_empty.py", + "has_formula": false, + "name": "firm_months_empty", + "unit": null, + "value_type": "int" + }, + "firm_n_associated_companies": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/firm_n_associated_companies.py", + "has_formula": false, + "name": "firm_n_associated_companies", + "unit": null, + "value_type": "int" + }, + "firm_n_properties": { + "default_value": 1, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/business_rates/firm_n_properties.py", + "has_formula": false, + "name": "firm_n_properties", + "unit": null, + "value_type": "int" + }, + "firm_non_trading_profits": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/corporation_tax/firm_non_trading_profits.py", + "has_formula": false, + "name": "firm_non_trading_profits", + "unit": "GBP", + "value_type": "float" + }, + "firm_only_tax": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/contrib/policyengine/firm/firm_only_tax.py", + "has_formula": true, + "name": "firm_only_tax", + "unit": "GBP", + "value_type": "float" + }, + "firm_output_vat": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/vat/firm/firm_output_vat.py", + "has_formula": true, + "name": "firm_output_vat", + "unit": "GBP", + "value_type": "float" + }, + "firm_partial_exemption_recovery_share": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/vat/firm/firm_partial_exemption_recovery_share.py", + "has_formula": true, + "name": "firm_partial_exemption_recovery_share", + "unit": "/1", + "value_type": "float" + }, + "firm_paybill": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/firm_paybill.py", + "has_formula": false, + "name": "firm_paybill", + "unit": "GBP", + "value_type": "float" + }, + "firm_paybill_above_auto_enrolment_upper_limit": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/employer_costs/firm_paybill_above_auto_enrolment_upper_limit.py", + "has_formula": false, + "name": "firm_paybill_above_auto_enrolment_upper_limit", + "unit": "GBP", + "value_type": "float" + }, + "firm_paybill_after_minimum_wage": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/minimum_wage/firm/firm_paybill_after_minimum_wage.py", + "has_formula": true, + "name": "firm_paybill_after_minimum_wage", + "unit": "GBP", + "value_type": "float" + }, + "firm_paybill_below_auto_enrolment_earnings_trigger": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/employer_costs/firm_paybill_below_auto_enrolment_earnings_trigger.py", + "has_formula": false, + "name": "firm_paybill_below_auto_enrolment_earnings_trigger", + "unit": "GBP", + "value_type": "float" + }, + "firm_paybill_below_secondary_threshold": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/employer_costs/firm_paybill_below_secondary_threshold.py", + "has_formula": false, + "name": "firm_paybill_below_secondary_threshold", + "unit": "GBP", + "value_type": "float" + }, + "firm_prior_year_secondary_class_1_liabilities": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/national_insurance/employment_allowance/firm_prior_year_secondary_class_1_liabilities.py", + "has_formula": true, + "name": "firm_prior_year_secondary_class_1_liabilities", + "unit": "GBP", + "value_type": "float" + }, + "firm_profits_before_losses": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/corporation_tax/firm_profits_before_losses.py", + "has_formula": true, + "name": "firm_profits_before_losses", + "unit": "GBP", + "value_type": "float" + }, + "firm_property_occupied": { + "default_value": true, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/business_rates/firm_property_occupied.py", + "has_formula": false, + "name": "firm_property_occupied", + "unit": null, + "value_type": "bool" + }, + "firm_pubs_and_live_music_venues_rate_relief": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/business_rates/firm/firm_pubs_and_live_music_venues_rate_relief.py", + "has_formula": true, + "name": "firm_pubs_and_live_music_venues_rate_relief", + "unit": "GBP", + "value_type": "float" + }, + "firm_qualifying_rd_expenditure": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/rd/firm_qualifying_rd_expenditure.py", + "has_formula": false, + "name": "firm_qualifying_rd_expenditure", + "unit": "GBP", + "value_type": "float" + }, + "firm_rateable_value": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/firm_rateable_value.py", + "has_formula": false, + "name": "firm_rateable_value", + "unit": "GBP", + "value_type": "float" + }, + "firm_rates_in_england": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/business_rates/firm/firm_rates_in_england.py", + "has_formula": true, + "name": "firm_rates_in_england", + "unit": null, + "value_type": "bool" + }, + "firm_rd_additional_deduction": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/corporation_tax/rd_relief/firm_rd_additional_deduction.py", + "has_formula": true, + "name": "firm_rd_additional_deduction", + "unit": "GBP", + "value_type": "float" + }, + "firm_rd_expenditure_credit": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/corporation_tax/rd_relief/firm_rd_expenditure_credit.py", + "has_formula": true, + "name": "firm_rd_expenditure_credit", + "unit": "GBP", + "value_type": "float" + }, + "firm_rd_intensity": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/corporation_tax/rd_relief/firm_rd_intensity.py", + "has_formula": true, + "name": "firm_rd_intensity", + "unit": "/1", + "value_type": "float" + }, + "firm_rd_payable_credit": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/corporation_tax/rd_relief/firm_rd_payable_credit.py", + "has_formula": true, + "name": "firm_rd_payable_credit", + "unit": "GBP", + "value_type": "float" + }, + "firm_rd_staff_paye_nic": { + "default_value": 0, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/rd/firm_rd_staff_paye_nic.py", + "has_formula": false, + "name": "firm_rd_staff_paye_nic", + "unit": "GBP", + "value_type": "float" + }, + "firm_rd_surrenderable_loss": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/corporation_tax/rd_relief/firm_rd_surrenderable_loss.py", + "has_formula": true, + "name": "firm_rd_surrenderable_loss", + "unit": "GBP", + "value_type": "float" + }, + "firm_rdec_excess_payable": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/corporation_tax/firm_rdec_excess_payable.py", + "has_formula": true, + "name": "firm_rdec_excess_payable", + "unit": "GBP", + "value_type": "float" + }, + "firm_rdec_paye_nic_cap_supplied": { + "default_value": false, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/rd/firm_rdec_paye_nic_cap_supplied.py", + "has_formula": false, + "name": "firm_rdec_paye_nic_cap_supplied", + "unit": null, + "value_type": "bool" + }, + "firm_recoverable_input_vat": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/vat/firm/firm_recoverable_input_vat.py", + "has_formula": true, + "name": "firm_recoverable_input_vat", + "unit": "GBP", + "value_type": "float" + }, + "firm_reduced_rated_supplies": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/vat/firm_reduced_rated_supplies.py", + "has_formula": false, + "name": "firm_reduced_rated_supplies", + "unit": "GBP", + "value_type": "float" + }, + "firm_region": { + "default_value": "LONDON", + "definition_period": "year", + "enum": { + "module": "policyengine_uk.variables.household.demographic.geography", + "name": "Region" + }, + "enum_members": [ + "UNKNOWN", + "NORTH_EAST", + "NORTH_WEST", + "YORKSHIRE", + "EAST_MIDLANDS", + "WEST_MIDLANDS", + "EAST_OF_ENGLAND", + "LONDON", + "SOUTH_EAST", + "SOUTH_WEST", + "WALES", + "SCOTLAND", + "NORTHERN_IRELAND" + ], + "file": "variables/firm/firm_region.py", + "has_formula": false, + "name": "firm_region", + "unit": null, + "value_type": "Enum" + }, + "firm_relevant_paye_nic_liabilities": { + "default_value": 0, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/rd/firm_relevant_paye_nic_liabilities.py", + "has_formula": false, + "name": "firm_relevant_paye_nic_liabilities", + "unit": "GBP", + "value_type": "float" + }, + "firm_retail_hospitality_leisure_rate_relief": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/business_rates/firm/firm_retail_hospitality_leisure_rate_relief.py", + "has_formula": true, + "name": "firm_retail_hospitality_leisure_rate_relief", + "unit": "GBP", + "value_type": "float" + }, + "firm_sba_qualifying_cost_brought_forward": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/capital_allowances/firm_sba_qualifying_cost_brought_forward.py", + "has_formula": false, + "name": "firm_sba_qualifying_cost_brought_forward", + "unit": "GBP", + "value_type": "float" + }, + "firm_sic_section": { + "default_value": "UNKNOWN", + "definition_period": "year", + "enum": { + "module": "policyengine_uk.variables.firm.firm_sic_section", + "name": "SICSection" + }, + "enum_members": [ + "UNKNOWN", + "A", + "B", + "C", + "D", + "E", + "F", + "G", + "H", + "I", + "J", + "K", + "L", + "M", + "N", + "O", + "P", + "Q", + "R", + "S", + "T", + "U" + ], + "file": "variables/firm/firm_sic_section.py", + "has_formula": false, + "name": "firm_sic_section", + "unit": null, + "value_type": "Enum" + }, + "firm_small_business_rate_relief": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/business_rates/firm/firm_small_business_rate_relief.py", + "has_formula": true, + "name": "firm_small_business_rate_relief", + "unit": "GBP", + "value_type": "float" + }, + "firm_small_profits_rate_excluded": { + "default_value": false, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/corporation_tax/firm_small_profits_rate_excluded.py", + "has_formula": false, + "name": "firm_small_profits_rate_excluded", + "unit": null, + "value_type": "bool" + }, + "firm_special_rate_first_year_allowance": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/corporation_tax/capital_allowances/firm_special_rate_first_year_allowance.py", + "has_formula": true, + "name": "firm_special_rate_first_year_allowance", + "unit": "GBP", + "value_type": "float" + }, + "firm_special_rate_first_year_allowance_available": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/corporation_tax/capital_allowances/firm_special_rate_first_year_allowance_available.py", + "has_formula": true, + "name": "firm_special_rate_first_year_allowance_available", + "unit": null, + "value_type": "bool" + }, + "firm_special_rate_pool_balance": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/corporation_tax/capital_allowances/firm_special_rate_pool_balance.py", + "has_formula": true, + "name": "firm_special_rate_pool_balance", + "unit": "GBP", + "value_type": "float" + }, + "firm_special_rate_pool_brought_forward": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/capital_allowances/firm_special_rate_pool_brought_forward.py", + "has_formula": false, + "name": "firm_special_rate_pool_brought_forward", + "unit": "GBP", + "value_type": "float" + }, + "firm_special_rate_pool_carried_forward": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/corporation_tax/capital_allowances/firm_special_rate_pool_carried_forward.py", + "has_formula": true, + "name": "firm_special_rate_pool_carried_forward", + "unit": "GBP", + "value_type": "float" + }, + "firm_special_rate_pool_writing_down_allowance": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/corporation_tax/capital_allowances/firm_special_rate_pool_writing_down_allowance.py", + "has_formula": true, + "name": "firm_special_rate_pool_writing_down_allowance", + "unit": "GBP", + "value_type": "float" + }, + "firm_standard_rated_supplies": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/vat/firm_standard_rated_supplies.py", + "has_formula": false, + "name": "firm_standard_rated_supplies", + "unit": "GBP", + "value_type": "float" + }, + "firm_structures_and_buildings_allowance": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/corporation_tax/capital_allowances/firm_structures_and_buildings_allowance.py", + "has_formula": true, + "name": "firm_structures_and_buildings_allowance", + "unit": "GBP", + "value_type": "float" + }, + "firm_tax": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/contrib/policyengine/firm/firm_tax.py", + "has_formula": true, + "name": "firm_tax", + "unit": "GBP", + "value_type": "float" + }, + "firm_taxable_profit": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/corporation_tax/firm_taxable_profit.py", + "has_formula": true, + "name": "firm_taxable_profit", + "unit": "GBP", + "value_type": "float" + }, + "firm_taxable_trading_profit": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/firm_taxable_trading_profit.py", + "has_formula": false, + "name": "firm_taxable_trading_profit", + "unit": "GBP", + "value_type": "float" + }, + "firm_total_relevant_expenditure": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/rd/firm_total_relevant_expenditure.py", + "has_formula": false, + "name": "firm_total_relevant_expenditure", + "unit": "GBP", + "value_type": "float" + }, + "firm_turnover": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/firm_turnover.py", + "has_formula": false, + "name": "firm_turnover", + "unit": "GBP", + "value_type": "float" + }, + "firm_uses_flat_rate_scheme": { + "default_value": false, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/vat/firm_uses_flat_rate_scheme.py", + "has_formula": false, + "name": "firm_uses_flat_rate_scheme", + "unit": null, + "value_type": "bool" + }, + "firm_vat": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/vat/firm/firm_vat.py", + "has_formula": true, + "name": "firm_vat", + "unit": "GBP", + "value_type": "float" + }, + "firm_vat_flat_rate_liability": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/vat/firm/firm_vat_flat_rate_liability.py", + "has_formula": true, + "name": "firm_vat_flat_rate_liability", + "unit": "GBP", + "value_type": "float" + }, + "firm_vat_liability_if_registered": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/vat/firm/firm_vat_liability_if_registered.py", + "has_formula": true, + "name": "firm_vat_liability_if_registered", + "unit": "GBP", + "value_type": "float" + }, + "firm_vat_normal_liability": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/vat/firm/firm_vat_normal_liability.py", + "has_formula": true, + "name": "firm_vat_normal_liability", + "unit": "GBP", + "value_type": "float" + }, + "firm_vat_registered": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/vat/firm/firm_vat_registered.py", + "has_formula": true, + "name": "firm_vat_registered", + "unit": null, + "value_type": "bool" + }, + "firm_vat_taxable_turnover": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/gov/hmrc/vat/firm/firm_vat_taxable_turnover.py", + "has_formula": true, + "name": "firm_vat_taxable_turnover", + "unit": "GBP", + "value_type": "float" + }, + "firm_vat_voluntarily_registered": { + "default_value": false, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/vat/firm_vat_voluntarily_registered.py", + "has_formula": false, + "name": "firm_vat_voluntarily_registered", + "unit": null, + "value_type": "bool" + }, + "firm_weight": { + "default_value": 1, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/firm_weight.py", + "has_formula": false, + "name": "firm_weight", + "unit": null, + "value_type": "float" + }, + "firm_zero_rated_class_1_earnings": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/employer_costs/firm_zero_rated_class_1_earnings.py", + "has_formula": false, + "name": "firm_zero_rated_class_1_earnings", + "unit": "GBP", + "value_type": "float" + }, + "firm_zero_rated_supplies": { + "default_value": null, + "definition_period": "year", + "enum": null, + "enum_members": null, + "file": "variables/firm/vat/firm_zero_rated_supplies.py", + "has_formula": false, + "name": "firm_zero_rated_supplies", + "unit": "GBP", + "value_type": "float" + } + }, + "microcosm_only_columns_checked": [ + "base_weight", + "data_vintage", + "in_frame", + "ons_legal_status", + "ons_region_code", + "source_firm_id", + "source_firm_key", + "vat_registered", + "vat_scope" + ], + "policyengine_uk": { + "dirty": false, + "head_commit": "0d1c25010835c4f8b14b5f8030c696937ecd51f7", + "pull_request": "PolicyEngine/policyengine-uk#2940" + }, + "policyengine_uk_variable_names": [ + "BRMA_LHA_rate", + "CB_HITC", + "CTC_child_element", + "CTC_disabled_child_element", + "CTC_family_element", + "CTC_maximum_rate", + "CTC_severely_disabled_child_element", + "LHA_additional_bedrooms", + "LHA_allowed_bedrooms", + "LHA_cap", + "LHA_category", + "LHA_eligible", + "LVT", + "WTC_basic_element", + "WTC_childcare_element", + "WTC_couple_element", + "WTC_disabled_element", + "WTC_lone_parent_element", + "WTC_maximum_rate", + "WTC_severely_disabled_element", + "WTC_worker_element", + "a_and_e_visits", + "aa_category", + "access_fund", + "accommodation_type", + "add_rate_earned_income", + "add_rate_earned_income_tax", + "add_rate_savings_income", + "additional_minimum_guarantee", + "additional_residential_property_purchased", + "additional_state_pension", + "adjusted_employer_cost", + "adjusted_net_income", + "adjusted_total_income", + "admitted_patient_visits", + "adopter_is_foster_parent_or_close_relative", + "adult_dependants_grant", + "adult_dependants_grant_adult_eligible", + "adult_dependants_grant_adult_receives_student_finance", + "adult_dependants_grant_course_eligible", + "adult_dependants_grant_eligible", + "adult_dependants_grant_has_other_adult_dependant", + "adult_dependants_grant_household_income", + "adult_dependants_grant_other_adult_income", + "adult_dependants_grant_receives_postgraduate_loan", + "adult_ema", + "adult_index", + "adult_index_cg", + "afcs", + "afcs_reported", + "age", + "age_18_64", + "age_over_64", + "age_started_or_accepted_current_education_or_training", + "age_under_18", + "alcohol_and_tobacco_consumption", + "alcohol_duty", + "allowances", + "apprenticeship_levy", + "armed_forces_independence_payment", + "attendance_allowance", + "attends_private_school", + "attends_private_school_random_draw", + "bank_surcharge", + "base_net_income", + "baseline_business_rates", + "baseline_child_benefit_entitlement", + "baseline_ctc_entitlement", + "baseline_domestic_energy_vat", + "baseline_employer_cost", + "baseline_hbai_excluded_income", + "baseline_income_support_entitlement", + "baseline_pension_credit_entitlement", + "baseline_private_school_vat", + "baseline_vat", + "baseline_wtc_entitlement", + "basic_income", + "basic_rate_earned_income", + "basic_rate_earned_income_tax", + "basic_rate_savings_income", + "basic_rate_savings_income_pre_starter", + "basic_state_pension", + "beer_abv", + "beer_draught_share", + "beer_duty", + "beer_litres", + "benefit_cap_reduction", + "benefit_cap_welfare_benefits", + "benefits_in_kind", + "benefits_premiums", + "benunit_contains_household_head", + "benunit_count_adults", + "benunit_count_children", + "benunit_has_carer", + "benunit_id", + "benunit_is_liable_for_household_rent", + "benunit_is_rent_liable", + "benunit_is_renting", + "benunit_region", + "benunit_rent", + "benunit_reported_capital", + "benunit_tax", + "benunit_tenure_type", + "benunit_weekly_hours", + "benunit_weight", + "betting_exchange_commission", + "bi_household_phaseout", + "bi_individual_phaseout", + "bi_maximum", + "bi_phaseout", + "bingo_duty", + "bingo_net_receipts", + "birth_year", + "blind_persons_allowance", + "brma", + "bsp", + "bsp_reported", + "bursary_fund_16_to_19", + "bursary_fund_16_to_19_age_eligible", + "bursary_fund_16_to_19_in_care_or_care_leaver", + "bursary_fund_16_to_19_in_qualifying_education", + "bursary_fund_16_to_19_participation_costs", + "bursary_fund_16_to_19_receives_uc_or_esa_in_own_right", + "bursary_fund_16_to_19_receives_uc_or_is_in_own_right", + "bursary_fund_16_to_19_self_supporting", + "bursary_fund_16_to_19_vulnerable_group_eligible", + "bus_fare_spending", + "bus_fare_spending_reported", + "bus_in_london_trips", + "bus_pass_eligible", + "bus_subsidy_spending", + "business_rates", + "capital_allowances", + "capital_gains", + "capital_gains_badr", + "capital_gains_badr_behavioural_response", + "capital_gains_badr_elasticity", + "capital_gains_before_response", + "capital_gains_behavioural_response", + "capital_gains_carried_interest", + "capital_gains_elasticity", + "capital_gains_residential_property", + "capital_gains_tax", + "capital_income", + "capped_mcad", + "car_co2_emissions", + "car_engine_size", + "car_first_registration_date", + "car_fuel_benefit", + "car_fuel_type", + "car_is_ved_exempt", + "car_list_price", + "car_vehicle_excise_duty", + "carbon_consumption", + "carbon_tax", + "care_hours", + "care_to_learn", + "care_to_learn_eligible", + "care_to_learn_qualifying_child", + "carer_minimum_guarantee_addition", + "carer_premium", + "carer_support_payment", + "carer_support_payment_overlapping_benefits", + "carer_support_payment_overlapping_state_pension", + "carer_support_payment_pre_couple_limit", + "carer_support_payment_pre_overlap", + "carers_allowance", + "carers_allowance_earnings", + "carers_allowance_overlapping_benefits", + "carers_allowance_pre_couple_limit", + "carers_allowance_pre_overlap", + "carers_allowance_reported", + "carers_allowance_weekly_earnings_above_limit", + "cares_for_severely_disabled_person", + "cash_isa", + "cash_isa_balance", + "cash_isa_countable_capital", + "cash_isa_subscription_limit", + "cash_isa_subscriptions", + "cash_isa_subscriptions_above_limit", + "charitable_investment_gifts", + "child_benefit", + "child_benefit_child_index", + "child_benefit_entitlement", + "child_benefit_less_tax_charge", + "child_benefit_opts_out", + "child_benefit_reported", + "child_benefit_respective_amount", + "child_ema", + "child_index", + "child_limit_adoption_exception", + "child_limit_continuation_exception", + "child_limit_multiple_birth_exception", + "child_limit_non_consensual_conception_exception", + "child_limit_non_parental_caring_exception", + "child_minimum_guarantee_addition", + "child_tax_credit", + "child_tax_credit_pre_minimum", + "child_tax_credit_reported", + "childcare_expenses", + "childcare_grant", + "childcare_grant_child_eligible", + "childcare_grant_child_has_special_educational_needs", + "childcare_grant_eligible", + "childcare_grant_eligible_children", + "childcare_grant_full_time_student", + "childcare_grant_household_income", + "childcare_grant_provider_is_nanny", + "childcare_grant_receives_nhs_childcare_support", + "childcare_grant_receives_postgraduate_loan", + "childcare_grant_student_finance_eligible", + "childcare_grant_uses_qualifying_provider", + "cider_abv", + "cider_draught_share", + "cider_duty", + "cider_litres", + "cigarette_price_per_pack", + "cigarettes_per_week", + "cigars_grams_per_week", + "claimant_or_partner_esa_income", + "claimant_or_partner_jsa_income", + "claims_all_entitled_benefits", + "claims_legacy_benefits", + "claims_uc_at_legacy_closure", + "claims_universal_credit", + "cliff_evaluated", + "cliff_gap", + "clothing_and_footwear_consumption", + "communication_consumption", + "company_car_appropriate_percentage", + "company_car_availability", + "company_car_benefit", + "company_car_capital_contributions", + "company_car_co2_emissions", + "company_car_electric_range", + "company_car_fuel_type", + "company_car_list_price", + "company_car_private_fuel_provided", + "company_car_private_use_payments", + "company_car_registered_from_6_april_2020", + "consumer_debt", + "consumer_incident_tax_revenue_change", + "consumption", + "consumption_shareholding", + "corporate_incident_tax_revenue_change", + "corporate_land_value", + "corporate_sdlt", + "corporate_sector_wealth", + "corporate_tax_incidence", + "corporate_wealth", + "corporation_tax", + "corporation_tax_before_credits", + "cost_of_living_disability_payment", + "cost_of_living_means_tested_payment", + "cost_of_living_support_payment", + "council_tax", + "council_tax_band", + "council_tax_band_d_amount", + "council_tax_benefit", + "council_tax_benefit_reported", + "council_tax_discount_rate", + "council_tax_less_benefit", + "council_tax_reduction", + "council_tax_reduction_applicable_amount", + "council_tax_reduction_applicable_income", + "council_tax_reduction_applicant_has_non_dep_exemption", + "council_tax_reduction_assessable_capital", + "council_tax_reduction_attained_pension_age_before_cutoff", + "council_tax_reduction_carer_premium", + "council_tax_reduction_claimant_benunit", + "council_tax_reduction_claims_are_joint", + "council_tax_reduction_devolved_working_age", + "council_tax_reduction_enhanced_disability_premium", + "council_tax_reduction_head_applies_alone", + "council_tax_reduction_home_letting_income", + "council_tax_reduction_household_has_simulated_claim", + "council_tax_reduction_income_tax_on_other_counted_income", + "council_tax_reduction_individual_non_dep_deduction", + "council_tax_reduction_individual_non_dep_deduction_eligible", + "council_tax_reduction_joint_liability_share", + "council_tax_reduction_liable_person", + "council_tax_reduction_maximum_eligible_liability", + "council_tax_reduction_net_earnings", + "council_tax_reduction_non_dep_deduction_exempt", + "council_tax_reduction_non_dep_deductions", + "council_tax_reduction_non_dep_gross_income", + "council_tax_reduction_pension_contribution_deduction_rate", + "council_tax_reduction_pensioner", + "council_tax_reduction_pensioner_child_amounts", + "council_tax_reduction_pensioner_child_disability_premiums", + "council_tax_reduction_pensioner_earnings_disregard", + "council_tax_reduction_pensioner_family_premium", + "council_tax_reduction_premiums", + "council_tax_reduction_relevant_income_based_benefit", + "council_tax_reduction_relevant_universal_credit_payments", + "council_tax_reduction_scheme_supported", + "council_tax_reduction_scotland_self_employment_deductions", + "council_tax_reduction_severe_disability_premium", + "council_tax_reduction_tariff_income", + "council_tax_reduction_tax_deduction", + "council_tax_reduction_universal_credit_award", + "council_tax_reduction_working_age_adult_premiums", + "council_tax_reduction_working_age_applicable_amount", + "council_tax_reduction_working_age_applicable_income", + "council_tax_reduction_working_age_carers", + "council_tax_reduction_working_age_child_amounts", + "council_tax_reduction_working_age_childcare_deduction", + "council_tax_reduction_working_age_earned_income", + "council_tax_reduction_working_age_earnings_disregard", + "council_tax_reduction_working_age_employed_earned_income", + "council_tax_reduction_working_age_has_universal_credit", + "council_tax_reduction_working_age_passported", + "council_tax_reduction_working_age_person_earned_income", + "council_tax_reduction_working_age_personal_allowance", + "council_tax_reduction_working_age_unearned_income", + "council_tax_reduction_working_age_unearned_income_tax", + "council_tax_reduction_working_age_universal_credit_award", + "country", + "covenanted_payments", + "ctc_child_limit_affected", + "ctc_child_limit_position", + "ctc_entitlement", + "cumulative_non_residential_rent", + "cumulative_residential_rent", + "current_education", + "date_of_birth", + "deductible_property_finance_costs", + "deep_poverty_gap", + "deep_poverty_line", + "deficiency_relief", + "defined_benefit_pension_contributions", + "defined_benefit_pension_input_amount", + "defined_benefit_pension_share", + "dfe_education_spending", + "dft_subsidy_spending", + "diesel_litres", + "diesel_price", + "diesel_spending", + "directly_held_shares", + "disability_basic_income", + "disability_premium", + "disabled_students_allowance", + "disabled_students_allowance_course_eligible", + "disabled_students_allowance_eligible", + "disabled_students_allowance_eligible_expenses", + "disabled_students_allowance_has_qualifying_condition", + "disabled_students_allowance_receives_equivalent_support", + "dividend_income", + "dividend_income_tax", + "dla", + "dla_m", + "dla_m_category", + "dla_sc", + "dla_sc_category", + "dla_sc_middle_plus", + "domestic_energy_consumption", + "domestic_energy_vat", + "domestic_rates", + "early_years_school_start_deferred", + "early_years_term_share_before_school", + "earned_income", + "earned_income_tax", + "earned_taxable_income", + "ebr_alternative_fuel_payment", + "ebr_council_tax_rebate", + "ebr_energy_bills_credit", + "ebr_energy_bills_credit_eligible", + "education_budget_change", + "education_consumption", + "education_grants", + "eldest_adult_age", + "eldest_child_age", + "eldest_claimant_or_partner_age", + "electricity_consumption", + "electricity_consumption_kwh", + "employee_pension_contributions", + "employee_pension_contributions_reported", + "employer_cost", + "employer_ni_fixed_employer_cost_change", + "employer_ni_response_capital_incidence", + "employer_ni_response_consumer_incidence", + "employer_pension_contributions", + "employment_allowance", + "employment_allowance_eligible", + "employment_benefits", + "employment_deductions", + "employment_expenses", + "employment_income", + "employment_income_before_lsr", + "employment_income_behavioral_response", + "employment_sector", + "employment_status", + "energy_bills_rebate", + "enhanced_disability_premium", + "epg_subsidy", + "equiv_hbai_household_net_income", + "equiv_hbai_household_net_income_ahc", + "equiv_household_net_income", + "esa", + "esa_contrib", + "esa_contrib_reported", + "esa_exempt_work_earnings", + "esa_exempt_work_higher_earnings_limit", + "esa_includes_support_component", + "esa_income", + "esa_income_abolition_reached", + "esa_income_appointee_saving", + "esa_income_assessable_capital", + "esa_income_claimant_remunerative_work", + "esa_income_eligible", + "esa_income_payable_share", + "esa_income_remunerative_work_hours", + "esa_income_report_closed", + "esa_income_reported", + "esa_income_tariff_income", + "expected_lbtt", + "expected_ltt", + "expected_sdlt", + "extended_childcare_entitlement", + "extended_childcare_entitlement_eligible", + "extended_childcare_entitlement_limited_capability_or_specified_benefit", + "extended_childcare_entitlement_meets_income_requirements", + "extended_childcare_entitlement_per_child", + "extended_childcare_entitlement_qualifying_child", + "extended_childcare_entitlement_term_share", + "extended_childcare_entitlement_total_per_child", + "extended_childcare_entitlement_work_condition", + "external_child_payments", + "families", + "family_rent", + "family_type", + "financial_spread_betting_net_losses", + "firm_aia_main_pool_new", + "firm_aia_main_pool_used", + "firm_aia_share", + "firm_aia_special_rate_new", + "firm_aia_special_rate_used", + "firm_annual_investment_allowance", + "firm_annual_investment_allowance_limit", + "firm_apprenticeship_levy_allowance_share", + "firm_augmented_profits", + "firm_auto_enrolment_employer_contribution", + "firm_auto_enrolment_qualifying_earnings", + "firm_bank_surcharge_allowance_share", + "firm_business_rates", + "firm_business_rates_multiplier", + "firm_business_rates_reliefs", + "firm_capex_main_pool_new", + "firm_capex_main_pool_new_for_leasing", + "firm_capex_main_pool_used", + "firm_capex_special_rate_new", + "firm_capex_special_rate_used", + "firm_capex_structures", + "firm_capital_allowances", + "firm_charitable_rate_relief", + "firm_claims_employment_allowance", + "firm_claims_rd_sme_relief", + "firm_class_1_earnings_above_secondary_threshold", + "firm_class_1a_benefits", + "firm_class_1a_ni", + "firm_corporation_tax_lower_limit", + "firm_corporation_tax_upper_limit", + "firm_deductions_allowance_share", + "firm_disposal_proceeds_full_expensing", + "firm_disposal_proceeds_main_pool", + "firm_employees", + "firm_employees_above_auto_enrolment_upper_limit", + "firm_employees_below_auto_enrolment_earnings_trigger", + "firm_employees_below_secondary_threshold", + "firm_employer_ni", + "firm_employer_ni_before_allowance", + "firm_empty_property_rates_exemption", + "firm_exempt_distributions", + "firm_exempt_supplies", + "firm_flat_rate_percentage", + "firm_flat_rate_scheme_eligible", + "firm_flat_rate_sector_percentage", + "firm_flat_rate_turnover", + "firm_full_expensing_allowance", + "firm_full_expensing_balancing_charge", + "firm_gross_business_rates", + "firm_id", + "firm_in_england", + "firm_in_freeport", + "firm_input_costs", + "firm_input_vat", + "firm_is_bank", + "firm_is_charity", + "firm_is_industrial_property", + "firm_is_limited_cost_trader", + "firm_is_live_music_venue", + "firm_is_pub_or_live_music_venue", + "firm_is_public_body", + "firm_is_rd_intensive", + "firm_is_rhl_property", + "firm_is_single_director_company", + "firm_is_sme", + "firm_is_wales_higher_multiplier_excluded", + "firm_is_wales_retail_property", + "firm_legal_form", + "firm_liable_to_corporation_tax", + "firm_losses_brought_forward", + "firm_losses_used", + "firm_low_paid_hours", + "firm_low_paid_paybill", + "firm_main_pool_balance", + "firm_main_pool_balancing_charge", + "firm_main_pool_brought_forward", + "firm_main_pool_carried_forward", + "firm_main_pool_new_expenditure_after_full_expensing", + "firm_main_pool_writing_down_allowance", + "firm_main_rate_first_year_allowance", + "firm_marginal_relief", + "firm_minimum_wage_cost", + "firm_months_empty", + "firm_n_associated_companies", + "firm_n_properties", + "firm_non_trading_profits", + "firm_only_tax", + "firm_output_vat", + "firm_partial_exemption_recovery_share", + "firm_paybill", + "firm_paybill_above_auto_enrolment_upper_limit", + "firm_paybill_after_minimum_wage", + "firm_paybill_below_auto_enrolment_earnings_trigger", + "firm_paybill_below_secondary_threshold", + "firm_prior_year_secondary_class_1_liabilities", + "firm_profits_before_losses", + "firm_property_occupied", + "firm_pubs_and_live_music_venues_rate_relief", + "firm_qualifying_rd_expenditure", + "firm_rateable_value", + "firm_rates_in_england", + "firm_rd_additional_deduction", + "firm_rd_expenditure_credit", + "firm_rd_intensity", + "firm_rd_payable_credit", + "firm_rd_staff_paye_nic", + "firm_rd_surrenderable_loss", + "firm_rdec_excess_payable", + "firm_rdec_paye_nic_cap_supplied", + "firm_recoverable_input_vat", + "firm_reduced_rated_supplies", + "firm_region", + "firm_relevant_paye_nic_liabilities", + "firm_retail_hospitality_leisure_rate_relief", + "firm_sba_qualifying_cost_brought_forward", + "firm_sic_section", + "firm_small_business_rate_relief", + "firm_small_profits_rate_excluded", + "firm_special_rate_first_year_allowance", + "firm_special_rate_first_year_allowance_available", + "firm_special_rate_pool_balance", + "firm_special_rate_pool_brought_forward", + "firm_special_rate_pool_carried_forward", + "firm_special_rate_pool_writing_down_allowance", + "firm_standard_rated_supplies", + "firm_structures_and_buildings_allowance", + "firm_tax", + "firm_tax_change_total", + "firm_tax_incidence", + "firm_taxable_profit", + "firm_taxable_trading_profit", + "firm_total_relevant_expenditure", + "firm_turnover", + "firm_uses_flat_rate_scheme", + "firm_vat", + "firm_vat_flat_rate_liability", + "firm_vat_liability_if_registered", + "firm_vat_normal_liability", + "firm_vat_registered", + "firm_vat_taxable_turnover", + "firm_vat_voluntarily_registered", + "firm_weight", + "firm_zero_rated_class_1_earnings", + "firm_zero_rated_supplies", + "food_and_non_alcoholic_beverages_consumption", + "forgoes_universal_credit_for_tax_free_childcare", + "free_school_fruit_veg", + "free_school_meals", + "free_school_milk", + "free_tv_licence_value", + "fuel_duty", + "fuel_duty_vat_change", + "full_rate_vat_consumption", + "full_rate_vat_expenditure_rate", + "gambling_duty", + "gaming_duty", + "gas_consumption", + "gas_consumption_kwh", + "gender", + "general_betting_duty", + "gift_aid", + "gift_aid_grossed_up", + "gov_balance", + "gov_spending", + "gov_tax", + "gross_financial_wealth", + "gross_taxable_inputs", + "guarantee_credit", + "hand_rolling_tobacco_grams_per_week", + "has_attained_state_pension_credit_qualifying_age", + "has_company_car", + "has_education_maintenance_funding", + "has_enhanced_pip_dl_award", + "has_highest_dla_sc_award", + "has_lifetime_isa", + "has_mixed_age_couple_pension_credit_saving", + "has_non_dependant_for_council_tax_reduction_severe_disability_premium", + "has_non_dependant_for_severe_disability_premium", + "has_non_resident_overnight_carer", + "has_own_esa_award", + "has_student_loan", + "has_tax_credit_award", + "has_uc_award_with_carer_element", + "hbai_benefits", + "hbai_excluded_income", + "hbai_excluded_income_change", + "hbai_household_net_income", + "hbai_household_net_income_ahc", + "hbai_household_net_income_before_reset_to_zero", + "hbai_person_type", + "health_consumption", + "healthy_start_vouchers", + "heated_tobacco_grams_per_week", + "high_value_council_tax_surcharge", + "higher_rate_earned_income", + "higher_rate_earned_income_tax", + "higher_rate_savings_income", + "highest_education", + "horse_and_dog_pool_betting_net_losses", + "hours_worked", + "household_benefits", + "household_benefits_individual_non_dep_deduction", + "household_bus_fare_age_weight", + "household_count_people", + "household_energy_payment", + "household_equivalisation_ahc", + "household_equivalisation_bhc", + "household_furnishings_consumption", + "household_gross_income", + "household_id", + "household_income_decile", + "household_income_decile_ahc", + "household_land_value", + "household_lifetime_isa_balance", + "household_market_income", + "household_net_income", + "household_net_income_ahc", + "household_num_benunits", + "household_owns_tv", + "household_tax", + "household_uc_company_holding_pool_scale", + "household_uc_pool_company_holdings", + "household_uc_reported_financial_capital", + "household_uc_unreported_claimants", + "household_wealth_decile", + "household_weight", + "households", + "housing_benefit", + "housing_benefit_LHA_additional_bedrooms", + "housing_benefit_LHA_allowed_bedrooms", + "housing_benefit_LHA_category", + "housing_benefit_LHA_rate", + "housing_benefit_applicable_amount", + "housing_benefit_applicable_income", + "housing_benefit_applicable_income_childcare_element", + "housing_benefit_applicable_income_disregard", + "housing_benefit_applied_standard_earnings_disregard", + "housing_benefit_assessable_capital", + "housing_benefit_attained_pension_age_before_cutoff", + "housing_benefit_baseline_entitlement", + "housing_benefit_benefit_cap", + "housing_benefit_benefit_cap_reduction", + "housing_benefit_board_and_attendance_determination", + "housing_benefit_child_disability_premiums", + "housing_benefit_childcare_earnings_limit", + "housing_benefit_eligible", + "housing_benefit_entitlement", + "housing_benefit_family_premium", + "housing_benefit_family_premium_category", + "housing_benefit_has_main_phase_esa", + "housing_benefit_has_non_dependant", + "housing_benefit_individual_non_dep_deduction_eligible", + "housing_benefit_main_phase_esa_allowance_adjustment", + "housing_benefit_maintenance_disregard", + "housing_benefit_meals_deduction", + "housing_benefit_net_earnings", + "housing_benefit_non_dep_deduction_exempt", + "housing_benefit_non_dep_deductions", + "housing_benefit_non_dep_deductions_claimant_exempt", + "housing_benefit_non_dep_gross_income", + "housing_benefit_on_passporting_benefit", + "housing_benefit_pension_age_regulations_apply", + "housing_benefit_permitted_work_disregard", + "housing_benefit_pre_benefit_cap", + "housing_benefit_report_is_rate_rebate_only", + "housing_benefit_reported", + "housing_benefit_residential_capital_exception", + "housing_benefit_savings_credit_only_income", + "housing_benefit_severe_disability_premium_applies", + "housing_benefit_shares_accommodation", + "housing_benefit_special_earnings_disregard", + "housing_benefit_special_earnings_disregard_eligible", + "housing_benefit_specified_or_temporary_accommodation_disregard", + "housing_benefit_tariff_income", + "housing_benefit_widowed_parents_allowance_income", + "housing_benefit_wtc_disregard", + "housing_costs", + "housing_service_charges", + "housing_water_and_electricity_consumption", + "iidb", + "iidb_reported", + "in_FE", + "in_HE", + "in_absolute_poverty_fye2011_ahc", + "in_absolute_poverty_fye2011_bhc", + "in_deep_poverty", + "in_deep_poverty_ahc", + "in_deep_poverty_bhc", + "in_original_frs", + "in_poverty", + "in_poverty_ahc", + "in_poverty_bhc", + "in_receipt_of_guarantee_credit", + "in_receipt_of_income_support_jsa_ib_or_esa_ir", + "in_receipt_of_savings_credit_only", + "in_relative_poverty_ahc", + "in_relative_poverty_bhc", + "in_rural_fuel_duty_relief_area", + "in_social_housing", + "in_specified_or_temporary_accommodation", + "in_work", + "incapacity_benefit", + "incapacity_benefit_reported", + "income_decile", + "income_elasticity_lsr", + "income_not_otherwise_charged", + "income_support", + "income_support_applicable_amount", + "income_support_applicable_income", + "income_support_assessable_capital", + "income_support_earnings_disregard", + "income_support_eligible", + "income_support_entitlement", + "income_support_net_earnings", + "income_support_remunerative_work_hours", + "income_support_reported", + "income_support_tariff_income", + "income_tax", + "income_tax_before_winter_fuel_payment_charge", + "income_tax_charges", + "income_tax_pre_charges", + "income_tax_reductions", + "income_tax_relief_cap", + "individual_savings_account_dividend_income", + "individual_savings_account_interest_income", + "inflation_adjustment", + "inflation_adjustment_ahc", + "is_CTC_child_element_included", + "is_CTC_child_limit_exception", + "is_CTC_child_limit_exempt", + "is_CTC_child_limit_own_exception", + "is_CTC_eligible", + "is_SP_age", + "is_WA_adult", + "is_WTC_eligible", + "is_about_to_start_paid_work", + "is_adult", + "is_apprentice", + "is_approved_foster_parent_without_placement", + "is_before_child_benefit_terminal_date", + "is_before_first_september_following_16th_birthday", + "is_before_first_september_following_19th_birthday", + "is_before_universal_credit_qualifying_young_person_terminal_date", + "is_benefit_unit_non_dependant_for_council_tax_reduction", + "is_benefit_unit_non_dependant_for_legacy_benefits", + "is_benefit_unit_non_dependant_for_universal_credit", + "is_benunit_eldest_child", + "is_benunit_head", + "is_blind", + "is_cared_for_by_carer_benefit_recipient", + "is_carer_for_benefits", + "is_child", + "is_child_benefit_payable_for_person", + "is_child_for_child_benefit", + "is_child_for_child_tax_credit", + "is_child_for_pension_credit", + "is_child_for_universal_credit", + "is_child_for_working_tax_credit_childcare_element", + "is_child_or_qualifying_young_person_for_child_benefit", + "is_child_or_qualifying_young_person_for_child_tax_credit", + "is_child_or_qualifying_young_person_for_pension_credit", + "is_child_or_qualifying_young_person_for_universal_credit", + "is_child_or_young_person_for_council_tax_reduction", + "is_child_or_young_person_for_legacy_benefits", + "is_child_or_young_person_placed_with_family", + "is_child_receiving_extended_childcare", + "is_child_receiving_targeted_childcare", + "is_child_receiving_tax_free_childcare", + "is_child_receiving_universal_childcare", + "is_claimant_or_partner", + "is_council_tax_reduction_applicant_or_partner", + "is_council_tax_reduction_lone_parent", + "is_counted_resident_for_severe_disability_addition", + "is_couple", + "is_dependent_child_for_student_support", + "is_disabled_for_benefits", + "is_eldest_child", + "is_engaged_in_owned_company_trade", + "is_enhanced_disabled_for_benefits", + "is_entitled_to_carer_benefit", + "is_female", + "is_full_year_category_a_director", + "is_gainfully_employed_for_carers_allowance", + "is_guarantee_credit_eligible", + "is_hbai_adult", + "is_hbai_child_aged_14_or_over", + "is_hbai_child_under_14", + "is_hbai_dependent_child", + "is_hbai_pensioner", + "is_hbai_working_age_adult", + "is_higher_earner", + "is_household_head", + "is_housing_benefit_benefit_cap_exempt", + "is_housing_benefit_benefit_cap_exempt_specified_benefit", + "is_housing_benefit_benefit_cap_exempt_working_tax_credit", + "is_housing_benefit_benefit_cap_single_claimant_rate", + "is_housing_benefit_qualifying_parent_or_carer", + "is_housing_benefit_young_individual", + "is_in_approved_training", + "is_in_child_benefit_extension_period", + "is_in_child_tax_credit_extension_period", + "is_in_first_year_of_apprenticeship", + "is_in_full_time_education", + "is_in_non_advanced_education", + "is_in_remunerative_work_for_child_benefit", + "is_in_remunerative_work_for_child_tax_credit", + "is_lha_foster_child", + "is_lha_shared_accommodation_rate_specified_renter", + "is_liable_for_household_rent", + "is_lone_parent", + "is_looked_after_by_local_authority", + "is_looked_after_child", + "is_male", + "is_married", + "is_mixed_age_couple", + "is_newly_self_employed", + "is_non_dependant_of_household_head", + "is_of_compulsory_school_age", + "is_older_child", + "is_on_cliff", + "is_on_income_based_jsa", + "is_on_income_related_esa", + "is_on_income_support", + "is_on_pawhp_relevant_benefit", + "is_on_pension_credit", + "is_on_universal_credit", + "is_on_winter_fuel_payment_relevant_benefit", + "is_parent", + "is_pension_credit_eligible", + "is_placed_for_adoption", + "is_qualifying_young_person_for_child_benefit", + "is_qualifying_young_person_for_child_tax_credit", + "is_qualifying_young_person_for_pension_credit", + "is_qualifying_young_person_for_uc_education", + "is_qualifying_young_person_for_universal_credit", + "is_qualifying_young_person_on_uc_migration_day", + "is_qualifying_young_person_under_universal_credit_regulation_5", + "is_renting", + "is_resolved_household_head", + "is_responsible_for_child_or_qualifying_young_person_for_child_tax_credit", + "is_responsible_for_child_or_qualifying_young_person_for_universal_credit", + "is_responsible_for_child_or_young_person_for_council_tax_reduction", + "is_responsible_for_child_or_young_person_for_legacy_benefits", + "is_responsible_for_child_or_young_person_for_uc_or_housing_benefit", + "is_savings_credit_eligible", + "is_scp_eligible", + "is_scp_eligible_child", + "is_severely_disabled_for_benefits", + "is_severely_disabled_for_carers_allowance", + "is_shared_accommodation", + "is_single", + "is_single_person", + "is_uc_assessed_claimant", + "is_uc_benefit_cap_exempt", + "is_uc_benefit_cap_exempt_earnings", + "is_uc_benefit_cap_exempt_qualifying_age", + "is_uc_benefit_cap_exempt_specified_benefit", + "is_uc_benefit_cap_single_claimant_rate", + "is_uc_claimant", + "is_uc_eligible", + "is_uc_entitled", + "is_uc_entitled_baseline", + "is_uc_non_dependant_of_household_head", + "is_uc_single_or_joint_claimant", + "is_uc_work_allowance_eligible", + "is_young_child", + "isa_cash_interest_flat_rate_charge", + "isa_subscriptions", + "isa_subscriptions_above_limit", + "jsa", + "jsa_contrib", + "jsa_contrib_reported", + "jsa_income", + "jsa_income_assessable_capital", + "jsa_income_eligible", + "jsa_income_reported", + "jsa_income_tariff_income", + "jsa_remunerative_work_hours", + "kingston_upon_thames_council_tax_reduction", + "kingston_upon_thames_council_tax_reduction_individual_non_dep_deduction", + "kingston_upon_thames_council_tax_reduction_non_dep_deductions", + "land_and_buildings_transaction_tax", + "land_based_casino_net_losses", + "land_based_fixed_odds_betting_net_losses", + "land_transaction_tax", + "land_value", + "lbtt_liable", + "lbtt_on_non_residential_property_rent", + "lbtt_on_non_residential_property_transactions", + "lbtt_on_rent", + "lbtt_on_residential_property_rent", + "lbtt_on_residential_property_transactions", + "lbtt_on_transactions", + "left_pension_route_at_legacy_closure", + "legacy_benefits_closed", + "legacy_benefits_home_letting_income", + "legacy_means_test_deducted_income_tax", + "legacy_means_test_income_tax", + "legacy_means_test_uncounted_income_tax_without_earnings", + "legacy_prescribed_accommodation_capital_exception", + "lha_renter_has_non_dependant", + "lha_renter_meets_foster_parent_condition", + "liable_for_share_of_household_rent", + "lifetime_isa_balance", + "lifetime_isa_bonus", + "lifetime_isa_countable_capital", + "lifetime_isa_first_time_buyer", + "lifetime_isa_months_since_first_payment", + "lifetime_isa_payments", + "lifetime_isa_terminally_ill", + "lifetime_isa_withdrawal_charge", + "lifetime_isa_withdrawals", + "lifetime_isa_withdrawals_towards_first_home", + "liquid_fuel_consumption", + "local_authority", + "local_bus_single_fare_share", + "local_bus_trips", + "local_bus_uncapped_single_fare", + "loss_relief", + "lottery_duty", + "lpg_kg", + "ltt_liable", + "ltt_on_non_residential_property_rent", + "ltt_on_non_residential_property_transactions", + "ltt_on_rent", + "ltt_on_residential_property_rent", + "ltt_on_residential_property_transactions", + "ltt_on_transactions", + "lump_sum_income", + "machine_games_duty", + "machine_games_higher_rate_net_takings", + "machine_games_lower_rate_net_takings", + "machine_games_standard_rate_higher_stake_net_takings", + "machine_games_standard_rate_net_takings", + "main_residence_value", + "main_residential_property_purchased", + "main_residential_property_purchased_is_first_home", + "main_residential_property_purchased_is_in_uk", + "main_residential_property_purchased_with_mortgage", + "maintenance_expenses", + "maintenance_income", + "maintenance_loan", + "maintenance_loan_candidate_benunit_income", + "maintenance_loan_eligible", + "maintenance_loan_entitled_to_benefits", + "maintenance_loan_has_sponsor", + "maintenance_loan_household_income", + "maintenance_loan_in_england_system", + "maintenance_loan_in_higher_education", + "maintenance_loan_living_arrangement", + "maintenance_loan_sponsor_income", + "make_cb_hitc_household_based", + "marginal_tax_rate", + "marginal_tax_rate_on_capital_gains", + "marginal_tax_rate_wrt_employer_cost", + "marital_status", + "market_income", + "marriage_allowance", + "marriage_allowance_appropriate_percentage", + "marriage_allowance_if_income_conditions_met", + "marriage_allowance_reduction_at_stake", + "marriage_allowance_tax_reduction", + "married_couples_allowance", + "married_couples_allowance_deduction", + "maternity_allowance", + "maternity_allowance_reported", + "max_free_entitlement_hours_used", + "maximum_extended_childcare_hours_usage", + "meals_included_in_rent", + "meets_child_tax_credit_criteria_for_targeted_childcare_entitlement", + "meets_council_tax_reduction_enhanced_disability_premium_condition", + "meets_housing_benefit_additional_earnings_disregard_conditions", + "meets_lha_overnight_care_condition", + "meets_marriage_allowance_income_conditions", + "meets_pension_credit_age_conditions", + "meets_qualifying_young_person_age_condition_for_child_benefit", + "meets_qualifying_young_person_age_condition_for_child_tax_credit", + "meets_qualifying_young_person_age_condition_for_pension_credit", + "meets_qualifying_young_person_age_condition_for_universal_credit", + "meets_qualifying_young_person_education_or_training_condition_for_child_benefit", + "meets_qualifying_young_person_education_or_training_condition_for_child_tax_credit", + "meets_qualifying_young_person_education_or_training_condition_for_pension_credit", + "meets_qualifying_young_person_education_or_training_condition_for_universal_credit", + "meets_qualifying_young_person_entry_condition_for_child_benefit", + "meets_qualifying_young_person_entry_condition_for_child_tax_credit", + "meets_qualifying_young_person_entry_condition_for_pension_credit", + "meets_qualifying_young_person_entry_condition_for_universal_credit", + "meets_qualifying_young_person_extension_period_condition_for_child_benefit", + "meets_qualifying_young_person_terminal_date_condition_for_pension_credit", + "meets_qualifying_young_person_terminal_date_condition_for_universal_credit", + "meets_savings_credit_age_requirement", + "meets_severe_disability_addition_residence_condition", + "meets_tax_credit_criteria_for_targeted_childcare_entitlement", + "meets_uc_education_condition", + "meets_uc_higher_disabled_child_condition", + "meets_uc_minimum_age_condition", + "meets_universal_credit_criteria_for_targeted_childcare_entitlement", + "meets_working_tax_credit_criteria_for_targeted_childcare_entitlement", + "merton_council_tax_reduction", + "merton_council_tax_reduction_individual_non_dep_deduction", + "merton_council_tax_reduction_non_dep_deductions", + "minimum_guarantee", + "minimum_wage", + "minimum_wage_category", + "miscellaneous_consumption", + "miscellaneous_income", + "miscellaneous_income_before_trading_allowance", + "miscellaneous_income_trading_allowance_deduction", + "monthly_domestic_energy_consumption", + "monthly_ebr_alternative_fuel_payment", + "monthly_ebr_energy_bills_credit", + "monthly_epg_consumption_level", + "monthly_epg_subsidy", + "monthly_ni_epg_subsidy", + "months_since_last_birthday", + "months_since_state_pension_age", + "mortgage", + "mortgage_capital_repayment", + "mortgage_debt", + "mortgage_interest_repayment", + "national_insurance", + "national_lottery_ticket_spending", + "natural_gas_kg", + "net_financial_wealth", + "net_income", + "net_income_before_trade_loss_relief", + "net_pay_pension_relief", + "net_wealth", + "new_state_pension", + "newham_council_tax_reduction", + "newham_council_tax_reduction_individual_non_dep_deduction", + "newham_council_tax_reduction_non_dep_deductions", + "nhs_a_and_e_spending", + "nhs_admitted_patient_spending", + "nhs_budget_change", + "nhs_outpatient_spending", + "nhs_spending", + "ni_class_1_employee", + "ni_class_1_employee_additional", + "ni_class_1_employee_primary", + "ni_class_1_employer", + "ni_class_1_income", + "ni_class_1_secondary_liable", + "ni_class_1a", + "ni_class_2", + "ni_class_3", + "ni_class_4", + "ni_class_4_liable", + "ni_class_4_loss_relief", + "ni_class_4_losses_brought_forward", + "ni_class_4_losses_carried_forward", + "ni_class_4_main", + "ni_class_4_maximum", + "ni_class_4_profits", + "ni_class_4_profits_before_losses", + "ni_class_4_trading_loss", + "ni_employee", + "ni_employer", + "ni_epg_full_rate_applies", + "ni_epg_subsidy_calculable", + "ni_liable", + "ni_self_employed", + "non_cash_isa_cash_interest", + "non_primary_residence_wealth_tax", + "non_residential_property_purchased", + "non_residential_property_secured_debt", + "non_residential_property_value", + "non_residential_rent", + "non_savings_income_after_allowances", + "non_savings_taxable_income", + "num_adults", + "num_bedrooms", + "num_carers", + "num_children", + "num_disabled_adults", + "num_disabled_children", + "num_disabled_claimants_or_partners_for_legacy_benefits", + "num_enhanced_disabled_adults", + "num_enhanced_disabled_children", + "num_enhanced_disabled_claimants_or_partners_for_legacy_benefits", + "num_relevant_children_for_housing_benefit_childcare", + "num_severely_disabled_adults", + "num_severely_disabled_children", + "num_vehicles", + "ons_tenure_type", + "original_weight", + "other_deductions", + "other_fermented_abv", + "other_fermented_draught_share", + "other_fermented_duty", + "other_fermented_litres", + "other_investment_income", + "other_local_bus_trips", + "other_public_spending_budget_change", + "other_residential_property_secured_debt", + "other_residential_property_value", + "other_spread_betting_net_losses", + "other_tax_credits", + "other_tobacco_grams_per_week", + "outpatient_visits", + "over_16", + "overlapping_state_pension", + "owned_company_capital", + "owned_company_carries_on_property_business", + "owned_company_carries_on_trade", + "owned_company_holding_value", + "owned_company_income_share", + "owned_company_intermediary_earnings_chapter", + "owned_company_intermediary_earnings_from_main_employment", + "owned_company_is_main_employment", + "owned_company_trade_assets", + "owned_land", + "owns_vehicle", + "oxford_council_tax_reduction", + "oxford_council_tax_reduction_individual_non_dep_deduction", + "oxford_council_tax_reduction_non_dep_deductions", + "oxford_council_tax_reduction_universal_credit_income", + "oxford_council_tax_reduction_universal_credit_other_income", + "parents_learning_allowance", + "parents_learning_allowance_course_eligible", + "parents_learning_allowance_dependent_children", + "parents_learning_allowance_eligible", + "parents_learning_allowance_household_income", + "partners_care_for_same_severely_disabled_person", + "partners_unused_personal_allowance", + "pawhp", + "pawhp_eligible", + "pays_rent_to_householder", + "pays_scottish_income_tax", + "pension_age_benefits_premiums", + "pension_age_severe_disability_premium", + "pension_age_winter_heating_payment", + "pension_annual_allowance", + "pension_annual_allowance_adjusted_income", + "pension_annual_allowance_chargeable_amount", + "pension_annual_allowance_taxable_lump_sum_death_benefits", + "pension_annual_allowance_threshold_income", + "pension_contributions", + "pension_contributions_for_annual_allowance", + "pension_contributions_relief", + "pension_contributions_via_bonus_sacrifice", + "pension_contributions_via_salary_sacrifice", + "pension_contributions_via_salary_sacrifice_adjusted", + "pension_contributions_via_salary_sacrifice_from_pay", + "pension_contributions_via_salary_sacrifice_pre_2015", + "pension_credit", + "pension_credit_assessable_capital", + "pension_credit_deemed_income", + "pension_credit_earnings", + "pension_credit_earnings_disregard", + "pension_credit_employment_income_tax", + "pension_credit_entitlement", + "pension_credit_income", + "pension_credit_income_tax_without_earnings", + "pension_credit_income_tax_without_employment_income", + "pension_credit_reported", + "pension_credit_reported_capital", + "pension_credit_self_employment_deductions", + "pension_credit_self_employment_income_tax", + "pension_credit_war_pension_income", + "pension_credit_widowed_parents_allowance_income", + "pension_income", + "pension_tax_allowance", + "people", + "person_benunit_id", + "person_benunit_role", + "person_bus_fare_spending", + "person_household_id", + "person_household_role", + "person_id", + "person_legacy_benefits_closed", + "person_weight", + "personal_allowance", + "personal_pension_contributions", + "personal_pension_contributions_tax", + "personal_rent", + "petrol_litres", + "petrol_price", + "petrol_spending", + "pip", + "pip_dl", + "pip_dl_category", + "pip_dl_points", + "pip_m", + "pip_m_category", + "pip_m_points", + "pip_phase_in_draw", + "plan_1_interest_rate", + "plan_2_interest_rate", + "plan_4_interest_rate", + "plan_5_interest_rate", + "pool_betting_duty", + "pool_betting_net_receipts", + "post_tax_income", + "postgraduate_interest_rate", + "poverty_gap", + "poverty_gap_ahc", + "poverty_gap_bhc", + "poverty_line", + "poverty_line_ahc", + "poverty_line_bhc", + "poverty_threshold_ahc", + "poverty_threshold_bhc", + "poverty_threshold_fye2011_ahc", + "poverty_threshold_fye2011_bhc", + "pre_budget_change_household_benefits", + "pre_budget_change_household_net_income", + "pre_budget_change_household_tax", + "pre_budget_change_ons_household_income_decile", + "private_pension_income", + "private_pension_wealth", + "private_school_vat", + "private_school_vat_change", + "private_transfer_income", + "property_allowable_expenses", + "property_allowance_deduction", + "property_allowance_deduction_if_used", + "property_finance_cost_relief", + "property_finance_costs", + "property_finance_costs_brought_forward", + "property_finance_costs_carried_forward", + "property_finance_costs_relievable", + "property_finance_costs_relieved", + "property_income", + "property_income_after_finance_costs", + "property_income_tax", + "property_purchased", + "property_receipts_within_allowance", + "property_rental_income", + "property_wealth", + "qualifies_for_apprentice_minimum_wage", + "rail_subsidy_spending", + "rail_usage", + "raw_person_weight", + "real_hbai_household_net_income", + "real_hbai_household_net_income_ahc", + "real_household_net_income", + "real_household_net_income_ahc", + "received_allowances", + "received_allowances_dividend_income", + "received_allowances_earned_income", + "received_allowances_savings_income", + "receives_benefits_in_own_right", + "receives_carer_benefit", + "receives_carer_support_payment", + "receives_carers_allowance", + "receives_enhanced_disability_premium_qualifying_benefit", + "receives_enhanced_pip_dl", + "receives_highest_dla_sc", + "receives_income_support_in_own_right", + "receives_limited_capability_for_work_credits", + "receives_severe_disability_addition_qualifying_benefit", + "receives_severe_disability_premium_qualifying_benefit", + "receives_uc_carer_element", + "receives_uc_with_limited_capability_for_work", + "recreation_consumption", + "reduced_rate_vat_consumption", + "region", + "relation_type", + "relative_capital_gains_mtr_change", + "relative_capital_gains_retention_rate_change", + "relative_income_change", + "relative_wage_change", + "remote_gaming_duty", + "remote_gaming_net_losses", + "remote_other_betting_net_losses", + "remote_uk_horseracing_betting_net_losses", + "rent", + "rent_a_room_income_tax", + "rent_a_room_income_tax_after_reductions", + "rent_a_room_income_tax_without_earnings", + "rent_a_room_limit", + "rent_a_room_receipts", + "rent_a_room_relief", + "rent_from_boarders_and_lodgers", + "rent_paid_as_boarder", + "rent_paid_as_lodger", + "residential_property_value", + "restaurants_and_hotels_consumption", + "role", + "salary_sacrifice_broad_base_haircut", + "salary_sacrifice_pension_ni_employee", + "salary_sacrifice_pension_ni_employer", + "salary_sacrifice_pension_ni_excess", + "salary_sacrifice_returned_to_income", + "savings", + "savings_allowance", + "savings_credit", + "savings_credit_income", + "savings_income_tax", + "savings_interest_income", + "savings_starter_rate_income", + "scottish_carer_supplement", + "scottish_child_payment", + "scottish_funded_early_learning_childcare_eligible", + "scottish_funded_early_learning_childcare_start_date_reached", + "sda", + "sda_reported", + "sdlt_liable", + "sdlt_on_non_residential_property_rent", + "sdlt_on_non_residential_property_transactions", + "sdlt_on_rent", + "sdlt_on_residential_property_rent", + "sdlt_on_residential_property_transactions", + "sdlt_on_transactions", + "self_employment_gross_receipts", + "self_employment_income", + "severe_disability_minimum_guarantee_addition", + "severe_disability_premium", + "severe_disability_premium_before_non_dependant_test", + "severe_disability_premium_joint_occupier_exclusion_applies", + "share_like_capital", + "share_of_household_rent", + "shareholding", + "sic_industry_division", + "simulated_council_tax", + "simulated_council_tax_less_discounts", + "simulated_council_tax_reduction_benunit", + "soc2020_major_group", + "soc2020_sub_major_group", + "social_security_income", + "solid_fuel_consumption", + "sparkling_cider_abv", + "sparkling_cider_draught_share", + "sparkling_cider_duty", + "sparkling_cider_litres", + "spi_imputed", + "spirits_abv", + "spirits_draught_share", + "spirits_duty", + "spirits_litres", + "spousal_maintenance_income", + "squared_poverty_gap_ahc", + "squared_poverty_gap_bhc", + "ssmg", + "ssmg_reported", + "stamp_duty_land_tax", + "standard_minimum_guarantee", + "stands_as_sole_owner_or_partner_of_company", + "state_pension", + "state_pension_age", + "state_pension_age_addition", + "state_pension_age_date", + "state_pension_credit_qualifying_age", + "state_pension_reported", + "state_pension_reported_excluding_age_addition", + "state_pension_type", + "statutory_maternity_pay", + "statutory_paternity_pay", + "statutory_sick_pay", + "stocks_and_shares_isa", + "stocks_and_shares_isa_balance", + "stocks_and_shares_isa_countable_capital", + "stocks_and_shares_isa_subscriptions", + "structural_insurance_payments", + "student_loan_balance", + "student_loan_interest_rate", + "student_loan_plan", + "student_loan_repayment", + "student_loan_repayment_rate", + "student_loan_repayments", + "student_loans", + "student_payments", + "sublet_income", + "substitution_elasticity_lsr", + "targeted_childcare_entitlement", + "targeted_childcare_entitlement_eligible", + "tax", + "tax_band", + "tax_credit_award", + "tax_credits", + "tax_credits_applicable_income", + "tax_credits_current_year_income", + "tax_credits_reduction", + "tax_free_childcare", + "tax_free_childcare_caring_or_incapacity_benefit", + "tax_free_childcare_child_age_eligible", + "tax_free_childcare_eligible", + "tax_free_childcare_eligible_declaration_periods", + "tax_free_childcare_eligible_without_universal_credit", + "tax_free_childcare_expected_declaration_period_income", + "tax_free_childcare_meets_income_requirements", + "tax_free_childcare_meets_uk_connection", + "tax_free_childcare_on_adoption_leave", + "tax_free_childcare_on_carers_leave", + "tax_free_childcare_on_qualifying_leave", + "tax_free_childcare_on_shared_parental_leave", + "tax_free_childcare_program_eligible", + "tax_free_childcare_qualifying_child", + "tax_free_childcare_regarded_as_in_paid_work", + "tax_free_childcare_self_employment_start_up_period", + "tax_free_childcare_spend_routed_share", + "tax_free_childcare_treated_as_in_work", + "tax_free_childcare_uses_qualifying_provider", + "tax_free_childcare_without_universal_credit", + "tax_free_childcare_work_condition", + "tax_free_savings_income", + "tax_modelling", + "tax_reported", + "taxable_dividend_income", + "taxable_employment_income", + "taxable_miscellaneous_income", + "taxable_pension_income", + "taxable_property_income", + "taxable_property_income_after_allowances", + "taxable_rent_a_room_income", + "taxable_savings_interest_income", + "taxable_self_employment_income", + "taxable_social_security_income", + "taxed_dividend_income", + "taxed_income", + "taxed_savings_income", + "tenure_type", + "tobacco_duty", + "total_income", + "total_income_charged_to_tax", + "total_national_insurance", + "total_pension_income", + "total_wealth", + "trade_loss_relief_against_general_income", + "trade_loss_relief_against_savings_and_dividends", + "trading_allowance_claim_status", + "trading_allowance_deduction", + "trading_loss", + "transport_consumption", + "travel_grant", + "travel_grant_abroad_placement", + "travel_grant_clinical_placement", + "travel_grant_eligible", + "travel_grant_eligible_expenses", + "travel_grant_household_income", + "travel_grant_income_assessed_support", + "travel_grant_receives_means_tested_nhs_bursary", + "tv_licence", + "tv_licence_discount", + "tv_licence_free_licence_share", + "tv_licence_required", + "two_child_limit_payment", + "uc_LCWRA_element", + "uc_LHA_cap", + "uc_advance_repayment_amount", + "uc_assessable_capital", + "uc_award_carries_deductions", + "uc_benefit_cap", + "uc_benefit_cap_earnings_exception_threshold", + "uc_benefit_cap_reduction", + "uc_benefit_cap_reduction_after_floor", + "uc_benefit_cap_welfare_benefits", + "uc_carer_element", + "uc_carer_element_included_for_claimant", + "uc_child_element", + "uc_child_index", + "uc_child_limit_disregarded", + "uc_child_limit_exception", + "uc_child_limit_position", + "uc_childcare_element", + "uc_childcare_element_claimed", + "uc_childcare_element_eligible_children", + "uc_childcare_treated_as_in_paid_work", + "uc_childcare_work_condition", + "uc_claimant_company_holding_disregard", + "uc_company_capital", + "uc_company_gainful_self_employment", + "uc_company_holding_disregard", + "uc_company_intermediary_exclusion_applies", + "uc_company_owner_treatment_applies", + "uc_company_self_employed_earnings", + "uc_deduction_combination", + "uc_deduction_random_draw", + "uc_deduction_rate", + "uc_deduction_type_random_draw", + "uc_deductions", + "uc_disability_elements", + "uc_earned_income", + "uc_earned_income_before_work_allowance", + "uc_expected_hours", + "uc_has_deduction", + "uc_has_offer_of_paid_work_starting_by_end_of_next_assessment_period", + "uc_housing_costs_element", + "uc_income_reduction", + "uc_income_tax_on_earnings", + "uc_income_tax_on_trade", + "uc_individual_child_element", + "uc_individual_disabled_child_element", + "uc_individual_earned_income", + "uc_individual_earned_income_before_mif", + "uc_individual_non_dep_deduction", + "uc_individual_non_dep_deduction_eligible", + "uc_individual_severely_disabled_child_element", + "uc_is_adopter_in_first_year", + "uc_is_child_born_before_child_limit", + "uc_is_child_limit_affected", + "uc_is_excepted_from_education_condition", + "uc_is_foster_parent_or_new_friend_or_family_carer", + "uc_is_in_gainful_self_employment", + "uc_is_in_pregnancy_or_post_confinement_period", + "uc_is_in_startup_period", + "uc_is_ineligible_partner", + "uc_is_responsible_carer", + "uc_is_responsible_foster_parent_of_child_under_one", + "uc_is_student_with_no_work_related_requirements", + "uc_is_temporarily_absent_from_claimant_household", + "uc_latent_deduction_rate", + "uc_limited_capability_for_WRA", + "uc_limited_capability_for_work", + "uc_maximum_amount", + "uc_maximum_childcare_element_amount", + "uc_maximum_reduction", + "uc_member_of_couple_claims_as_single_person", + "uc_mif_applies", + "uc_migrated", + "uc_minimum_income_floor", + "uc_minimum_income_floor_gross", + "uc_minimum_income_floor_income_tax", + "uc_minimum_income_floor_national_insurance", + "uc_national_insurance_on_earnings", + "uc_national_insurance_on_trade", + "uc_new_claimant_health_element_draw", + "uc_non_dep_deduction_exempt", + "uc_non_dep_deductions", + "uc_non_dep_deductions_renter_exempt", + "uc_non_dep_receives_pension_credit", + "uc_non_dependants_counted", + "uc_non_residential_property_capital", + "uc_other_residential_property_capital", + "uc_property_capital", + "uc_receives_attendance_allowance", + "uc_receives_new_claimant_health_element", + "uc_receiving_education", + "uc_reported_capital", + "uc_standard_allowance", + "uc_standard_allowance_claimant_type", + "uc_tariff_income", + "uc_trading_losses_set_against_profits", + "uc_unable_to_provide_childcare", + "uc_unearned_carer_support_payment", + "uc_unearned_income", + "uc_work_allowance", + "uc_work_related_group_apart_from_earnings", + "uc_youngest_child_age", + "uk_total_alcohol_and_tobacco_consumption", + "uk_total_clothing_and_footwear_consumption", + "uk_total_communication_consumption", + "uk_total_corporate_wealth", + "uk_total_education_consumption", + "uk_total_food_and_non_alcoholic_beverages_consumption", + "uk_total_health_consumption", + "uk_total_household_furnishings_consumption", + "uk_total_housing_water_and_electricity_consumption", + "uk_total_miscellaneous_consumption", + "uk_total_private_pension_wealth", + "uk_total_recreation_consumption", + "uk_total_restaurants_and_hotels_consumption", + "uk_total_transport_consumption", + "uncapped_BRMA_LHA_rate", + "unit_and_investment_trusts", + "universal_childcare_entitlement", + "universal_childcare_entitlement_eligible", + "universal_credit", + "universal_credit_pre_benefit_cap", + "universal_credit_reported", + "unused_pension_annual_allowance", + "unused_personal_allowance", + "uses_energy_prepayment_meter", + "uses_property_allowance", + "uses_trading_allowance", + "vat", + "vat_change", + "vehicle_excise_duty", + "wales_childcare_offer", + "wales_childcare_offer_eligible", + "wales_childcare_offer_parent_condition", + "wales_childcare_offer_per_child", + "wales_childcare_offer_qualifying_child", + "war_widows_pension", + "war_widows_pension_reported", + "warm_home_discount", + "warm_home_discount_random_draw", + "water_and_sewerage_charges", + "wealth_tax", + "weekly_childcare_expenses", + "weekly_hours", + "westminster_council_tax_reduction", + "westminster_council_tax_reduction_individual_non_dep_deduction", + "westminster_council_tax_reduction_non_dep_deductions", + "widowed_parents_allowance", + "widowed_parents_allowance_reported", + "wine_abv", + "wine_draught_share", + "wine_duty", + "wine_litres", + "winter_fuel_allowance", + "winter_fuel_allowance_reported", + "winter_fuel_payment", + "winter_fuel_payment_charge", + "winter_fuel_payment_charge_ceiling", + "winter_fuel_payment_eligible", + "working_age_benefits_premiums", + "working_tax_credit", + "working_tax_credit_pre_minimum", + "working_tax_credit_reported", + "working_tax_credit_run_on", + "would_claim_CTC", + "would_claim_IS", + "would_claim_WTC", + "would_claim_adult_dependants_grant", + "would_claim_bursary_fund_16_to_19", + "would_claim_care_to_learn", + "would_claim_carers_allowance", + "would_claim_child_benefit", + "would_claim_childcare_grant", + "would_claim_council_tax_reduction", + "would_claim_disabled_students_allowance", + "would_claim_extended_childcare", + "would_claim_housing_benefit", + "would_claim_marriage_allowance", + "would_claim_parents_learning_allowance", + "would_claim_pc", + "would_claim_scp", + "would_claim_student_loan", + "would_claim_targeted_childcare", + "would_claim_tfc", + "would_claim_travel_grant", + "would_claim_uc", + "would_claim_uc_at_legacy_closure", + "would_claim_uc_childcare", + "would_claim_universal_childcare", + "would_claim_wales_childcare_offer", + "would_evade_tv_licence_fee", + "would_receive_warm_home_discount", + "wtc_entitlement", + "youngest_adult_age", + "youngest_child_age", + "youngest_child_age_for_legacy_benefits", + "youngest_claimant_or_partner_age" + ], + "schema_version": 1, + "snapshot_date": "2026-11-23" +} diff --git a/tools/build_uk_firms.py b/tools/build_uk_firms.py new file mode 100644 index 0000000000..61042e9f55 --- /dev/null +++ b/tools/build_uk_firms.py @@ -0,0 +1,100 @@ +"""Build the UK firm table locally (microcosm#1705). + +Runs ``microcosm.build.uk_runtime.firm_build.build_uk_firm_dataset`` on the +processed ONS/HMRC tables in ``--processed-dir`` and writes ``uk_firms.parquet`` +and ``uk_firms.receipt.json`` to ``--out-dir``. Nothing is published or uploaded. + +``--rules`` picks the VAT rules and has no default: + +- ``policyengine-uk`` runs policyengine-uk's firm entity + (``PolicyEngineUKFirmRules``), which needs a policyengine-uk that includes + PolicyEngine/policyengine-uk#2940 (the ``uk`` extra's release does not); +- ``axiom`` runs a compiled Axiom UK VAT RuleSpec artifact, named by + ``--axiom-artifact``, through ``axiom-rules-engine``. +""" + +from __future__ import annotations + +import argparse +import sys +from pathlib import Path + +from microcosm.build.uk_runtime.firm_build import build_uk_firm_dataset +from microcosm.build.uk_runtime.firm_generation import UKFirmGenerationConfig +from microcosm.build.uk_runtime.firm_rules import UKFirmRules + +RULES_CHOICES = ("policyengine-uk", "axiom") +DEFAULT_DATA_VINTAGE = "2024-25" + + +def _parse_args(argv: list[str] | None) -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--processed-dir", type=Path, required=True) + parser.add_argument("--out-dir", type=Path, required=True) + parser.add_argument("--rules", choices=RULES_CHOICES, required=True) + parser.add_argument( + "--axiom-artifact", + type=Path, + help="compiled Axiom UK VAT RuleSpec artifact (with --rules axiom)", + ) + parser.add_argument("--data-vintage", default=DEFAULT_DATA_VINTAGE) + parser.add_argument("--seed", type=int, default=42) + parser.add_argument( + "--fast", + action="store_true", + help="thin the candidate draw as UKFirmGenerationConfig.fast does", + ) + parser.add_argument("--n-iterations", type=int) + args = parser.parse_args(argv) + if args.rules == "axiom" and args.axiom_artifact is None: + parser.error("--rules axiom needs --axiom-artifact") + if args.rules != "axiom" and args.axiom_artifact is not None: + parser.error("--axiom-artifact applies only with --rules axiom") + return args + + +def _rules(args: argparse.Namespace) -> UKFirmRules: + if args.rules == "axiom": + from microcosm.build.uk_runtime.firm_generation import AxiomVATRuleEvaluator + from microcosm.build.uk_runtime.firm_rules import LegacyVATEvaluatorRules + + return LegacyVATEvaluatorRules( + AxiomVATRuleEvaluator(artifact_path=args.axiom_artifact) + ) + from microcosm.build.uk_runtime.firm_policyengine_uk_rules import ( + PolicyEngineUKFirmRules, + ) + + return PolicyEngineUKFirmRules() + + +def _config(args: argparse.Namespace, rules: UKFirmRules) -> UKFirmGenerationConfig: + overrides: dict[str, object] = {"seed": args.seed, "firm_rules": rules} + if args.n_iterations is not None: + overrides["n_iterations"] = args.n_iterations + if args.fast: + config = UKFirmGenerationConfig.fast(**overrides) + else: + config = UKFirmGenerationConfig(**overrides) + return config.with_vintage(args.data_vintage) + + +def main(argv: list[str] | None = None) -> int: + args = _parse_args(argv) + rules = _rules(args) + built = build_uk_firm_dataset( + processed_dir=args.processed_dir, + output_dir=args.out_dir, + rules=rules, + config=_config(args, rules), + ) + receipt = built["receipt"] + print( + f"Wrote {receipt['output']['rows']} firm rows to {built['table_path']}" + f"\nWrote the receipt to {built['receipt_path']}" + ) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/compare_uk_firm_taxes_to_receipts.py b/tools/compare_uk_firm_taxes_to_receipts.py new file mode 100644 index 0000000000..2683c208fc --- /dev/null +++ b/tools/compare_uk_firm_taxes_to_receipts.py @@ -0,0 +1,269 @@ +#!/usr/bin/env python3 +"""Compare weighted UK firm tax totals with official 2024-25 receipts. + +Another process runs policyengine-uk on the generated firms and writes the +weighted totals as JSON:: + + { + "period": 2024, + "totals": {"firm_vat": 1.7e11, ...}, # GBP, summed with firm_weight + "inputs_populated": {"firm_vat": true, ...}, # false: the tax's inputs are unset + "note": "free text" + } + +This tool sets those totals beside the official figures in +``tests/fixtures/uk/firm_tax_receipts_2024_25.csv`` (HMRC cash receipts and +MHCLG NNDR3, each with its URL, edition and access date) and prints a markdown +table: model total, official figure, gap (model less official, and ratio) and +the reasons the two may not measure the same thing. + +Usage:: + + uv run --no-sync python tools/compare_uk_firm_taxes_to_receipts.py \ + --taxes-json firm_tax_totals.json [--out comparison.md] + +Every tax in ``totals`` needs an explicit true/false ``inputs_populated`` flag; +the tool refuses the JSON otherwise. A tax whose inputs are not populated prints +"input not populated" in place of a gap, never a -100% shortfall. A tax with no official figure prints "no official +figure fetched". The comparison is a diagnostic, not a calibration target. +""" + +from __future__ import annotations + +import argparse +import json +import sys +from collections.abc import Mapping, Sequence +from pathlib import Path +from typing import Any + +from microcosm.build.firms.receipts import ( + INPUT_NOT_POPULATED as INPUT_NOT_POPULATED, +) +from microcosm.build.firms.receipts import ( + NO_MODEL_TOTAL as NO_MODEL_TOTAL, +) +from microcosm.build.firms.receipts import ( + NO_OFFICIAL_FIGURE as NO_OFFICIAL_FIGURE, +) +from microcosm.build.firms.receipts import ( + RECEIPT_SOURCE_COLUMNS, + ComparisonRow, + Receipt, + build_comparison_rows, + compare_total, + render_comparison_markdown, +) +from microcosm.build.firms.receipts import read_receipts as _read_receipts + +REPOSITORY_ROOT = Path(__file__).resolve().parents[1] +DEFAULT_RECEIPTS = ( + REPOSITORY_ROOT + / "packages" + / "microcosm-build" + / "tests" + / "fixtures" + / "uk" + / "firm_tax_receipts_2024_25.csv" +) + +REQUIRED_COLUMNS = ( + "tax", + "official_value_gbp", + "period", + "measure", + "source_publisher", + "source_title", + "edition", + "url", + "accessed", + "note", +) +#: Columns every row with an official figure must fill. +SOURCE_COLUMNS = RECEIPT_SOURCE_COLUMNS + + +VAT_IN_SAMPLE_CAVEAT = ( + "In-sample check: the firm generator is calibrated to HMRC VAT liability " + "by turnover band and sector, so agreement here does not validate the model." +) + +PAYBILL_ASSUMED_CAVEAT = ( + "Assumed input, not a validation: firm_paybill is not observed, and this " + "build does not set it. Any total here rests on a paybill assumed outside " + "the build, so agreement or disagreement reflects that assumption, not the " + "model." +) + +PAY_SPLIT_UNSET_CAVEAT = ( + "The pay-distribution inputs (firm_employees_below_secondary_threshold, " + "firm_paybill_below_secondary_threshold) are unset, so policyengine-uk " + "takes the Class 1 base as paybill less headcount times the secondary " + "threshold (an average-pay approximation), which understates the base " + "where some staff earn below the threshold." +) + +#: What policyengine-uk's variable measures, and how it differs from the +#: official measure in the receipts CSV. Read with the CSV's ``measure``. +MODEL_CAVEATS: Mapping[str, str] = { + "firm_vat": ( + VAT_IN_SAMPLE_CAVEAT + + " Model: accrued VAT liability of generated firms; official: HMRC cash " + "receipts for all VAT, whose timing and coverage differ from the " + "liability of firms in the ONS frame." + ), + "firm_employer_ni": ( + PAYBILL_ASSUMED_CAVEAT + + " " + + PAY_SPLIT_UNSET_CAVEAT + + " Model: employer Class 1 secondary NICs after the Employment " + "Allowance, accrued; official: cash, and also includes Class 1A " + "(benefits in kind), so the official figure is larger in concept. " + "Employment Allowance: firm_is_single_director_company is unset, so no " + "firm is excluded as a single-director company and the allowance is " + "overstated. Employers outside the generated VAT/PAYE frame (e.g. " + "households employing domestic staff) pay into the official total." + ), + "apprenticeship_levy": ( + PAYBILL_ASSUMED_CAVEAT + + " Model: accrued levy liability of generated firms; official: cash " + "receipts from all employers, including those outside the generated " + "VAT/PAYE frame." + ), + "corporation_tax": ( + "Model: onshore CT after the R&D expenditure credit, accrued, excluding " + "the bank surcharge; official: onshore cash receipts gross of provisional " + "tax credits (offshore ring-fence CT removed, Bank Surcharge and Bank Levy " + "outside), with instalment timing that spans financial years." + ), + "bank_surcharge": ( + "Model: surcharge on taxable profit above the allowance, accrued; " + "official: cash receipts. Bank Levy is not compared." + ), + "firm_business_rates": ( + "England only on both sides: the model gives 0 outside England. Model: " + "gross rates less reliefs, one aggregate property per firm; official: " + "NNDR3 gross rates payable less reliefs, before transitional " + "arrangements, and including non-firm ratepayers (e.g. public bodies)." + ), +} + + +#: Taxes computed from the assumed firm_paybill. +PAYBILL_TAXES = frozenset({"firm_employer_ni", "apprenticeship_levy"}) + + +def read_receipts(path: Path) -> dict[str, Receipt]: + """Read the receipts CSV, refusing missing columns or unsourced figures.""" + + return _read_receipts(path, name_column="tax", value_column="official_value_gbp") + + +def financial_year(period: int) -> str: + """2024 -> "2024-25", the UK financial year policyengine-uk's period starts.""" + + return f"{period}-{(period + 1) % 100:02d}" + + +def format_gbp(value: float) -> str: + """GBP in billions with a sign, e.g. -1.23bn -> "-£1.23bn".""" + + sign = "-" if value < 0 else "" + return f"{sign}£{abs(value) / 1e9:,.2f}bn" + + +def _reasons(tax: str, receipt: Receipt | None) -> list[str]: + """Why the model total and the official figure may differ, in order.""" + + reasons = [] + if receipt is not None and receipt.measure: + reasons.append(f"Official measure: {receipt.measure}.") + if tax in MODEL_CAVEATS: + reasons.append(MODEL_CAVEATS[tax]) + if tax == "firm_vat" and VAT_IN_SAMPLE_CAVEAT not in " ".join(reasons): + reasons.insert(0, VAT_IN_SAMPLE_CAVEAT) + if tax in PAYBILL_TAXES and PAYBILL_ASSUMED_CAVEAT not in " ".join(reasons): + reasons.insert(0, PAYBILL_ASSUMED_CAVEAT) + return reasons + + +def compare_tax( + tax: str, + *, + model_total: float | None, + populated: bool, + receipt: Receipt | None, +) -> ComparisonRow: + """One table row. No gap or percentage unless both sides are real figures.""" + + return compare_total( + tax, + model_total=model_total, + populated=populated, + official_value=None if receipt is None else receipt.official_value, + reasons=_reasons(tax, receipt), + format_value=format_gbp, + ) + + +def build_rows( + taxes: Mapping[str, Any], receipts: Mapping[str, Receipt] +) -> list[ComparisonRow]: + """Rows in receipts order, then any model-only taxes.""" + + return build_comparison_rows( + taxes.get("totals", {}), + taxes.get("inputs_populated", {}), + receipts, + reasons_for=_reasons, + format_value=format_gbp, + ) + + +def render_markdown( + rows: Sequence[ComparisonRow], + receipts: Mapping[str, Receipt], + *, + period: str, + note: str | None = None, +) -> str: + return render_comparison_markdown( + rows, + receipts, + title=f"UK firm taxes against official receipts, {period}", + name_header="Tax", + note=note, + ) + + +def compare(taxes: Mapping[str, Any], receipts: Mapping[str, Receipt]) -> str: + """The markdown report for a taxes JSON object and the receipts.""" + + period = financial_year(int(taxes["period"])) + periods = {r.period for r in receipts.values()} + if periods != {period}: + raise ValueError( + f"model period {period} does not match receipts {sorted(periods)}" + ) + return render_markdown( + build_rows(taxes, receipts), receipts, period=period, note=taxes.get("note") + ) + + +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--taxes-json", type=Path, required=True) + parser.add_argument("--receipts", type=Path, default=DEFAULT_RECEIPTS) + parser.add_argument("--out", type=Path, help="also write the markdown here") + args = parser.parse_args(argv) + + taxes = json.loads(args.taxes_json.read_text(encoding="utf-8")) + report = compare(taxes, read_receipts(args.receipts)) + sys.stdout.write(report) + if args.out is not None: + args.out.write_text(report, encoding="utf-8") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/snapshot_policyengine_uk_firm_inputs.py b/tools/snapshot_policyengine_uk_firm_inputs.py new file mode 100644 index 0000000000..fba29ca624 --- /dev/null +++ b/tools/snapshot_policyengine_uk_firm_inputs.py @@ -0,0 +1,193 @@ +"""Snapshot policyengine-uk's firm variables for engine-free tests. + +Reads a policyengine-uk checkout's source with ``ast`` (it never imports +``policyengine_uk``), through ``microcosm.build.firms.read_entity_variables``, +and writes, as sorted JSON: + +- every ``Variable`` subclass whose ``entity`` is ``Firm``, anywhere in the + package except its ``tests/`` directory, with its value type, unit, default + value, enum members (the ``possible_values`` class resolved through the + defining module's imports, so ``Region`` comes from + ``variables/household/demographic/geography.py``), definition period, + whether it has a formula (a ``formula`` or ``formula_*`` method or + attribute, ``adds`` or ``subtracts``) and its file relative to the package; +- the formula-less firm variables, which a dataset sets as inputs; +- every policyengine-uk variable name, and which of Microcosm's own firm + columns (``MICROCOSM_ONLY_COLUMNS``) collide with one; +- the checkout's HEAD commit, whether its working tree is dirty, the pull + request the firm entity comes from and the snapshot date. + +A variable created at runtime (by a reform or a loop) is not in the source +and so not in the snapshot. + +``--check`` regenerates the snapshot and fails if anything but the snapshot +date differs from ``--out``, so a moved policyengine-uk HEAD or a changed firm +variable shows up before the fixture is refreshed. + +The tool refuses a checkout with a dirty working tree, since its HEAD commit +would not identify the source it read; ``--allow-dirty`` overrides that for a +local look (the snapshot then records ``dirty`` true). + +Usage:: + + uv run --no-sync python tools/snapshot_policyengine_uk_firm_inputs.py \\ + --policyengine-uk-root ../policyengine-uk \\ + --out packages/microcosm-build/tests/fixtures/uk/policyengine_uk_firm_inputs.json +""" + +from __future__ import annotations + +import argparse +import json +import os +import subprocess +import sys +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +from microcosm.build.firms import read_entity_variables + +SCHEMA_VERSION = 1 +PACKAGE_NAME = "policyengine_uk" +FIRM_ENTITY = "Firm" +#: The policyengine-uk pull request that adds the firm entity. +POLICYENGINE_UK_PULL_REQUEST = "PolicyEngine/policyengine-uk#2940" + +#: Columns Microcosm's firm table carries that are not policyengine-uk inputs. +#: ``ons_legal_status`` and ``ons_region_code`` arrive with the region and +#: legal-status draws (a later PR of the #1706 split); they are checked here +#: already so the committed snapshot does not change when they do. +#: None may share a name with a policyengine-uk variable, or a dataset load +#: would read it as one. +MICROCOSM_ONLY_COLUMNS = ( + "in_frame", + "vat_scope", + "vat_registered", + "base_weight", + "data_vintage", + "source_firm_id", + "source_firm_key", + "ons_legal_status", + "ons_region_code", +) + +#: Fields ``--check`` ignores: the date the snapshot was taken. +_VOLATILE_FIELDS = ("snapshot_date",) + + +def _git(root: Path, *args: str) -> str: + environment = dict(os.environ) + local = subprocess.run( + ["git", "rev-parse", "--local-env-vars"], + capture_output=True, + text=True, + check=True, + ).stdout.split() + for name in local: + environment.pop(name, None) + return subprocess.run( + ["git", "-C", str(root), *args], + capture_output=True, + text=True, + check=True, + env=environment, + ).stdout + + +def build_snapshot( + root: Path, *, snapshot_date: str, allow_dirty: bool = False +) -> dict[str, Any]: + """The firm-input snapshot of the policyengine-uk checkout at ``root``. + + Raises ``ValueError`` when the checkout's working tree is dirty, unless + ``allow_dirty``. + """ + + package_dir = root / PACKAGE_NAME + if not package_dir.is_dir(): + raise ValueError(f"{root} holds no {PACKAGE_NAME} package.") + dirty = bool(_git(root, "status", "--porcelain").strip()) + if dirty and not allow_dirty: + raise ValueError( + f"{root} has a dirty working tree; commit or stash the changes, " + "or pass --allow-dirty." + ) + read = read_entity_variables(package_dir, entity=FIRM_ENTITY) + variable_names = set(read.variable_names) + firm_variables = read.variables + inputs = read.input_names + return { + "collisions": sorted(set(MICROCOSM_ONLY_COLUMNS) & variable_names), + "firm_input_names": inputs, + "firm_variables": firm_variables, + "microcosm_only_columns_checked": sorted(MICROCOSM_ONLY_COLUMNS), + "policyengine_uk": { + "dirty": dirty, + "head_commit": _git(root, "rev-parse", "HEAD").strip(), + "pull_request": POLICYENGINE_UK_PULL_REQUEST, + }, + "policyengine_uk_variable_names": sorted(variable_names), + "schema_version": SCHEMA_VERSION, + "snapshot_date": snapshot_date, + } + + +def render(snapshot: dict[str, Any]) -> str: + return json.dumps(snapshot, indent=2, sort_keys=True) + "\n" + + +def _stable(snapshot: dict[str, Any]) -> dict[str, Any]: + return { + key: value for key, value in snapshot.items() if key not in _VOLATILE_FIELDS + } + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--policyengine-uk-root", type=Path, required=True) + parser.add_argument("--out", type=Path, required=True) + parser.add_argument( + "--check", + action="store_true", + help="Fail if --out differs from a fresh snapshot (ignoring its date).", + ) + parser.add_argument( + "--allow-dirty", + action="store_true", + help="Read a policyengine-uk checkout with a dirty working tree.", + ) + args = parser.parse_args(argv) + try: + snapshot = build_snapshot( + args.policyengine_uk_root.resolve(), + snapshot_date=datetime.now(UTC).date().isoformat(), + allow_dirty=args.allow_dirty, + ) + except ValueError as error: + print(error, file=sys.stderr) + return 1 + if args.check: + committed = json.loads(args.out.read_text(encoding="utf-8")) + if _stable(committed) != _stable(snapshot): + changed = sorted( + key + for key in set(_stable(committed)) | set(_stable(snapshot)) + if committed.get(key) != snapshot.get(key) + ) + print(f"{args.out} is stale; changed fields: {changed}", file=sys.stderr) + return 1 + print(f"{args.out} matches the policyengine-uk checkout.") + return 0 + args.out.write_text(render(snapshot), encoding="utf-8") + inputs = snapshot["firm_input_names"] + print( + f"Wrote {args.out}: {len(snapshot['firm_variables'])} firm variables, " + f"{len(inputs)} inputs, HEAD {snapshot['policyengine_uk']['head_commit']}" + f"{' (dirty)' if snapshot['policyengine_uk']['dirty'] else ''}." + ) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/uk_firm_paper_parity.py b/tools/uk_firm_paper_parity.py new file mode 100644 index 0000000000..4921e8122b --- /dev/null +++ b/tools/uk_firm_paper_parity.py @@ -0,0 +1,782 @@ +#!/usr/bin/env python3 +"""Compare Microcosm's experimental UK firm generator with the firm-microsim paper. + +The paper (PolicyEngine/firm-microsim-paper) generates a synthetic UK firm +population from processed ONS and HMRC tables. Microcosm ports that generator +into ``microcosm.build.uk_runtime.firm_generation``. Parity is distributional, +not row or weight identity: the two generators use different random streams +and different calibration losses (the paper minimises symmetric relative error +with dropout and an L1 penalty; Microcosm minimises capped MAPE). + +Usage:: + + # Compare Microcosm (full census draw) with the committed paper reference. + uv run --no-sync python tools/uk_firm_paper_parity.py --full + + # Thinned Microcosm run (window 0.30, tails 0.05, the paper's fast preset). + uv run --no-sync python tools/uk_firm_paper_parity.py --fast + + # Also re-run the paper generator from a checkout and compare with that. + uv run --no-sync python tools/uk_firm_paper_parity.py --full \ + --paper-root ../firm-microsim-paper + +``--paper-root`` runs the paper inside its own environment +(``/.venv/bin/python`` when present, else ``uv run --project``) +by invoking this file's ``paper-extract`` subcommand there. The committed +``paper_reference_2024_25.json`` fixture was assembled by hand from one +``paper-extract`` run per mode; ``.provenance.json`` records the commands. + +VAT rules: Microcosm keeps VAT law out of the generator and requires a rules +object. ``--rules paper-formula`` supplies a PARITY-ONLY double defined in this +file that reproduces the paper's standard-rate approximation, +0.20 x (turnover - inputs). It is not a statement of UK VAT law and is not +shipped in ``src``. +""" + +from __future__ import annotations + +import argparse +import json +import os +import subprocess +import sys +import time +from collections.abc import Mapping +from dataclasses import dataclass, fields +from pathlib import Path +from typing import Any + +import numpy as np +import pandas as pd + +REPOSITORY_ROOT = Path(__file__).resolve().parents[1] +FIXTURE_DIR = ( + REPOSITORY_ROOT + / "packages" + / "microcosm-build" + / "tests" + / "fixtures" + / "uk" + / "firm_2024_25" +) +REFERENCE_FILE = "paper_reference_2024_25.json" +VINTAGE = "2024-25" +THRESHOLD_K = 90.0 +SEED = 42 +PAPER_VAT_RATE = 0.20 + +HMRC_BANDS: tuple[str, ...] = ( + "Negative_or_Zero", + "£1_to_Threshold", + "£Threshold_to_£150k", + "£150k_to_£300k", + "£300k_to_£500k", + "£500k_to_£1m", + "£1m_to_£10m", + "Greater_than_£10m", +) +# The paper calibrates net VAT on every positive band except £1_to_Threshold. +CALIBRATED_VAT_BANDS: tuple[str, ...] = HMRC_BANDS[2:] +EMPLOYMENT_BANDS: tuple[str, ...] = ( + "0-4", + "5-9", + "10-19", + "20-49", + "50-99", + "100-249", + "250+", +) +EMPLOYMENT_UPPER: tuple[float, ...] = (4, 9, 19, 49, 99, 249, float("inf")) +HMRC_UPPER: tuple[float, ...] = (0.0, THRESHOLD_K, 150, 300, 500, 1000, 10000) + +# Thinning presets: (window fraction, tail fraction). +FAST_PRESET = (0.30, 0.05) +CI_PRESET = (0.05, 0.01) + + +# --------------------------------------------------------------------------- +# Shared summary (pure pandas: runs in either environment) +# --------------------------------------------------------------------------- +def hmrc_band_index(turnover_k: np.ndarray, threshold_k: float) -> np.ndarray: + """Map turnover (GBP thousands) to HMRC band indices 0-7.""" + + edges = np.array([0.0, threshold_k, 150, 300, 500, 1000, 10000]) + return np.searchsorted(edges, np.asarray(turnover_k, dtype=np.float64), "left") + + +def employment_band_index(employment: np.ndarray) -> np.ndarray: + """Map employment counts to ONS employment band indices 0-6.""" + + edges = np.array(EMPLOYMENT_UPPER[:-1]) + return np.searchsorted(edges, np.asarray(employment, dtype=np.float64), "left") + + +def summarise_firms( + firms: pd.DataFrame, + *, + weight_column: str, + threshold_k: float = THRESHOLD_K, +) -> dict[str, Any]: + """Return the parity statistics for one generated firm table. + + Net VAT is recomputed with the paper formula on both sides so the + comparison isolates weights and draws from the rules double. + """ + + weight = firms[weight_column].to_numpy(dtype=np.float64) + turnover = firms["annual_turnover_k"].to_numpy(dtype=np.float64) + inputs = firms["annual_input_k"].to_numpy(dtype=np.float64) + registered = firms["vat_registered"].to_numpy(dtype=bool) + if "in_frame" in firms.columns: + frame = firms["in_frame"].to_numpy(dtype=bool) + else: + frame = turnover > 0 + band = hmrc_band_index(turnover, threshold_k) + emp_band = employment_band_index(firms["employment"].to_numpy()) + sic = firms["sic_code"].astype(int).to_numpy() + liability_m = PAPER_VAT_RATE * (turnover - inputs) * weight / 1000.0 + + def by_band(mask: np.ndarray, values: np.ndarray) -> dict[str, float]: + sums = np.bincount(band[mask], weights=values[mask], minlength=8) + return {name: float(sums[i]) for i, name in enumerate(HMRC_BANDS)} + + emp_sums = np.bincount(emp_band[frame], weights=weight[frame], minlength=7) + sector = pd.Series(weight[registered]).groupby(sic[registered]).sum().sort_index() + window = frame & (turnover > 80.0) & (turnover <= 100.0) + summary: dict[str, Any] = { + "rows_total": int(len(firms)), + "rows_in_frame": int(frame.sum()), + "rows_appended": int((~frame).sum()), + "weighted_frame_population": float(weight[frame].sum()), + "weighted_all_rows": float(weight.sum()), + "registered_traders": float(weight[registered].sum()), + "hmrc_band_registered": by_band(registered, weight), + "hmrc_band_frame": by_band(frame, weight), + "employment_band_frame": { + name: float(emp_sums[i]) for i, name in enumerate(EMPLOYMENT_BANDS) + }, + "net_vat_by_band_m": by_band(registered, liability_m), + "sector_registered": {str(int(k)): float(v) for k, v in sector.items()}, + "frame_mass_80_100k": float(weight[window].sum()), + } + if "base_weight" in firms.columns: + base = firms["base_weight"].to_numpy(dtype=np.float64) + summary["base_weighted_frame_rows"] = float(base[frame].sum()) + summary["base_weighted_frame_by_band"] = by_band(frame, base) + summary["base_weighted_frame_by_sic"] = { + str(int(k)): float(v) + for k, v in pd.Series(base[frame]).groupby(sic[frame]).sum().items() + } + return summary + + +def accuracy(estimate: float, target: float) -> float: + """Paper accuracy: ``max(0, 1 - |estimate - target| / |target|)``.""" + + if abs(target) < 1e-9: + return 1.0 if abs(estimate) < 1e-9 else 0.0 + return max(0.0, 1.0 - abs(estimate - target) / abs(target)) + + +# --------------------------------------------------------------------------- +# Official targets read straight from the processed CSVs +# --------------------------------------------------------------------------- +def official_targets(processed_dir: Path) -> dict[str, Any]: + """Return the target vector the paper derives from the six processed CSVs.""" + + turnover = pd.read_csv(processed_dir / "ons_firm_turnover.csv") + employment = pd.read_csv(processed_dir / "ons_firm_employment.csv") + pop_band = pd.read_csv(processed_dir / "hmrc_vat_population_by_turnover_band.csv") + pop_sector = pd.read_csv( + processed_dir / "hmrc_vat_population_by_sector.csv", dtype={"Trade_Sector": str} + ) + liab_band = pd.read_csv(processed_dir / "hmrc_vat_liability_by_turnover_band.csv") + + sic_col = turnover["SIC Code"] + total_row = turnover[sic_col.isna() | (sic_col.astype(str) == "")] + if len(total_row) and "Total" in total_row.columns: + ons_total = int(total_row.iloc[0]["Total"]) + else: + rows = turnover[~turnover["Description"].str.contains("Total", na=False)] + ons_total = int(rows["Total"].sum()) + sector_rows = turnover[sic_col.notna() & (sic_col.astype(str) != "")] + sector_rows = sector_rows[ + ~sector_rows["Description"].str.contains("Total", na=False) + ] + band_cols = [ + c for c in turnover.columns if c not in {"SIC Code", "Description", "Total"} + ] + draw_rows = int(sector_rows[band_cols].fillna(0).astype(int).sum().sum()) + draw_rows_by_sic = { + str(int(r["SIC Code"])): int(r[band_cols].fillna(0).astype(int).sum()) + for _, r in sector_rows.iterrows() + } + + hmrc_bands = {b: float(pop_band.iloc[-1][b]) for b in HMRC_BANDS} + vat_bands = {b: float(liab_band.iloc[-1][b]) for b in HMRC_BANDS[1:]} + emp_rows = employment[~employment["Description"].str.contains("Total", na=False)] + emp_targets = {b: float(emp_rows[b].fillna(0).sum()) for b in EMPLOYMENT_BANDS} + sector = pop_sector[pop_sector["Trade_Sector"] != "Total"] + band_total = float(sum(hmrc_bands.values())) + sector_total = float(sector.iloc[:, -1].astype(float).sum()) + scale = band_total / sector_total if sector_total > 0 else 1.0 + sector_targets = { + str(int(r["Trade_Sector"])): float(r.iloc[-1]) * scale + for _, r in sector.iterrows() + } + return { + "ons_total": ons_total, + "ons_draw_rows": draw_rows, + "ons_draw_rows_by_sic": draw_rows_by_sic, + "pre_thinning_rows": draw_rows + int(round(hmrc_bands["Negative_or_Zero"])), + "hmrc_bands": hmrc_bands, + "vat_liability_bands_m": vat_bands, + "employment_bands": emp_targets, + "sector_registered_scaled": sector_targets, + "sector_scale": scale, + } + + +def propensities_from_summary( + summary: Mapping[str, Any], targets: Mapping[str, Any] +) -> dict[str, float]: + """Registration propensity per positive band: HMRC count / base frame mass.""" + + mass = summary.get("base_weighted_frame_by_band") + if mass is None: + return {} + out: dict[str, float] = {} + for name in HMRC_BANDS[1:]: + if mass[name] > 0: + out[name] = min(1.0, targets["hmrc_bands"][name] / mass[name]) + return out + + +def accuracies( + summary: Mapping[str, Any], targets: Mapping[str, Any] +) -> dict[str, float]: + """Paper-style accuracy per calibrated dimension against official targets.""" + + def mean(values: list[float]) -> float: + return float(np.mean(values)) if values else 0.0 + + return { + "hmrc_bands": mean( + [ + accuracy(summary["hmrc_band_registered"][b], targets["hmrc_bands"][b]) + for b in HMRC_BANDS + ] + ), + "ons_population": accuracy( + summary["weighted_frame_population"], targets["ons_total"] + ), + "employment": mean( + [ + accuracy( + summary["employment_band_frame"][b], targets["employment_bands"][b] + ) + for b in EMPLOYMENT_BANDS + ] + ), + "sector": mean( + [ + accuracy(summary["sector_registered"].get(k, 0.0), v) + for k, v in targets["sector_registered_scaled"].items() + ] + ), + "vat_liability_band": mean( + [ + accuracy( + summary["net_vat_by_band_m"][b], targets["vat_liability_bands_m"][b] + ) + for b in CALIBRATED_VAT_BANDS + ] + ), + } + + +# --------------------------------------------------------------------------- +# Paper side (runs inside the paper's environment) +# --------------------------------------------------------------------------- +def _paper_extract(mode: str, out_path: Path, n_iterations: int | None) -> None: + import importlib + + import firm_microsim + from firm_microsim.config import Config + + # ``firm_microsim.generate`` the attribute is the function; load the module. + paper_calibration = importlib.import_module("firm_microsim.calibration") + paper_generate = importlib.import_module("firm_microsim.generate") + + captured: dict[str, Any] = {} + + original_propensity = paper_calibration.registration_propensity + + def capture_propensity(band_indices, frame_mask, base_weights, hmrc_bands): + prop = original_propensity(band_indices, frame_mask, base_weights, hmrc_bands) + bands = band_indices.cpu().numpy() + frame = frame_mask.cpu().numpy() + values = prop.cpu().numpy() + base = base_weights.cpu().numpy().astype(np.float64) + captured["propensities"] = { + name: float(values[frame & (bands == i)][0]) + for i, name in enumerate(HMRC_BANDS) + if i > 0 and (frame & (bands == i)).any() + } + captured["base_weighted_frame_by_band"] = { + name: float(base[frame & (bands == i)].sum()) + for i, name in enumerate(HMRC_BANDS) + } + return prop + + paper_calibration.registration_propensity = capture_propensity + + original_base = paper_generate.generate_base_firms + + def capture_base(*args, **kwargs): + sic, turnover = original_base(*args, **kwargs) + captured["pre_thinning_frame_rows"] = int(len(sic)) + return sic, turnover + + paper_generate.generate_base_firms = capture_base + + overrides: dict[str, Any] = {"seed": SEED} + if mode == "fast": + overrides.update( + sample_window_fraction=FAST_PRESET[0], sample_tail_fraction=FAST_PRESET[1] + ) + elif mode == "ci": + overrides.update( + sample_window_fraction=CI_PRESET[0], sample_tail_fraction=CI_PRESET[1] + ) + if n_iterations is not None: + overrides["n_iterations"] = n_iterations + config = Config.for_vintage(VINTAGE, **overrides) + + started = time.perf_counter() + firms, report = paper_generate.generate(config, write=False, return_report=True) + runtime = time.perf_counter() - started + + processed = Path(config.processed_dir) + targets = official_targets(processed) + summary = summarise_firms(firms, weight_column="weight", threshold_k=THRESHOLD_K) + summary["pre_thinning_frame_rows"] = captured.get("pre_thinning_frame_rows") + summary["pre_thinning_rows"] = ( + captured["pre_thinning_frame_rows"] + summary["rows_appended"] + ) + summary["propensities"] = captured.get("propensities", {}) + summary["base_weighted_frame_by_band"] = captured.get("base_weighted_frame_by_band") + summary["accuracy_paper_report"] = { + "hmrc_bands": report.hmrc_bands, + "ons_population": report.ons_population, + "employment": report.employment, + "sector": report.sector, + "vat_liability_band": report.vat_liability_band, + "overall": report.overall, + "vat_liability_sector_diagnostic": report.vat_liability_sector, + "vat_liability_below_threshold_diagnostic": ( + report.vat_liability_below_threshold + ), + } + summary["accuracy_recomputed"] = accuracies(summary, targets) + payload = { + "metadata": { + "paper_package_version": getattr(firm_microsim, "__version__", None), + "paper_commit": _git_head(processed), + "vintage": VINTAGE, + "vat_threshold_k": THRESHOLD_K, + "seed": SEED, + "mode": mode, + "sample_window_fraction": config.sample_window_fraction, + "sample_tail_fraction": config.sample_tail_fraction, + "n_iterations": config.n_iterations, + "runtime_seconds": round(runtime, 1), + "command": ( + "python tools/uk_firm_paper_parity.py paper-extract " + f"--mode {mode} (paper generate(write=False))" + ), + }, + "targets": targets, + "summary": summary, + } + out_path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n") + + +def _git_head(path: Path) -> str | None: + try: + return subprocess.run( + ["git", "-C", str(path), "rev-parse", "HEAD"], + check=True, + capture_output=True, + text=True, + ).stdout.strip() + except (OSError, subprocess.CalledProcessError): + return None + + +def run_paper(paper_root: Path, mode: str, out_path: Path) -> dict[str, Any]: + """Run the paper generator in its own environment and return its summary.""" + + python = paper_root / ".venv" / "bin" / "python" + if python.exists(): + command = [str(python)] + else: + command = ["uv", "run", "--project", str(paper_root), "python"] + command += [str(Path(__file__).resolve()), "paper-extract", "--mode", mode] + command += ["--out", str(out_path)] + subprocess.run(command, check=True, cwd=paper_root) + return json.loads(out_path.read_text()) + + +# --------------------------------------------------------------------------- +# Microcosm side +# --------------------------------------------------------------------------- +class PaperFormulaVATRules: + """PARITY-ONLY VAT rules double: 0.20 x (turnover - inputs) for every firm. + + Reproduces the paper's standard-rate approximation so parity runs compare + weights and draws, not VAT law. Implements both the legacy + ``net_liability_k`` evaluator and the ``UKFirmRules.evaluate`` protocol. + """ + + provenance = {"rules": "paper-formula", "status": "parity-only double"} + + def net_liability_k( + self, + *, + turnover_k: np.ndarray, + input_cost_k: np.ndarray, + vat_registered: np.ndarray, + data_vintage: str, + ) -> np.ndarray: + del vat_registered, data_vintage + return PAPER_VAT_RATE * ( + np.asarray(turnover_k, dtype=np.float64) + - np.asarray(input_cost_k, dtype=np.float64) + ) + + def evaluate(self, firms: pd.DataFrame, *, period: int): + from microcosm.build.uk_runtime.firm_rules import UKFirmRuleOutputs + + del period + liability = PAPER_VAT_RATE * ( + firms["firm_turnover"].to_numpy(dtype=np.float64) + - firms["firm_input_costs"].to_numpy(dtype=np.float64) + ) + return UKFirmRuleOutputs( + firm_id=firms["firm_id"].to_numpy(dtype=np.int64), + vat_liability_if_registered=liability, + provenance=dict(self.provenance), + ) + + +def microcosm_config( + *, + window_fraction: float, + tail_fraction: float, + n_iterations: int | None = None, + seed: int = SEED, +): + """Build a Microcosm generator config wired to the paper-formula double.""" + + from microcosm.build.uk_runtime.firm_generation import UKFirmGenerationConfig + + names = {f.name for f in fields(UKFirmGenerationConfig)} + rules = PaperFormulaVATRules() + values: dict[str, Any] = {"data_vintage": VINTAGE, "seed": seed} + if "firm_rules" in names: + values["firm_rules"] = rules + else: + values["vat_rule_evaluator"] = rules + if window_fraction < 1.0 or tail_fraction < 1.0: + if "sample_window_fraction" not in names: + raise SystemExit( + "UKFirmGenerationConfig has no sample_window_fraction; " + "thinned runs need the stratified-thinning generator." + ) + values["sample_window_fraction"] = window_fraction + values["sample_tail_fraction"] = tail_fraction + if n_iterations is not None: + values["n_iterations"] = n_iterations + # Construct directly so __post_init__ resolves the 2024-25 £90k threshold; + # replace() on a default config would keep the 2023-24 £85k it resolved. + return UKFirmGenerationConfig(**values) + + +def run_microcosm(processed_dir: Path, config) -> tuple[dict[str, Any], float, Any]: + """Run the Microcosm generator and return (summary, runtime seconds, result).""" + + from microcosm.build.uk_runtime.firm_generation import ( + generate_uk_firm_population, + read_uk_firm_source_data, + ) + + data = read_uk_firm_source_data(processed_dir) + started = time.perf_counter() + result = generate_uk_firm_population(data, config) + runtime = time.perf_counter() - started + summary = summarise_firms(result.firms, weight_column="firm_weight") + return summary, runtime, result + + +# --------------------------------------------------------------------------- +# Parity table +# --------------------------------------------------------------------------- +@dataclass(frozen=True) +class Check: + name: str + paper: float | None + microcosm: float | None + kind: str # "exact", "rel", "abs", "min", "info" + tolerance: float + + @property + def diff(self) -> float | None: + if self.paper is None or self.microcosm is None: + return None + if self.kind == "rel": + return (self.microcosm - self.paper) / self.paper if self.paper else 0.0 + return self.microcosm - self.paper + + @property + def passed(self) -> bool | None: + if self.microcosm is None or self.kind == "info": + return None + if self.kind == "min": + return self.microcosm >= self.tolerance + diff = self.diff + if diff is None: + return None + return abs(diff) <= self.tolerance + + +def parity_checks( + paper: Mapping[str, Any], + micro: Mapping[str, Any], + targets: Mapping[str, Any], + *, + thinned: bool, +) -> list[Check]: + """Build the provisional parity checks from the scoping decision.""" + + band_tol = 0.03 if thinned else 0.01 + window_tol = 0.10 if thinned else 0.05 + checks: list[Check] = [] + pre_rows = micro.get("base_weighted_frame_rows") + checks.append( + Check( + "pre-thinning row count", + paper.get("pre_thinning_rows"), + None if pre_rows is None else round(pre_rows) + micro["rows_appended"], + "exact", + 0.0, + ) + ) + # Propensities depend on each generator's own turnover draw, so they are + # shown side by side for information only; the 1e-6 identity (HMRC count / + # own base-weighted frame mass) is asserted on Microcosm's run in the test. + micro_prop = propensities_from_summary(micro, targets) + for band, value in paper.get("propensities", {}).items(): + checks.append( + Check(f"propensity {band} (info)", value, micro_prop.get(band), "info", 0.0) + ) + checks.append( + Check( + "weighted frame population", + paper["weighted_frame_population"], + micro["weighted_frame_population"], + "rel", + 0.005, + ) + ) + checks.append( + Check( + "registered traders", + paper["registered_traders"], + micro["registered_traders"], + "rel", + 0.005, + ) + ) + for band in HMRC_BANDS: + checks.append( + Check( + f"HMRC registered {band}", + paper["hmrc_band_registered"][band], + micro["hmrc_band_registered"][band], + "rel", + band_tol, + ) + ) + for band in EMPLOYMENT_BANDS: + checks.append( + Check( + f"employment {band}", + paper["employment_band_frame"][band], + micro["employment_band_frame"][band], + "rel", + 0.02, + ) + ) + micro_acc = accuracies(micro, targets) + paper_acc = paper.get("accuracy_recomputed", accuracies(paper, targets)) + checks.append( + Check( + "net VAT by calibrated band (mean accuracy)", + paper_acc["vat_liability_band"], + micro_acc["vat_liability_band"], + "min", + 0.96, + ) + ) + checks.append( + Check( + "sector counts (mean accuracy)", + paper_acc["sector"], + micro_acc["sector"], + "min", + 0.90, + ) + ) + checks.append( + Check( + "frame mass £80-100k", + paper["frame_mass_80_100k"], + micro["frame_mass_80_100k"], + "rel", + window_tol, + ) + ) + return checks + + +#: Values below this magnitude print with significant digits, not as integers. +_SIGNIFICANT_DIGITS_BELOW = 10.0 + + +def _fmt(value: float | None, kind: str) -> str: + if value is None: + return "n/a" + small = abs(value) < _SIGNIFICANT_DIGITS_BELOW + if kind in {"min"} or (small and kind != "exact"): + return f"{value:.6g}" + return f"{value:,.0f}" + + +def render_table(checks: list[Check]) -> str: + """Return a markdown parity table.""" + + lines = [ + "| Check | Paper | Microcosm | Diff | Tolerance | Result |", + "| --- | ---: | ---: | ---: | --- | --- |", + ] + for check in checks: + diff = check.diff + if check.kind == "rel" and diff is not None: + diff_text = f"{diff:+.2%}" + tol_text = f"±{check.tolerance:.1%}" + elif check.kind == "min": + diff_text = "" if diff is None else f"{diff:+.4f}" + tol_text = f"≥ {check.tolerance:.0%}" + elif check.kind == "info": + diff_text = "n/a" if diff is None else f"{diff:+.4f}" + tol_text = "info" + elif check.kind == "exact": + diff_text = "n/a" if diff is None else f"{diff:+,.0f}" + tol_text = "exact" + else: + diff_text = "n/a" if diff is None else f"{diff:+.2e}" + tol_text = f"±{check.tolerance:g}" + passed = check.passed + result = "n/a" if passed is None else ("pass" if passed else "FAIL") + lines.append( + f"| {check.name} | {_fmt(check.paper, check.kind)} | " + f"{_fmt(check.microcosm, check.kind)} | {diff_text} | {tol_text} | {result} |" + ) + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- +def main(argv: list[str] | None = None) -> int: + argv = list(sys.argv[1:] if argv is None else argv) + if argv and argv[0] == "paper-extract": + parser = argparse.ArgumentParser(prog="uk_firm_paper_parity.py paper-extract") + parser.add_argument("--mode", choices=["full", "fast", "ci"], default="full") + parser.add_argument("--out", type=Path, required=True) + parser.add_argument("--n-iterations", type=int, default=None) + args = parser.parse_args(argv[1:]) + _paper_extract(args.mode, args.out, args.n_iterations) + return 0 + + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + mode = parser.add_mutually_exclusive_group() + mode.add_argument("--full", dest="mode", action="store_const", const="full") + mode.add_argument("--fast", dest="mode", action="store_const", const="fast") + mode.add_argument("--ci", dest="mode", action="store_const", const="ci") + parser.set_defaults(mode="full") + parser.add_argument( + "--paper-root", + type=Path, + default=None, + help="Paper checkout; when given, re-runs the paper generator (full).", + ) + parser.add_argument( + "--processed-dir", + type=Path, + default=FIXTURE_DIR, + help="Processed 2024-25 CSV directory (default: committed fixture).", + ) + parser.add_argument( + "--reference", + type=Path, + default=FIXTURE_DIR / REFERENCE_FILE, + help="Paper reference JSON used when --paper-root is not given.", + ) + parser.add_argument( + "--rules", + choices=["paper-formula"], + default="paper-formula", + help="VAT rules double (parity only).", + ) + parser.add_argument("--n-iterations", type=int, default=None) + parser.add_argument("--json-out", type=Path, default=None) + args = parser.parse_args(argv) + + if args.paper_root is not None: + out = Path(os.environ.get("TMPDIR", "/tmp")) / "firm_paper_reference.json" + paper_payload = run_paper(args.paper_root.resolve(), "full", out) + else: + paper_payload = json.loads(args.reference.read_text())["runs"]["full"] + + window, tail = {"full": (1.0, 1.0), "fast": FAST_PRESET, "ci": CI_PRESET}[args.mode] + config = microcosm_config( + window_fraction=window, tail_fraction=tail, n_iterations=args.n_iterations + ) + micro, runtime, _ = run_microcosm(args.processed_dir, config) + targets = official_targets(args.processed_dir) + checks = parity_checks( + paper_payload["summary"], micro, targets, thinned=args.mode != "full" + ) + print( + f"Microcosm mode={args.mode} (window {window}, tails {tail}), " + f"seed {SEED}, rules {args.rules} (parity-only), " + f"{micro['rows_total']:,} rows, {runtime:.1f} s" + ) + meta = paper_payload["metadata"] + print( + f"Paper reference: mode={meta['mode']}, commit {meta.get('paper_commit')}, " + f"{meta['runtime_seconds']} s" + ) + print() + print(render_table(checks)) + if args.json_out is not None: + args.json_out.write_text( + json.dumps({"microcosm": micro, "runtime_seconds": runtime}, indent=2) + ) + return 0 if all(c.passed is not False for c in checks) else 1 + + +if __name__ == "__main__": + raise SystemExit(main())