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-attributes.added.md b/changelog.d/1705-uk-firm-attributes.added.md new file mode 100644 index 0000000000..953066f7ee --- /dev/null +++ b/changelog.d/1705-uk-firm-attributes.added.md @@ -0,0 +1,7 @@ +UK firms gain region and legal status, and the policyengine-uk firm table gains the five inputs that depend on them (microcosm#1705). `uk_runtime/firm_attributes.py` draws `ons_region_code` given SIC division × turnover band (ONS UK Business 2025, Table 8) and `ons_legal_status` given industry group × turnover band (Table 13), with seeded categorical draws per cell after calibration, falling back from the cell to the row total and then to the UK total. Legal status is also weighted by the employment band through Table 12 (see `1705-uk-firm-legal-status-employment.changed.md`). The two draws are independent given their cells. Table 15 (region × legal status) is held out: on the 20-iteration thinned 2024-25 test build (seed 42), the weighted in-frame joint distribution is 0.033 in total variation from it (0.035 once legal status is coupled to the employment band through Table 12). The tables are committed under `tests/fixtures/uk/firm_attributes_2025/` with workbook provenance, and `tools/extract_uk_firm_ons_attribute_tables.py --check` re-extracts them from the paper repository's workbook. + +`to_policyengine_uk_firm_table` emits `firm_legal_form`, `firm_region`, `firm_in_england`, `firm_is_public_body` and `firm_is_charity` when both ONS columns are present, and the unchanged base table otherwise. It never falls back to policyengine-uk's defaults (`LONDON`, `COMPANY`). The legal-status mapping is in `1705-uk-firm-legal-status-mapping.changed.md`: statuses 5–7 map to `OTHER` (outside corporation tax), status 4 to `COMPANY`, statuses 4–6 set `firm_is_public_body` and status 7 sets `firm_is_charity`, all assumptions. `firm_in_england`, which policyengine-uk defines by the firm's property, comes from the enterprise's region. `UK_FIRM_POLICYENGINE_UK_INPUT_STATUS` records every one of policyengine-uk's formula-less firm inputs (71 at `0d1c25010`) as set, derived, assumed or not set; paybill, profit, capital expenditure, R&D, rateable value and the remaining flags stay unset, with no placeholder values, until sources arrive. The validator now refuses missing values in every column. + +A committed snapshot of policyengine-uk's firm variables (`tests/fixtures/uk/policyengine_uk_firm_inputs.json`, from PolicyEngine/policyengine-uk#2940, refreshed with `tools/snapshot_policyengine_uk_firm_inputs.py`, which reads the source with `ast` and refuses a dirty checkout unless `--allow-dirty` is passed) lets an engine-free test check that every exported column is a policyengine-uk firm input and that every enum value is a member. + +`uk_runtime/firm_target_candidates.py` declares value-free M2 target candidates: three ONS UK Business tables available as fixtures, and ONS UK Business Table 3, DBT business population estimates, ONS ABS, HMRC corporation tax (capital allowances included), R&D and PAYE RTI statistics, and MHCLG/VOA business rates pending Ledger sources. Each candidate names the policyengine-uk inputs it would inform. None is wired into the solver, and `uk/uk_firms_targets.json` is unchanged. diff --git a/changelog.d/1705-uk-firm-export-layout.changed.md b/changelog.d/1705-uk-firm-export-layout.changed.md new file mode 100644 index 0000000000..c8fb100cee --- /dev/null +++ b/changelog.d/1705-uk-firm-export-layout.changed.md @@ -0,0 +1 @@ +The UK firm export's layout is now a base table plus a registry of optional input groups (microcosm#1705). `uk_runtime/firm_table.py`'s `UK_FIRM_EXPORT_GROUPS` holds one `UKFirmExportGroup` per group, with the source columns that switch it on, the policyengine-uk and Microcosm-only columns it adds, the groups it extends, and how it fills and checks its columns; the first is `attributes` (the ONS region and legal status draws), and each later input group is one more entry. `to_policyengine_uk_firm_table` emits the base and every group whose source columns the rows carry, and `validate_uk_firm_table` accepts the base and each valid set of groups (`UK_FIRM_TABLE_LAYOUTS`) and runs each present group's checks. `uk_firm_table_columns` and `uk_firm_export_groups` give a set of groups' layout and the groups a population carries. The named layouts (`UK_FIRM_TABLE_COLUMNS`, `UK_FIRM_EXTENDED_TABLE_COLUMNS` and their policyengine-uk column constants) are now derived from the registry and unchanged, and a test pins that the same-seed test build exports the same columns, dtypes and values as before. diff --git a/changelog.d/1705-uk-firm-legal-status-employment.changed.md b/changelog.d/1705-uk-firm-legal-status-employment.changed.md new file mode 100644 index 0000000000..39470f5859 --- /dev/null +++ b/changelog.d/1705-uk-firm-legal-status-employment.changed.md @@ -0,0 +1 @@ +Condition the UK firm ONS legal status draw on employment as well as turnover (microcosm#1705), using ONS UK Business 2025 Table 12 (legal status by industry group and employment sizeband), so sole proprietors and partnerships no longer take large headcounts at their turnover cell's rate. The status-by-employment fit against Table 12 is in-sample, since Table 12 is now a draw input. About twice as much employment now sits in ONS legal statuses 4–7 (public corporations, central and local government, and non-profit bodies), which moves toward Table 12. diff --git a/changelog.d/1705-uk-firm-legal-status-mapping.changed.md b/changelog.d/1705-uk-firm-legal-status-mapping.changed.md new file mode 100644 index 0000000000..89e2a47b7c --- /dev/null +++ b/changelog.d/1705-uk-firm-legal-status-mapping.changed.md @@ -0,0 +1 @@ +The UK firm export maps ONS legal status 4 (public corporation or nationalised body) to `COMPANY` and marks it `firm_is_public_body`, so policyengine-uk charges it corporation tax and excludes it from the Employment Allowance; it previously mapped to `OTHER` (microcosm#1705). Every status 7 body (non-profit body or mutual association) is now exported with `firm_is_charity`, an assumption since ONS does not split charities out, which gives it policyengine-uk's charitable rate relief. (Its Employment Allowance charity exception matters only for public bodies, and no status 7 body is one, so the allowance does not move.) Limited liability partnerships are not drawn apart: ONS does not name them and they most likely sit with companies (status 1), a caveat only. The build receipt's `data_years` now also records the year each input group's source describes (`ons_attributes` for the ONS UK Business 2025 tables), apart from `rule_period`. 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..aa3dbe8aa7 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,57 @@ 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, attributes 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. + +Region and legal status are drawn after calibration from ONS UK Business 2025 +Tables 8, 12 and 13 (`uk_runtime/firm_attributes.py`; legal status is +conditioned on the turnover band through Table 13 and on the employment band +through Table 12), with Table 15 held out, and feed policyengine-uk's +`firm_region`, `firm_in_england`, `firm_legal_form`, `firm_is_public_body` +and `firm_is_charity`. Public corporations (ONS status 4) export as +`COMPANY` and as public bodies, so they are liable to corporation tax and +outside the Employment Allowance; every non-profit body or mutual (status 7) +is assumed a charity. ONS does not name limited liability partnerships; they +most likely sit with companies (status 1), so they are charged corporation +tax although an LLP is transparent for tax. That is a caveat, not a drawn +flag. `firm_table.UK_FIRM_POLICYENGINE_UK_INPUT_STATUS` records which of +policyengine-uk's 71 firm inputs (at `0d1c25010`) microcosm sets. The build +receipt's `data_years` records the year each input group's source describes, +apart from the rule period. + +An engine-free test checks the export against a committed snapshot of +policyengine-uk's firm variables. Value-free target candidates for the next +Ledger sources are declared in `uk_runtime/firm_target_candidates.py`; they are +not yet in `uk/uk_firms_targets.json` or the solve. + +The other policyengine-uk firm inputs (paybill, profit, rateable value, R&D, +capital expenditure, the pay-distribution inputs and several flags) wait for +sources. + ## External Prerequisites The first integration should depend on these upstream artifacts: @@ -21,7 +76,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 +88,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 +135,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 +166,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 +206,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..18cdf46ff2 100644 --- a/packages/microcosm-build/README.md +++ b/packages/microcosm-build/README.md @@ -102,10 +102,23 @@ 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. `uk_runtime/firm_attributes.py` adds region and +legal status from the ONS UK Business tables, and +`uk_runtime/firm_target_candidates.py` lists the value-free target candidates +for the next Ledger sources. 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..85c39e24e8 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,16 @@ uk_zero_weight_strata, write_uk_calibration_diagnostics, ) +from microcosm.build.uk_runtime.firm_attributes import ( + UK_FIRM_LEGAL_STATUS_EMPLOYMENT_FILE, + UKFirmAttributeSourceData, + assign_uk_firm_attributes, + read_uk_firm_attribute_source_data, + uk_firm_attribute_fallback_counts, +) +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 +70,6 @@ UKFirmValidationReport, UKFirmVATRuleEvaluator, assign_employment, - assign_vat_flags, build_firm_target_matrix, employment_band_name, generate_base_firms, @@ -77,6 +86,46 @@ 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_EXPORT_GROUPS, + UK_FIRM_EXTENDED_TABLE_COLUMNS, + UK_FIRM_POLICYENGINE_UK_INPUT_STATUS, + UK_FIRM_TABLE_COLUMNS, + UK_FIRM_TABLE_LAYOUTS, + UKFirmExportGroup, + build_candidate_rules_table, + to_policyengine_uk_firm_table, + uk_firm_export_groups, + uk_firm_policyengine_uk_columns, + uk_firm_table_columns, + validate_uk_firm_table, +) +from microcosm.build.uk_runtime.firm_target_candidates import ( + UK_FIRM_TARGET_CANDIDATES, + UKFirmTargetCandidate, + UKFirmTargetFilter, + uk_firm_target_candidates_feeding, +) +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 +869,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 +1025,42 @@ "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", + "UKFirmAttributeSourceData", + "assign_uk_firm_attributes", + "read_uk_firm_attribute_source_data", + "uk_firm_attribute_fallback_counts", + "UK_FIRM_LEGAL_STATUS_EMPLOYMENT_FILE", + "UK_FIRM_TARGET_CANDIDATES", + "UKFirmTargetCandidate", + "UKFirmTargetFilter", + "uk_firm_target_candidates_feeding", + "UK_FIRM_EXTENDED_TABLE_COLUMNS", + "UK_FIRM_EXPORT_GROUPS", + "UK_FIRM_TABLE_LAYOUTS", + "UKFirmExportGroup", + "uk_firm_export_groups", + "uk_firm_policyengine_uk_columns", + "uk_firm_table_columns", "write_uk_calibration_diagnostics", "load_bound_spine_sidecar", "spine_provenance_from_sidecar", diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_attributes.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_attributes.py new file mode 100644 index 0000000000..f5e7456d98 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_attributes.py @@ -0,0 +1,642 @@ +"""Region and legal status for synthetic UK firms, from ONS UK Business 2025. + +Two published ONS tables give the firm attributes policyengine-uk's Firm +entity needs but the firm generator does not draw: + +- Table 8 counts enterprises by SIC division, region and the seven ONS + turnover bands; it gives ``ons_region_code``. +- Table 13 counts enterprises by broad industry group, legal status and its + own ten turnover bands; it gives ``ons_legal_status`` (ONS codes 1 to 7). +- Table 12 counts enterprises by the same industry groups, legal status and + seven employment sizebands; when present it conditions ``ons_legal_status`` + on the firm's ONS ``employment`` as well as its turnover. + +:func:`assign_uk_firm_attributes` draws both after calibration, so it never +changes a weight or an existing column. Region is drawn conditional on the +firm's (SIC division, Table 8 band) cell and legal status conditional on its +(industry group, Table 13 band) cell. The two draws are independent given +those cells: no published table crosses region with legal status by industry, +so any dependence beyond what sector and turnover carry is not modelled +(Table 15, region by legal status by turnover, is held out to check it). + +No published table crosses legal status with both turnover and employment, so +the legal status weights combine the two tables under an assumption: within an +industry group and legal status, a firm's employment band is independent of +its turnover band. The firm's Table 13 distribution (cell, row or UK total, as +below) is multiplied, status by status, by Table 12's share of that status's +enterprises in the group that fall in the firm's employment band, +``P(employment band | group, status)``. Without that factor, a sole +proprietor's draw ignored headcount and firms of any size became sole +proprietors at their turnover cell's rate. When every product is zero (no +status in the turnover distribution has enterprises in that employment band) +the factor is dropped and the Table 13 distribution alone is used; a division +without a Table 12 group uses Table 12's UK total over groups. Employment +bands are parsed from Table 12's labels like turnover bands ("0-4" is +``[0, 5)``). + +Band edges and industry groups are parsed from the tables' own labels. A band +label ``"lo-hi"`` in thousands of pounds is the interval ``[lo, hi + 1)`` and +``"lo+"`` is open above, as in the firm generator's ONS bands, where "50-99" +is ``[50, 100)``. An industry-group key ``"01-03"`` covers SIC divisions 1 to +3 inclusive and ``"45"`` covers division 45 alone. + +Fallback (an assumption; see ``docs/firm-support-plan.md``): when a firm's +cell holds no enterprises, or its division or group is absent from the table, +the draw uses the row total of its division or group over every band, then the +UK total over every division and band. +Out-of-frame firms (``in_frame`` False, or zero or negative turnover: the +HMRC Negative_or_Zero traders appended before calibration) have no ONS band, +and were allocated to sectors by the sector shares of the frame, so they draw +from their division's or group's row total, then the UK total; they never use +a band cell. :func:`uk_firm_attribute_fallback_counts` reports which level +each firm used. +""" + +from __future__ import annotations + +import re +from collections.abc import Mapping +from dataclasses import dataclass +from pathlib import Path +from types import MappingProxyType + +import numpy as np +import pandas as pd + +__all__ = [ + "UK_FIRM_ATTRIBUTE_FALLBACK_LEVELS", + "UK_FIRM_LEGAL_STATUS_EMPLOYMENT_FILE", + "UK_FIRM_LEGAL_STATUS_TURNOVER_FILE", + "UK_FIRM_REGION_TURNOVER_FILE", + "UKFirmAttributeSourceData", + "assign_uk_firm_attributes", + "industry_group_divisions", + "parse_turnover_band_lowers", + "read_uk_firm_attribute_source_data", + "turnover_band_index", + "uk_firm_attribute_fallback_counts", +] + +UK_FIRM_REGION_TURNOVER_FILE = "ons_region_turnover.csv" +UK_FIRM_LEGAL_STATUS_TURNOVER_FILE = "ons_legal_status_turnover.csv" +UK_FIRM_LEGAL_STATUS_EMPLOYMENT_FILE = "ons_legal_status_employment.csv" + +#: The distribution each firm's draw used, most specific first. +UK_FIRM_ATTRIBUTE_FALLBACK_LEVELS: tuple[str, ...] = ("cell", "row", "uk") +_CELL, _ROW, _UK = range(len(UK_FIRM_ATTRIBUTE_FALLBACK_LEVELS)) + +_REGION_COLUMNS = ("sic_division", "region_code", "turnover_band", "enterprises") +_LEGAL_STATUS_COLUMNS = ( + "industry_group", + "legal_status", + "turnover_band", + "enterprises", +) +_LEGAL_STATUS_EMPLOYMENT_COLUMNS = ( + "industry_group", + "legal_status", + "employment_band", + "enterprises", +) +_CLOSED_BAND = re.compile(r"^\s*(\d+)\s*-\s*(\d+)\s*$") +_OPEN_BAND = re.compile(r"^\s*(\d+)\s*\+\s*$") +_GROUP_KEY = re.compile(r"^\s*(\d+)\s*(?:-\s*(\d+)\s*)?$") + + +def parse_turnover_band_lowers(labels: object) -> dict[str, float]: + """Each band label's inclusive lower edge in thousands of pounds. + + Labels are ``"lo-hi"`` (the interval ``[lo, hi + 1)``) or one open top band + ``"lo+"``. The bands must start at zero and be contiguous; anything else, + a ``"Total"`` column included, raises. Returned in ascending order. + """ + + closed: list[tuple[float, float, str]] = [] + open_bands: list[tuple[float, str]] = [] + for label in dict.fromkeys(str(label) for label in labels): + if match := _CLOSED_BAND.match(label): + lower, upper = float(match.group(1)), float(match.group(2)) + if upper < lower: + raise ValueError(f"turnover band {label!r} is reversed") + closed.append((lower, upper, label)) + elif match := _OPEN_BAND.match(label): + open_bands.append((float(match.group(1)), label)) + else: + raise ValueError(f"unparseable turnover band label {label!r}") + if len(open_bands) != 1: + raise ValueError( + f"expected exactly one open turnover band, got {len(open_bands)}" + ) + closed.sort() + expected = 0.0 + lowers: dict[str, float] = {} + for lower, upper, label in closed: + if lower != expected: + raise ValueError( + f"turnover band {label!r} starts at {lower:g}, expected {expected:g}" + ) + lowers[label] = lower + expected = upper + 1.0 + open_lower, open_label = open_bands[0] + if open_lower != expected: + raise ValueError( + f"open turnover band {open_label!r} starts at {open_lower:g}, " + f"expected {expected:g}" + ) + lowers[open_label] = open_lower + return lowers + + +def turnover_band_index( + turnover_k: np.ndarray, band_lowers: Mapping[str, float] +) -> np.ndarray: + """Index into ``band_lowers`` (ascending) of each positive turnover. + + Uses lower edges only, so a turnover between one band's published upper + label and the next band's lower edge (99.5 between "50-99" and "100-249") + falls in the lower band. Callers route non-positive turnover elsewhere. + """ + + lowers = np.fromiter(band_lowers.values(), dtype=np.float64) + return ( + np.searchsorted(lowers, np.asarray(turnover_k, dtype=np.float64), "right") - 1 + ) + + +def industry_group_divisions(keys: object) -> dict[int, str]: + """Map each SIC division to the industry-group key that covers it. + + A key ``"lo-hi"`` covers divisions ``lo`` to ``hi`` inclusive and a key + ``"nn"`` covers one division. Overlapping or unparseable keys raise. + """ + + division_group: dict[int, str] = {} + for key in dict.fromkeys(str(key) for key in keys): + match = _GROUP_KEY.match(key) + if match is None: + raise ValueError(f"unparseable industry group key {key!r}") + lower = int(match.group(1)) + upper = int(match.group(2)) if match.group(2) is not None else lower + if upper < lower: + raise ValueError(f"industry group key {key!r} is reversed") + for division in range(lower, upper + 1): + if division in division_group: + raise ValueError( + f"SIC division {division} is in industry groups " + f"{division_group[division]!r} and {key!r}" + ) + division_group[division] = key + return division_group + + +@dataclass(frozen=True) +class _CellTable: + """Enterprise counts as ``counts[row, band, category]``.""" + + row_index: Mapping[int, int] + band_lowers: Mapping[str, float] + categories: tuple[object, ...] + counts: np.ndarray + + +def _cell_table( + frame: pd.DataFrame, + *, + row_key: pd.Series, + category: pd.Series, + band_column: str = "turnover_band", +) -> _CellTable: + band_lowers = parse_turnover_band_lowers(frame[band_column]) + band_position = {label: i for i, label in enumerate(band_lowers)} + row_values = sorted(set(row_key)) + row_index = {value: i for i, value in enumerate(row_values)} + categories = tuple(sorted(set(category))) + category_index = {value: i for i, value in enumerate(categories)} + enterprises = pd.to_numeric(frame["enterprises"], errors="raise").to_numpy( + dtype=np.float64 + ) + if not np.isfinite(enterprises).all() or (enterprises < 0).any(): + raise ValueError("enterprise counts must be finite and non-negative") + counts = np.zeros( + (len(row_values), len(band_lowers), len(categories)), dtype=np.float64 + ) + np.add.at( + counts, + ( + row_key.map(row_index).to_numpy(dtype=np.int64), + frame[band_column].map(band_position).to_numpy(dtype=np.int64), + category.map(category_index).to_numpy(dtype=np.int64), + ), + enterprises, + ) + if counts.sum() <= 0: + raise ValueError("an ONS attribute table holds no enterprises") + return _CellTable( + row_index=MappingProxyType(row_index), + band_lowers=MappingProxyType(band_lowers), + categories=categories, + counts=counts, + ) + + +def _group_status_table(frame: pd.DataFrame, band_column: str) -> _CellTable: + groups = frame["industry_group"].astype(str).str.strip() + statuses = frame["legal_status"].astype(str).str.strip().astype(int) + if not statuses.between(1, 7).all(): + raise ValueError("ONS legal status codes run from 1 to 7") + # Row ids are the industry groups' positions in key order; the division + # map sends each division to its group's position. + group_keys = sorted(set(groups)) + industry_group_divisions(group_keys) + position = {key: i for i, key in enumerate(group_keys)} + return _cell_table( + frame, + row_key=groups.map(position), + category=statuses, + band_column=band_column, + ) + + +@dataclass(frozen=True) +class UKFirmAttributeSourceData: + """The ONS UK Business 2025 tables the attribute draws read. + + ``region_turnover`` is Table 8 in long form (``sic_division``, + ``region_code``, ``turnover_band``, ``enterprises``) and + ``legal_status_turnover`` is Table 13 (``industry_group``, + ``legal_status``, ``turnover_band``, ``enterprises``). The optional + ``legal_status_employment`` is Table 12 (``industry_group``, + ``legal_status``, ``employment_band``, ``enterprises``); without it legal + status is conditioned on turnover alone. Keys are strings, except + ``legal_status`` (int) and ``enterprises`` (float). + """ + + region_turnover: pd.DataFrame + legal_status_turnover: pd.DataFrame + legal_status_employment: pd.DataFrame | None = None + + def __post_init__(self) -> None: + tables = [ + ("region_turnover", self.region_turnover, _REGION_COLUMNS), + ( + "legal_status_turnover", + self.legal_status_turnover, + _LEGAL_STATUS_COLUMNS, + ), + ] + if self.legal_status_employment is not None: + tables.append( + ( + "legal_status_employment", + self.legal_status_employment, + _LEGAL_STATUS_EMPLOYMENT_COLUMNS, + ) + ) + for name, frame, columns in tables: + missing = [column for column in columns if column not in frame.columns] + if missing: + raise ValueError(f"{name} is missing columns {missing}") + # Parse once here so a malformed table fails on read, not on draw. + self._region_table() + status_table = self._legal_status_table() + if self.legal_status_employment is not None: + employment_table = self._legal_status_employment_table() + if employment_table.categories != status_table.categories: + raise ValueError( + "legal_status_employment and legal_status_turnover hold " + "different legal status codes" + ) + + def _region_table(self) -> _CellTable: + frame = self.region_turnover + return _cell_table( + frame, + row_key=frame["sic_division"].astype(str).str.strip().astype(int), + category=frame["region_code"].astype(str).str.strip(), + ) + + def _legal_status_table(self) -> _CellTable: + return _group_status_table(self.legal_status_turnover, "turnover_band") + + def _legal_status_employment_table(self) -> _CellTable: + if self.legal_status_employment is None: + raise ValueError("no legal_status_employment table") + return _group_status_table(self.legal_status_employment, "employment_band") + + def _division_group_rows(self, frame: pd.DataFrame | None = None) -> dict[int, int]: + if frame is None: + frame = self.legal_status_turnover + groups = sorted(set(frame["industry_group"].astype(str).str.strip())) + position = {key: i for i, key in enumerate(groups)} + return { + division: position[key] + for division, key in industry_group_divisions(groups).items() + } + + +def read_uk_firm_attribute_source_data( + directory: str | Path, +) -> UKFirmAttributeSourceData: + """Read Tables 8, 13 and, when present, 12 from ``directory``. + + ``directory`` holds the fixture CSVs. Table 12 + (:data:`UK_FIRM_LEGAL_STATUS_EMPLOYMENT_FILE`) is optional; without it + legal status is drawn on turnover alone. + """ + + directory = Path(directory) + employment_path = directory / UK_FIRM_LEGAL_STATUS_EMPLOYMENT_FILE + legal_status_employment = None + if employment_path.is_file(): + legal_status_employment = pd.read_csv( + employment_path, + dtype={ + "industry_group": str, + "legal_status": int, + "employment_band": str, + "enterprises": float, + }, + keep_default_na=False, + ) + return UKFirmAttributeSourceData( + region_turnover=pd.read_csv( + directory / UK_FIRM_REGION_TURNOVER_FILE, + dtype={ + "sic_division": str, + "region_code": str, + "turnover_band": str, + "enterprises": float, + }, + keep_default_na=False, + ), + legal_status_turnover=pd.read_csv( + directory / UK_FIRM_LEGAL_STATUS_TURNOVER_FILE, + dtype={ + "industry_group": str, + "legal_status": int, + "turnover_band": str, + "enterprises": float, + }, + keep_default_na=False, + ), + legal_status_employment=legal_status_employment, + ) + + +def _firm_inputs(firms: pd.DataFrame) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """``(division, turnover_k, banded)`` per firm; banded firms are in frame.""" + + for column in ("sic_code", "annual_turnover_k"): + if column not in firms.columns: + raise ValueError(f"firms frame is missing {column!r}") + division = firms["sic_code"].astype(str).str.strip().astype(int).to_numpy() + turnover = firms["annual_turnover_k"].to_numpy(dtype=np.float64) + if np.isnan(turnover).any(): + raise ValueError("annual_turnover_k holds NaN") + banded = turnover > 0 + if "in_frame" in firms.columns: + banded &= firms["in_frame"].to_numpy(dtype=bool) + return division, turnover, banded + + +def _resolve( + table: _CellTable, + rows: np.ndarray, + turnover: np.ndarray, + banded: np.ndarray, +) -> tuple[np.ndarray, np.ndarray]: + """Each firm's distribution id and fallback level. + + ``rows`` holds the table row of each firm, or -1 when the table has none. + Distribution ids index :func:`_distributions`: cells first + (``row * n_bands + band``), then row totals, then the UK total. + """ + + n_rows, n_bands, _ = table.counts.shape + cell_total = table.counts.sum(axis=2) + row_total = cell_total.sum(axis=1) + has_row = rows >= 0 + safe_row = np.where(has_row, rows, 0) + band = np.zeros(len(rows), dtype=np.int64) + band[banded] = turnover_band_index(turnover[banded], table.band_lowers) + cell_ok = banded & has_row & (cell_total[safe_row, band] > 0) + row_ok = ~cell_ok & has_row & (row_total[safe_row] > 0) + level = np.full(len(rows), _UK, dtype=np.int64) + level[row_ok] = _ROW + level[cell_ok] = _CELL + distribution = np.full(len(rows), n_rows * n_bands + n_rows, dtype=np.int64) + distribution[row_ok] = n_rows * n_bands + safe_row[row_ok] + distribution[cell_ok] = safe_row[cell_ok] * n_bands + band[cell_ok] + return distribution, level + + +def _distributions(table: _CellTable) -> np.ndarray: + """Counts per distribution id: cells, then row totals, then the UK total.""" + + n_rows, n_bands, n_categories = table.counts.shape + return np.concatenate( + [ + table.counts.reshape(n_rows * n_bands, n_categories), + table.counts.sum(axis=1), + table.counts.sum(axis=(0, 1))[None, :], + ] + ) + + +def _draw( + rng: np.random.Generator, + distribution: np.ndarray, + counts: np.ndarray, +) -> np.ndarray: + """One categorical draw per distribution, in ascending id order.""" + + category = np.empty(len(distribution), dtype=np.int64) + order = np.argsort(distribution, kind="stable") + ids, starts = np.unique(distribution[order], return_index=True) + ends = np.append(starts[1:], len(order)) + for distribution_id, start, end in zip(ids, starts, ends, strict=True): + weights = counts[distribution_id] + category[order[start:end]] = rng.choice( + len(weights), size=end - start, p=weights / weights.sum() + ) + return category + + +def _map_rows(lookup: Mapping[int, int], division: np.ndarray) -> np.ndarray: + """Table row of each firm's division, or -1, mapped once per division.""" + + unique, inverse = np.unique(division, return_inverse=True) + rows = np.array([lookup.get(int(d), -1) for d in unique], dtype=np.int64) + return rows[inverse] + + +def _region_rows( + source: UKFirmAttributeSourceData, division: np.ndarray +) -> tuple[_CellTable, np.ndarray]: + table = source._region_table() + return table, _map_rows(table.row_index, division) + + +def _legal_status_rows( + source: UKFirmAttributeSourceData, division: np.ndarray +) -> tuple[_CellTable, np.ndarray]: + table = source._legal_status_table() + return table, _map_rows(source._division_group_rows(), division) + + +def _employment(firms: pd.DataFrame) -> np.ndarray: + if "employment" not in firms.columns: + raise ValueError("firms frame is missing 'employment'") + employment = firms["employment"].to_numpy(dtype=np.float64) + if np.isnan(employment).any(): + raise ValueError("employment holds NaN") + if (employment < 0).any(): + raise ValueError("employment must be non-negative") + return employment + + +def _employment_weighting( + source: UKFirmAttributeSourceData, + division: np.ndarray, + employment: np.ndarray, +) -> tuple[np.ndarray, np.ndarray]: + """Each firm's employment key and ``P(band | group, status)`` per key. + + Keys index the rows of the returned likelihood: ``row * n_bands + band``, + where row is the firm's Table 12 group, or the extra UK row after the + groups when its division has none. + """ + + table = source._legal_status_employment_table() + n_rows, n_bands, _ = table.counts.shape + counts = np.concatenate([table.counts, table.counts.sum(axis=0)[None]], axis=0) + status_total = counts.sum(axis=1, keepdims=True) + likelihood = np.divide( + counts, + status_total, + out=np.zeros_like(counts), + where=status_total > 0, + ) + rows = _map_rows( + source._division_group_rows(source.legal_status_employment), division + ) + rows = np.where(rows >= 0, rows, n_rows) + band = turnover_band_index(employment, table.band_lowers) + return rows * n_bands + band, likelihood.reshape((n_rows + 1) * n_bands, -1) + + +def _legal_status_distributions( + source: UKFirmAttributeSourceData, + division: np.ndarray, + turnover: np.ndarray, + banded: np.ndarray, + employment: np.ndarray | None, +) -> tuple[_CellTable, np.ndarray, np.ndarray, np.ndarray]: + """``(table, distribution, counts, employment_dropped)`` for legal status. + + Without Table 12 (or ``employment``) these are the Table 13 distributions. + With it, each distribution is a (Table 13 distribution, employment key) + pair, numbered in ascending pair order, whose weights are the Table 13 + counts times the employment likelihood, or the Table 13 counts alone when + that product is all zero (``employment_dropped`` is True for those firms). + """ + + table, rows = _legal_status_rows(source, division) + distribution, _ = _resolve(table, rows, turnover, banded) + counts = _distributions(table) + dropped = np.zeros(len(distribution), dtype=bool) + if source.legal_status_employment is None or employment is None: + return table, distribution, counts, dropped + key, likelihood = _employment_weighting(source, division, employment) + pair = distribution * len(likelihood) + key + unique, inverse = np.unique(pair, return_inverse=True) + weights = counts[unique // len(likelihood)] * likelihood[unique % len(likelihood)] + empty = weights.sum(axis=1) <= 0 + weights[empty] = counts[unique[empty] // len(likelihood)] + return table, inverse.reshape(-1), weights, empty[inverse.reshape(-1)] + + +def assign_uk_firm_attributes( + firms: pd.DataFrame, + source: UKFirmAttributeSourceData, + *, + seed: int, +) -> pd.DataFrame: + """Return a copy of ``firms`` with ``ons_region_code`` and ``ons_legal_status``. + + Run after calibration: weights and every existing column are unchanged. + One generator, ``default_rng(seed + 2)``, draws region first and legal + status second, each with one categorical draw per distribution (cell, row + total or UK total; for legal status, paired with the firm's employment + band when Table 12 is present) in ascending distribution order, so the + result depends only on the frame, the tables and the seed. See the module + docstring for the conditioning, the independence assumptions and the + fallback. With Table 12, ``firms`` needs a non-negative ``employment``. + """ + + division, turnover, banded = _firm_inputs(firms) + employment = ( + _employment(firms) if source.legal_status_employment is not None else None + ) + rng = np.random.default_rng(seed + 2) + region_table, region_rows = _region_rows(source, division) + region_distribution, _ = _resolve(region_table, region_rows, turnover, banded) + region = _draw(rng, region_distribution, _distributions(region_table)) + status_table, status_distribution, status_counts, _ = _legal_status_distributions( + source, division, turnover, banded, employment + ) + status = _draw(rng, status_distribution, status_counts) + + result = firms.copy() + result["ons_region_code"] = pd.Series( + np.asarray(region_table.categories, dtype=object)[region], + index=firms.index, + dtype=object, + ) + result["ons_legal_status"] = pd.Series( + np.asarray(status_table.categories, dtype=np.int64)[status], + index=firms.index, + dtype=np.int64, + ) + return result + + +def uk_firm_attribute_fallback_counts( + firms: pd.DataFrame, + source: UKFirmAttributeSourceData, +) -> pd.DataFrame: + """Firms and base weight per attribute and fallback level. + + One row per (``attribute``, ``level``) with ``firms`` (rows) and + ``weight`` (sum of ``base_weight``, or of ones when the frame has none). + ``level`` is one of :data:`UK_FIRM_ATTRIBUTE_FALLBACK_LEVELS`. The levels + are those :func:`assign_uk_firm_attributes` uses; no random draw is made. + """ + + division, turnover, banded = _firm_inputs(firms) + weight = ( + firms["base_weight"].to_numpy(dtype=np.float64) + if "base_weight" in firms.columns + else np.ones(len(firms), dtype=np.float64) + ) + n_levels = len(UK_FIRM_ATTRIBUTE_FALLBACK_LEVELS) + records = [] + for attribute, (table, rows) in ( + ("ons_region_code", _region_rows(source, division)), + ("ons_legal_status", _legal_status_rows(source, division)), + ): + _, level = _resolve(table, rows, turnover, banded) + firm_counts = np.bincount(level, minlength=n_levels) + weights = np.bincount(level, weights=weight, minlength=n_levels) + for index, name in enumerate(UK_FIRM_ATTRIBUTE_FALLBACK_LEVELS): + records.append( + { + "attribute": attribute, + "level": name, + "firms": int(firm_counts[index]), + "weight": float(weights[index]), + } + ) + return pd.DataFrame.from_records( + records, columns=["attribute", "level", "firms", "weight"] + ) 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..acfca6c51c --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_build.py @@ -0,0 +1,258 @@ +"""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. ``assign_uk_firm_attributes`` draws ONS region and legal status; +4. ``to_policyengine_uk_firm_table`` exports policyengine-uk firm columns; +5. ``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 frame's +sources for a checked vintage, then one entry per input group read, from +``UK_FIRM_INPUT_DATA_YEARS``), the +configuration's JSON-safe fields, the output's hash and shape, the +calibration's accuracy figures, the attribute fallback counts 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 types import MappingProxyType +from typing import Any + +import numpy as np +import pandas as pd + +from microcosm.build.uk_runtime.firm_attributes import ( + assign_uk_firm_attributes, + read_uk_firm_attribute_source_data, + uk_firm_attribute_fallback_counts, +) +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" + +#: The years each input group's source describes, recorded in the receipt's +#: ``data_years`` beside the frame's and apart from ``rule_period``. A key +#: appears only when its group's source is read. Each value is the source's +#: own reference period, from its fixture provenance; the build reads the +#: 2024-25 fixtures only. +UK_FIRM_INPUT_DATA_YEARS: Mapping[str, str] = MappingProxyType( + { + # ONS UK Business 2025 Tables 8, 12 and 13: the 2025 frame, whose + # turnover bands are mostly from VAT returns for 2023-24 (note 4). + "ons_attributes": "2025 frame (turnover mostly 2023-24)", + } +) + + +def _input_data_years(groups: Mapping[str, bool]) -> dict[str, str]: + """``UK_FIRM_INPUT_DATA_YEARS`` entries of the groups switched on.""" + + unknown = sorted(set(groups) - set(UK_FIRM_INPUT_DATA_YEARS)) + if unknown: + raise ValueError(f"No UK firm data year for input groups {unknown}.") + return {key: UK_FIRM_INPUT_DATA_YEARS[key] for key, on in groups.items() if on} + + +#: 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, + attributes_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) + attributes = Path(attributes_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.") + + attribute_source = read_uk_firm_attribute_source_data(attributes) + firms = assign_uk_firm_attributes( + result.firms, attribute_source, seed=result.config.seed + ) + table = to_policyengine_uk_firm_table( + 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) + + fallback = uk_firm_attribute_fallback_counts(firms, attribute_source) + 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) or {}), + **_input_data_years( + { + "ons_attributes": True, + } + ), + }, + "config": _config_record(result.config), + "inputs": { + "processed": _csv_hashes(processed), + "attributes": _csv_hashes(attributes), + }, + "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), + "uk_firm_attribute_fallback_counts": _records(fallback), + "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..99fff35e17 --- /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, 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..a3339f4d04 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_table.py @@ -0,0 +1,863 @@ +"""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, checked by + ``validate_uk_firm_table``. + +The export's layout is a base plus optional input groups. The base is +policyengine-uk's firm inputs the generator always gives +(``UK_FIRM_POLICYENGINE_UK_COLUMNS``) followed by the Microcosm-only columns +(``UK_FIRM_MICROCOSM_COLUMNS``): ``UK_FIRM_TABLE_COLUMNS``. +``UK_FIRM_EXPORT_GROUPS`` registers each optional group +(``UKFirmExportGroup``): the source columns that switch it on, the +policyengine-uk and Microcosm-only columns it adds, the groups it extends, +and how it fills and checks its columns. The export emits the base and every +group whose source columns the rows carry; ``uk_firm_table_columns`` gives a +set of groups' layout, which places every group's policyengine-uk columns, +in registry order, after the base ones, and its Microcosm-only columns after +the base Microcosm-only ones. Adding an input is one registry entry. + +The group today: + +- ``attributes``: the ONS attribute draws (``ons_legal_status`` and + ``ons_region_code``) give ``firm_legal_form``, ``firm_region``, + ``firm_in_england``, ``firm_is_public_body`` and ``firm_is_charity``; the + draws stay as + Microcosm-only columns. Its layout is ``UK_FIRM_EXTENDED_TABLE_COLUMNS``. + +``UK_FIRM_POLICYENGINE_UK_INPUT_STATUS`` records, for every formula-less +policyengine-uk firm input, whether the fullest table (every group) sets it. +The base table leaves ``firm_region`` and ``firm_legal_form`` unset, so +policyengine-uk's defaults (London, company) apply; ``firm_paybill`` and the +other money inputs are never set. +""" + +from __future__ import annotations + +import itertools +from collections.abc import Callable, Iterable, Mapping +from dataclasses import dataclass +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, +) +from microcosm.calibrate.geography_constants import ( + UK_REGION_TIER, + UK_REGION_TIER_ENUM, +) + +#: 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) + +#: The ONS attribute draws the extended export reads and carries: the ONS +#: legal status code (1-7, UK Business: Activity, Size and Location tables) +#: and the GSS code of the firm's English region or nation. Microcosm-only. +UK_FIRM_ONS_ATTRIBUTE_COLUMNS = ("ons_legal_status", "ons_region_code") + +#: policyengine-uk ``FirmLegalForm`` member names, in declaration order. +UK_FIRM_LEGAL_FORMS: tuple[str, ...] = ( + "COMPANY", + "SOLE_TRADER", + "PARTNERSHIP", + "OTHER", +) + +#: ONS legal status code -> policyengine-uk ``FirmLegalForm`` member name. +#: +#: 1 company (including building societies), 2 sole proprietor and +#: 3 partnership map one to one. 4 public corporation or nationalised body +#: maps to ``COMPANY``, so policyengine-uk charges it corporation tax, and it +#: is a public body (:data:`UK_FIRM_PUBLIC_BODY_ONS_LEGAL_STATUSES`). +#: 5 central government, 6 local authority and 7 non-profit body or mutual +#: association map to ``OTHER``, outside corporation tax; that is an +#: assumption, since some non-profit bodies do pay it. The raw code stays in +#: ``ons_legal_status``. +#: +#: Limited liability partnerships are not drawn apart. The ONS tables do not +#: name them; DBT's Business Population Estimates 2025 methodology note, on +#: the same IDBR frame, counts them with companies, so they most likely sit +#: in status 1 and are charged corporation tax here, although an LLP is +#: transparent for tax (its members pay income tax). This is a caveat, not a +#: drawn flag. +UK_FIRM_ONS_LEGAL_STATUS_TO_LEGAL_FORM: Mapping[int, str] = MappingProxyType( + { + 1: "COMPANY", + 2: "SOLE_TRADER", + 3: "PARTNERSHIP", + 4: "COMPANY", + 5: "OTHER", + 6: "OTHER", + 7: "OTHER", + } +) + +#: ONS legal statuses read as public bodies for ``firm_is_public_body``: +#: public corporations (4), central government (5) and local authorities (6). +#: policyengine-uk keys its Employment Allowance exclusion on this flag +#: (unless the firm is a charity). +UK_FIRM_PUBLIC_BODY_ONS_LEGAL_STATUSES: frozenset[int] = frozenset({4, 5, 6}) + +#: ONS legal statuses read as charities for ``firm_is_charity``: every +#: non-profit body or mutual association (7). An assumption: ONS does not +#: split charities from other non-profit bodies and mutuals, so all of +#: status 7 takes policyengine-uk's charity treatment: mandatory charitable +#: rate relief. (The Employment Allowance charity exception applies only to +#: public bodies, and no status 7 body is one.) +UK_FIRM_CHARITY_ONS_LEGAL_STATUSES: frozenset[int] = frozenset({7}) + +#: GSS region codes -> policyengine-uk ``Region`` member names: the shared +#: region tier (nine English regions, then Wales, Scotland and Northern +#: Ireland). ``Region.UNKNOWN`` is never emitted. +UK_FIRM_REGION_CODE_TO_REGION: Mapping[str, str] = UK_REGION_TIER_ENUM + +#: GSS codes of the nine English regions, for ``firm_in_england``. +UK_FIRM_ENGLISH_REGION_CODES: frozenset[str] = frozenset( + code for tier, code in UK_REGION_TIER if tier == "region" +) + +#: policyengine-uk firm inputs the extended export adds, in order. +UK_FIRM_ATTRIBUTE_POLICYENGINE_UK_COLUMNS = ( + "firm_legal_form", + "firm_region", + "firm_in_england", + "firm_is_public_body", + "firm_is_charity", +) + +#: Values of ``UK_FIRM_POLICYENGINE_UK_INPUT_STATUS``: +#: +#: - ``set``: mapped directly from a generator column or ONS draw; +#: - ``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; policyengine_uk/variables/firm/) +#: -> how the fullest export, with every group, fills it. The keys with status +#: other than ``not_set`` are exactly the base policyengine-uk columns and those +#: of every ``UK_FIRM_EXPORT_GROUPS`` entry; a table without some groups sets a +#: subset of them. +UK_FIRM_POLICYENGINE_UK_INPUT_STATUS: Mapping[str, str] = MappingProxyType( + { + # Generator columns, mapped directly (thousands of pounds to pounds, + # SIC division to section). + "firm_id": "set", + "firm_weight": "set", + "firm_turnover": "set", + "firm_input_costs": "set", + "firm_employees": "set", + "firm_sic_section": "set", + # GSS code to Region member, one to one. + "firm_region": "set", + # Turnover split by VAT scope; voluntary registration from the + # registration threshold. + "firm_standard_rated_supplies": "derived", + "firm_exempt_supplies": "derived", + "firm_vat_voluntarily_registered": "derived", + # policyengine-uk's firm_in_england means the firm's property is in + # England; the export reads it from the enterprise's ONS region, so a + # multi-site enterprise's property is assumed to sit in its region. + "firm_in_england": "assumed", + # ASSUMED_INPUT_VAT_RATE on all input costs; ONS statuses 5-7 to + # OTHER and 4 to COMPANY; ONS statuses 4-6 as public bodies; ONS + # status 7 as charities. + "firm_input_vat": "assumed", + "firm_legal_form": "assumed", + "firm_is_public_body": "assumed", + "firm_paybill": "not_set", + "firm_taxable_trading_profit": "not_set", + "firm_rateable_value": "not_set", + # Not drawn: no source yet. Placeholders would flow into NIC, CT, + # VAT and business rates revenue. + "firm_n_associated_companies": "not_set", + # Small profits rate exclusion (policyengine-uk 0d1c25010). + "firm_small_profits_rate_excluded": "not_set", + "firm_is_bank": "not_set", + "firm_is_charity": "assumed", + "firm_is_single_director_company": "not_set", + "firm_in_freeport": "not_set", + # VAT. + "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", + # Business rates. + "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", + # Welsh rates (policyengine-uk 0d1c25010). + "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", + # Capital allowances. + "firm_aia_share": "not_set", + "firm_capex_main_pool_new": "not_set", + # Leasing assets outside full expensing (policyengine-uk 0d1c25010). + "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", + # Corporation tax. + "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", + # Employer costs. + "firm_apprenticeship_levy_allowance_share": "not_set", + "firm_claims_employment_allowance": "not_set", + "firm_zero_rated_class_1_earnings": "not_set", + # Class 1A on benefits in kind (policyengine-uk d856de5a7). + "firm_class_1a_benefits": "not_set", + # Pay distribution within the paybill (policyengine-uk ca037fad2). + "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", + # National Minimum Wage floor (policyengine-uk ca037fad2). + "firm_low_paid_hours": "not_set", + "firm_low_paid_paybill": "not_set", + # R&D. + "firm_is_sme": "not_set", + "firm_qualifying_rd_expenditure": "not_set", + # RDEC PAYE/NIC cap (policyengine-uk d856de5a7). + "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 _ons_attributes(frame: pd.DataFrame) -> tuple[np.ndarray, np.ndarray]: + """``ons_legal_status`` as int64 and ``ons_region_code`` as str, checked.""" + + status = frame["ons_legal_status"] + if status.isna().any() or not pd.api.types.is_integer_dtype(status): + raise ValueError("UK firm ons_legal_status must be integers.") + status_values = status.to_numpy(np.int64) + if not np.isin(status_values, list(UK_FIRM_ONS_LEGAL_STATUS_TO_LEGAL_FORM)).all(): + raise ValueError( + "UK firm ons_legal_status must be ONS legal status codes " + f"{sorted(UK_FIRM_ONS_LEGAL_STATUS_TO_LEGAL_FORM)}." + ) + codes = frame["ons_region_code"] + if not codes.map(lambda code: isinstance(code, str)).all(): + raise ValueError("UK firm ons_region_code must be strings.") + code_values = codes.to_numpy(object) + if not pd.Series(code_values).isin(list(UK_FIRM_REGION_CODE_TO_REGION)).all(): + raise ValueError( + "UK firm ons_region_code must be GSS codes of the English regions " + "or the nations." + ) + return status_values, code_values + + +def _attribute_columns( + status: np.ndarray, region_code: np.ndarray +) -> dict[str, np.ndarray]: + """The policyengine-uk columns the ONS attribute draws give.""" + + return { + "firm_legal_form": np.array( + [UK_FIRM_ONS_LEGAL_STATUS_TO_LEGAL_FORM[int(s)] for s in status], + dtype=object, + ), + "firm_region": np.array( + [UK_FIRM_REGION_CODE_TO_REGION[code] for code in region_code], + dtype=object, + ), + "firm_in_england": np.isin(region_code, list(UK_FIRM_ENGLISH_REGION_CODES)), + "firm_is_public_body": np.isin( + status, list(UK_FIRM_PUBLIC_BODY_ONS_LEGAL_STATUSES) + ), + "firm_is_charity": np.isin(status, list(UK_FIRM_CHARITY_ONS_LEGAL_STATUSES)), + } + + +def _validate_attribute_columns(df: pd.DataFrame) -> None: + status, region_code = _ons_attributes(df) + for column in ("firm_in_england", "firm_is_public_body", "firm_is_charity"): + if not pd.api.types.is_bool_dtype(df[column]): + raise ValueError(f"UK firm {column} must be boolean.") + if not df["firm_legal_form"].isin(UK_FIRM_LEGAL_FORMS).all(): + raise ValueError("UK firm firm_legal_form must be FirmLegalForm member names.") + if not df["firm_region"].isin(list(UK_FIRM_REGION_CODE_TO_REGION.values())).all(): + raise ValueError("UK firm firm_region must be Region member names.") + expected = _attribute_columns(status, region_code) + for column, values in expected.items(): + if not np.array_equal(df[column].to_numpy(values.dtype), values): + source = ( + "ons_region_code" + if column in ("firm_region", "firm_in_england") + else "ons_legal_status" + ) + raise ValueError(f"UK firm {column} does not follow {source}.") + + +def _attribute_group_columns(ordered: pd.DataFrame) -> dict[str, np.ndarray]: + status, region_code = _ons_attributes(ordered) + return { + **_attribute_columns(status, region_code), + "ons_legal_status": status, + "ons_region_code": region_code, + } + + +@dataclass(frozen=True) +class UKFirmExportGroup: + """An optional input group of the policyengine-uk firm export. + + ``source_columns`` are the generator rows' columns that switch the group + on: the export emits it when the rows carry all of them and raises when + they carry only some. ``requires`` names the groups it extends, which + must be emitted too. ``policyengine_uk_columns`` and + ``microcosm_columns`` are the columns it adds, in order. + ``columns(ordered)`` fills both from the rows ordered by ``firm_id``; + ``validate(table)`` raises ``ValueError`` unless the table's columns of + the group meet its contract. + """ + + name: str + source_columns: tuple[str, ...] + policyengine_uk_columns: tuple[str, ...] + microcosm_columns: tuple[str, ...] + requires: tuple[str, ...] + columns: Callable[[pd.DataFrame], Mapping[str, np.ndarray]] + validate: Callable[[pd.DataFrame], None] + + +#: The export's optional input groups, in column order. A group appears +#: after every group it requires. +UK_FIRM_EXPORT_GROUPS: tuple[UKFirmExportGroup, ...] = ( + UKFirmExportGroup( + name="attributes", + source_columns=UK_FIRM_ONS_ATTRIBUTE_COLUMNS, + policyengine_uk_columns=UK_FIRM_ATTRIBUTE_POLICYENGINE_UK_COLUMNS, + microcosm_columns=UK_FIRM_ONS_ATTRIBUTE_COLUMNS, + requires=(), + columns=_attribute_group_columns, + validate=_validate_attribute_columns, + ), +) + +_GROUPS_BY_NAME: Mapping[str, UKFirmExportGroup] = MappingProxyType( + {group.name: group for group in UK_FIRM_EXPORT_GROUPS} +) + + +def _check_export_groups() -> None: + seen: set[str] = set() + columns = list(UK_FIRM_TABLE_COLUMNS) + for group in UK_FIRM_EXPORT_GROUPS: + if group.name in seen: + raise ValueError(f"UK firm export group {group.name} repeats.") + unknown = [name for name in group.requires if name not in seen] + if unknown: + raise ValueError( + f"UK firm export group {group.name} requires {unknown}, which " + "must come before it." + ) + seen.add(group.name) + columns += [*group.policyengine_uk_columns, *group.microcosm_columns] + if len(set(columns)) != len(columns): + raise ValueError("UK firm export groups repeat a column.") + + +_check_export_groups() + + +def _ordered_groups(groups: Iterable[str]) -> tuple[UKFirmExportGroup, ...]: + names = set(groups) + unknown = sorted(names - set(_GROUPS_BY_NAME)) + if unknown: + raise ValueError(f"Unknown UK firm export groups {unknown}.") + ordered = tuple(g for g in UK_FIRM_EXPORT_GROUPS if g.name in names) + for group in ordered: + missing = [name for name in group.requires if name not in names] + if missing: + raise ValueError( + f"UK firm export group {group.name} extends {missing}, which " + "are not included." + ) + return ordered + + +def uk_firm_policyengine_uk_columns(groups: Iterable[str] = ()) -> tuple[str, ...]: + """policyengine-uk columns of the export with ``groups``, in order.""" + + return ( + *UK_FIRM_POLICYENGINE_UK_COLUMNS, + *( + column + for group in _ordered_groups(groups) + for column in group.policyengine_uk_columns + ), + ) + + +def uk_firm_table_columns(groups: Iterable[str] = ()) -> tuple[str, ...]: + """The export's columns with ``groups``, in order. + + The base and each group's policyengine-uk columns, then the base and + each group's Microcosm-only columns, groups in registry order. A group + without a group it requires raises ``ValueError``. + """ + + names = tuple(groups) + ordered = _ordered_groups(names) + return ( + *uk_firm_policyengine_uk_columns(names), + *UK_FIRM_MICROCOSM_COLUMNS, + *(column for group in ordered for column in group.microcosm_columns), + ) + + +def _layouts() -> Mapping[tuple[str, ...], tuple[str, ...]]: + layouts: dict[tuple[str, ...], tuple[str, ...]] = {} + names = [group.name for group in UK_FIRM_EXPORT_GROUPS] + for size in range(len(names) + 1): + for combination in itertools.combinations(names, size): + chosen = set(combination) + if all( + set(_GROUPS_BY_NAME[name].requires) <= chosen for name in combination + ): + layouts[combination] = uk_firm_table_columns(combination) + return MappingProxyType(layouts) + + +#: Every valid set of export groups (names in registry order) -> its layout. +UK_FIRM_TABLE_LAYOUTS: Mapping[tuple[str, ...], tuple[str, ...]] = _layouts() + + +def uk_firm_export_groups(firms: pd.DataFrame) -> tuple[str, ...]: + """Names of the export groups whose source columns ``firms`` carries. + + Raises ``ValueError`` when ``firms`` carries some of a group's source + columns but not all, or a group without one it extends. + """ + + present: list[str] = [] + for group in UK_FIRM_EXPORT_GROUPS: + carried = [c for c in group.source_columns if c in firms.columns] + if not carried: + continue + if len(carried) != len(group.source_columns): + needs = "both" if len(group.source_columns) == 2 else "all of them" + raise ValueError( + f"UK firm population carries {carried} without the rest of " + f"{list(group.source_columns)}; the {group.name} export needs " + f"{needs}." + ) + for name in group.requires: + if name not in present: + raise ValueError( + f"UK firm population carries {', '.join(carried)} without " + f"{list(_GROUPS_BY_NAME[name].source_columns)}; the " + f"{group.name} export extends the {name} one." + ) + present.append(group.name) + return tuple(present) + + +#: policyengine-uk firm input variables in the extended export (base and +#: attributes), in order. +UK_FIRM_EXTENDED_POLICYENGINE_UK_COLUMNS = uk_firm_policyengine_uk_columns( + ("attributes",) +) + +#: Microcosm-only columns the extended export carries after the +#: policyengine-uk ones: the base ones and the ONS attribute draws. +UK_FIRM_MICROCOSM_ONLY_COLUMNS = ( + *UK_FIRM_MICROCOSM_COLUMNS, + *_GROUPS_BY_NAME["attributes"].microcosm_columns, +) + +#: The extended export's columns (base and attributes), in order. +UK_FIRM_EXTENDED_TABLE_COLUMNS = uk_firm_table_columns(("attributes",)) + + +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`` of the ``UK_FIRM_EXPORT_GROUPS`` whose source + columns ``firms`` carries (``uk_firm_export_groups``), ordered by + ``firm_id``: ``UK_FIRM_TABLE_COLUMNS`` with none and + ``UK_FIRM_EXTENDED_TABLE_COLUMNS`` with both + ``UK_FIRM_ONS_ATTRIBUTE_COLUMNS``. Some of a group's source + columns without the rest (one ONS attribute column without the other), + or a group without one it extends, raises ``ValueError``. Columns: + + - 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; + - extended only: ``firm_legal_form`` maps ``ons_legal_status`` through + ``UK_FIRM_ONS_LEGAL_STATUS_TO_LEGAL_FORM``, ``firm_region`` maps + ``ons_region_code`` through ``UK_FIRM_REGION_CODE_TO_REGION``, + ``firm_in_england`` is an English region, ``firm_is_public_body`` an + ONS status in ``UK_FIRM_PUBLIC_BODY_ONS_LEGAL_STATUSES`` and + ``firm_is_charity`` one in ``UK_FIRM_CHARITY_ONS_LEGAL_STATUSES``. A code outside + those maps raises: nothing falls back to policyengine-uk's London or + company defaults. + + The result passes ``validate_uk_firm_table``. + """ + + _require(firms, UK_FIRM_EXPORT_SOURCE_COLUMNS, "UK firm population") + groups = _ordered_groups(uk_firm_export_groups(firms)) + 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), + ) + if groups: + added: dict[str, np.ndarray] = {} + for group in groups: + added.update(group.columns(ordered)) + layout = uk_firm_table_columns([group.name for group in groups]) + table = table.assign(**added)[list(layout)] + 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 one of ``UK_FIRM_TABLE_LAYOUTS`` (the base table + and each valid set of ``UK_FIRM_EXPORT_GROUPS``), in order; no missing + value in any column (policyengine-uk rejects NaN); 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; voluntary registration + only for registered firms; and each present group's own checks. The + attribute group needs ONS legal status codes, GSS region codes, and + ``firm_legal_form``, ``firm_region``, ``firm_in_england``, + ``firm_is_public_body`` and ``firm_is_charity`` as those codes give them. + """ + + columns = tuple(df.columns) + groups = next( + (names for names, layout in UK_FIRM_TABLE_LAYOUTS.items() if layout == columns), + None, + ) + if groups is None: + raise ValueError( + f"UK firm table columns {list(df.columns)} are not one of " + f"{[list(layout) for layout in UK_FIRM_TABLE_LAYOUTS.values()]}." + ) + missing = [column for column in columns if df[column].isna().any()] + if missing: + raise ValueError(f"UK firm table has missing values in {missing}.") + 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.") + for group in _ordered_groups(groups): + group.validate(df) + + +__all__ = [ + "ASSUMED_INPUT_VAT_RATE", + "UK_FIRM_ATTRIBUTE_POLICYENGINE_UK_COLUMNS", + "UK_FIRM_CANDIDATE_RULES_COLUMNS", + "UK_FIRM_CANDIDATE_SOURCE_COLUMNS", + "UK_FIRM_ENGLISH_REGION_CODES", + "UK_FIRM_EXPORT_GROUPS", + "UK_FIRM_EXPORT_SOURCE_COLUMNS", + "UK_FIRM_EXTENDED_POLICYENGINE_UK_COLUMNS", + "UK_FIRM_EXTENDED_TABLE_COLUMNS", + "UK_FIRM_INPUT_STATUSES", + "UK_FIRM_CHARITY_ONS_LEGAL_STATUSES", + "UK_FIRM_LEGAL_FORMS", + "UK_FIRM_MICROCOSM_COLUMNS", + "UK_FIRM_MICROCOSM_ONLY_COLUMNS", + "UK_FIRM_ONS_ATTRIBUTE_COLUMNS", + "UK_FIRM_ONS_LEGAL_STATUS_TO_LEGAL_FORM", + "UK_FIRM_POLICYENGINE_UK_COLUMNS", + "UK_FIRM_POLICYENGINE_UK_INPUT_STATUS", + "UK_FIRM_PUBLIC_BODY_ONS_LEGAL_STATUSES", + "UK_FIRM_REGION_CODE_TO_REGION", + "UK_FIRM_SIC_SECTIONS", + "UK_FIRM_SIC_SECTION_UNKNOWN", + "UK_FIRM_TABLE_COLUMNS", + "UK_FIRM_TABLE_LAYOUTS", + "UKFirmExportGroup", + "build_candidate_rules_table", + "to_policyengine_uk_firm_table", + "uk_firm_export_groups", + "uk_firm_policyengine_uk_columns", + "uk_firm_sic_sections", + "uk_firm_table_columns", + "validate_uk_firm_table", +] diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_target_candidates.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_target_candidates.py new file mode 100644 index 0000000000..643d48cf3c --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/firm_target_candidates.py @@ -0,0 +1,440 @@ +"""Candidate UK firm calibration targets beyond the committed contract (M2). + +``UK_FIRM_TARGET_CANDIDATES`` declares the published firm statistics that +could calibrate the policyengine-uk firm inputs the generator does not draw +yet (paybill, profit, capital expenditure, R&D, rateable value) and the ONS +attribute tables the firm attribute draws read. They are declarations only: + +- no observed values, band edges or Ledger record-set ids + (``ledger_record_set_id`` stays ``None`` until a Ledger source records the + statistic); +- nothing reads them in calibration; ``uk_firms_targets.json`` keeps the + committed contract's targets; +- ``feeds_inputs`` names the formula-less policyengine-uk firm inputs a + target would inform, so most inputs registered as not set can point at a + candidate that would inform them. Some not-set inputs have no candidate + yet; the tests pin which. + +``status`` is ``pending_ledger_source`` for a statistic no Ledger source or +Microcosm fixture holds in the form the candidate needs, and +``fixture_available`` for an ONS UK Business table Microcosm holds as a test +fixture at the candidate's dimensions. ``publication`` is the title as the +publisher gives it: an edition title (with its year) where the candidate +names one edition, such as the ONS UK Business 2025 tables Microcosm holds, +and a series title otherwise, where the edition a target reads is the Ledger +source's choice. Concepts follow +``uk_firms_targets.json`` (``uk.firm.count``, ``uk.firm.annual_turnover``, +``uk.firm.sic_code``, ``uk.firm.turnover_band``, ``uk.firm.employment_band``), +with new ``uk.firm.*`` and ``uk.tax.*`` ids in the same style where the +contract has none. +""" + +from __future__ import annotations + +from dataclasses import dataclass + +#: A statistic no Ledger source or Microcosm fixture holds yet, at the +#: candidate's dimensions. +PENDING_LEDGER_SOURCE = "pending_ledger_source" +#: An ONS UK Business table Microcosm holds as a test fixture, at the +#: candidate's dimensions. +FIXTURE_AVAILABLE = "fixture_available" +UK_FIRM_TARGET_CANDIDATE_STATUSES = (PENDING_LEDGER_SOURCE, FIXTURE_AVAILABLE) + +_ONS_UK_BUSINESS_2025 = "UK business; activity, size and location: 2025" +_DBT_BPE_2025 = "Business population estimates for the UK and regions 2025" +#: The UK-level ABS release, which carries the SIC-level estimates. The +#: combined "UK and regional" title was retired after the 2021 results. +_ONS_ABS = "Non-financial business economy, UK (Annual Business Survey)" +_HMRC_CT = "Corporation Tax statistics" +_HMRC_RD = "Research and Development Tax Credits Statistics" +_HMRC_PAYE_RTI = ( + "Earnings and employment from Pay As You Earn Real Time Information, UK" +) +_MHCLG_NNDR = ( + "National non-domestic rates collected by councils in England: " + "forecast 2025 to 2026" +) +_VOA_STOCK = "Non-domestic rating: stock of properties" + + +@dataclass(frozen=True) +class UKFirmTargetFilter: + """A predicate on a firm concept: ``concept operator value``.""" + + concept: str + operator: str + value: object + + +@dataclass(frozen=True) +class UKFirmTargetCandidate: + """One candidate firm target: what it would measure and what it would feed.""" + + target_id: str + family: str + source_name: str + publication: str + concept: str + status: str + feeds_inputs: tuple[str, ...] + dimensions: tuple[str, ...] = () + filters: tuple[UKFirmTargetFilter, ...] = () + #: The table of ``publication`` the candidate reads, where it names one. + source_table: str | None = None + entity: str = "firm" + ledger_record_set_id: str | None = None + + +_COMPANY = UKFirmTargetFilter("uk.firm.legal_form", "==", "COMPANY") + +UK_FIRM_TARGET_CANDIDATES: tuple[UKFirmTargetCandidate, ...] = ( + # ONS UK Business 2025 tables Microcosm holds as fixtures. + UKFirmTargetCandidate( + target_id="ons.uk_business.enterprise_count.sic_region_turnover_bands", + family="ons_uk_business", + source_name="ons", + publication=_ONS_UK_BUSINESS_2025, + source_table="Table 8", + concept="uk.firm.count", + dimensions=("uk.firm.sic_code", "uk.firm.region", "uk.firm.turnover_band"), + status=FIXTURE_AVAILABLE, + feeds_inputs=("firm_region", "firm_in_england"), + ), + UKFirmTargetCandidate( + target_id=( + "ons.uk_business.enterprise_count.industry_legal_status_turnover_bands" + ), + family="ons_uk_business", + source_name="ons", + publication=_ONS_UK_BUSINESS_2025, + source_table="Table 13", + concept="uk.firm.count", + dimensions=( + "uk.firm.industry_group", + "uk.firm.legal_status", + "uk.firm.turnover_band", + ), + status=FIXTURE_AVAILABLE, + feeds_inputs=("firm_legal_form", "firm_is_public_body"), + ), + UKFirmTargetCandidate( + target_id=( + "ons.uk_business.enterprise_count.region_legal_status_turnover_bands" + ), + family="ons_uk_business", + source_name="ons", + publication=_ONS_UK_BUSINESS_2025, + source_table="Table 15", + concept="uk.firm.count", + dimensions=( + "uk.firm.region", + "uk.firm.legal_status", + "uk.firm.turnover_band", + ), + status=FIXTURE_AVAILABLE, + feeds_inputs=( + "firm_region", + "firm_in_england", + "firm_legal_form", + "firm_is_public_body", + ), + ), + UKFirmTargetCandidate( + # Table 3 is SIC division x employment band x region; Microcosm holds + # no regional extract of it, so it waits for a source like the rest. + target_id="ons.uk_business.enterprise_count.region_employment_bands", + family="ons_uk_business", + source_name="ons", + publication=_ONS_UK_BUSINESS_2025, + source_table="Table 3", + concept="uk.firm.count", + dimensions=( + "uk.firm.sic_code", + "uk.firm.region", + "uk.firm.employment_band", + ), + status=PENDING_LEDGER_SOURCE, + feeds_inputs=("firm_region", "firm_in_england", "firm_employees"), + ), + # DBT business population estimates: all private-sector businesses, + # unregistered ones included. BPE's legal forms (companies, sole + # proprietorships, partnerships) are not ONS legal status codes 1-7. + UKFirmTargetCandidate( + target_id="dbt.bpe.business_count.legal_form_employment_bands", + family="dbt_bpe", + source_name="dbt", + publication=_DBT_BPE_2025, + concept="uk.firm.count", + dimensions=("uk.firm.legal_form", "uk.firm.employment_band"), + status=PENDING_LEDGER_SOURCE, + feeds_inputs=("firm_legal_form", "firm_employees"), + ), + UKFirmTargetCandidate( + target_id="dbt.bpe.business_count.region_employment_bands", + family="dbt_bpe", + source_name="dbt", + publication=_DBT_BPE_2025, + concept="uk.firm.count", + dimensions=("uk.firm.region", "uk.firm.employment_band"), + status=PENDING_LEDGER_SOURCE, + feeds_inputs=("firm_region", "firm_in_england", "firm_employees"), + ), + UKFirmTargetCandidate( + target_id="dbt.bpe.turnover.sic_employment_bands", + family="dbt_bpe", + source_name="dbt", + publication=_DBT_BPE_2025, + concept="uk.firm.annual_turnover", + dimensions=("uk.firm.sic_code", "uk.firm.employment_band"), + status=PENDING_LEDGER_SOURCE, + feeds_inputs=("firm_turnover", "firm_employees"), + ), + # ONS Annual Business Survey: the non-financial business economy. + UKFirmTargetCandidate( + target_id="ons.abs.turnover.sic", + family="ons_abs", + source_name="ons", + publication=_ONS_ABS, + concept="uk.firm.annual_turnover", + dimensions=("uk.firm.sic_code",), + status=PENDING_LEDGER_SOURCE, + feeds_inputs=("firm_turnover",), + ), + UKFirmTargetCandidate( + target_id="ons.abs.purchases.sic", + family="ons_abs", + source_name="ons", + publication=_ONS_ABS, + concept="uk.firm.input_costs", + dimensions=("uk.firm.sic_code",), + status=PENDING_LEDGER_SOURCE, + feeds_inputs=("firm_input_costs", "firm_input_vat"), + ), + UKFirmTargetCandidate( + target_id="ons.abs.employment_costs.sic", + family="ons_abs", + source_name="ons", + publication=_ONS_ABS, + concept="uk.firm.paybill", + dimensions=("uk.firm.sic_code",), + status=PENDING_LEDGER_SOURCE, + feeds_inputs=("firm_paybill",), + ), + UKFirmTargetCandidate( + target_id="ons.abs.capital_expenditure.sic", + family="ons_abs", + source_name="ons", + publication=_ONS_ABS, + concept="uk.firm.capital_expenditure", + dimensions=("uk.firm.sic_code",), + status=PENDING_LEDGER_SOURCE, + feeds_inputs=( + "firm_capex_main_pool_new", + "firm_capex_main_pool_used", + "firm_capex_special_rate_new", + "firm_capex_special_rate_used", + "firm_capex_structures", + ), + ), + # HMRC Corporation Tax statistics: companies only. Companies and + # liability are banded by corporation tax liability (Tables 10A/10B), + # not by taxable profit. + UKFirmTargetCandidate( + target_id="hmrc.corporation_tax.company_count.liability_bands", + family="hmrc_corporation_tax", + source_name="hmrc", + publication=_HMRC_CT, + concept="uk.firm.count", + dimensions=("uk.tax.corporation_tax.liability_band",), + filters=(_COMPANY,), + status=PENDING_LEDGER_SOURCE, + feeds_inputs=( + "firm_legal_form", + "firm_taxable_trading_profit", + "firm_non_trading_profits", + ), + ), + UKFirmTargetCandidate( + target_id="hmrc.corporation_tax.liability.liability_bands", + family="hmrc_corporation_tax", + source_name="hmrc", + publication=_HMRC_CT, + concept="uk.tax.corporation_tax.liability", + dimensions=("uk.tax.corporation_tax.liability_band",), + filters=(_COMPANY,), + status=PENDING_LEDGER_SOURCE, + feeds_inputs=( + "firm_taxable_trading_profit", + "firm_non_trading_profits", + "firm_losses_brought_forward", + "firm_n_associated_companies", + ), + ), + UKFirmTargetCandidate( + target_id="hmrc.corporation_tax.liability.sic", + family="hmrc_corporation_tax", + source_name="hmrc", + publication=_HMRC_CT, + concept="uk.tax.corporation_tax.liability", + dimensions=("uk.firm.sic_code",), + filters=(_COMPANY,), + status=PENDING_LEDGER_SOURCE, + feeds_inputs=("firm_taxable_trading_profit", "firm_is_bank"), + ), + # HMRC capital allowances: Tables 12-14 of the Corporation Tax + # statistics (12A claims by allowance type; 14A qualifying expenditure + # by type). There is no separate capital allowances series. + UKFirmTargetCandidate( + target_id="hmrc.capital_allowances.amount_claimed.allowance_type", + family="hmrc_capital_allowances", + source_name="hmrc", + publication=_HMRC_CT, + source_table="Table 12A", + concept="uk.tax.corporation_tax.capital_allowances", + dimensions=("uk.tax.capital_allowance_type",), + filters=(_COMPANY,), + status=PENDING_LEDGER_SOURCE, + feeds_inputs=( + "firm_capex_main_pool_new", + "firm_capex_main_pool_used", + "firm_capex_special_rate_new", + "firm_capex_special_rate_used", + "firm_capex_structures", + "firm_aia_share", + "firm_main_pool_brought_forward", + "firm_special_rate_pool_brought_forward", + "firm_sba_qualifying_cost_brought_forward", + "firm_disposal_proceeds_main_pool", + ), + ), + # HMRC R&D tax relief statistics: claims and expenditure by scheme. + UKFirmTargetCandidate( + target_id="hmrc.rd_tax_relief.claim_count.scheme", + family="hmrc_rd_tax_relief", + source_name="hmrc", + publication=_HMRC_RD, + concept="uk.firm.count", + dimensions=("uk.tax.rd_relief_scheme",), + filters=(_COMPANY,), + status=PENDING_LEDGER_SOURCE, + feeds_inputs=("firm_is_sme", "firm_qualifying_rd_expenditure"), + ), + UKFirmTargetCandidate( + target_id="hmrc.rd_tax_relief.qualifying_expenditure.scheme", + family="hmrc_rd_tax_relief", + source_name="hmrc", + publication=_HMRC_RD, + concept="uk.firm.qualifying_rd_expenditure", + dimensions=("uk.tax.rd_relief_scheme",), + filters=(_COMPANY,), + status=PENDING_LEDGER_SOURCE, + feeds_inputs=( + "firm_is_sme", + "firm_qualifying_rd_expenditure", + "firm_total_relevant_expenditure", + ), + ), + # HMRC PAYE Real Time Information: payrolled employees and their pay. + UKFirmTargetCandidate( + target_id="hmrc.paye_rti.payrolled_employees.sic", + family="hmrc_paye_rti", + source_name="hmrc", + publication=_HMRC_PAYE_RTI, + concept="uk.firm.employees", + dimensions=("uk.firm.sic_code",), + status=PENDING_LEDGER_SOURCE, + feeds_inputs=("firm_employees",), + ), + UKFirmTargetCandidate( + # PAYE RTI regions are the employee's residence (NUTS1), not the + # employer's region, so this does not inform firm_region or + # firm_in_england. + target_id="hmrc.paye_rti.payrolled_employees.region", + family="hmrc_paye_rti", + source_name="hmrc", + publication=_HMRC_PAYE_RTI, + concept="uk.firm.employees", + dimensions=("uk.firm.region",), + status=PENDING_LEDGER_SOURCE, + feeds_inputs=("firm_employees",), + ), + UKFirmTargetCandidate( + # Derived, not published: PAYE RTI gives mean pay and payrolled + # employees by SIC section, and the paybill would be their product. + target_id="hmrc.paye_rti.paybill.sic", + family="hmrc_paye_rti", + source_name="hmrc", + publication=_HMRC_PAYE_RTI, + concept="uk.firm.paybill", + dimensions=("uk.firm.sic_code",), + status=PENDING_LEDGER_SOURCE, + feeds_inputs=("firm_paybill",), + ), + # Business rates in England: MHCLG collection and VOA rating lists. + UKFirmTargetCandidate( + target_id="mhclg.nndr.gross_rates_payable.england", + family="mhclg_nndr", + source_name="mhclg", + publication=_MHCLG_NNDR, + concept="uk.tax.business_rates.gross_liability", + filters=(UKFirmTargetFilter("uk.firm.in_england", "==", True),), + status=PENDING_LEDGER_SOURCE, + feeds_inputs=("firm_rateable_value", "firm_in_england", "firm_n_properties"), + ), + UKFirmTargetCandidate( + target_id="mhclg.nndr.reliefs.relief_type", + family="mhclg_nndr", + source_name="mhclg", + publication=_MHCLG_NNDR, + concept="uk.tax.business_rates.relief", + dimensions=("uk.tax.business_rates_relief_type",), + filters=(UKFirmTargetFilter("uk.firm.in_england", "==", True),), + status=PENDING_LEDGER_SOURCE, + feeds_inputs=( + "firm_rateable_value", + "firm_is_charity", + "firm_is_rhl_property", + "firm_is_pub_or_live_music_venue", + "firm_property_occupied", + "firm_months_empty", + ), + ), + # The VOA stock of properties covers England and Wales only. + UKFirmTargetCandidate( + target_id="voa.non_domestic_rating.rateable_value.sector_region", + family="voa_non_domestic_rating", + source_name="voa", + publication=_VOA_STOCK, + concept="uk.firm.rateable_value", + dimensions=("uk.property.non_domestic_sector", "uk.firm.region"), + status=PENDING_LEDGER_SOURCE, + feeds_inputs=( + "firm_rateable_value", + "firm_is_industrial_property", + "firm_n_properties", + "firm_region", + ), + ), +) + + +def uk_firm_target_candidates_feeding(input_name: str) -> tuple[str, ...]: + """Ids of the candidates whose ``feeds_inputs`` name ``input_name``.""" + + return tuple( + candidate.target_id + for candidate in UK_FIRM_TARGET_CANDIDATES + if input_name in candidate.feeds_inputs + ) + + +__all__ = [ + "FIXTURE_AVAILABLE", + "PENDING_LEDGER_SOURCE", + "UK_FIRM_TARGET_CANDIDATES", + "UK_FIRM_TARGET_CANDIDATE_STATUSES", + "UKFirmTargetCandidate", + "UKFirmTargetFilter", + "uk_firm_target_candidates_feeding", +] 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_attribute_fixtures.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_attribute_fixtures.py new file mode 100644 index 0000000000..0e61f7c78f --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_attribute_fixtures.py @@ -0,0 +1,255 @@ +"""The ONS UK Business 2025 attribute fixtures for the experimental firm table. + +``tests/fixtures/uk/firm_attributes_2025`` holds long-format enterprise counts +from Tables 8, 12, 13 and 15 of the ONS workbook tracked in firm-microsim-paper, +written by ``tools/extract_uk_firm_ons_attribute_tables.py``. These checks read +only the committed CSVs and ``.provenance.json``; they never open the workbook. + +ONS control-rounds every cell to base 5, so the tables are checked against the +paper's UK totals within a tolerance, never for exact equality with each other. +""" + +from __future__ import annotations + +import hashlib +import json +from functools import cache +from typing import Any + +import pandas as pd +import pytest + +from microcosm.calibrate.geography_constants import ( + UK_REGION_TIER, + UK_REGION_TIER_ENUM, +) +from test_support.paths import paths_for + +FIXTURES = paths_for("microcosm-build").tests / "fixtures" / "uk" +FIXTURE_DIR = FIXTURES / "firm_attributes_2025" +ONS_TURNOVER = FIXTURES / "firm_2024_25" / "ons_firm_turnover.csv" +RELATIVE_TOLERANCE = 0.01 + +#: The twelve ITL1 region-tier GSS codes, in the workbook's column order. +REGION_CODES = tuple(code for _, code in UK_REGION_TIER) +TABLE_8_BANDS = ("0-49", "50-99", "100-249", "250-499", "500-999", "1000-4999", "5000+") +TABLE_13_BANDS = ( + "0-49", + "50-99", + "100-249", + "250-499", + "500-999", + "1000-1999", + "2000-4999", + "5000-9999", + "10000-49999", + "50000+", +) +TABLE_12_BANDS = ("0-4", "5-9", "10-19", "20-49", "50-99", "100-249", "250+") +LEGAL_STATUSES = tuple(range(1, 8)) +INDUSTRY_GROUPS = ( + "01-03", + "05-39", + "41-43", + "45", + "46", + "47", + "49-53", + "55-56", + "58-63", + "64-66", + "68", + "69-75", + "77-82", + "84", + "85", + "86-88", + "90-99", +) + +FILES: dict[str, dict[str, Any]] = { + "ons_region_turnover.csv": { + "columns": ["sic_division", "region_code", "turnover_band", "enterprises"], + "keys": { + "sic_division": None, + "region_code": REGION_CODES, + "turnover_band": TABLE_8_BANDS, + }, + "rows": 88 * len(REGION_CODES) * len(TABLE_8_BANDS), + }, + "ons_legal_status_turnover.csv": { + "columns": ["industry_group", "legal_status", "turnover_band", "enterprises"], + "keys": { + "industry_group": INDUSTRY_GROUPS, + "legal_status": LEGAL_STATUSES, + "turnover_band": TABLE_13_BANDS, + }, + "rows": len(INDUSTRY_GROUPS) * len(LEGAL_STATUSES) * len(TABLE_13_BANDS), + }, + "ons_legal_status_employment.csv": { + "columns": ["industry_group", "legal_status", "employment_band", "enterprises"], + "keys": { + "industry_group": INDUSTRY_GROUPS, + "legal_status": LEGAL_STATUSES, + "employment_band": TABLE_12_BANDS, + }, + "rows": len(INDUSTRY_GROUPS) * len(LEGAL_STATUSES) * len(TABLE_12_BANDS), + }, + "ons_legal_status_region_turnover.csv": { + "columns": ["region_code", "legal_status", "turnover_band", "enterprises"], + "keys": { + "region_code": REGION_CODES, + "legal_status": LEGAL_STATUSES, + "turnover_band": TABLE_13_BANDS, + }, + "rows": len(REGION_CODES) * len(LEGAL_STATUSES) * len(TABLE_13_BANDS), + }, +} + + +@cache +def _provenance() -> dict[str, Any]: + return json.loads((FIXTURE_DIR / ".provenance.json").read_text(encoding="utf-8")) + + +@cache +def _table(name: str) -> pd.DataFrame: + frame = pd.read_csv( + FIXTURE_DIR / name, + dtype={ + "sic_division": str, + "region_code": str, + "industry_group": str, + "turnover_band": str, + "employment_band": str, + }, + ) + return frame + + +@cache +def _uk_totals() -> pd.Series: + """The ``Total`` row of the paper's ONS Table 8 extract, by sizeband.""" + + turnover = pd.read_csv(ONS_TURNOVER, dtype={"SIC Code": str}) + total = turnover.loc[turnover["Description"] == "Total"] + assert len(total) == 1 + return total.iloc[0][[*TABLE_8_BANDS, "Total"]].astype(int) + + +def _assert_close(actual: int, expected: int, label: str) -> None: + assert expected > 0, label + assert abs(actual - expected) <= RELATIVE_TOLERANCE * expected, ( + label, + actual, + expected, + ) + + +@pytest.mark.parametrize("name", sorted(FILES)) +def test_fixture_bytes_match_provenance(name: str) -> None: + payload = (FIXTURE_DIR / name).read_bytes() + record = _provenance()["files"][name] + assert hashlib.sha256(payload).hexdigest() == record["sha256"] + assert len(payload) == record["bytes"] + assert len(_table(name)) == record["rows"] + + +def test_provenance_records_the_source() -> None: + provenance = _provenance() + assert set(provenance["files"]) == set(FILES) + assert provenance["workbook_tracked_at_paper_commit"] is True + assert len(provenance["paper_commit"]) == 40 + assert len(provenance["workbook"]["sha256"]) == 64 + assert provenance["workbook"]["source_url"].startswith("https://www.ons.gov.uk/") + assert list(provenance["region_codes"]) == list(REGION_CODES) + assert list(provenance["legal_status"]) == [str(code) for code in LEGAL_STATUSES] + assert list(provenance["industry_groups"]) == list(INDUSTRY_GROUPS) + bands = provenance["turnover_bands"] + assert bands["ons_region_turnover.csv"] == list(TABLE_8_BANDS) + assert bands["ons_legal_status_turnover.csv"] == list(TABLE_13_BANDS) + assert set(bands["table_13_to_table_8"]) == set(TABLE_13_BANDS) + assert set(bands["table_13_to_table_8"].values()) == set(TABLE_8_BANDS) + employment = provenance["employment_bands"] + assert employment["ons_legal_status_employment.csv"] == list(TABLE_12_BANDS) + assert provenance["files"]["ons_legal_status_employment.csv"]["source_sheet"] == ( + "Table 12" + ) + + +@pytest.mark.parametrize("name", sorted(FILES)) +def test_fixture_shape_and_keys(name: str) -> None: + spec = FILES[name] + frame = _table(name) + assert list(frame.columns) == spec["columns"] + assert len(frame) == spec["rows"] + keys = list(spec["keys"]) + assert not frame.duplicated(keys).any() + for column, values in spec["keys"].items(): + if values is not None: + assert tuple(frame[column].drop_duplicates()) == values + enterprises = frame["enterprises"] + assert pd.api.types.is_integer_dtype(enterprises) + assert (enterprises >= 0).all() + assert not frame.isna().any().any() + + +def test_sic_divisions_match_the_paper_turnover_table() -> None: + divisions = _table("ons_region_turnover.csv")["sic_division"].drop_duplicates() + turnover = pd.read_csv(ONS_TURNOVER, dtype={"SIC Code": str}) + paper = turnover["SIC Code"].dropna() + assert divisions.str.fullmatch(r"\d{2}").all() + assert list(divisions) == list(paper) + + +def test_region_codes_are_the_uk_region_tier() -> None: + assert set(REGION_CODES) == set(UK_REGION_TIER_ENUM) + + +def test_regional_table_sums_track_uk_totals() -> None: + frame = _table("ons_region_turnover.csv") + totals = _uk_totals() + by_band = frame.groupby("turnover_band")["enterprises"].sum() + for band in TABLE_8_BANDS: + _assert_close(int(by_band[band]), int(totals[band]), f"Table 8 {band}") + _assert_close( + int(frame["enterprises"].sum()), int(totals["Total"]), "Table 8 total" + ) + + +@pytest.mark.parametrize( + ("name", "label"), + [ + ("ons_legal_status_turnover.csv", "Table 13"), + ("ons_legal_status_region_turnover.csv", "Table 15"), + ], +) +def test_legal_status_table_sums_track_uk_totals(name: str, label: str) -> None: + collapse = _provenance()["turnover_bands"]["table_13_to_table_8"] + frame = _table(name) + totals = _uk_totals() + by_band = frame.groupby(frame["turnover_band"].map(collapse))["enterprises"].sum() + for band in TABLE_8_BANDS: + _assert_close(int(by_band[band]), int(totals[band]), f"{label} {band}") + _assert_close( + int(frame["enterprises"].sum()), int(totals["Total"]), f"{label} total" + ) + + +def test_employment_table_tracks_uk_total_and_table_13_statuses() -> None: + """Table 12 counts the same enterprises as Table 13, by employment.""" + + employment = _table("ons_legal_status_employment.csv") + turnover = _table("ons_legal_status_turnover.csv") + _assert_close( + int(employment["enterprises"].sum()), + int(_uk_totals()["Total"]), + "Table 12 total", + ) + by_status = employment.groupby("legal_status")["enterprises"].sum() + expected = turnover.groupby("legal_status")["enterprises"].sum() + for status in LEGAL_STATUSES: + if expected[status] >= 1000: + _assert_close( + int(by_status[status]), int(expected[status]), f"status {status}" + ) diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_attributes.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_attributes.py new file mode 100644 index 0000000000..68205f96db --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_attributes.py @@ -0,0 +1,606 @@ +"""Region and legal status draws for UK firms from ONS Tables 8, 12 and 13.""" + +from __future__ import annotations + +from pathlib import Path + +import numpy as np +import pandas as pd +import pytest + +from microcosm.build.uk_runtime import firm_generation +from microcosm.build.uk_runtime.firm_attributes import ( + UK_FIRM_ATTRIBUTE_FALLBACK_LEVELS, + UK_FIRM_LEGAL_STATUS_EMPLOYMENT_FILE, + UK_FIRM_LEGAL_STATUS_TURNOVER_FILE, + UK_FIRM_REGION_TURNOVER_FILE, + UKFirmAttributeSourceData, + assign_uk_firm_attributes, + industry_group_divisions, + parse_turnover_band_lowers, + read_uk_firm_attribute_source_data, + turnover_band_index, + uk_firm_attribute_fallback_counts, +) +from test_support.paths import paths_for + +FIXTURES = paths_for("microcosm-build").package / "tests" / "fixtures" / "uk" +ATTRIBUTE_FIXTURES = FIXTURES / "firm_attributes_2025" + +REGIONS = ("E12000001", "E12000007", "W92000004") +REGION_BANDS = ("0-49", "50-99", "100+") +#: Table 8 counts by division, then band, then region. Division 2's "50-99" +#: cell is empty, so its firms fall back to division 2's row total. +REGION_COUNTS = { + "01": {"0-49": (600, 300, 100), "50-99": (100, 100, 800), "100+": (50, 900, 50)}, + "02": {"0-49": (100, 0, 0), "50-99": (0, 0, 0), "100+": (0, 0, 100)}, + "45": {"0-49": (200, 200, 600), "50-99": (500, 500, 0), "100+": (0, 1000, 0)}, +} +STATUSES = (1, 2, 5) +STATUS_BANDS = ("0-49", "50-149", "150+") +#: Table 13 counts by industry group, then band, then legal status. +STATUS_COUNTS = { + "01-03": { + "0-49": (100, 800, 100), + "50-149": (500, 500, 0), + "150+": (900, 50, 50), + }, + "45": {"0-49": (300, 700, 0), "50-149": (0, 0, 0), "150+": (1000, 0, 0)}, +} +EMPLOYMENT_BANDS = ("0-4", "5-49", "50+") +#: Table 12 counts by industry group, then employment band, then legal status. +#: In 01-03, P(band | status) is (.2, .8, 0) for status 1, (.9, .1, 0) for +#: status 2 and (0, .5, .5) for status 5. Group 45 is absent, so division 45 +#: uses the UK total, where group 46 moves status 1 to (.1, .4, .5). +EMPLOYMENT_COUNTS = { + "01-03": {"0-4": (200, 900, 0), "5-49": (800, 100, 100), "50+": (0, 0, 100)}, + "46": {"0-4": (0, 0, 0), "5-49": (0, 0, 0), "50+": (1000, 0, 0)}, +} + + +def _write_employment(directory: Path) -> Path: + pd.DataFrame( + [ + (group, status, band, count) + for group, bands in EMPLOYMENT_COUNTS.items() + for band, counts in bands.items() + for status, count in zip(STATUSES, counts, strict=True) + ], + columns=["industry_group", "legal_status", "employment_band", "enterprises"], + ).to_csv(directory / UK_FIRM_LEGAL_STATUS_EMPLOYMENT_FILE, index=False) + return directory + + +def _write_source(directory: Path) -> Path: + pd.DataFrame( + [ + (division, region, band, count) + for division, bands in REGION_COUNTS.items() + for band, counts in bands.items() + for region, count in zip(REGIONS, counts, strict=True) + ], + columns=["sic_division", "region_code", "turnover_band", "enterprises"], + ).to_csv(directory / UK_FIRM_REGION_TURNOVER_FILE, index=False) + pd.DataFrame( + [ + (group, status, band, count) + for group, bands in STATUS_COUNTS.items() + for band, counts in bands.items() + for status, count in zip(STATUSES, counts, strict=True) + ], + columns=["industry_group", "legal_status", "turnover_band", "enterprises"], + ).to_csv(directory / UK_FIRM_LEGAL_STATUS_TURNOVER_FILE, index=False) + return directory + + +@pytest.fixture +def source(tmp_path: Path) -> UKFirmAttributeSourceData: + return read_uk_firm_attribute_source_data(_write_source(tmp_path)) + + +@pytest.fixture +def employment_source(tmp_path: Path) -> UKFirmAttributeSourceData: + return read_uk_firm_attribute_source_data( + _write_employment(_write_source(tmp_path)) + ) + + +def _firms(division: list[int], turnover: list[float], **extra) -> pd.DataFrame: + n = len(division) + frame = pd.DataFrame( + { + "firm_id": np.arange(n, dtype=np.int64), + "sic_code": [str(d).zfill(5) for d in division], + "annual_turnover_k": np.asarray(turnover, dtype=np.float32), + "employment": np.ones(n, dtype=np.int64), + "firm_weight": np.ones(n, dtype=np.float32), + "base_weight": np.ones(n, dtype=np.float64), + "in_frame": np.ones(n, dtype=bool), + "vat_scope": np.ones(n, dtype=bool), + } + ) + for name, values in extra.items(): + frame[name] = values + return frame + + +def _large_frame(seed: int = 7) -> pd.DataFrame: + """Firms in division 1 and 45, turnover spread over every band.""" + + rng = np.random.default_rng(seed) + n = 60_000 + division = rng.choice([1, 45], size=n) + turnover = rng.choice([10.0, 75.0, 120.0, 400.0], size=n) + frame = _firms(division.tolist(), turnover.tolist()) + frame["base_weight"] = rng.uniform(0.5, 1.5, size=n) + return frame + + +# Parsing ------------------------------------------------------------------ + + +def test_band_lowers_parse_closed_and_open_labels() -> None: + lowers = parse_turnover_band_lowers(["50-99", "0-49", "5000+", "100-4999"]) + assert lowers == {"0-49": 0.0, "50-99": 50.0, "100-4999": 100.0, "5000+": 5000.0} + + +@pytest.mark.parametrize( + "labels", + [ + ["0-49", "50-99", "Total", "100+"], + ["0-49", "50-99"], + ["0-49", "100+", "200+"], + ["0-49", "60-99", "100+"], + ["5-49", "50+"], + ], +) +def test_band_lowers_refuse_malformed_labels(labels) -> None: + with pytest.raises(ValueError): + parse_turnover_band_lowers(labels) + + +def test_band_index_uses_contiguous_lower_edges() -> None: + lowers = parse_turnover_band_lowers(["0-49", "50-99", "100-249", "250+"]) + turnover = np.array([0.1, 49.999, 50.0, 99.5, 100.0, 249.9, 250.0, 1e9]) + assert turnover_band_index(turnover, lowers).tolist() == [0, 0, 1, 1, 2, 2, 3, 3] + + +def test_industry_groups_are_parsed_from_their_keys() -> None: + mapping = industry_group_divisions(["01-03", "45", "05-09"]) + assert mapping == { + 1: "01-03", + 2: "01-03", + 3: "01-03", + 45: "45", + 5: "05-09", + 6: "05-09", + 7: "05-09", + 8: "05-09", + 9: "05-09", + } + with pytest.raises(ValueError, match="division 3"): + industry_group_divisions(["01-03", "03-05"]) + with pytest.raises(ValueError): + industry_group_divisions(["Total"]) + + +def test_source_data_refuses_missing_columns(tmp_path: Path) -> None: + directory = _write_source(tmp_path) + frame = pd.read_csv(directory / UK_FIRM_REGION_TURNOVER_FILE) + with pytest.raises(ValueError, match="missing columns"): + UKFirmAttributeSourceData( + region_turnover=frame.drop(columns="region_code"), + legal_status_turnover=pd.read_csv( + directory / UK_FIRM_LEGAL_STATUS_TURNOVER_FILE + ), + ) + + +def test_source_data_refuses_a_legal_status_outside_one_to_seven( + tmp_path: Path, +) -> None: + directory = _write_source(tmp_path) + statuses = pd.read_csv(directory / UK_FIRM_LEGAL_STATUS_TURNOVER_FILE) + statuses.loc[0, "legal_status"] = 8 + with pytest.raises(ValueError, match="1 to 7"): + UKFirmAttributeSourceData( + region_turnover=pd.read_csv(directory / UK_FIRM_REGION_TURNOVER_FILE), + legal_status_turnover=statuses, + ) + + +# Draws -------------------------------------------------------------------- + + +def test_other_columns_are_unchanged_and_input_is_not_mutated(source) -> None: + firms = _firms([1, 2, 45, 99], [10.0, 75.0, 400.0, 20.0]) + firms.index = pd.Index([10, 11, 12, 13]) + before = firms.copy(deep=True) + result = assign_uk_firm_attributes(firms, source, seed=3) + pd.testing.assert_frame_equal(firms, before) + assert list(result.columns) == [ + *firms.columns, + "ons_region_code", + "ons_legal_status", + ] + pd.testing.assert_frame_equal(result[firms.columns], before) + + +def test_output_dtypes(source) -> None: + result = assign_uk_firm_attributes( + _firms([1, 2, 45], [10.0, 75.0, 400.0]), source, seed=0 + ) + assert result["ons_region_code"].dtype == object + assert all(isinstance(code, str) for code in result["ons_region_code"]) + assert set(result["ons_region_code"]) <= set(REGIONS) + assert result["ons_legal_status"].dtype == np.int64 + assert result["ons_legal_status"].between(1, 7).all() + + +def test_draws_are_reproducible_by_seed(source) -> None: + firms = _large_frame() + first = assign_uk_firm_attributes(firms, source, seed=11) + again = assign_uk_firm_attributes(firms, source, seed=11) + other = assign_uk_firm_attributes(firms, source, seed=12) + pd.testing.assert_frame_equal(first, again) + assert not first["ons_region_code"].equals(other["ons_region_code"]) + + +def test_draws_use_one_generator_seeded_at_seed_plus_two(source) -> None: + # One cell for each attribute: division 1, "0-49" (regions 600/300/100) + # and group 01-03, "0-49" (statuses 100/800/100). Region draws first. + seed = 3 + firms = _firms([1] * 40, [10.0] * 40) + result = assign_uk_firm_attributes(firms, source, seed=seed) + + rng = np.random.default_rng(seed + 2) + region = rng.choice(3, size=40, p=np.array([600, 300, 100]) / 1000) + status = rng.choice(3, size=40, p=np.array([100, 800, 100]) / 1000) + assert result["ons_region_code"].tolist() == [REGIONS[i] for i in region] + assert result["ons_legal_status"].tolist() == [STATUSES[i] for i in status] + + +def test_zero_count_categories_are_never_drawn(source) -> None: + # Division 1, "100+": region shares 50/900/50; group 45 "150+" is all + # status 1; division 45 "100+" is all London. + firms = _firms([45] * 500, [400.0] * 500) + result = assign_uk_firm_attributes(firms, source, seed=5) + assert set(result["ons_region_code"]) == {"E12000007"} + assert set(result["ons_legal_status"]) == {1} + + +def _shares(codes: pd.Series, weight: np.ndarray, categories) -> np.ndarray: + totals = np.array( + [weight[(codes == category).to_numpy()].sum() for category in categories] + ) + return totals / totals.sum() + + +@pytest.mark.parametrize( + ("division", "turnover", "region_band", "status_group", "status_band"), + [ + (1, 10.0, "0-49", "01-03", "0-49"), + (1, 75.0, "50-99", "01-03", "50-149"), + (1, 120.0, "100+", "01-03", "50-149"), + (1, 400.0, "100+", "01-03", "150+"), + (45, 10.0, "0-49", "45", "0-49"), + (45, 75.0, "50-99", "45", "0-49"), + ], +) +def test_base_weighted_shares_track_source_cells( + source, division, turnover, region_band, status_group, status_band +) -> None: + firms = _large_frame() + result = assign_uk_firm_attributes(firms, source, seed=21) + in_cell = ( + (firms["sic_code"].astype(int) == division) + & (firms["annual_turnover_k"] == turnover) + ).to_numpy() + weight = firms["base_weight"].to_numpy()[in_cell] + expected_region = np.array( + REGION_COUNTS[str(division).zfill(2)][region_band], dtype=float + ) + np.testing.assert_allclose( + _shares(result["ons_region_code"][in_cell], weight, REGIONS), + expected_region / expected_region.sum(), + atol=0.025, + ) + if turnover == 75.0 and division == 45: + # Group 45's "50-149" cell is empty: the group row total applies. + expected_status = np.sum(list(STATUS_COUNTS["45"].values()), axis=0) + else: + expected_status = np.array(STATUS_COUNTS[status_group][status_band]) + expected_status = np.asarray(expected_status, dtype=float) + np.testing.assert_allclose( + _shares(result["ons_legal_status"][in_cell], weight, STATUSES), + expected_status / expected_status.sum(), + atol=0.025, + ) + + +# Fallbacks ---------------------------------------------------------------- + + +def _levels(source, firms: pd.DataFrame) -> dict[tuple[str, str], int]: + counts = uk_firm_attribute_fallback_counts(firms, source) + return { + (row.attribute, row.level): row.firms + for row in counts.itertuples(index=False) + if row.firms + } + + +def test_fallback_levels_cover_every_path(source) -> None: + firms = _firms( + # cell; empty cell (division 2, "50-99") -> row; unknown division -> UK; + # out of frame (in_frame False) -> row; zero turnover -> row; + # out of frame with an unknown division -> UK. + [1, 2, 99, 1, 45, 99], + [10.0, 75.0, 20.0, 30.0, 0.0, 0.0], + in_frame=[True, True, True, False, True, False], + ) + assert _levels(source, firms) == { + ("ons_region_code", "cell"): 1, + ("ons_region_code", "row"): 3, + ("ons_region_code", "uk"): 2, + # Division 2 is in group "01-03", whose "50-149" cell is populated. + ("ons_legal_status", "cell"): 2, + ("ons_legal_status", "row"): 2, + ("ons_legal_status", "uk"): 2, + } + + +def test_fallback_counts_report_every_level_with_base_weight(source) -> None: + firms = _firms([1, 99], [10.0, 10.0]) + firms["base_weight"] = [2.5, 4.0] + counts = uk_firm_attribute_fallback_counts(firms, source) + assert list(counts.columns) == ["attribute", "level", "firms", "weight"] + assert len(counts) == 2 * len(UK_FIRM_ATTRIBUTE_FALLBACK_LEVELS) + region = counts[counts["attribute"] == "ons_region_code"].set_index("level") + assert region.loc["cell", "weight"] == 2.5 + assert region.loc["row", "weight"] == 0.0 + assert region.loc["uk", "weight"] == 4.0 + + +def test_row_and_uk_fallbacks_draw_from_their_totals(source) -> None: + n = 40_000 + # Division 2 in frame at 75 (empty cell) -> division 2 row: 100 / 0 / 100. + row = assign_uk_firm_attributes(_firms([2] * n, [75.0] * n), source, seed=1) + np.testing.assert_allclose( + _shares(row["ons_region_code"], np.ones(n), REGIONS), + [0.5, 0.0, 0.5], + atol=0.02, + ) + # Unknown division -> UK total over every division and band. + uk = assign_uk_firm_attributes(_firms([99] * n, [20.0] * n), source, seed=1) + uk_counts = np.sum( + [counts for bands in REGION_COUNTS.values() for counts in bands.values()], + axis=0, + ).astype(float) + np.testing.assert_allclose( + _shares(uk["ons_region_code"], np.ones(n), REGIONS), + uk_counts / uk_counts.sum(), + atol=0.02, + ) + # Out of frame in division 1 -> division 1 row total, whatever the turnover. + out = assign_uk_firm_attributes( + _firms([1] * n, [10.0] * n, in_frame=np.zeros(n, dtype=bool)), + source, + seed=1, + ) + row_counts = np.sum(list(REGION_COUNTS["01"].values()), axis=0).astype(float) + np.testing.assert_allclose( + _shares(out["ons_region_code"], np.ones(n), REGIONS), + row_counts / row_counts.sum(), + atol=0.02, + ) + + +def test_nan_turnover_is_refused(source) -> None: + with pytest.raises(ValueError, match="NaN"): + assign_uk_firm_attributes(_firms([1], [float("nan")]), source, seed=0) + + +# Employment (Table 12) ---------------------------------------------------- + + +def test_table_12_is_read_only_when_present(source, employment_source) -> None: + assert source.legal_status_employment is None + frame = employment_source.legal_status_employment + assert frame is not None + assert list(frame.columns) == [ + "industry_group", + "legal_status", + "employment_band", + "enterprises", + ] + + +def test_table_12_must_hold_the_table_13_statuses(tmp_path: Path) -> None: + directory = _write_employment(_write_source(tmp_path)) + source = read_uk_firm_attribute_source_data(directory) + employment = source.legal_status_employment.copy() + employment["legal_status"] = employment["legal_status"].replace(5, 6) + with pytest.raises(ValueError, match="different legal status codes"): + UKFirmAttributeSourceData( + region_turnover=source.region_turnover, + legal_status_turnover=source.legal_status_turnover, + legal_status_employment=employment, + ) + with pytest.raises(ValueError, match="missing columns"): + UKFirmAttributeSourceData( + region_turnover=source.region_turnover, + legal_status_turnover=source.legal_status_turnover, + legal_status_employment=employment.drop(columns="employment_band"), + ) + + +def test_employment_draw_continues_the_same_generator(employment_source) -> None: + # Division 1, turnover "0-49" (100/800/100), employment band "0-4" + # (likelihoods .2/.9/0): weights 20/720/0. Region draws first, unchanged. + seed = 3 + firms = _firms([1] * 40, [10.0] * 40) + result = assign_uk_firm_attributes(firms, employment_source, seed=seed) + + rng = np.random.default_rng(seed + 2) + region = rng.choice(3, size=40, p=np.array([600, 300, 100]) / 1000) + status = rng.choice(3, size=40, p=np.array([20, 720, 0]) / 740) + assert result["ons_region_code"].tolist() == [REGIONS[i] for i in region] + assert result["ons_legal_status"].tolist() == [STATUSES[i] for i in status] + + +def test_employment_leaves_region_and_fallback_levels_unchanged( + source, employment_source +) -> None: + firms = _large_frame() + firms["employment"] = np.random.default_rng(1).integers(0, 400, len(firms)) + without = assign_uk_firm_attributes(firms, source, seed=9) + with_employment = assign_uk_firm_attributes(firms, employment_source, seed=9) + pd.testing.assert_series_equal( + without["ons_region_code"], with_employment["ons_region_code"] + ) + pd.testing.assert_frame_equal( + uk_firm_attribute_fallback_counts(firms, source), + uk_firm_attribute_fallback_counts(firms, employment_source), + ) + + +@pytest.mark.parametrize( + ("division", "turnover", "employment", "expected"), + [ + # Turnover cell 100/800/100 times likelihoods for each band. + (1, 10.0, 0, (20, 720, 0)), + (1, 10.0, 12, (80, 80, 50)), + # A large firm cannot be a sole proprietor in 01-03: only status 5. + (1, 10.0, 300, (0, 0, 1)), + # Out of frame: group 01-03's row total (1500/1350/150) x "5-49". + (2, 0.0, 12, (1200, 135, 75)), + # Division 45 has no Table 12 group: the UK total's likelihoods. + (45, 10.0, 1, (30, 630, 0)), + # Group 45 "150+" is all status 1, whose "50+" likelihood is .5 in + # the UK total. + (45, 400.0, 300, (1, 0, 0)), + ], +) +def test_status_shares_track_turnover_times_employment_likelihood( + employment_source, division, turnover, employment, expected +) -> None: + n = 40_000 + firms = _firms([division] * n, [turnover] * n, employment=[employment] * n) + result = assign_uk_firm_attributes(firms, employment_source, seed=4) + expected = np.asarray(expected, dtype=float) + np.testing.assert_allclose( + _shares(result["ons_legal_status"], np.ones(n), STATUSES), + expected / expected.sum(), + atol=0.01, + ) + + +def test_an_all_zero_product_drops_the_employment_factor(tmp_path: Path) -> None: + # Group 01-03 "150+" is 900/50/50; with a Table 12 in which no status + # has a "50+" enterprise, the product is zero and Table 13 alone applies. + directory = _write_employment(_write_source(tmp_path)) + employment = pd.read_csv(directory / UK_FIRM_LEGAL_STATUS_EMPLOYMENT_FILE) + employment.loc[employment["employment_band"] == "50+", "enterprises"] = 0 + employment.to_csv(directory / UK_FIRM_LEGAL_STATUS_EMPLOYMENT_FILE, index=False) + source = read_uk_firm_attribute_source_data(directory) + n = 40_000 + firms = _firms([1] * n, [400.0] * n, employment=[300] * n) + result = assign_uk_firm_attributes(firms, source, seed=8) + np.testing.assert_allclose( + _shares(result["ons_legal_status"], np.ones(n), STATUSES), + np.array([900, 50, 50]) / 1000, + atol=0.01, + ) + + +@pytest.mark.parametrize( + ("employment", "match"), + [([float("nan")], "NaN"), ([-1], "non-negative")], +) +def test_bad_employment_is_refused(employment_source, employment, match) -> None: + firms = _firms([1], [10.0], employment=employment) + with pytest.raises(ValueError, match=match): + assign_uk_firm_attributes(firms, employment_source, seed=0) + + +def test_missing_employment_is_refused_only_with_table_12( + source, employment_source +) -> None: + firms = _firms([1], [10.0]).drop(columns="employment") + assign_uk_firm_attributes(firms, source, seed=0) + with pytest.raises(ValueError, match="employment"): + assign_uk_firm_attributes(firms, employment_source, seed=0) + + +# Real fixtures ------------------------------------------------------------ + + +def test_real_fixtures_cover_every_ons_division() -> None: + source = read_uk_firm_attribute_source_data(ATTRIBUTE_FIXTURES) + turnover = pd.read_csv( + FIXTURES / "firm_2024_25" / "ons_firm_turnover.csv", dtype={"SIC Code": str} + ) + divisions = [ + int(code) for code in turnover["SIC Code"].dropna() if code.strip().isdigit() + ] + groups = industry_group_divisions( + source.legal_status_turnover["industry_group"].astype(str).str.strip() + ) + assert sorted(set(divisions) - set(groups)) == [] + region_divisions = set( + source.region_turnover["sic_division"].astype(str).str.strip().astype(int) + ) + assert sorted(set(divisions) - region_divisions) == [] + # Table 8 uses the generator's seven ONS bands, labelled alike, with the + # same lower edges. + lowers = parse_turnover_band_lowers(source.region_turnover["turnover_band"]) + assert list(lowers) == [label for label in turnover.columns if label[0].isdigit()] + assert lowers == { + band: lower + for band, (lower, _, _) in firm_generation.ONS_TURNOVER_BANDS.items() + } + # Divisions Table 8 counts no enterprise in (05, 07, 12, ...) have none in + # the generator's frame either, so only out-of-frame traders reach the UK + # total; every division with enterprises resolves to a cell or its row. + populated = ( + turnover.loc[turnover["SIC Code"].str.strip().str.isdigit(), "Total"] + .astype(float) + .gt(0) + .to_numpy() + ) + populated_divisions = [ + d for d, kept in zip(divisions, populated, strict=True) if kept + ] + firms = _firms( + populated_divisions, + np.linspace(1.0, 60_000.0, num=len(populated_divisions)).tolist(), + ) + counts = uk_firm_attribute_fallback_counts(firms, source) + assert set(counts.loc[counts["firms"] > 0, "level"]) <= {"cell", "row"} + + +def test_real_table_12_shares_table_13_groups_and_bounds_sole_proprietors() -> None: + source = read_uk_firm_attribute_source_data(ATTRIBUTE_FIXTURES) + employment = source.legal_status_employment + assert employment is not None + assert set(employment["industry_group"]) == set( + source.legal_status_turnover["industry_group"] + ) + lowers = parse_turnover_band_lowers(employment["employment_band"]) + assert list(lowers.values()) == [0.0, 5.0, 10.0, 20.0, 50.0, 100.0, 250.0] + # A sole proprietor with a large headcount is rare in Table 12, so with + # employment in the draw it is rare among drawn firms of that size too, + # whatever their turnover. + n = 20_000 + rng = np.random.default_rng(0) + firms = _firms( + rng.choice([1, 41, 47, 56, 86], size=n).tolist(), + rng.choice([20.0, 300.0, 1500.0], size=n).tolist(), + employment=rng.choice([1, 300], size=n), + ) + result = assign_uk_firm_attributes(firms, source, seed=5) + sole = result["ons_legal_status"].to_numpy() == 2 + large = firms["employment"].to_numpy() == 300 + assert sole[~large].mean() > 0.05 + assert sole[large].mean() < 0.01 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..63f93997a5 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_build.py @@ -0,0 +1,311 @@ +"""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_INPUT_DATA_YEARS, + 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_EXTENDED_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" +ATTRIBUTES = FIXTURES / "firm_attributes_2025" +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, + attributes_dir=ATTRIBUTES, + 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), ("attributes", ATTRIBUTES)): + 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" + # The attribute source's year, and no key for an input group not read. + assert set(receipt["data_years"]) == { + "ons_frame_turnover", + "ons_frame_turnover_note", + "hmrc_vat_statistics", + "ons_attributes", + } + assert ( + receipt["data_years"]["ons_attributes"] + == (UK_FIRM_INPUT_DATA_YEARS["ons_attributes"]) + ) + 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"] + attributes = { + row["attribute"] for row in receipt["uk_firm_attribute_fallback_counts"] + } + assert attributes == {"ons_region_code", "ons_legal_status"} + assert receipt["output"]["columns"] == list(UK_FIRM_EXTENDED_TABLE_COLUMNS) + assert set(receipt["inputs"]) == {"processed", "attributes"} + + +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), + "--attributes-dir", + str(ATTRIBUTES), + "--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), + "--attributes-dir", + str(ATTRIBUTES), + "--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), + "--attributes-dir", + str(ATTRIBUTES), + "--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"]) + + +def test_input_data_years_refuse_an_unknown_group() -> None: + from microcosm.build.uk_runtime.firm_build import _input_data_years + + assert _input_data_years({"ons_attributes": True}) == { + "ons_attributes": UK_FIRM_INPUT_DATA_YEARS["ons_attributes"] + } + with pytest.raises(ValueError, match="No UK firm data year"): + _input_data_years({"unknown_source": True}) diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_extended_export.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_extended_export.py new file mode 100644 index 0000000000..b75da18ad0 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_extended_export.py @@ -0,0 +1,261 @@ +"""End to end: generated UK firms, ONS attribute draws, policyengine-uk table. + +A thinned 2024-25 build on the paper-parity fixture gets region and legal +status from the ONS UK Business 2025 attribute tables and is exported with +policyengine-uk's firm column names. The ONS Table 15 grid (region x legal +status), which the draws never read, is the held-out check. +""" + +from __future__ import annotations + +from functools import cache + +import numpy as np +import pandas as pd + +from microcosm.build.uk_runtime.firm_attributes import ( + assign_uk_firm_attributes, + read_uk_firm_attribute_source_data, + uk_firm_attribute_fallback_counts, +) +from microcosm.build.uk_runtime.firm_generation import ( + UKFirmGenerationConfig, + UKFirmGenerationResult, + generate_uk_firm_population, + read_uk_firm_source_data, +) +from microcosm.build.uk_runtime.firm_rules import UKFirmRuleOutputs +from microcosm.build.uk_runtime.firm_table import ( + UK_FIRM_EXTENDED_TABLE_COLUMNS, + UK_FIRM_TABLE_COLUMNS, + to_policyengine_uk_firm_table, + validate_uk_firm_table, +) +from microcosm.calibrate.geography_constants import UK_REGION_TIER_ENUM +from test_support.paths import paths_for + +FIXTURES = paths_for("microcosm-build").tests / "fixtures" / "uk" +SEED = 42 + + +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"}, + ) + + +@cache +def _generated() -> UKFirmGenerationResult: + config = UKFirmGenerationConfig( + data_vintage="2024-25", + seed=SEED, + n_iterations=20, + sample_window_fraction=0.02, + sample_tail_fraction=0.005, + firm_rules=_StandardRateDouble(), + ) + return generate_uk_firm_population( + read_uk_firm_source_data(FIXTURES / "firm_2024_25"), config + ) + + +@cache +def _with_attributes() -> pd.DataFrame: + source = read_uk_firm_attribute_source_data(FIXTURES / "firm_attributes_2025") + return assign_uk_firm_attributes(_generated().firms, source, seed=SEED) + + +def test_attribute_draws_leave_generated_columns_unchanged() -> None: + firms = _generated().firms + attributed = _with_attributes() + + pd.testing.assert_frame_equal(attributed[list(firms.columns)], firms) + + +def test_extended_export_validates_and_keeps_the_base_columns() -> None: + result = _generated() + threshold_k = result.config.vat_threshold + base = to_policyengine_uk_firm_table(result.firms, threshold_k=threshold_k) + extended = to_policyengine_uk_firm_table( + _with_attributes(), threshold_k=threshold_k + ) + + validate_uk_firm_table(extended) + assert tuple(extended.columns) == UK_FIRM_EXTENDED_TABLE_COLUMNS + assert tuple(base.columns) == UK_FIRM_TABLE_COLUMNS + pd.testing.assert_frame_equal(extended[list(UK_FIRM_TABLE_COLUMNS)], base) + assert not extended.isna().to_numpy().any() + + +def test_in_frame_firms_use_cells_and_out_of_frame_firms_their_row() -> None: + source = read_uk_firm_attribute_source_data(FIXTURES / "firm_attributes_2025") + firms = _with_attributes() + counts = uk_firm_attribute_fallback_counts(firms, source) + by_level = counts.set_index(["attribute", "level"])["firms"] + in_frame = int(firms["in_frame"].to_numpy(dtype=bool).sum()) + out_of_frame = len(firms) - in_frame + + assert in_frame > 0 + assert out_of_frame > 0 + for attribute in ("ons_region_code", "ons_legal_status"): + # Every in-frame firm has positive turnover and a populated cell; the + # out-of-frame traders draw from their division's or group's row; no + # firm reaches the UK total. + assert int(by_level[(attribute, "cell")]) == in_frame + assert int(by_level[(attribute, "row")]) == out_of_frame + assert int(by_level[(attribute, "uk")]) == 0 + + +def test_weighted_region_by_legal_status_tracks_held_out_table_15() -> None: + held_out = pd.read_csv( + FIXTURES / "firm_attributes_2025" / "ons_legal_status_region_turnover.csv", + dtype={"region_code": str}, + ) + official = held_out.groupby(["region_code", "legal_status"])["enterprises"].sum() + official = official / official.sum() + + firms = _with_attributes() + frame = firms[firms["in_frame"].to_numpy(dtype=bool)] + modelled = frame.groupby(["ons_region_code", "ons_legal_status"])[ + "firm_weight" + ].sum() + modelled.index = modelled.index.set_names(["region_code", "legal_status"]) + modelled = (modelled / modelled.sum()).reindex(official.index, fill_value=0.0) + + # Held out, not calibrated: region and legal status are drawn + # independently given SIC x turnover cells, so the joint share is + # loose. Locally (seed 42, legal status coupled to employment band) the + # total variation distance is 0.035 and the + # company share 0.768 against 0.767; gate only gross failures. + assert float((modelled - official).abs().sum()) / 2 < 0.06 + company = modelled.xs(1, level="legal_status").sum() + official_company = official.xs(1, level="legal_status").sum() + assert abs(company - official_company) < 0.02 + + +#: The two export layouts as named constants spelled them before the group +#: registry (microcosm#1705), written out so a registry change cannot move +#: them unnoticed. Each column's dtype kind: integer, float, bool or string. +_BASE_POLICYENGINE_UK = ( + ("firm_id", "int"), + ("firm_weight", "float"), + ("firm_turnover", "float"), + ("firm_input_costs", "float"), + ("firm_employees", "int"), + ("firm_sic_section", "str"), + ("firm_standard_rated_supplies", "float"), + ("firm_exempt_supplies", "float"), + ("firm_vat_voluntarily_registered", "bool"), + ("firm_input_vat", "float"), +) +_ATTRIBUTE_POLICYENGINE_UK = ( + ("firm_legal_form", "str"), + ("firm_region", "str"), + ("firm_in_england", "bool"), + ("firm_is_public_body", "bool"), + ("firm_is_charity", "bool"), +) +_BASE_MICROCOSM = ( + ("in_frame", "bool"), + ("vat_scope", "bool"), + ("vat_registered", "bool"), + ("base_weight", "float"), + ("data_vintage", "str"), + ("source_firm_id", "int"), + ("source_firm_key", "str"), +) +_ATTRIBUTE_MICROCOSM = (("ons_legal_status", "int"), ("ons_region_code", "str")) +_LEGACY_LAYOUTS = { + "base": (*_BASE_POLICYENGINE_UK, *_BASE_MICROCOSM), + "extended": ( + *_BASE_POLICYENGINE_UK, + *_ATTRIBUTE_POLICYENGINE_UK, + *_BASE_MICROCOSM, + *_ATTRIBUTE_MICROCOSM, + ), +} +_DTYPE_CHECKS = { + "int": lambda series: series.dtype == np.int64, + "float": lambda series: series.dtype == np.float64, + "bool": lambda series: series.dtype == np.bool_, + "str": pd.api.types.is_string_dtype, +} + + +def _legacy_extended(base: pd.DataFrame, rows: pd.DataFrame) -> pd.DataFrame: + """The pre-registry assembly of the extended export, spelled out. + + ``rows`` are the attributed generator rows ordered by ``firm_id``. ONS + legal statuses 1 and 4 are COMPANY, 5-7 OTHER, 4-6 public bodies and 7 + charities; the nine E12 codes are English regions. + """ + + status = rows["ons_legal_status"].to_numpy(np.int64) + code = rows["ons_region_code"].to_numpy(object) + legal_form = {1: "COMPANY", 2: "SOLE_TRADER", 3: "PARTNERSHIP", 4: "COMPANY"} + region = dict(UK_REGION_TIER_ENUM) + table = base.assign( + firm_legal_form=np.array( + [legal_form.get(int(s), "OTHER") for s in status], dtype=object + ), + firm_region=np.array([region[c] for c in code], dtype=object), + firm_in_england=np.array([c.startswith("E12") for c in code], dtype=bool), + firm_is_public_body=np.isin(status, [4, 5, 6]), + firm_is_charity=status == 7, + ons_legal_status=status, + ons_region_code=code, + ) + return table[[column for column, _ in _LEGACY_LAYOUTS["extended"]]] + + +def _exports() -> dict[str, pd.DataFrame]: + threshold_k = _generated().config.vat_threshold + attributed = _with_attributes() + return { + layout: to_policyengine_uk_firm_table(firms, threshold_k=threshold_k) + for layout, firms in ( + ("base", _generated().firms), + ("extended", attributed), + ) + } + + +def test_export_layouts_match_the_pre_registry_constants() -> None: + """Same-seed builds export the two layouts the named constants gave. + + Columns, their order and dtypes are the literal pre-registry layouts; + the named constants still spell them; the extended export + equals the base export assembled with its columns as the pre-registry + code assembled them. + """ + + assert UK_FIRM_TABLE_COLUMNS == tuple(c for c, _ in _LEGACY_LAYOUTS["base"]) + assert UK_FIRM_EXTENDED_TABLE_COLUMNS == tuple( + c for c, _ in _LEGACY_LAYOUTS["extended"] + ) + exports = _exports() + for layout, table in exports.items(): + expected = _LEGACY_LAYOUTS[layout] + assert list(table.columns) == [column for column, _ in expected], layout + for column, kind in expected: + assert _DTYPE_CHECKS[kind](table[column]), (layout, column) + validate_uk_firm_table(table) + assert table.index.equals(pd.RangeIndex(len(table))) + + base, extended = (exports[k] for k in ("base", "extended")) + rows = _with_attributes().sort_values("firm_id", kind="stable") + legacy_extended = _legacy_extended(base, rows) + pd.testing.assert_frame_equal(extended, legacy_extended, check_exact=True) + # Exporting the same seed's rows again gives the same tables. + for layout, table in _exports().items(): + pd.testing.assert_frame_equal(table, exports[layout], check_exact=True) 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..f453645e3d --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_policyengine_uk_schema.py @@ -0,0 +1,175 @@ +"""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 +import pytest + +from microcosm.build.firms import ( + EntityVariables, + export_schema_problems, + input_status_problems, +) +from microcosm.build.uk_runtime.firm_table import ( + UK_FIRM_EXPORT_GROUPS, + UK_FIRM_EXTENDED_TABLE_COLUMNS, + UK_FIRM_INPUT_STATUSES, + UK_FIRM_LEGAL_FORMS, + UK_FIRM_MICROCOSM_COLUMNS, + UK_FIRM_MICROCOSM_ONLY_COLUMNS, + UK_FIRM_ONS_LEGAL_STATUS_TO_LEGAL_FORM, + UK_FIRM_POLICYENGINE_UK_INPUT_STATUS, + UK_FIRM_REGION_CODE_TO_REGION, + UK_FIRM_SIC_SECTIONS, + UK_FIRM_TABLE_COLUMNS, + to_policyengine_uk_firm_table, + uk_firm_policyengine_uk_columns, +) +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(*, attributes: bool = False) -> pd.DataFrame: + firms = 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], + } + ) + if attributes: + firms["ons_legal_status"] = np.array([1, 2, 5, 7], dtype=np.int64) + firms["ons_region_code"] = ["E12000007", "W92000004", "S92000003", "N92000002"] + return firms + + +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( + group.name for group in UK_FIRM_EXPORT_GROUPS + ), + ) + == [] + ) + + +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_legal_forms_and_regions_are_enum_members() -> None: + legal_form = _variable("firm_legal_form") + region = _variable("firm_region") + + assert legal_form["enum"]["name"] == "FirmLegalForm" + assert UK_FIRM_LEGAL_FORMS == tuple(legal_form["enum_members"]) + assert set(UK_FIRM_ONS_LEGAL_STATUS_TO_LEGAL_FORM.values()) <= set( + legal_form["enum_members"] + ) + assert region["enum"] == { + "module": "policyengine_uk.variables.household.demographic.geography", + "name": "Region", + } + assert set(UK_FIRM_REGION_CODE_TO_REGION.values()) <= set(region["enum_members"]) + + +def test_microcosm_only_columns_collide_with_no_policyengine_uk_variable() -> None: + snapshot = _snapshot() + microcosm_only = {*UK_FIRM_MICROCOSM_COLUMNS, *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) + + +@pytest.mark.parametrize( + ("attributes", "expected", "groups"), + [ + (False, UK_FIRM_TABLE_COLUMNS, ()), + (True, UK_FIRM_EXTENDED_TABLE_COLUMNS, ("attributes",)), + ], +) +def test_export_loads_as_policyengine_uk_firm_inputs( + attributes, expected, groups +) -> None: + table = to_policyengine_uk_firm_table( + _firms(attributes=attributes), threshold_k=90.0 + ) + assert tuple(table.columns) == expected + assert ( + export_schema_problems( + table, _variables(), columns=uk_firm_policyengine_uk_columns(groups) + ) + == [] + ) 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..0daa265887 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_table.py @@ -0,0 +1,554 @@ +"""UK firm tables in policyengine-uk names: candidates, export and contract.""" + +from __future__ import annotations + +import itertools + +import numpy as np +import pandas as pd +import pytest + +from microcosm.build.uk_runtime.firm_table import ( + ASSUMED_INPUT_VAT_RATE, + UK_FIRM_ATTRIBUTE_POLICYENGINE_UK_COLUMNS, + UK_FIRM_CANDIDATE_RULES_COLUMNS, + UK_FIRM_CHARITY_ONS_LEGAL_STATUSES, + UK_FIRM_ENGLISH_REGION_CODES, + UK_FIRM_EXPORT_GROUPS, + UK_FIRM_EXTENDED_POLICYENGINE_UK_COLUMNS, + UK_FIRM_EXTENDED_TABLE_COLUMNS, + UK_FIRM_INPUT_STATUSES, + UK_FIRM_LEGAL_FORMS, + UK_FIRM_MICROCOSM_COLUMNS, + UK_FIRM_MICROCOSM_ONLY_COLUMNS, + UK_FIRM_ONS_ATTRIBUTE_COLUMNS, + UK_FIRM_ONS_LEGAL_STATUS_TO_LEGAL_FORM, + UK_FIRM_POLICYENGINE_UK_COLUMNS, + UK_FIRM_POLICYENGINE_UK_INPUT_STATUS, + UK_FIRM_PUBLIC_BODY_ONS_LEGAL_STATUSES, + UK_FIRM_REGION_CODE_TO_REGION, + UK_FIRM_SIC_SECTIONS, + UK_FIRM_TABLE_COLUMNS, + UK_FIRM_TABLE_LAYOUTS, + UKFirmExportGroup, + build_candidate_rules_table, + to_policyengine_uk_firm_table, + uk_firm_export_groups, + uk_firm_policyengine_uk_columns, + uk_firm_sic_sections, + uk_firm_table_columns, + 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") + +#: policyengine-uk ``FirmLegalForm`` members (policyengine_uk/variables/firm/ +#: firm_legal_form.py) and ``Region`` members (policyengine_uk/variables/ +#: household/demographic/geography.py), in declaration order. +_POLICYENGINE_UK_FIRM_LEGAL_FORM_MEMBERS = ( + "COMPANY", + "SOLE_TRADER", + "PARTNERSHIP", + "OTHER", +) +_POLICYENGINE_UK_REGION_MEMBERS = ( + "UNKNOWN", + "NORTH_EAST", + "NORTH_WEST", + "YORKSHIRE", + "EAST_MIDLANDS", + "WEST_MIDLANDS", + "EAST_OF_ENGLAND", + "LONDON", + "SOUTH_EAST", + "SOUTH_WEST", + "WALES", + "SCOTLAND", + "NORTHERN_IRELAND", +) + + +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) + + +def _attributed_firms() -> pd.DataFrame: + # Firms 4, 2, 1, 3: a Welsh company, a local authority in the North East, a + # Scottish partnership and a London sole trader. + return _firms().assign( + ons_legal_status=np.array([1, 6, 3, 2], dtype=np.int64), + ons_region_code=["W92000004", "E12000001", "S92000003", "E12000007"], + ) + + +def test_base_export_columns_are_unchanged() -> None: + assert 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", + ) + assert UK_FIRM_TABLE_COLUMNS == ( + *UK_FIRM_POLICYENGINE_UK_COLUMNS, + "in_frame", + "vat_scope", + "vat_registered", + "base_weight", + "data_vintage", + "source_firm_id", + "source_firm_key", + ) + table = to_policyengine_uk_firm_table(_firms(), threshold_k=90.0) + assert tuple(table.columns) == UK_FIRM_TABLE_COLUMNS + + +def test_extended_columns_add_the_attributes_after_the_base_ones() -> None: + assert UK_FIRM_EXTENDED_POLICYENGINE_UK_COLUMNS == ( + *UK_FIRM_POLICYENGINE_UK_COLUMNS, + *UK_FIRM_ATTRIBUTE_POLICYENGINE_UK_COLUMNS, + ) + assert UK_FIRM_MICROCOSM_ONLY_COLUMNS == ( + *UK_FIRM_MICROCOSM_COLUMNS, + "ons_legal_status", + "ons_region_code", + ) + assert UK_FIRM_EXTENDED_TABLE_COLUMNS == ( + *UK_FIRM_EXTENDED_POLICYENGINE_UK_COLUMNS, + *UK_FIRM_MICROCOSM_ONLY_COLUMNS, + ) + assert "region" not in UK_FIRM_EXTENDED_TABLE_COLUMNS + assert len(set(UK_FIRM_EXTENDED_TABLE_COLUMNS)) == len( + UK_FIRM_EXTENDED_TABLE_COLUMNS + ) + + +def test_attribute_maps_match_policyengine_uk_members() -> None: + assert UK_FIRM_LEGAL_FORMS == _POLICYENGINE_UK_FIRM_LEGAL_FORM_MEMBERS + assert set(UK_FIRM_ONS_LEGAL_STATUS_TO_LEGAL_FORM) == set(range(1, 8)) + assert set(UK_FIRM_ONS_LEGAL_STATUS_TO_LEGAL_FORM.values()) == set( + UK_FIRM_LEGAL_FORMS + ) + assert UK_FIRM_PUBLIC_BODY_ONS_LEGAL_STATUSES == {4, 5, 6} + assert UK_FIRM_CHARITY_ONS_LEGAL_STATUSES == {7} + assert UK_FIRM_ONS_LEGAL_STATUS_TO_LEGAL_FORM[4] == "COMPANY" + assert UK_FIRM_ONS_LEGAL_STATUS_TO_LEGAL_FORM[7] == "OTHER" + # Every Region member but UNKNOWN, each from exactly one GSS code. + regions = list(UK_FIRM_REGION_CODE_TO_REGION.values()) + assert sorted(regions) == sorted(_POLICYENGINE_UK_REGION_MEMBERS[1:]) + assert len(set(regions)) == len(regions) + assert UK_FIRM_ENGLISH_REGION_CODES == {f"E1200000{i}" for i in range(1, 10)} + assert set(UK_FIRM_REGION_CODE_TO_REGION) == UK_FIRM_ENGLISH_REGION_CODES | { + "W92000004", + "S92000003", + "N92000002", + } + + +def test_extended_export_maps_the_ons_attributes() -> None: + table = to_policyengine_uk_firm_table(_attributed_firms(), threshold_k=90.0) + assert tuple(table.columns) == UK_FIRM_EXTENDED_TABLE_COLUMNS + validate_uk_firm_table(table) + # Ordered by firm_id: 1, 2, 3, 4. + assert table["ons_legal_status"].tolist() == [3, 6, 2, 1] + assert pd.api.types.is_integer_dtype(table["ons_legal_status"]) + assert table["ons_region_code"].tolist() == [ + "S92000003", + "E12000001", + "E12000007", + "W92000004", + ] + assert table["firm_legal_form"].tolist() == [ + "PARTNERSHIP", + "OTHER", + "SOLE_TRADER", + "COMPANY", + ] + assert table["firm_region"].tolist() == [ + "SCOTLAND", + "NORTH_EAST", + "LONDON", + "WALES", + ] + assert table["firm_in_england"].tolist() == [False, True, True, False] + assert table["firm_is_public_body"].tolist() == [False, True, False, False] + assert pd.api.types.is_bool_dtype(table["firm_in_england"]) + assert pd.api.types.is_bool_dtype(table["firm_is_public_body"]) + assert table["firm_is_charity"].tolist() == [False, False, False, False] + assert pd.api.types.is_bool_dtype(table["firm_is_charity"]) + base = to_policyengine_uk_firm_table(_firms(), threshold_k=90.0) + pd.testing.assert_frame_equal(table[list(UK_FIRM_TABLE_COLUMNS)], base) + + +def test_public_corporations_are_companies_and_non_profits_charities() -> None: + # Firms 4, 2, 1, 3 (ordered 1, 2, 3, 4): a public corporation, a + # non-profit body, central government and a company. + firms = _attributed_firms().assign( + ons_legal_status=np.array([1, 7, 4, 5], dtype=np.int64) + ) + table = to_policyengine_uk_firm_table(firms, threshold_k=90.0) + validate_uk_firm_table(table) + assert table["ons_legal_status"].tolist() == [4, 7, 5, 1] + assert table["firm_legal_form"].tolist() == ["COMPANY", "OTHER", "OTHER", "COMPANY"] + assert table["firm_is_public_body"].tolist() == [True, False, True, False] + assert table["firm_is_charity"].tolist() == [False, True, False, False] + with pytest.raises(ValueError, match="follow ons_legal_status"): + validate_uk_firm_table(table.assign(firm_is_charity=False)) + + +@pytest.mark.parametrize("column", UK_FIRM_ONS_ATTRIBUTE_COLUMNS) +def test_export_refuses_one_ons_attribute_without_the_other(column) -> None: + with pytest.raises(ValueError, match="needs both"): + to_policyengine_uk_firm_table( + _attributed_firms().drop(columns=column), threshold_k=90.0 + ) + + +@pytest.mark.parametrize( + ("column", "values", "match"), + [ + ("ons_legal_status", np.array([1, 8, 3, 2]), "legal status codes"), + ("ons_legal_status", np.array([1, 0, 3, 2]), "legal status codes"), + ("ons_legal_status", [1.0, np.nan, 3.0, 2.0], "integers"), + ("ons_region_code", ["W92000004", "E12000010", "S92000003", ""], "GSS"), + ("ons_region_code", ["W92000004", None, "S92000003", "E12000007"], "str"), + ("ons_region_code", ["W92000004", "LONDON", "S92000003", "E12000007"], "GSS"), + ], +) +def test_export_never_falls_back_to_policyengine_uk_defaults( + column, values, match +) -> None: + firms = _attributed_firms().assign(**{column: values}) + with pytest.raises(ValueError, match=match): + to_policyengine_uk_firm_table(firms, threshold_k=90.0) + + +@pytest.mark.parametrize( + ("mutate", "match"), + [ + (lambda t: t.assign(firm_legal_form="LIMITED"), "FirmLegalForm"), + (lambda t: t.assign(firm_region="UNKNOWN"), "Region member"), + (lambda t: t.assign(firm_region="E12000007"), "Region member"), + (lambda t: t.assign(firm_legal_form="COMPANY"), "follow ons_legal_status"), + (lambda t: t.assign(firm_region="LONDON"), "follow ons_region_code"), + (lambda t: t.assign(firm_in_england=True), "follow ons_region_code"), + (lambda t: t.assign(firm_is_public_body=False), "follow ons_legal_status"), + (lambda t: t.assign(firm_in_england=[0, 1, 1, 0]), "boolean"), + (lambda t: t.assign(ons_legal_status=[3.0, 6.0, 2.0, 1.0]), "integers"), + (lambda t: t.assign(ons_legal_status=[3, 9, 2, 1]), "legal status codes"), + (lambda t: t.assign(ons_region_code=[1, 2, 3, 4]), "strings"), + (lambda t: t.assign(ons_region_code="E92000001"), "GSS"), + (lambda t: t.drop(columns="ons_region_code"), "columns"), + (lambda t: t.drop(columns="firm_region"), "columns"), + (lambda t: t.rename(columns={"ons_region_code": "region"}), "columns"), + ], +) +def test_validation_refuses_extended_tables_outside_the_contract(mutate, match) -> None: + table = to_policyengine_uk_firm_table(_attributed_firms(), threshold_k=90.0) + with pytest.raises(ValueError, match=match): + validate_uk_firm_table(mutate(table)) + + +@pytest.mark.parametrize("extended", [False, True]) +def test_validation_refuses_missing_values_in_any_column(extended) -> None: + firms = _attributed_firms() if extended else _firms() + table = to_policyengine_uk_firm_table(firms, threshold_k=90.0) + for column in table.columns: + broken = table.astype({column: object}) + broken.loc[1, column] = np.nan + with pytest.raises(ValueError, match=f"missing values in .*{column}"): + validate_uk_firm_table(broken) + + +def test_input_status_covers_every_exported_policyengine_uk_column() -> None: + assert set(UK_FIRM_POLICYENGINE_UK_INPUT_STATUS.values()) <= set( + UK_FIRM_INPUT_STATUSES + ) + exported = { + name + for name, status in UK_FIRM_POLICYENGINE_UK_INPUT_STATUS.items() + if status in ("set", "derived", "assumed") + } + assert exported == set( + uk_firm_policyengine_uk_columns(group.name for group in UK_FIRM_EXPORT_GROUPS) + ) + # The same set straight from the registry: the base and every group. + assert exported == set(UK_FIRM_POLICYENGINE_UK_COLUMNS) | { + column + for group in UK_FIRM_EXPORT_GROUPS + for column in group.policyengine_uk_columns + } + # firm_in_england is the enterprise's region standing in for its + # property's location, so it is an assumption, not a derivation. + assert { + name + for name, status in UK_FIRM_POLICYENGINE_UK_INPUT_STATUS.items() + if status == "assumed" + } == { + "firm_input_vat", + "firm_legal_form", + "firm_is_public_body", + "firm_is_charity", + "firm_in_england", + } + assert all( + name.startswith("firm_") for name in UK_FIRM_POLICYENGINE_UK_INPUT_STATUS + ) + assert not set(UK_FIRM_MICROCOSM_ONLY_COLUMNS) & set( + UK_FIRM_POLICYENGINE_UK_INPUT_STATUS + ) + with pytest.raises(TypeError): + UK_FIRM_POLICYENGINE_UK_INPUT_STATUS["firm_paybill"] = "set" # type: ignore[index] + + +def test_export_groups_register_the_attribute_inputs() -> None: + assert all(isinstance(group, UKFirmExportGroup) for group in UK_FIRM_EXPORT_GROUPS) + names = [group.name for group in UK_FIRM_EXPORT_GROUPS] + assert names == [ + "attributes", + ] + (attributes,) = UK_FIRM_EXPORT_GROUPS + assert attributes.source_columns == UK_FIRM_ONS_ATTRIBUTE_COLUMNS + assert attributes.policyengine_uk_columns == ( + UK_FIRM_ATTRIBUTE_POLICYENGINE_UK_COLUMNS + ) + assert attributes.microcosm_columns == UK_FIRM_ONS_ATTRIBUTE_COLUMNS + assert attributes.requires == () + # Each group comes after the groups it extends, and no column repeats. + for index, group in enumerate(UK_FIRM_EXPORT_GROUPS): + assert set(group.requires) <= set(names[:index]) + every = uk_firm_table_columns(names) + assert len(set(every)) == len(every) + + +def test_layouts_are_the_base_and_each_closed_set_of_groups() -> None: + # The base, then attributes with any subset of the groups that extend + # it. + extending = [] + expected = {(): UK_FIRM_TABLE_COLUMNS} + for size in range(len(extending) + 1): + for chosen in itertools.combinations(extending, size): + names = ("attributes", *chosen) + expected[names] = uk_firm_table_columns(names) + assert dict(UK_FIRM_TABLE_LAYOUTS) == expected + assert UK_FIRM_TABLE_LAYOUTS[("attributes",)] == UK_FIRM_EXTENDED_TABLE_COLUMNS + assert uk_firm_table_columns() == UK_FIRM_TABLE_COLUMNS + assert uk_firm_policyengine_uk_columns() == UK_FIRM_POLICYENGINE_UK_COLUMNS + # Order of the names given does not matter: the registry orders them. + assert uk_firm_table_columns(iter(["attributes"])) == ( + UK_FIRM_EXTENDED_TABLE_COLUMNS + ) + with pytest.raises(ValueError, match="Unknown"): + uk_firm_table_columns(["not_a_registered_group"]) + + +def test_export_groups_follow_the_rows_source_columns() -> None: + assert uk_firm_export_groups(_firms()) == () + assert uk_firm_export_groups(_attributed_firms()) == ("attributes",) + with pytest.raises(ValueError, match="needs both"): + uk_firm_export_groups(_attributed_firms().drop(columns="ons_region_code")) diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_target_candidates.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_target_candidates.py new file mode 100644 index 0000000000..02192ff7b6 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_firm_target_candidates.py @@ -0,0 +1,186 @@ +"""The M2 UK firm target candidates: declarations only, none in the contract.""" + +from __future__ import annotations + +import json +from dataclasses import asdict + +from microcosm.build.uk_runtime.firm_generation import ( + UK_FIRM_TARGET_IDS, + load_uk_firms_contract, +) +from microcosm.build.uk_runtime.firm_table import ( + UK_FIRM_POLICYENGINE_UK_INPUT_STATUS, +) +from microcosm.build.uk_runtime.firm_target_candidates import ( + FIXTURE_AVAILABLE, + PENDING_LEDGER_SOURCE, + UK_FIRM_TARGET_CANDIDATE_STATUSES, + UK_FIRM_TARGET_CANDIDATES, + uk_firm_target_candidates_feeding, +) +from test_support.microcosm_build.uk_firm_target_keys import carried_forbidden_keys +from test_support.paths import paths_for + +SNAPSHOT = ( + paths_for("microcosm-build").tests + / "fixtures" + / "uk" + / "policyengine_uk_firm_inputs.json" +) + +#: The ONS UK Business 2025 tables Microcosm holds as fixtures. +_FIXTURE_TABLES = {"Table 8", "Table 13", "Table 15"} + +#: The tables pending candidates name: ONS UK Business Table 3 (no regional +#: extract in Microcosm) and Corporation Tax statistics Table 12A. +_PENDING_TABLES = {"Table 3", "Table 12A"} + +#: Every family that must declare at least one pending candidate. +_PENDING_FAMILIES = { + "ons_uk_business", + "dbt_bpe", + "ons_abs", + "hmrc_corporation_tax", + "hmrc_capital_allowances", + "hmrc_rd_tax_relief", + "hmrc_paye_rti", + "mhclg_nndr", + "voa_non_domestic_rating", +} + + +def _snapshot_inputs() -> set[str]: + return set(json.loads(SNAPSHOT.read_text(encoding="utf-8"))["firm_input_names"]) + + +def test_candidates_are_value_free_and_hook_free() -> None: + carried = carried_forbidden_keys( + [asdict(candidate) for candidate in UK_FIRM_TARGET_CANDIDATES] + ) + + assert not carried, sorted(carried) + + +def test_candidate_ids_are_unique_and_outside_the_contract() -> None: + ids = [candidate.target_id for candidate in UK_FIRM_TARGET_CANDIDATES] + + assert len(ids) == len(set(ids)) + assert set(ids).isdisjoint(UK_FIRM_TARGET_IDS.values()) + + +def test_candidates_carry_no_ledger_record_set_id() -> None: + assert all( + candidate.ledger_record_set_id is None + for candidate in UK_FIRM_TARGET_CANDIDATES + ) + + +def test_committed_contract_keeps_its_eight_targets() -> None: + contract = load_uk_firms_contract() + + assert len(contract["targets"]) == 8 + assert [target["target_id"] for target in contract["targets"]] == list( + UK_FIRM_TARGET_IDS.values() + ) + + +def test_candidates_feed_policyengine_uk_firm_inputs() -> None: + inputs = _snapshot_inputs() + + for candidate in UK_FIRM_TARGET_CANDIDATES: + assert candidate.feeds_inputs, candidate.target_id + assert set(candidate.feeds_inputs) <= inputs, ( + candidate.target_id, + sorted(set(candidate.feeds_inputs) - inputs), + ) + + +def test_candidate_statuses_families_and_fixture_tables() -> None: + for candidate in UK_FIRM_TARGET_CANDIDATES: + assert candidate.status in UK_FIRM_TARGET_CANDIDATE_STATUSES + assert candidate.entity == "firm" + assert candidate.publication + assert candidate.concept.startswith(("uk.firm.", "uk.tax.")) + assert all( + dimension.startswith(("uk.firm.", "uk.tax.", "uk.property.")) + for dimension in candidate.dimensions + ), candidate.target_id + assert candidate.target_id.startswith(f"{candidate.source_name}."), ( + candidate.target_id + ) + fixture = [c for c in UK_FIRM_TARGET_CANDIDATES if c.status == FIXTURE_AVAILABLE] + pending = [ + c for c in UK_FIRM_TARGET_CANDIDATES if c.status == PENDING_LEDGER_SOURCE + ] + + assert {c.source_table for c in fixture} == _FIXTURE_TABLES + assert all(c.family == "ons_uk_business" for c in fixture) + assert {c.family for c in pending} == _PENDING_FAMILIES + assert {c.source_table for c in pending} - {None} == _PENDING_TABLES + + +#: not_set policyengine-uk inputs that no candidate informs yet: no source is +#: declared for them. +_NOT_SET_WITHOUT_CANDIDATE = { + # Class 1A, live music venue relief and the RDEC PAYE/NIC cap + # (policyengine-uk d856de5a7). + "firm_class_1a_benefits", + # Welsh rates, the small profits rate exclusion and full expensing + # (policyengine-uk 0d1c25010). + "firm_capex_main_pool_new_for_leasing", + "firm_disposal_proceeds_full_expensing", + "firm_is_wales_higher_multiplier_excluded", + "firm_is_wales_retail_property", + "firm_small_profits_rate_excluded", + "firm_is_live_music_venue", + "firm_rd_staff_paye_nic", + "firm_rdec_paye_nic_cap_supplied", + "firm_relevant_paye_nic_liabilities", + "firm_apprenticeship_levy_allowance_share", + "firm_deductions_allowance_share", + "firm_exempt_distributions", + "firm_in_freeport", + "firm_is_limited_cost_trader", + "firm_reduced_rated_supplies", + "firm_uses_flat_rate_scheme", + "firm_zero_rated_class_1_earnings", + "firm_zero_rated_supplies", + # Bank surcharge allowance share (policyengine-uk 57a99a67a). + "firm_bank_surcharge_allowance_share", + # Pay-distribution and minimum-wage inputs (policyengine-uk ca037fad2). + "firm_employees_above_auto_enrolment_upper_limit", + "firm_employees_below_auto_enrolment_earnings_trigger", + "firm_low_paid_hours", + "firm_low_paid_paybill", + "firm_paybill_above_auto_enrolment_upper_limit", + "firm_paybill_below_auto_enrolment_earnings_trigger", + "firm_employees_below_secondary_threshold", + "firm_paybill_below_secondary_threshold", + # Employment Allowance flags. + "firm_claims_employment_allowance", + "firm_is_single_director_company", +} + + +def test_not_set_inputs_without_a_candidate_are_pinned() -> None: + not_set = { + name + for name, status in UK_FIRM_POLICYENGINE_UK_INPUT_STATUS.items() + if status == "not_set" + } + without = {name for name in not_set if not uk_firm_target_candidates_feeding(name)} + + assert without == _NOT_SET_WITHOUT_CANDIDATE + + +def test_candidates_feeding_names_the_candidates_for_an_input() -> None: + feeding = uk_firm_target_candidates_feeding("firm_paybill") + + assert feeding + assert all( + "firm_paybill" in candidate.feeds_inputs + for candidate in UK_FIRM_TARGET_CANDIDATES + if candidate.target_id in feeding + ) + assert uk_firm_target_candidates_feeding("not_a_firm_input") == () 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/engine_free/uk/test_uk_firms_targets.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_firms_targets.py index 3f11775d40..5c696ec591 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_firms_targets.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_firms_targets.py @@ -3,7 +3,6 @@ from __future__ import annotations import json -from collections.abc import Mapping from importlib import resources as importlib_resources from microcosm.build.uk_runtime.firm_generation import ( @@ -12,22 +11,8 @@ load_uk_firms_contract, uk_firm_target_profile_from_mapping, ) +from test_support.microcosm_build.uk_firm_target_keys import carried_forbidden_keys -FORBIDDEN_VALUE_KEYS = {"aggregation", "operation", "registry", "target_value", "value"} -FORBIDDEN_RUNTIME_KEYS = { - "callable", - "command", - "execute", - "executable", - "function", - "import", - "imports", - "module", - "python_code", - "runtime_code", - "script", - "solver", -} FIRM_SELECTOR_KEYS = { "source_name", "source_measure_id", @@ -41,31 +26,6 @@ def _load() -> dict: return load_uk_firms_contract() -def _is_filter_predicate(node: Mapping) -> bool: - return ( - "value" in node - and "operator" in node - and ("concept" in node or "variable" in node) - ) - - -def _carried_forbidden_keys(node, *, in_defaults: bool = False) -> set[str]: - carried: set[str] = set() - if isinstance(node, Mapping): - forbidden = set(FORBIDDEN_VALUE_KEYS | FORBIDDEN_RUNTIME_KEYS) - if _is_filter_predicate(node): - forbidden.discard("value") - if in_defaults: - forbidden.discard("operation") - carried.update(forbidden.intersection(node)) - for child in node.values(): - carried.update(_carried_forbidden_keys(child)) - elif isinstance(node, (list, tuple)): - for child in node: - carried.update(_carried_forbidden_keys(child)) - return carried - - def test_uk_firms_targets_are_registered_in_the_country_package() -> None: package = json.loads( importlib_resources.files("microcosm.build.uk") @@ -104,12 +64,10 @@ def test_uk_firms_targets_have_unique_target_ids_in_runtime_order() -> None: def test_uk_firms_targets_are_value_free_and_hook_free() -> None: resource = _load() - carried = _carried_forbidden_keys( + carried = carried_forbidden_keys( {key: value for key, value in resource.items() if key != "resolution_defaults"} ) - carried |= _carried_forbidden_keys( - resource["resolution_defaults"], in_defaults=True - ) + carried |= carried_forbidden_keys(resource["resolution_defaults"], in_defaults=True) assert not carried, sorted(carried) 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_attributes_2025/.provenance.json b/packages/microcosm-build/tests/fixtures/uk/firm_attributes_2025/.provenance.json new file mode 100644 index 0000000000..35d30b7559 --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_attributes_2025/.provenance.json @@ -0,0 +1,276 @@ +{ + "source_repository": "PolicyEngine/firm-microsim-paper", + "paper_commit": "aa1ce07045255b0ddc9942894810259be86b747f", + "paper_commit_short": "aa1ce07", + "workbook_tracked_at_paper_commit": true, + "workbook": { + "source_path": "data/raw/ons/ukbusinessworkbook2025new.xlsx", + "sha256": "5e51666eb97e6170051154aa09181fc785558712fa66816d2590aef998a09b6b", + "bytes": 1050564, + "publication": "ONS, UK Business: Activity, Size and Location, 2025", + "published": "2025-09-24", + "source_url": "https://www.ons.gov.uk/businessindustryandtrade/business/activitysizeandlocation/datasets/ukbusinessactivitysizeandlocation", + "source_url_note": "ONS dataset landing page, as recorded for the 2025 edition in firm-microsim-paper data/README.md; not a direct file link.", + "reference_period_note": "Workbook note 4: turnover for most traders is from VAT returns covering the financial year 2023/2024.", + "employment_note": "Workbook note 5: IDBR employment is drawn mainly from BRES, with PAYE jobs or employment imputed from VAT turnover for the smallest units." + }, + "extraction_date": "2026-11-22", + "tool": "tools/extract_uk_firm_ons_attribute_tables.py", + "command": "uv run --no-sync python tools/extract_uk_firm_ons_attribute_tables.py --workbook /data/raw/ons/ukbusinessworkbook2025new.xlsx", + "unit": "VAT and/or PAYE based enterprises", + "disclosure": { + "rounding": "Counts are control rounded to base 5 by ONS (workbook row 3).", + "zeros": "Workbook note 7: values may be rounded down to zero, so zeros are not necessarily true zeros; totals across tables may differ by minor amounts. Zeros are kept as 0.", + "suppressed_or_blank_cells": "A blank or non-numeric cell inside a data block is written as 0 and counted per file (blank_cells_written_as_zero, non_numeric_cells_written_as_zero). The 2025 workbook has none: disclosure control is by rounding, not suppression markers." + }, + "excluded": [ + "Table 8 aggregate geographies K02000001 (UK), K03000001 (GB), K04000001 (England and Wales), E92000001 (England)", + "Table 15 aggregate geography rows (the same four codes)", + "every Total column and the Total row of each table", + "the Total legal status block of Tables 12, 13 and 15" + ], + "region_codes": { + "E12000001": "North East", + "E12000002": "North West", + "E12000003": "Yorkshire and The Humber", + "E12000004": "East Midlands", + "E12000005": "West Midlands", + "E12000006": "East", + "E12000007": "London", + "E12000008": "South East", + "E12000009": "South West", + "W92000004": "Wales", + "S92000003": "Scotland", + "N92000002": "Northern Ireland" + }, + "legal_status": { + "1": { + "label": "Company (incl. Building Society)", + "source": "Tables 12, 13 and 15 row 4, verbatim" + }, + "2": { + "label": "Sole Proprietor", + "source": "Tables 12, 13 and 15 row 4, verbatim" + }, + "3": { + "label": "Partnership", + "source": "Tables 12, 13 and 15 row 4, verbatim" + }, + "4": { + "label": "Public Corporation/Nationalised Body", + "source": "Tables 12, 13 and 15 row 4, verbatim" + }, + "5": { + "label": "Central Government", + "source": "Tables 12, 13 and 15 row 4, verbatim" + }, + "6": { + "label": "Local Authority", + "source": "Tables 12, 13 and 15 row 4, verbatim" + }, + "7": { + "label": "Non-profit Body or Mutual Association", + "source": "Tables 12, 13 and 15 row 4, verbatim" + } + }, + "industry_groups": { + "01-03": { + "label": "Agriculture, forestry & fishing", + "sic_divisions": "01-03" + }, + "05-39": { + "label": "Production", + "sic_divisions": "05-39" + }, + "41-43": { + "label": "Construction", + "sic_divisions": "41-43" + }, + "45": { + "label": "Motor trades", + "sic_divisions": "45" + }, + "46": { + "label": "Wholesale", + "sic_divisions": "46" + }, + "47": { + "label": "Retail", + "sic_divisions": "47" + }, + "49-53": { + "label": "Transport & Storage (inc. postal)", + "sic_divisions": "49-53" + }, + "55-56": { + "label": "Accommodation & food services", + "sic_divisions": "55-56" + }, + "58-63": { + "label": "Information & communication", + "sic_divisions": "58-63" + }, + "64-66": { + "label": "Finance & insurance", + "sic_divisions": "64-66" + }, + "68": { + "label": "Property", + "sic_divisions": "68" + }, + "69-75": { + "label": "Professional, scientific & technical", + "sic_divisions": "69-75" + }, + "77-82": { + "label": "Business administration & support services", + "sic_divisions": "77-82" + }, + "84": { + "label": "Public administration & defence", + "sic_divisions": "84" + }, + "85": { + "label": "Education", + "sic_divisions": "85" + }, + "86-88": { + "label": "Health", + "sic_divisions": "86-88" + }, + "90-99": { + "label": "Arts, entertainment, recreation & other services", + "sic_divisions": "90-99" + } + }, + "turnover_bands": { + "unit": "GBP thousands", + "ons_region_turnover.csv": [ + "0-49", + "50-99", + "100-249", + "250-499", + "500-999", + "1000-4999", + "5000+" + ], + "ons_legal_status_turnover.csv": [ + "0-49", + "50-99", + "100-249", + "250-499", + "500-999", + "1000-1999", + "2000-4999", + "5000-9999", + "10000-49999", + "50000+" + ], + "ons_legal_status_region_turnover.csv": [ + "0-49", + "50-99", + "100-249", + "250-499", + "500-999", + "1000-1999", + "2000-4999", + "5000-9999", + "10000-49999", + "50000+" + ], + "table_8_labels_note": "The same seven labels as the columns of tests/fixtures/uk/firm_2024_25/ons_firm_turnover.csv.", + "table_13_to_table_8": { + "0-49": "0-49", + "50-99": "50-99", + "100-249": "100-249", + "250-499": "250-499", + "500-999": "500-999", + "1000-1999": "1000-4999", + "2000-4999": "1000-4999", + "5000-9999": "5000+", + "10000-49999": "5000+", + "50000+": "5000+" + } + }, + "employment_bands": { + "unit": "persons employed (IDBR employment, workbook note 5)", + "ons_legal_status_employment.csv": [ + "0-4", + "5-9", + "10-19", + "20-49", + "50-99", + "100-249", + "250+" + ] + }, + "sic_division_key": "Two-digit SIC 2007 division as text ('01'); read with dtype=str. All 88 divisions of Table 8, all-zero divisions included.", + "files": { + "ons_region_turnover.csv": { + "sha256": "f537abecdf97a4f146190c4743bc98ea9cd78ffd37e6e41b574333f6123cd0a4", + "bytes": 174583, + "rows": 7392, + "columns": [ + "sic_division", + "region_code", + "turnover_band", + "enterprises" + ], + "source_sheet": "Table 8", + "source_title": "Table 8 - Number of VAT and/or PAYE based enterprises within region by Standard Industrial Classification (SIC) division, turnover sizebands (\u00a3000's) and region [note 1] [note 2] [note 3] [note 4] [note 6] [note 7]", + "blank_cells_written_as_zero": 0, + "non_numeric_cells_written_as_zero": {}, + "zero_cells": 926 + }, + "ons_legal_status_turnover.csv": { + "sha256": "8b8b803ac4e1ef7d58b60dcbb9ea566769a0ef399df0677de9c38184210e2fa8", + "bytes": 22081, + "rows": 1190, + "columns": [ + "industry_group", + "legal_status", + "turnover_band", + "enterprises" + ], + "source_sheet": "Table 13", + "source_title": "Table 13 - Number of VAT and/or PAYE based enterprises by legal status, broad industry group and turnover sizebands (\u00a3000's) [note 1] [note 2] [note 3] [note 4 ] [note 6] [note 7]", + "blank_cells_written_as_zero": 0, + "non_numeric_cells_written_as_zero": {}, + "zero_cells": 449 + }, + "ons_legal_status_employment.csv": { + "sha256": "26b7e18afa1965eb92a5907d4c119da0de9aa2d4d800bdf329842933cbddb816", + "bytes": 13020, + "rows": 833, + "columns": [ + "industry_group", + "legal_status", + "employment_band", + "enterprises" + ], + "source_sheet": "Table 12", + "source_title": "Table 12 - Number of VAT and/or PAYE based enterprises by legal status, broad industry group and employment sizebands [note 1] [note 2] [note 3] [note 5] [note 6] [note 7]", + "blank_cells_written_as_zero": 0, + "non_numeric_cells_written_as_zero": {}, + "zero_cells": 325, + "role": "draw input: conditions legal status on employment within industry group" + }, + "ons_legal_status_region_turnover.csv": { + "sha256": "18c46f4de27a3dcdd273230df7ff1f3feee2ca4ece20943616a9cc8729b07bd4", + "bytes": 20223, + "rows": 840, + "columns": [ + "region_code", + "legal_status", + "turnover_band", + "enterprises" + ], + "source_sheet": "Table 15", + "source_title": "Table 15 - Number of VAT and/or PAYE based enterprises by legal status, region and turnover sizebands (\u00a3000's) [note 1] [note 2] [note 3] [note 4] [note 6] [note 7]", + "blank_cells_written_as_zero": 0, + "non_numeric_cells_written_as_zero": {}, + "zero_cells": 131, + "role": "held out: a check on drawn legal status by region, not a draw input" + } + } +} diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_attributes_2025/ons_legal_status_employment.csv b/packages/microcosm-build/tests/fixtures/uk/firm_attributes_2025/ons_legal_status_employment.csv new file mode 100644 index 0000000000..ac36a7a4ff --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_attributes_2025/ons_legal_status_employment.csv @@ -0,0 +1,834 @@ +industry_group,legal_status,employment_band,enterprises +01-03,1,0-4,18805 +01-03,1,5-9,3520 +01-03,1,10-19,1565 +01-03,1,20-49,780 +01-03,1,50-99,295 +01-03,1,100-249,130 +01-03,1,250+,90 +01-03,2,0-4,50570 +01-03,2,5-9,1590 +01-03,2,10-19,350 +01-03,2,20-49,75 +01-03,2,50-99,15 +01-03,2,100-249,5 +01-03,2,250+,0 +01-03,3,0-4,54345 +01-03,3,5-9,6080 +01-03,3,10-19,1455 +01-03,3,20-49,275 +01-03,3,50-99,60 +01-03,3,100-249,15 +01-03,3,250+,15 +01-03,4,0-4,0 +01-03,4,5-9,0 +01-03,4,10-19,0 +01-03,4,20-49,0 +01-03,4,50-99,0 +01-03,4,100-249,0 +01-03,4,250+,0 +01-03,5,0-4,5 +01-03,5,5-9,0 +01-03,5,10-19,0 +01-03,5,20-49,0 +01-03,5,50-99,0 +01-03,5,100-249,0 +01-03,5,250+,0 +01-03,6,0-4,0 +01-03,6,5-9,0 +01-03,6,10-19,0 +01-03,6,20-49,0 +01-03,6,50-99,0 +01-03,6,100-249,0 +01-03,6,250+,0 +01-03,7,0-4,570 +01-03,7,5-9,100 +01-03,7,10-19,65 +01-03,7,20-49,40 +01-03,7,50-99,10 +01-03,7,100-249,5 +01-03,7,250+,5 +05-39,1,0-4,77815 +05-39,1,5-9,18620 +05-39,1,10-19,12120 +05-39,1,20-49,9325 +05-39,1,50-99,4045 +05-39,1,100-249,2345 +05-39,1,250+,1405 +05-39,2,0-4,14780 +05-39,2,5-9,860 +05-39,2,10-19,175 +05-39,2,20-49,25 +05-39,2,50-99,5 +05-39,2,100-249,0 +05-39,2,250+,0 +05-39,3,0-4,3585 +05-39,3,5-9,1075 +05-39,3,10-19,275 +05-39,3,20-49,65 +05-39,3,50-99,10 +05-39,3,100-249,5 +05-39,3,250+,0 +05-39,4,0-4,0 +05-39,4,5-9,0 +05-39,4,10-19,0 +05-39,4,20-49,0 +05-39,4,50-99,0 +05-39,4,100-249,5 +05-39,4,250+,0 +05-39,5,0-4,5 +05-39,5,5-9,0 +05-39,5,10-19,0 +05-39,5,20-49,0 +05-39,5,50-99,0 +05-39,5,100-249,0 +05-39,5,250+,5 +05-39,6,0-4,20 +05-39,6,5-9,15 +05-39,6,10-19,5 +05-39,6,20-49,5 +05-39,6,50-99,0 +05-39,6,100-249,0 +05-39,6,250+,5 +05-39,7,0-4,310 +05-39,7,5-9,75 +05-39,7,10-19,30 +05-39,7,20-49,15 +05-39,7,50-99,5 +05-39,7,100-249,0 +05-39,7,250+,0 +41-43,1,0-4,266585 +41-43,1,5-9,28215 +41-43,1,10-19,11875 +41-43,1,20-49,5375 +41-43,1,50-99,1450 +41-43,1,100-249,630 +41-43,1,250+,305 +41-43,2,0-4,56570 +41-43,2,5-9,1530 +41-43,2,10-19,160 +41-43,2,20-49,10 +41-43,2,50-99,0 +41-43,2,100-249,0 +41-43,2,250+,0 +41-43,3,0-4,9920 +41-43,3,5-9,1335 +41-43,3,10-19,230 +41-43,3,20-49,30 +41-43,3,50-99,5 +41-43,3,100-249,0 +41-43,3,250+,0 +41-43,4,0-4,0 +41-43,4,5-9,0 +41-43,4,10-19,0 +41-43,4,20-49,0 +41-43,4,50-99,0 +41-43,4,100-249,0 +41-43,4,250+,0 +41-43,5,0-4,5 +41-43,5,5-9,0 +41-43,5,10-19,0 +41-43,5,20-49,0 +41-43,5,50-99,0 +41-43,5,100-249,0 +41-43,5,250+,0 +41-43,6,0-4,5 +41-43,6,5-9,0 +41-43,6,10-19,5 +41-43,6,20-49,0 +41-43,6,50-99,0 +41-43,6,100-249,0 +41-43,6,250+,0 +41-43,7,0-4,505 +41-43,7,5-9,40 +41-43,7,10-19,30 +41-43,7,20-49,10 +41-43,7,50-99,0 +41-43,7,100-249,5 +41-43,7,250+,0 +45,1,0-4,44955 +45,1,5-9,10440 +45,1,10-19,3760 +45,1,20-49,1485 +45,1,50-99,440 +45,1,100-249,255 +45,1,250+,210 +45,2,0-4,14530 +45,2,5-9,1400 +45,2,10-19,140 +45,2,20-49,15 +45,2,50-99,0 +45,2,100-249,0 +45,2,250+,0 +45,3,0-4,3490 +45,3,5-9,1405 +45,3,10-19,250 +45,3,20-49,30 +45,3,50-99,5 +45,3,100-249,0 +45,3,250+,0 +45,4,0-4,0 +45,4,5-9,0 +45,4,10-19,0 +45,4,20-49,0 +45,4,50-99,0 +45,4,100-249,0 +45,4,250+,0 +45,5,0-4,0 +45,5,5-9,0 +45,5,10-19,0 +45,5,20-49,0 +45,5,50-99,0 +45,5,100-249,0 +45,5,250+,0 +45,6,0-4,0 +45,6,5-9,0 +45,6,10-19,0 +45,6,20-49,0 +45,6,50-99,0 +45,6,100-249,0 +45,6,250+,0 +45,7,0-4,45 +45,7,5-9,0 +45,7,10-19,5 +45,7,20-49,0 +45,7,50-99,0 +45,7,100-249,0 +45,7,250+,0 +46,1,0-4,58470 +46,1,5-9,13480 +46,1,10-19,8825 +46,1,20-49,5300 +46,1,50-99,1860 +46,1,100-249,845 +46,1,250+,505 +46,2,0-4,7100 +46,2,5-9,400 +46,2,10-19,85 +46,2,20-49,5 +46,2,50-99,0 +46,2,100-249,5 +46,2,250+,0 +46,3,0-4,2680 +46,3,5-9,695 +46,3,10-19,210 +46,3,20-49,60 +46,3,50-99,5 +46,3,100-249,0 +46,3,250+,0 +46,4,0-4,0 +46,4,5-9,0 +46,4,10-19,0 +46,4,20-49,0 +46,4,50-99,0 +46,4,100-249,0 +46,4,250+,0 +46,5,0-4,0 +46,5,5-9,0 +46,5,10-19,0 +46,5,20-49,0 +46,5,50-99,0 +46,5,100-249,0 +46,5,250+,0 +46,6,0-4,0 +46,6,5-9,0 +46,6,10-19,0 +46,6,20-49,0 +46,6,50-99,0 +46,6,100-249,0 +46,6,250+,0 +46,7,0-4,130 +46,7,5-9,25 +46,7,10-19,20 +46,7,20-49,10 +46,7,50-99,0 +46,7,100-249,5 +46,7,250+,0 +47,1,0-4,121085 +47,1,5-9,24880 +47,1,10-19,11080 +47,1,20-49,4915 +47,1,50-99,1205 +47,1,100-249,460 +47,1,250+,445 +47,2,0-4,28570 +47,2,5-9,3790 +47,2,10-19,620 +47,2,20-49,85 +47,2,50-99,5 +47,2,100-249,5 +47,2,250+,0 +47,3,0-4,9250 +47,3,5-9,3925 +47,3,10-19,1100 +47,3,20-49,225 +47,3,50-99,35 +47,3,100-249,5 +47,3,250+,0 +47,4,0-4,0 +47,4,5-9,0 +47,4,10-19,0 +47,4,20-49,0 +47,4,50-99,0 +47,4,100-249,0 +47,4,250+,0 +47,5,0-4,0 +47,5,5-9,0 +47,5,10-19,0 +47,5,20-49,0 +47,5,50-99,0 +47,5,100-249,0 +47,5,250+,0 +47,6,0-4,0 +47,6,5-9,0 +47,6,10-19,0 +47,6,20-49,0 +47,6,50-99,0 +47,6,100-249,0 +47,6,250+,0 +47,7,0-4,795 +47,7,5-9,205 +47,7,10-19,110 +47,7,20-49,70 +47,7,50-99,20 +47,7,100-249,5 +47,7,250+,10 +49-53,1,0-4,63400 +49-53,1,5-9,6710 +49-53,1,10-19,3860 +49-53,1,20-49,2645 +49-53,1,50-99,1085 +49-53,1,100-249,540 +49-53,1,250+,380 +49-53,2,0-4,31080 +49-53,2,5-9,940 +49-53,2,10-19,220 +49-53,2,20-49,40 +49-53,2,50-99,5 +49-53,2,100-249,0 +49-53,2,250+,0 +49-53,3,0-4,1885 +49-53,3,5-9,605 +49-53,3,10-19,250 +49-53,3,20-49,75 +49-53,3,50-99,5 +49-53,3,100-249,0 +49-53,3,250+,0 +49-53,4,0-4,5 +49-53,4,5-9,0 +49-53,4,10-19,0 +49-53,4,20-49,5 +49-53,4,50-99,5 +49-53,4,100-249,15 +49-53,4,250+,35 +49-53,5,0-4,0 +49-53,5,5-9,0 +49-53,5,10-19,0 +49-53,5,20-49,0 +49-53,5,50-99,5 +49-53,5,100-249,0 +49-53,5,250+,5 +49-53,6,0-4,5 +49-53,6,5-9,0 +49-53,6,10-19,0 +49-53,6,20-49,0 +49-53,6,50-99,0 +49-53,6,100-249,5 +49-53,6,250+,5 +49-53,7,0-4,365 +49-53,7,5-9,70 +49-53,7,10-19,65 +49-53,7,20-49,50 +49-53,7,50-99,15 +49-53,7,100-249,5 +49-53,7,250+,0 +55-56,1,0-4,71345 +55-56,1,5-9,29930 +55-56,1,10-19,20820 +55-56,1,20-49,10840 +55-56,1,50-99,2360 +55-56,1,100-249,940 +55-56,1,250+,690 +55-56,2,0-4,15265 +55-56,2,5-9,5100 +55-56,2,10-19,1630 +55-56,2,20-49,425 +55-56,2,50-99,15 +55-56,2,100-249,0 +55-56,2,250+,5 +55-56,3,0-4,5720 +55-56,3,5-9,3395 +55-56,3,10-19,2055 +55-56,3,20-49,735 +55-56,3,50-99,60 +55-56,3,100-249,15 +55-56,3,250+,0 +55-56,4,0-4,0 +55-56,4,5-9,0 +55-56,4,10-19,0 +55-56,4,20-49,0 +55-56,4,50-99,0 +55-56,4,100-249,0 +55-56,4,250+,0 +55-56,5,0-4,5 +55-56,5,5-9,5 +55-56,5,10-19,0 +55-56,5,20-49,5 +55-56,5,50-99,0 +55-56,5,100-249,0 +55-56,5,250+,0 +55-56,6,0-4,0 +55-56,6,5-9,0 +55-56,6,10-19,0 +55-56,6,20-49,5 +55-56,6,50-99,0 +55-56,6,100-249,0 +55-56,6,250+,0 +55-56,7,0-4,2125 +55-56,7,5-9,1990 +55-56,7,10-19,905 +55-56,7,20-49,250 +55-56,7,50-99,40 +55-56,7,100-249,10 +55-56,7,250+,5 +58-63,1,0-4,153470 +58-63,1,5-9,11175 +58-63,1,10-19,6750 +58-63,1,20-49,4450 +58-63,1,50-99,1720 +58-63,1,100-249,825 +58-63,1,250+,540 +58-63,2,0-4,6645 +58-63,2,5-9,100 +58-63,2,10-19,15 +58-63,2,20-49,5 +58-63,2,50-99,0 +58-63,2,100-249,0 +58-63,2,250+,0 +58-63,3,0-4,855 +58-63,3,5-9,60 +58-63,3,10-19,10 +58-63,3,20-49,10 +58-63,3,50-99,5 +58-63,3,100-249,0 +58-63,3,250+,0 +58-63,4,0-4,0 +58-63,4,5-9,0 +58-63,4,10-19,0 +58-63,4,20-49,0 +58-63,4,50-99,0 +58-63,4,100-249,0 +58-63,4,250+,5 +58-63,5,0-4,0 +58-63,5,5-9,0 +58-63,5,10-19,0 +58-63,5,20-49,0 +58-63,5,50-99,0 +58-63,5,100-249,5 +58-63,5,250+,0 +58-63,6,0-4,0 +58-63,6,5-9,0 +58-63,6,10-19,0 +58-63,6,20-49,5 +58-63,6,50-99,0 +58-63,6,100-249,0 +58-63,6,250+,0 +58-63,7,0-4,725 +58-63,7,5-9,170 +58-63,7,10-19,75 +58-63,7,20-49,45 +58-63,7,50-99,20 +58-63,7,100-249,5 +58-63,7,250+,5 +64-66,1,0-4,36425 +64-66,1,5-9,4465 +64-66,1,10-19,2000 +64-66,1,20-49,1170 +64-66,1,50-99,645 +64-66,1,100-249,380 +64-66,1,250+,435 +64-66,2,0-4,1070 +64-66,2,5-9,100 +64-66,2,10-19,20 +64-66,2,20-49,0 +64-66,2,50-99,0 +64-66,2,100-249,0 +64-66,2,250+,0 +64-66,3,0-4,285 +64-66,3,5-9,135 +64-66,3,10-19,95 +64-66,3,20-49,20 +64-66,3,50-99,5 +64-66,3,100-249,0 +64-66,3,250+,0 +64-66,4,0-4,5 +64-66,4,5-9,0 +64-66,4,10-19,0 +64-66,4,20-49,0 +64-66,4,50-99,0 +64-66,4,100-249,0 +64-66,4,250+,5 +64-66,5,0-4,0 +64-66,5,5-9,0 +64-66,5,10-19,0 +64-66,5,20-49,5 +64-66,5,50-99,5 +64-66,5,100-249,0 +64-66,5,250+,5 +64-66,6,0-4,0 +64-66,6,5-9,0 +64-66,6,10-19,0 +64-66,6,20-49,0 +64-66,6,50-99,0 +64-66,6,100-249,0 +64-66,6,250+,0 +64-66,7,0-4,9005 +64-66,7,5-9,95 +64-66,7,10-19,65 +64-66,7,20-49,25 +64-66,7,50-99,10 +64-66,7,100-249,10 +64-66,7,250+,5 +68,1,0-4,84205 +68,1,5-9,9925 +68,1,10-19,4015 +68,1,20-49,1085 +68,1,50-99,295 +68,1,100-249,170 +68,1,250+,165 +68,2,0-4,7165 +68,2,5-9,475 +68,2,10-19,115 +68,2,20-49,20 +68,2,50-99,5 +68,2,100-249,0 +68,2,250+,0 +68,3,0-4,10480 +68,3,5-9,790 +68,3,10-19,265 +68,3,20-49,50 +68,3,50-99,10 +68,3,100-249,5 +68,3,250+,0 +68,4,0-4,5 +68,4,5-9,0 +68,4,10-19,0 +68,4,20-49,5 +68,4,50-99,0 +68,4,100-249,5 +68,4,250+,10 +68,5,0-4,5 +68,5,5-9,0 +68,5,10-19,0 +68,5,20-49,0 +68,5,50-99,0 +68,5,100-249,0 +68,5,250+,0 +68,6,0-4,5 +68,6,5-9,5 +68,6,10-19,5 +68,6,20-49,0 +68,6,50-99,0 +68,6,100-249,0 +68,6,250+,0 +68,7,0-4,2315 +68,7,5-9,295 +68,7,10-19,180 +68,7,20-49,85 +68,7,50-99,40 +68,7,100-249,40 +68,7,250+,70 +69-75,1,0-4,310135 +69-75,1,5-9,26265 +69-75,1,10-19,14510 +69-75,1,20-49,8050 +69-75,1,50-99,2845 +69-75,1,100-249,1315 +69-75,1,250+,875 +69-75,2,0-4,42480 +69-75,2,5-9,2235 +69-75,2,10-19,470 +69-75,2,20-49,40 +69-75,2,50-99,5 +69-75,2,100-249,0 +69-75,2,250+,0 +69-75,3,0-4,4385 +69-75,3,5-9,1350 +69-75,3,10-19,865 +69-75,3,20-49,400 +69-75,3,50-99,105 +69-75,3,100-249,40 +69-75,3,250+,15 +69-75,4,0-4,0 +69-75,4,5-9,5 +69-75,4,10-19,0 +69-75,4,20-49,0 +69-75,4,50-99,0 +69-75,4,100-249,0 +69-75,4,250+,5 +69-75,5,0-4,10 +69-75,5,5-9,5 +69-75,5,10-19,5 +69-75,5,20-49,5 +69-75,5,50-99,5 +69-75,5,100-249,0 +69-75,5,250+,15 +69-75,6,0-4,5 +69-75,6,5-9,0 +69-75,6,10-19,0 +69-75,6,20-49,0 +69-75,6,50-99,0 +69-75,6,100-249,0 +69-75,6,250+,0 +69-75,7,0-4,1905 +69-75,7,5-9,535 +69-75,7,10-19,345 +69-75,7,20-49,190 +69-75,7,50-99,70 +69-75,7,100-249,40 +69-75,7,250+,35 +77-82,1,0-4,137955 +77-82,1,5-9,18010 +77-82,1,10-19,10980 +77-82,1,20-49,6090 +77-82,1,50-99,2850 +77-82,1,100-249,1585 +77-82,1,250+,1160 +77-82,2,0-4,30645 +77-82,2,5-9,2475 +77-82,2,10-19,525 +77-82,2,20-49,90 +77-82,2,50-99,10 +77-82,2,100-249,5 +77-82,2,250+,0 +77-82,3,0-4,4335 +77-82,3,5-9,965 +77-82,3,10-19,315 +77-82,3,20-49,70 +77-82,3,50-99,15 +77-82,3,100-249,5 +77-82,3,250+,0 +77-82,4,0-4,0 +77-82,4,5-9,0 +77-82,4,10-19,0 +77-82,4,20-49,0 +77-82,4,50-99,5 +77-82,4,100-249,0 +77-82,4,250+,5 +77-82,5,0-4,5 +77-82,5,5-9,5 +77-82,5,10-19,0 +77-82,5,20-49,5 +77-82,5,50-99,10 +77-82,5,100-249,5 +77-82,5,250+,10 +77-82,6,0-4,5 +77-82,6,5-9,5 +77-82,6,10-19,5 +77-82,6,20-49,5 +77-82,6,50-99,0 +77-82,6,100-249,0 +77-82,6,250+,0 +77-82,7,0-4,2740 +77-82,7,5-9,615 +77-82,7,10-19,385 +77-82,7,20-49,100 +77-82,7,50-99,40 +77-82,7,100-249,15 +77-82,7,250+,10 +84,1,0-4,25 +84,1,5-9,0 +84,1,10-19,0 +84,1,20-49,5 +84,1,50-99,0 +84,1,100-249,0 +84,1,250+,0 +84,2,0-4,0 +84,2,5-9,0 +84,2,10-19,0 +84,2,20-49,0 +84,2,50-99,0 +84,2,100-249,0 +84,2,250+,0 +84,3,0-4,0 +84,3,5-9,0 +84,3,10-19,0 +84,3,20-49,0 +84,3,50-99,0 +84,3,100-249,0 +84,3,250+,0 +84,4,0-4,0 +84,4,5-9,0 +84,4,10-19,5 +84,4,20-49,0 +84,4,50-99,0 +84,4,100-249,0 +84,4,250+,5 +84,5,0-4,5 +84,5,5-9,5 +84,5,10-19,10 +84,5,20-49,15 +84,5,50-99,35 +84,5,100-249,20 +84,5,250+,125 +84,6,0-4,6480 +84,6,5-9,545 +84,6,10-19,195 +84,6,20-49,110 +84,6,50-99,10 +84,6,100-249,35 +84,6,250+,295 +84,7,0-4,25 +84,7,5-9,5 +84,7,10-19,0 +84,7,20-49,5 +84,7,50-99,0 +84,7,100-249,0 +84,7,250+,0 +85,1,0-4,25955 +85,1,5-9,3660 +85,1,10-19,2665 +85,1,20-49,1445 +85,1,50-99,535 +85,1,100-249,245 +85,1,250+,145 +85,2,0-4,2025 +85,2,5-9,855 +85,2,10-19,420 +85,2,20-49,70 +85,2,50-99,5 +85,2,100-249,0 +85,2,250+,0 +85,3,0-4,390 +85,3,5-9,230 +85,3,10-19,160 +85,3,20-49,45 +85,3,50-99,0 +85,3,100-249,0 +85,3,250+,0 +85,4,0-4,0 +85,4,5-9,5 +85,4,10-19,5 +85,4,20-49,0 +85,4,50-99,0 +85,4,100-249,0 +85,4,250+,0 +85,5,0-4,20 +85,5,5-9,15 +85,5,10-19,60 +85,5,20-49,310 +85,5,50-99,435 +85,5,100-249,755 +85,5,250+,1035 +85,6,0-4,10 +85,6,5-9,15 +85,6,10-19,70 +85,6,20-49,340 +85,6,50-99,280 +85,6,100-249,190 +85,6,250+,140 +85,7,0-4,2460 +85,7,5-9,1395 +85,7,10-19,970 +85,7,20-49,585 +85,7,50-99,385 +85,7,100-249,380 +85,7,250+,380 +86-88,1,0-4,52045 +86-88,1,5-9,7880 +86-88,1,10-19,7905 +86-88,1,20-49,5620 +86-88,1,50-99,2605 +86-88,1,100-249,1105 +86-88,1,250+,605 +86-88,2,0-4,4840 +86-88,2,5-9,3145 +86-88,2,10-19,1815 +86-88,2,20-49,495 +86-88,2,50-99,45 +86-88,2,100-249,5 +86-88,2,250+,0 +86-88,3,0-4,425 +86-88,3,5-9,1070 +86-88,3,10-19,2555 +86-88,3,20-49,3310 +86-88,3,50-99,825 +86-88,3,100-249,130 +86-88,3,250+,15 +86-88,4,0-4,5 +86-88,4,5-9,0 +86-88,4,10-19,0 +86-88,4,20-49,0 +86-88,4,50-99,0 +86-88,4,100-249,0 +86-88,4,250+,5 +86-88,5,0-4,0 +86-88,5,5-9,0 +86-88,5,10-19,5 +86-88,5,20-49,10 +86-88,5,50-99,0 +86-88,5,100-249,5 +86-88,5,250+,260 +86-88,6,0-4,70 +86-88,6,5-9,55 +86-88,6,10-19,10 +86-88,6,20-49,10 +86-88,6,50-99,5 +86-88,6,100-249,0 +86-88,6,250+,5 +86-88,7,0-4,8995 +86-88,7,5-9,4620 +86-88,7,10-19,3005 +86-88,7,20-49,1885 +86-88,7,50-99,930 +86-88,7,100-249,515 +86-88,7,250+,400 +90-99,1,0-4,96550 +90-99,1,5-9,13945 +90-99,1,10-19,6430 +90-99,1,20-49,3000 +90-99,1,50-99,860 +90-99,1,100-249,415 +90-99,1,250+,280 +90-99,2,0-4,29790 +90-99,2,5-9,3525 +90-99,2,10-19,495 +90-99,2,20-49,60 +90-99,2,50-99,10 +90-99,2,100-249,0 +90-99,2,250+,0 +90-99,3,0-4,6620 +90-99,3,5-9,1630 +90-99,3,10-19,445 +90-99,3,20-49,100 +90-99,3,50-99,15 +90-99,3,100-249,5 +90-99,3,250+,0 +90-99,4,0-4,0 +90-99,4,5-9,0 +90-99,4,10-19,0 +90-99,4,20-49,0 +90-99,4,50-99,0 +90-99,4,100-249,0 +90-99,4,250+,5 +90-99,5,0-4,10 +90-99,5,5-9,0 +90-99,5,10-19,5 +90-99,5,20-49,5 +90-99,5,50-99,10 +90-99,5,100-249,10 +90-99,5,250+,30 +90-99,6,0-4,30 +90-99,6,5-9,30 +90-99,6,10-19,20 +90-99,6,20-49,20 +90-99,6,50-99,10 +90-99,6,100-249,15 +90-99,6,250+,0 +90-99,7,0-4,16460 +90-99,7,5-9,5310 +90-99,7,10-19,2975 +90-99,7,20-49,1820 +90-99,7,50-99,545 +90-99,7,100-249,290 +90-99,7,250+,180 diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_attributes_2025/ons_legal_status_region_turnover.csv b/packages/microcosm-build/tests/fixtures/uk/firm_attributes_2025/ons_legal_status_region_turnover.csv new file mode 100644 index 0000000000..2fec35b791 --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_attributes_2025/ons_legal_status_region_turnover.csv @@ -0,0 +1,841 @@ +region_code,legal_status,turnover_band,enterprises +E12000001,1,0-49,5300 +E12000001,1,50-99,10275 +E12000001,1,100-249,17830 +E12000001,1,250-499,7500 +E12000001,1,500-999,4915 +E12000001,1,1000-1999,2910 +E12000001,1,2000-4999,2080 +E12000001,1,5000-9999,830 +E12000001,1,10000-49999,765 +E12000001,1,50000+,230 +E12000001,2,0-49,2380 +E12000001,2,50-99,2710 +E12000001,2,100-249,4380 +E12000001,2,250-499,1595 +E12000001,2,500-999,675 +E12000001,2,1000-1999,160 +E12000001,2,2000-4999,40 +E12000001,2,5000-9999,5 +E12000001,2,10000-49999,0 +E12000001,2,50000+,0 +E12000001,3,0-49,730 +E12000001,3,50-99,635 +E12000001,3,100-249,1590 +E12000001,3,250-499,985 +E12000001,3,500-999,615 +E12000001,3,1000-1999,320 +E12000001,3,2000-4999,190 +E12000001,3,5000-9999,25 +E12000001,3,10000-49999,15 +E12000001,3,50000+,5 +E12000001,4,0-49,0 +E12000001,4,50-99,0 +E12000001,4,100-249,0 +E12000001,4,250-499,0 +E12000001,4,500-999,0 +E12000001,4,1000-1999,0 +E12000001,4,2000-4999,0 +E12000001,4,5000-9999,0 +E12000001,4,10000-49999,0 +E12000001,4,50000+,0 +E12000001,5,0-49,5 +E12000001,5,50-99,0 +E12000001,5,100-249,10 +E12000001,5,250-499,0 +E12000001,5,500-999,15 +E12000001,5,1000-1999,15 +E12000001,5,2000-4999,20 +E12000001,5,5000-9999,15 +E12000001,5,10000-49999,40 +E12000001,5,50000+,20 +E12000001,6,0-49,10 +E12000001,6,50-99,155 +E12000001,6,100-249,40 +E12000001,6,250-499,25 +E12000001,6,500-999,5 +E12000001,6,1000-1999,5 +E12000001,6,2000-4999,5 +E12000001,6,5000-9999,5 +E12000001,6,10000-49999,10 +E12000001,6,50000+,10 +E12000001,7,0-49,400 +E12000001,7,50-99,400 +E12000001,7,100-249,725 +E12000001,7,250-499,570 +E12000001,7,500-999,325 +E12000001,7,1000-1999,195 +E12000001,7,2000-4999,90 +E12000001,7,5000-9999,30 +E12000001,7,10000-49999,30 +E12000001,7,50000+,10 +E12000002,1,0-49,22230 +E12000002,1,50-99,40645 +E12000002,1,100-249,68160 +E12000002,1,250-499,29715 +E12000002,1,500-999,19890 +E12000002,1,1000-1999,11625 +E12000002,1,2000-4999,8590 +E12000002,1,5000-9999,3415 +E12000002,1,10000-49999,3065 +E12000002,1,50000+,970 +E12000002,2,0-49,7045 +E12000002,2,50-99,7700 +E12000002,2,100-249,12250 +E12000002,2,250-499,4395 +E12000002,2,500-999,1860 +E12000002,2,1000-1999,520 +E12000002,2,2000-4999,130 +E12000002,2,5000-9999,15 +E12000002,2,10000-49999,5 +E12000002,2,50000+,0 +E12000002,3,0-49,2565 +E12000002,3,50-99,1975 +E12000002,3,100-249,4275 +E12000002,3,250-499,2425 +E12000002,3,500-999,1690 +E12000002,3,1000-1999,975 +E12000002,3,2000-4999,445 +E12000002,3,5000-9999,55 +E12000002,3,10000-49999,25 +E12000002,3,50000+,10 +E12000002,4,0-49,0 +E12000002,4,50-99,0 +E12000002,4,100-249,0 +E12000002,4,250-499,0 +E12000002,4,500-999,0 +E12000002,4,1000-1999,0 +E12000002,4,2000-4999,0 +E12000002,4,5000-9999,0 +E12000002,4,10000-49999,5 +E12000002,4,50000+,5 +E12000002,5,0-49,10 +E12000002,5,50-99,5 +E12000002,5,100-249,20 +E12000002,5,250-499,15 +E12000002,5,500-999,20 +E12000002,5,1000-1999,55 +E12000002,5,2000-4999,60 +E12000002,5,5000-9999,70 +E12000002,5,10000-49999,90 +E12000002,5,50000+,45 +E12000002,6,0-49,15 +E12000002,6,50-99,360 +E12000002,6,100-249,90 +E12000002,6,250-499,35 +E12000002,6,500-999,35 +E12000002,6,1000-1999,30 +E12000002,6,2000-4999,30 +E12000002,6,5000-9999,25 +E12000002,6,10000-49999,25 +E12000002,6,50000+,20 +E12000002,7,0-49,2040 +E12000002,7,50-99,1075 +E12000002,7,100-249,1915 +E12000002,7,250-499,1310 +E12000002,7,500-999,810 +E12000002,7,1000-1999,410 +E12000002,7,2000-4999,290 +E12000002,7,5000-9999,105 +E12000002,7,10000-49999,80 +E12000002,7,50000+,25 +E12000003,1,0-49,15335 +E12000003,1,50-99,26955 +E12000003,1,100-249,45670 +E12000003,1,250-499,20440 +E12000003,1,500-999,13520 +E12000003,1,1000-1999,8280 +E12000003,1,2000-4999,6145 +E12000003,1,5000-9999,2485 +E12000003,1,10000-49999,2280 +E12000003,1,50000+,645 +E12000003,2,0-49,6120 +E12000003,2,50-99,6740 +E12000003,2,100-249,10180 +E12000003,2,250-499,3600 +E12000003,2,500-999,1460 +E12000003,2,1000-1999,345 +E12000003,2,2000-4999,90 +E12000003,2,5000-9999,5 +E12000003,2,10000-49999,10 +E12000003,2,50000+,0 +E12000003,3,0-49,2305 +E12000003,3,50-99,1695 +E12000003,3,100-249,4075 +E12000003,3,250-499,2485 +E12000003,3,500-999,1530 +E12000003,3,1000-1999,760 +E12000003,3,2000-4999,420 +E12000003,3,5000-9999,65 +E12000003,3,10000-49999,25 +E12000003,3,50000+,0 +E12000003,4,0-49,0 +E12000003,4,50-99,0 +E12000003,4,100-249,0 +E12000003,4,250-499,0 +E12000003,4,500-999,0 +E12000003,4,1000-1999,0 +E12000003,4,2000-4999,0 +E12000003,4,5000-9999,0 +E12000003,4,10000-49999,5 +E12000003,4,50000+,0 +E12000003,5,0-49,10 +E12000003,5,50-99,5 +E12000003,5,100-249,10 +E12000003,5,250-499,10 +E12000003,5,500-999,15 +E12000003,5,1000-1999,35 +E12000003,5,2000-4999,55 +E12000003,5,5000-9999,30 +E12000003,5,10000-49999,60 +E12000003,5,50000+,35 +E12000003,6,0-49,25 +E12000003,6,50-99,430 +E12000003,6,100-249,140 +E12000003,6,250-499,45 +E12000003,6,500-999,20 +E12000003,6,1000-1999,5 +E12000003,6,2000-4999,5 +E12000003,6,5000-9999,5 +E12000003,6,10000-49999,15 +E12000003,6,50000+,10 +E12000003,7,0-49,1285 +E12000003,7,50-99,840 +E12000003,7,100-249,1530 +E12000003,7,250-499,1100 +E12000003,7,500-999,700 +E12000003,7,1000-1999,350 +E12000003,7,2000-4999,185 +E12000003,7,5000-9999,65 +E12000003,7,10000-49999,55 +E12000003,7,50000+,20 +E12000004,1,0-49,15210 +E12000004,1,50-99,25545 +E12000004,1,100-249,43415 +E12000004,1,250-499,19860 +E12000004,1,500-999,12820 +E12000004,1,1000-1999,7785 +E12000004,1,2000-4999,5685 +E12000004,1,5000-9999,2260 +E12000004,1,10000-49999,2005 +E12000004,1,50000+,540 +E12000004,2,0-49,5945 +E12000004,2,50-99,6080 +E12000004,2,100-249,9015 +E12000004,2,250-499,3125 +E12000004,2,500-999,1275 +E12000004,2,1000-1999,320 +E12000004,2,2000-4999,100 +E12000004,2,5000-9999,10 +E12000004,2,10000-49999,0 +E12000004,2,50000+,0 +E12000004,3,0-49,3035 +E12000004,3,50-99,1485 +E12000004,3,100-249,3500 +E12000004,3,250-499,2040 +E12000004,3,500-999,1300 +E12000004,3,1000-1999,660 +E12000004,3,2000-4999,350 +E12000004,3,5000-9999,65 +E12000004,3,10000-49999,25 +E12000004,3,50000+,0 +E12000004,4,0-49,0 +E12000004,4,50-99,0 +E12000004,4,100-249,0 +E12000004,4,250-499,0 +E12000004,4,500-999,0 +E12000004,4,1000-1999,0 +E12000004,4,2000-4999,0 +E12000004,4,5000-9999,0 +E12000004,4,10000-49999,5 +E12000004,4,50000+,5 +E12000004,5,0-49,10 +E12000004,5,50-99,10 +E12000004,5,100-249,10 +E12000004,5,250-499,10 +E12000004,5,500-999,20 +E12000004,5,1000-1999,45 +E12000004,5,2000-4999,60 +E12000004,5,5000-9999,35 +E12000004,5,10000-49999,65 +E12000004,5,50000+,25 +E12000004,6,0-49,30 +E12000004,6,50-99,590 +E12000004,6,100-249,210 +E12000004,6,250-499,85 +E12000004,6,500-999,40 +E12000004,6,1000-1999,25 +E12000004,6,2000-4999,30 +E12000004,6,5000-9999,15 +E12000004,6,10000-49999,15 +E12000004,6,50000+,10 +E12000004,7,0-49,2350 +E12000004,7,50-99,750 +E12000004,7,100-249,1235 +E12000004,7,250-499,895 +E12000004,7,500-999,465 +E12000004,7,1000-1999,255 +E12000004,7,2000-4999,165 +E12000004,7,5000-9999,40 +E12000004,7,10000-49999,40 +E12000004,7,50000+,20 +E12000005,1,0-49,18675 +E12000005,1,50-99,32675 +E12000005,1,100-249,53085 +E12000005,1,250-499,24045 +E12000005,1,500-999,15890 +E12000005,1,1000-1999,9525 +E12000005,1,2000-4999,7005 +E12000005,1,5000-9999,2800 +E12000005,1,10000-49999,2410 +E12000005,1,50000+,765 +E12000005,2,0-49,6775 +E12000005,2,50-99,6870 +E12000005,2,100-249,9670 +E12000005,2,250-499,3660 +E12000005,2,500-999,1605 +E12000005,2,1000-1999,385 +E12000005,2,2000-4999,100 +E12000005,2,5000-9999,20 +E12000005,2,10000-49999,0 +E12000005,2,50000+,0 +E12000005,3,0-49,2585 +E12000005,3,50-99,1745 +E12000005,3,100-249,3855 +E12000005,3,250-499,2290 +E12000005,3,500-999,1540 +E12000005,3,1000-1999,795 +E12000005,3,2000-4999,400 +E12000005,3,5000-9999,60 +E12000005,3,10000-49999,30 +E12000005,3,50000+,5 +E12000005,4,0-49,0 +E12000005,4,50-99,0 +E12000005,4,100-249,0 +E12000005,4,250-499,0 +E12000005,4,500-999,0 +E12000005,4,1000-1999,0 +E12000005,4,2000-4999,0 +E12000005,4,5000-9999,0 +E12000005,4,10000-49999,0 +E12000005,4,50000+,5 +E12000005,5,0-49,15 +E12000005,5,50-99,5 +E12000005,5,100-249,10 +E12000005,5,250-499,10 +E12000005,5,500-999,20 +E12000005,5,1000-1999,30 +E12000005,5,2000-4999,70 +E12000005,5,5000-9999,65 +E12000005,5,10000-49999,100 +E12000005,5,50000+,30 +E12000005,6,0-49,20 +E12000005,6,50-99,530 +E12000005,6,100-249,85 +E12000005,6,250-499,40 +E12000005,6,500-999,25 +E12000005,6,1000-1999,5 +E12000005,6,2000-4999,5 +E12000005,6,5000-9999,10 +E12000005,6,10000-49999,15 +E12000005,6,50000+,10 +E12000005,7,0-49,1165 +E12000005,7,50-99,835 +E12000005,7,100-249,1505 +E12000005,7,250-499,920 +E12000005,7,500-999,610 +E12000005,7,1000-1999,350 +E12000005,7,2000-4999,205 +E12000005,7,5000-9999,90 +E12000005,7,10000-49999,65 +E12000005,7,50000+,30 +E12000006,1,0-49,24770 +E12000006,1,50-99,40925 +E12000006,1,100-249,70240 +E12000006,1,250-499,31030 +E12000006,1,500-999,20200 +E12000006,1,1000-1999,11910 +E12000006,1,2000-4999,8585 +E12000006,1,5000-9999,3490 +E12000006,1,10000-49999,3005 +E12000006,1,50000+,825 +E12000006,2,0-49,7095 +E12000006,2,50-99,8355 +E12000006,2,100-249,11890 +E12000006,2,250-499,4180 +E12000006,2,500-999,1645 +E12000006,2,1000-1999,435 +E12000006,2,2000-4999,135 +E12000006,2,5000-9999,15 +E12000006,2,10000-49999,10 +E12000006,2,50000+,0 +E12000006,3,0-49,2080 +E12000006,3,50-99,1780 +E12000006,3,100-249,4090 +E12000006,3,250-499,2530 +E12000006,3,500-999,1655 +E12000006,3,1000-1999,800 +E12000006,3,2000-4999,535 +E12000006,3,5000-9999,100 +E12000006,3,10000-49999,35 +E12000006,3,50000+,5 +E12000006,4,0-49,0 +E12000006,4,50-99,0 +E12000006,4,100-249,5 +E12000006,4,250-499,0 +E12000006,4,500-999,0 +E12000006,4,1000-1999,0 +E12000006,4,2000-4999,0 +E12000006,4,5000-9999,0 +E12000006,4,10000-49999,5 +E12000006,4,50000+,5 +E12000006,5,0-49,10 +E12000006,5,50-99,5 +E12000006,5,100-249,15 +E12000006,5,250-499,20 +E12000006,5,500-999,20 +E12000006,5,1000-1999,60 +E12000006,5,2000-4999,90 +E12000006,5,5000-9999,70 +E12000006,5,10000-49999,100 +E12000006,5,50000+,25 +E12000006,6,0-49,50 +E12000006,6,50-99,935 +E12000006,6,100-249,245 +E12000006,6,250-499,100 +E12000006,6,500-999,50 +E12000006,6,1000-1999,90 +E12000006,6,2000-4999,85 +E12000006,6,5000-9999,20 +E12000006,6,10000-49999,35 +E12000006,6,50000+,10 +E12000006,7,0-49,1675 +E12000006,7,50-99,1005 +E12000006,7,100-249,1730 +E12000006,7,250-499,1180 +E12000006,7,500-999,700 +E12000006,7,1000-1999,370 +E12000006,7,2000-4999,220 +E12000006,7,5000-9999,80 +E12000006,7,10000-49999,85 +E12000006,7,50000+,25 +E12000007,1,0-49,65630 +E12000007,1,50-99,90490 +E12000007,1,100-249,145320 +E12000007,1,250-499,63835 +E12000007,1,500-999,41825 +E12000007,1,1000-1999,24090 +E12000007,1,2000-4999,17795 +E12000007,1,5000-9999,7440 +E12000007,1,10000-49999,7600 +E12000007,1,50000+,3045 +E12000007,2,0-49,8800 +E12000007,2,50-99,10300 +E12000007,2,100-249,17220 +E12000007,2,250-499,7790 +E12000007,2,500-999,3355 +E12000007,2,1000-1999,1035 +E12000007,2,2000-4999,305 +E12000007,2,5000-9999,60 +E12000007,2,10000-49999,10 +E12000007,2,50000+,0 +E12000007,3,0-49,1075 +E12000007,3,50-99,955 +E12000007,3,100-249,2055 +E12000007,3,250-499,1455 +E12000007,3,500-999,1145 +E12000007,3,1000-1999,705 +E12000007,3,2000-4999,400 +E12000007,3,5000-9999,85 +E12000007,3,10000-49999,70 +E12000007,3,50000+,20 +E12000007,4,0-49,5 +E12000007,4,50-99,0 +E12000007,4,100-249,0 +E12000007,4,250-499,0 +E12000007,4,500-999,0 +E12000007,4,1000-1999,0 +E12000007,4,2000-4999,5 +E12000007,4,5000-9999,0 +E12000007,4,10000-49999,15 +E12000007,4,50000+,20 +E12000007,5,0-49,20 +E12000007,5,50-99,5 +E12000007,5,100-249,20 +E12000007,5,250-499,15 +E12000007,5,500-999,25 +E12000007,5,1000-1999,40 +E12000007,5,2000-4999,95 +E12000007,5,5000-9999,100 +E12000007,5,10000-49999,150 +E12000007,5,50000+,75 +E12000007,6,0-49,5 +E12000007,6,50-99,5 +E12000007,6,100-249,5 +E12000007,6,250-499,5 +E12000007,6,500-999,20 +E12000007,6,1000-1999,100 +E12000007,6,2000-4999,170 +E12000007,6,5000-9999,45 +E12000007,6,10000-49999,30 +E12000007,6,50000+,25 +E12000007,7,0-49,2070 +E12000007,7,50-99,1905 +E12000007,7,100-249,3160 +E12000007,7,250-499,2075 +E12000007,7,500-999,1580 +E12000007,7,1000-1999,1045 +E12000007,7,2000-4999,815 +E12000007,7,5000-9999,320 +E12000007,7,10000-49999,315 +E12000007,7,50000+,120 +E12000008,1,0-49,39405 +E12000008,1,50-99,62585 +E12000008,1,100-249,108265 +E12000008,1,250-499,45775 +E12000008,1,500-999,29670 +E12000008,1,1000-1999,17710 +E12000008,1,2000-4999,12485 +E12000008,1,5000-9999,4710 +E12000008,1,10000-49999,4280 +E12000008,1,50000+,1500 +E12000008,2,0-49,9445 +E12000008,2,50-99,11530 +E12000008,2,100-249,17850 +E12000008,2,250-499,6390 +E12000008,2,500-999,2530 +E12000008,2,1000-1999,630 +E12000008,2,2000-4999,160 +E12000008,2,5000-9999,20 +E12000008,2,10000-49999,10 +E12000008,2,50000+,0 +E12000008,3,0-49,3140 +E12000008,3,50-99,2240 +E12000008,3,100-249,5055 +E12000008,3,250-499,2880 +E12000008,3,500-999,1770 +E12000008,3,1000-1999,965 +E12000008,3,2000-4999,705 +E12000008,3,5000-9999,135 +E12000008,3,10000-49999,35 +E12000008,3,50000+,5 +E12000008,4,0-49,0 +E12000008,4,50-99,0 +E12000008,4,100-249,0 +E12000008,4,250-499,0 +E12000008,4,500-999,5 +E12000008,4,1000-1999,0 +E12000008,4,2000-4999,0 +E12000008,4,5000-9999,0 +E12000008,4,10000-49999,5 +E12000008,4,50000+,5 +E12000008,5,0-49,15 +E12000008,5,50-99,5 +E12000008,5,100-249,15 +E12000008,5,250-499,20 +E12000008,5,500-999,20 +E12000008,5,1000-1999,40 +E12000008,5,2000-4999,70 +E12000008,5,5000-9999,85 +E12000008,5,10000-49999,125 +E12000008,5,50000+,50 +E12000008,6,0-49,75 +E12000008,6,50-99,690 +E12000008,6,100-249,265 +E12000008,6,250-499,115 +E12000008,6,500-999,55 +E12000008,6,1000-1999,50 +E12000008,6,2000-4999,45 +E12000008,6,5000-9999,40 +E12000008,6,10000-49999,50 +E12000008,6,50000+,20 +E12000008,7,0-49,2455 +E12000008,7,50-99,1600 +E12000008,7,100-249,2730 +E12000008,7,250-499,1850 +E12000008,7,500-999,1080 +E12000008,7,1000-1999,610 +E12000008,7,2000-4999,415 +E12000008,7,5000-9999,205 +E12000008,7,10000-49999,180 +E12000008,7,50000+,40 +E12000009,1,0-49,18865 +E12000009,1,50-99,29630 +E12000009,1,100-249,52340 +E12000009,1,250-499,24490 +E12000009,1,500-999,15875 +E12000009,1,1000-1999,9175 +E12000009,1,2000-4999,6475 +E12000009,1,5000-9999,2370 +E12000009,1,10000-49999,1945 +E12000009,1,50000+,520 +E12000009,2,0-49,9660 +E12000009,2,50-99,10180 +E12000009,2,100-249,14320 +E12000009,2,250-499,4730 +E12000009,2,500-999,1870 +E12000009,2,1000-1999,510 +E12000009,2,2000-4999,145 +E12000009,2,5000-9999,20 +E12000009,2,10000-49999,5 +E12000009,2,50000+,5 +E12000009,3,0-49,4965 +E12000009,3,50-99,3125 +E12000009,3,100-249,6815 +E12000009,3,250-499,3785 +E12000009,3,500-999,2295 +E12000009,3,1000-1999,1065 +E12000009,3,2000-4999,545 +E12000009,3,5000-9999,100 +E12000009,3,10000-49999,35 +E12000009,3,50000+,5 +E12000009,4,0-49,0 +E12000009,4,50-99,0 +E12000009,4,100-249,0 +E12000009,4,250-499,0 +E12000009,4,500-999,0 +E12000009,4,1000-1999,0 +E12000009,4,2000-4999,0 +E12000009,4,5000-9999,5 +E12000009,4,10000-49999,5 +E12000009,4,50000+,5 +E12000009,5,0-49,5 +E12000009,5,50-99,0 +E12000009,5,100-249,5 +E12000009,5,250-499,20 +E12000009,5,500-999,20 +E12000009,5,1000-1999,30 +E12000009,5,2000-4999,50 +E12000009,5,5000-9999,55 +E12000009,5,10000-49999,85 +E12000009,5,50000+,30 +E12000009,6,0-49,65 +E12000009,6,50-99,890 +E12000009,6,100-249,175 +E12000009,6,250-499,90 +E12000009,6,500-999,45 +E12000009,6,1000-1999,25 +E12000009,6,2000-4999,25 +E12000009,6,5000-9999,15 +E12000009,6,10000-49999,15 +E12000009,6,50000+,10 +E12000009,7,0-49,1715 +E12000009,7,50-99,1120 +E12000009,7,100-249,2060 +E12000009,7,250-499,1300 +E12000009,7,500-999,740 +E12000009,7,1000-1999,390 +E12000009,7,2000-4999,280 +E12000009,7,5000-9999,75 +E12000009,7,10000-49999,70 +E12000009,7,50000+,25 +W92000004,1,0-49,6975 +W92000004,1,50-99,12085 +W92000004,1,100-249,21050 +W92000004,1,250-499,9640 +W92000004,1,500-999,6335 +W92000004,1,1000-1999,3825 +W92000004,1,2000-4999,2660 +W92000004,1,5000-9999,1065 +W92000004,1,10000-49999,855 +W92000004,1,50000+,250 +W92000004,2,0-49,6025 +W92000004,2,50-99,4735 +W92000004,2,100-249,7080 +W92000004,2,250-499,2580 +W92000004,2,500-999,1125 +W92000004,2,1000-1999,270 +W92000004,2,2000-4999,55 +W92000004,2,5000-9999,10 +W92000004,2,10000-49999,0 +W92000004,2,50000+,0 +W92000004,3,0-49,3700 +W92000004,3,50-99,2125 +W92000004,3,100-249,3585 +W92000004,3,250-499,1935 +W92000004,3,500-999,1230 +W92000004,3,1000-1999,600 +W92000004,3,2000-4999,270 +W92000004,3,5000-9999,30 +W92000004,3,10000-49999,10 +W92000004,3,50000+,0 +W92000004,4,0-49,0 +W92000004,4,50-99,0 +W92000004,4,100-249,0 +W92000004,4,250-499,0 +W92000004,4,500-999,0 +W92000004,4,1000-1999,5 +W92000004,4,2000-4999,0 +W92000004,4,5000-9999,0 +W92000004,4,10000-49999,5 +W92000004,4,50000+,5 +W92000004,5,0-49,0 +W92000004,5,50-99,0 +W92000004,5,100-249,0 +W92000004,5,250-499,0 +W92000004,5,500-999,0 +W92000004,5,1000-1999,5 +W92000004,5,2000-4999,5 +W92000004,5,5000-9999,0 +W92000004,5,10000-49999,5 +W92000004,5,50000+,15 +W92000004,6,0-49,30 +W92000004,6,50-99,375 +W92000004,6,100-249,155 +W92000004,6,250-499,95 +W92000004,6,500-999,25 +W92000004,6,1000-1999,5 +W92000004,6,2000-4999,5 +W92000004,6,5000-9999,5 +W92000004,6,10000-49999,20 +W92000004,6,50000+,5 +W92000004,7,0-49,700 +W92000004,7,50-99,585 +W92000004,7,100-249,1210 +W92000004,7,250-499,680 +W92000004,7,500-999,400 +W92000004,7,1000-1999,185 +W92000004,7,2000-4999,120 +W92000004,7,5000-9999,35 +W92000004,7,10000-49999,30 +W92000004,7,50000+,10 +S92000003,1,0-49,13400 +S92000003,1,50-99,22490 +S92000003,1,100-249,38845 +S92000003,1,250-499,17390 +S92000003,1,500-999,11460 +S92000003,1,1000-1999,6860 +S92000003,1,2000-4999,4875 +S92000003,1,5000-9999,1910 +S92000003,1,10000-49999,1790 +S92000003,1,50000+,515 +S92000003,2,0-49,7130 +S92000003,2,50-99,6090 +S92000003,2,100-249,9900 +S92000003,2,250-499,3865 +S92000003,2,500-999,1535 +S92000003,2,1000-1999,400 +S92000003,2,2000-4999,105 +S92000003,2,5000-9999,15 +S92000003,2,10000-49999,5 +S92000003,2,50000+,0 +S92000003,3,0-49,2745 +S92000003,3,50-99,1935 +S92000003,3,100-249,4420 +S92000003,3,250-499,3065 +S92000003,3,500-999,2150 +S92000003,3,1000-1999,1220 +S92000003,3,2000-4999,445 +S92000003,3,5000-9999,55 +S92000003,3,10000-49999,30 +S92000003,3,50000+,5 +S92000003,4,0-49,0 +S92000003,4,50-99,0 +S92000003,4,100-249,0 +S92000003,4,250-499,0 +S92000003,4,500-999,0 +S92000003,4,1000-1999,0 +S92000003,4,2000-4999,0 +S92000003,4,5000-9999,0 +S92000003,4,10000-49999,0 +S92000003,4,50000+,5 +S92000003,5,0-49,0 +S92000003,5,50-99,0 +S92000003,5,100-249,0 +S92000003,5,250-499,5 +S92000003,5,500-999,5 +S92000003,5,1000-1999,10 +S92000003,5,2000-4999,20 +S92000003,5,5000-9999,20 +S92000003,5,10000-49999,25 +S92000003,5,50000+,25 +S92000003,6,0-49,5 +S92000003,6,50-99,10 +S92000003,6,100-249,5 +S92000003,6,250-499,5 +S92000003,6,500-999,5 +S92000003,6,1000-1999,5 +S92000003,6,2000-4999,5 +S92000003,6,5000-9999,5 +S92000003,6,10000-49999,20 +S92000003,6,50000+,10 +S92000003,7,0-49,1390 +S92000003,7,50-99,1265 +S92000003,7,100-249,2270 +S92000003,7,250-499,1425 +S92000003,7,500-999,960 +S92000003,7,1000-1999,490 +S92000003,7,2000-4999,275 +S92000003,7,5000-9999,85 +S92000003,7,10000-49999,80 +S92000003,7,50000+,20 +N92000002,1,0-49,4000 +N92000002,1,50-99,5850 +N92000002,1,100-249,10010 +N92000002,1,250-499,5610 +N92000002,1,500-999,4300 +N92000002,1,1000-1999,3100 +N92000002,1,2000-4999,2535 +N92000002,1,5000-9999,1005 +N92000002,1,10000-49999,890 +N92000002,1,50000+,210 +N92000002,2,0-49,10430 +N92000002,2,50-99,5520 +N92000002,2,100-249,7195 +N92000002,2,250-499,2670 +N92000002,2,500-999,1225 +N92000002,2,1000-1999,405 +N92000002,2,2000-4999,100 +N92000002,2,5000-9999,20 +N92000002,2,10000-49999,10 +N92000002,2,50000+,0 +N92000002,3,0-49,3310 +N92000002,3,50-99,1650 +N92000002,3,100-249,2535 +N92000002,3,250-499,1730 +N92000002,3,500-999,1215 +N92000002,3,1000-1999,690 +N92000002,3,2000-4999,205 +N92000002,3,5000-9999,50 +N92000002,3,10000-49999,20 +N92000002,3,50000+,0 +N92000002,4,0-49,0 +N92000002,4,50-99,0 +N92000002,4,100-249,0 +N92000002,4,250-499,5 +N92000002,4,500-999,0 +N92000002,4,1000-1999,0 +N92000002,4,2000-4999,0 +N92000002,4,5000-9999,0 +N92000002,4,10000-49999,5 +N92000002,4,50000+,5 +N92000002,5,0-49,0 +N92000002,5,50-99,0 +N92000002,5,100-249,5 +N92000002,5,250-499,0 +N92000002,5,500-999,5 +N92000002,5,1000-1999,5 +N92000002,5,2000-4999,10 +N92000002,5,5000-9999,10 +N92000002,5,10000-49999,15 +N92000002,5,50000+,10 +N92000002,6,0-49,0 +N92000002,6,50-99,0 +N92000002,6,100-249,5 +N92000002,6,250-499,5 +N92000002,6,500-999,10 +N92000002,6,1000-1999,10 +N92000002,6,2000-4999,15 +N92000002,6,5000-9999,45 +N92000002,6,10000-49999,10 +N92000002,6,50000+,5 +N92000002,7,0-49,725 +N92000002,7,50-99,530 +N92000002,7,100-249,1060 +N92000002,7,250-499,460 +N92000002,7,500-999,335 +N92000002,7,1000-1999,175 +N92000002,7,2000-4999,85 +N92000002,7,5000-9999,30 +N92000002,7,10000-49999,10 +N92000002,7,50000+,0 diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_attributes_2025/ons_legal_status_turnover.csv b/packages/microcosm-build/tests/fixtures/uk/firm_attributes_2025/ons_legal_status_turnover.csv new file mode 100644 index 0000000000..dfc55fe412 --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_attributes_2025/ons_legal_status_turnover.csv @@ -0,0 +1,1191 @@ +industry_group,legal_status,turnover_band,enterprises +01-03,1,0-49,3540 +01-03,1,50-99,3845 +01-03,1,100-249,5875 +01-03,1,250-499,3725 +01-03,1,500-999,3160 +01-03,1,1000-1999,2455 +01-03,1,2000-4999,1645 +01-03,1,5000-9999,550 +01-03,1,10000-49999,335 +01-03,1,50000+,55 +01-03,2,0-49,23040 +01-03,2,50-99,13405 +01-03,2,100-249,10340 +01-03,2,250-499,3595 +01-03,2,500-999,1525 +01-03,2,1000-1999,505 +01-03,2,2000-4999,155 +01-03,2,5000-9999,30 +01-03,2,10000-49999,5 +01-03,2,50000+,0 +01-03,3,0-49,16865 +01-03,3,50-99,8535 +01-03,3,100-249,16180 +01-03,3,250-499,10095 +01-03,3,500-999,6465 +01-03,3,1000-1999,2975 +01-03,3,2000-4999,940 +01-03,3,5000-9999,140 +01-03,3,10000-49999,50 +01-03,3,50000+,0 +01-03,4,0-49,0 +01-03,4,50-99,0 +01-03,4,100-249,0 +01-03,4,250-499,0 +01-03,4,500-999,0 +01-03,4,1000-1999,0 +01-03,4,2000-4999,0 +01-03,4,5000-9999,0 +01-03,4,10000-49999,0 +01-03,4,50000+,5 +01-03,5,0-49,0 +01-03,5,50-99,0 +01-03,5,100-249,0 +01-03,5,250-499,0 +01-03,5,500-999,0 +01-03,5,1000-1999,0 +01-03,5,2000-4999,0 +01-03,5,5000-9999,0 +01-03,5,10000-49999,0 +01-03,5,50000+,0 +01-03,6,0-49,0 +01-03,6,50-99,0 +01-03,6,100-249,0 +01-03,6,250-499,0 +01-03,6,500-999,0 +01-03,6,1000-1999,0 +01-03,6,2000-4999,0 +01-03,6,5000-9999,0 +01-03,6,10000-49999,0 +01-03,6,50000+,0 +01-03,7,0-49,200 +01-03,7,50-99,135 +01-03,7,100-249,200 +01-03,7,250-499,105 +01-03,7,500-999,85 +01-03,7,1000-1999,40 +01-03,7,2000-4999,25 +01-03,7,5000-9999,5 +01-03,7,10000-49999,5 +01-03,7,50000+,0 +05-39,1,0-49,13340 +05-39,1,50-99,19495 +05-39,1,100-249,30240 +05-39,1,250-499,16450 +05-39,1,500-999,13850 +05-39,1,1000-1999,10655 +05-39,1,2000-4999,9775 +05-39,1,5000-9999,4770 +05-39,1,10000-49999,5220 +05-39,1,50000+,1880 +05-39,2,0-49,3725 +05-39,2,50-99,4130 +05-39,2,100-249,5985 +05-39,2,250-499,1450 +05-39,2,500-999,430 +05-39,2,1000-1999,95 +05-39,2,2000-4999,25 +05-39,2,5000-9999,5 +05-39,2,10000-49999,0 +05-39,2,50000+,0 +05-39,3,0-49,795 +05-39,3,50-99,865 +05-39,3,100-249,1740 +05-39,3,250-499,890 +05-39,3,500-999,435 +05-39,3,1000-1999,170 +05-39,3,2000-4999,75 +05-39,3,5000-9999,15 +05-39,3,10000-49999,25 +05-39,3,50000+,5 +05-39,4,0-49,0 +05-39,4,50-99,0 +05-39,4,100-249,0 +05-39,4,250-499,0 +05-39,4,500-999,0 +05-39,4,1000-1999,0 +05-39,4,2000-4999,0 +05-39,4,5000-9999,0 +05-39,4,10000-49999,5 +05-39,4,50000+,0 +05-39,5,0-49,0 +05-39,5,50-99,0 +05-39,5,100-249,0 +05-39,5,250-499,0 +05-39,5,500-999,0 +05-39,5,1000-1999,5 +05-39,5,2000-4999,0 +05-39,5,5000-9999,0 +05-39,5,10000-49999,0 +05-39,5,50000+,5 +05-39,6,0-49,5 +05-39,6,50-99,5 +05-39,6,100-249,10 +05-39,6,250-499,10 +05-39,6,500-999,10 +05-39,6,1000-1999,5 +05-39,6,2000-4999,0 +05-39,6,5000-9999,0 +05-39,6,10000-49999,0 +05-39,6,50000+,5 +05-39,7,0-49,90 +05-39,7,50-99,70 +05-39,7,100-249,110 +05-39,7,250-499,80 +05-39,7,500-999,45 +05-39,7,1000-1999,20 +05-39,7,2000-4999,10 +05-39,7,5000-9999,5 +05-39,7,10000-49999,5 +05-39,7,50000+,0 +41-43,1,0-49,23100 +41-43,1,50-99,52605 +41-43,1,100-249,98965 +41-43,1,250-499,59965 +41-43,1,500-999,38910 +41-43,1,1000-1999,19625 +41-43,1,2000-4999,12805 +41-43,1,5000-9999,4415 +41-43,1,10000-49999,3355 +41-43,1,50000+,690 +41-43,2,0-49,8770 +41-43,2,50-99,15485 +41-43,2,100-249,24830 +41-43,2,250-499,5740 +41-43,2,500-999,2980 +41-43,2,1000-1999,380 +41-43,2,2000-4999,70 +41-43,2,5000-9999,15 +41-43,2,10000-49999,0 +41-43,2,50000+,0 +41-43,3,0-49,1565 +41-43,3,50-99,2130 +41-43,3,100-249,4445 +41-43,3,250-499,1910 +41-43,3,500-999,960 +41-43,3,1000-1999,335 +41-43,3,2000-4999,100 +41-43,3,5000-9999,25 +41-43,3,10000-49999,30 +41-43,3,50000+,20 +41-43,4,0-49,0 +41-43,4,50-99,0 +41-43,4,100-249,0 +41-43,4,250-499,0 +41-43,4,500-999,0 +41-43,4,1000-1999,0 +41-43,4,2000-4999,0 +41-43,4,5000-9999,0 +41-43,4,10000-49999,0 +41-43,4,50000+,0 +41-43,5,0-49,0 +41-43,5,50-99,0 +41-43,5,100-249,0 +41-43,5,250-499,0 +41-43,5,500-999,0 +41-43,5,1000-1999,5 +41-43,5,2000-4999,0 +41-43,5,5000-9999,0 +41-43,5,10000-49999,0 +41-43,5,50000+,0 +41-43,6,0-49,5 +41-43,6,50-99,0 +41-43,6,100-249,0 +41-43,6,250-499,0 +41-43,6,500-999,0 +41-43,6,1000-1999,5 +41-43,6,2000-4999,0 +41-43,6,5000-9999,0 +41-43,6,10000-49999,0 +41-43,6,50000+,0 +41-43,7,0-49,165 +41-43,7,50-99,90 +41-43,7,100-249,120 +41-43,7,250-499,90 +41-43,7,500-999,55 +41-43,7,1000-1999,25 +41-43,7,2000-4999,35 +41-43,7,5000-9999,5 +41-43,7,10000-49999,5 +41-43,7,50000+,0 +45,1,0-49,3420 +45,1,50-99,9295 +45,1,100-249,17475 +45,1,250-499,12045 +45,1,500-999,7995 +45,1,1000-1999,4680 +45,1,2000-4999,3530 +45,1,5000-9999,1380 +45,1,10000-49999,1270 +45,1,50000+,460 +45,2,0-49,1915 +45,2,50-99,2905 +45,2,100-249,6970 +45,2,250-499,2665 +45,2,500-999,1105 +45,2,1000-1999,380 +45,2,2000-4999,120 +45,2,5000-9999,15 +45,2,10000-49999,10 +45,2,50000+,0 +45,3,0-49,290 +45,3,50-99,500 +45,3,100-249,1720 +45,3,250-499,1350 +45,3,500-999,710 +45,3,1000-1999,360 +45,3,2000-4999,195 +45,3,5000-9999,35 +45,3,10000-49999,20 +45,3,50000+,0 +45,4,0-49,0 +45,4,50-99,0 +45,4,100-249,0 +45,4,250-499,0 +45,4,500-999,0 +45,4,1000-1999,0 +45,4,2000-4999,0 +45,4,5000-9999,0 +45,4,10000-49999,0 +45,4,50000+,0 +45,5,0-49,0 +45,5,50-99,0 +45,5,100-249,0 +45,5,250-499,0 +45,5,500-999,0 +45,5,1000-1999,0 +45,5,2000-4999,0 +45,5,5000-9999,0 +45,5,10000-49999,0 +45,5,50000+,0 +45,6,0-49,0 +45,6,50-99,0 +45,6,100-249,0 +45,6,250-499,0 +45,6,500-999,0 +45,6,1000-1999,0 +45,6,2000-4999,0 +45,6,5000-9999,0 +45,6,10000-49999,0 +45,6,50000+,0 +45,7,0-49,10 +45,7,50-99,15 +45,7,100-249,15 +45,7,250-499,5 +45,7,500-999,5 +45,7,1000-1999,0 +45,7,2000-4999,0 +45,7,5000-9999,0 +45,7,10000-49999,0 +45,7,50000+,0 +46,1,0-49,9860 +46,1,50-99,7865 +46,1,100-249,15840 +46,1,250-499,12600 +46,1,500-999,11775 +46,1,1000-1999,9640 +46,1,2000-4999,9820 +46,1,5000-9999,5040 +46,1,10000-49999,5195 +46,1,50000+,1650 +46,2,0-49,1985 +46,2,50-99,1555 +46,2,100-249,2105 +46,2,250-499,950 +46,2,500-999,570 +46,2,1000-1999,285 +46,2,2000-4999,110 +46,2,5000-9999,20 +46,2,10000-49999,10 +46,2,50000+,5 +46,3,0-49,545 +46,3,50-99,450 +46,3,100-249,885 +46,3,250-499,610 +46,3,500-999,460 +46,3,1000-1999,375 +46,3,2000-4999,210 +46,3,5000-9999,75 +46,3,10000-49999,40 +46,3,50000+,5 +46,4,0-49,0 +46,4,50-99,0 +46,4,100-249,0 +46,4,250-499,0 +46,4,500-999,0 +46,4,1000-1999,0 +46,4,2000-4999,0 +46,4,5000-9999,0 +46,4,10000-49999,0 +46,4,50000+,0 +46,5,0-49,0 +46,5,50-99,0 +46,5,100-249,0 +46,5,250-499,0 +46,5,500-999,0 +46,5,1000-1999,0 +46,5,2000-4999,0 +46,5,5000-9999,0 +46,5,10000-49999,0 +46,5,50000+,0 +46,6,0-49,0 +46,6,50-99,0 +46,6,100-249,0 +46,6,250-499,0 +46,6,500-999,0 +46,6,1000-1999,0 +46,6,2000-4999,0 +46,6,5000-9999,0 +46,6,10000-49999,0 +46,6,50000+,0 +46,7,0-49,40 +46,7,50-99,20 +46,7,100-249,35 +46,7,250-499,25 +46,7,500-999,20 +46,7,1000-1999,15 +46,7,2000-4999,10 +46,7,5000-9999,5 +46,7,10000-49999,15 +46,7,50000+,0 +47,1,0-49,15780 +47,1,50-99,21415 +47,1,100-249,47585 +47,1,250-499,32040 +47,1,500-999,22705 +47,1,1000-1999,12805 +47,1,2000-4999,7365 +47,1,5000-9999,2360 +47,1,10000-49999,1530 +47,1,50000+,485 +47,2,0-49,4060 +47,2,50-99,5305 +47,2,100-249,13065 +47,2,250-499,6605 +47,2,500-999,3135 +47,2,1000-1999,700 +47,2,2000-4999,170 +47,2,5000-9999,25 +47,2,10000-49999,10 +47,2,50000+,0 +47,3,0-49,905 +47,3,50-99,1355 +47,3,100-249,4515 +47,3,250-499,3980 +47,3,500-999,2455 +47,3,1000-1999,930 +47,3,2000-4999,295 +47,3,5000-9999,75 +47,3,10000-49999,30 +47,3,50000+,0 +47,4,0-49,0 +47,4,50-99,0 +47,4,100-249,0 +47,4,250-499,0 +47,4,500-999,0 +47,4,1000-1999,0 +47,4,2000-4999,0 +47,4,5000-9999,0 +47,4,10000-49999,0 +47,4,50000+,0 +47,5,0-49,0 +47,5,50-99,0 +47,5,100-249,0 +47,5,250-499,0 +47,5,500-999,0 +47,5,1000-1999,0 +47,5,2000-4999,0 +47,5,5000-9999,0 +47,5,10000-49999,0 +47,5,50000+,0 +47,6,0-49,0 +47,6,50-99,0 +47,6,100-249,0 +47,6,250-499,0 +47,6,500-999,0 +47,6,1000-1999,0 +47,6,2000-4999,0 +47,6,5000-9999,0 +47,6,10000-49999,0 +47,6,50000+,0 +47,7,0-49,140 +47,7,50-99,160 +47,7,100-249,445 +47,7,250-499,235 +47,7,500-999,135 +47,7,1000-1999,55 +47,7,2000-4999,25 +47,7,5000-9999,10 +47,7,10000-49999,5 +47,7,50000+,5 +49-53,1,0-49,10825 +49-53,1,50-99,17665 +49-53,1,100-249,24680 +49-53,1,250-499,7920 +49-53,1,500-999,6340 +49-53,1,1000-1999,4260 +49-53,1,2000-4999,3485 +49-53,1,5000-9999,1530 +49-53,1,10000-49999,1435 +49-53,1,50000+,480 +49-53,2,0-49,20195 +49-53,2,50-99,6090 +49-53,2,100-249,4060 +49-53,2,250-499,1175 +49-53,2,500-999,515 +49-53,2,1000-1999,190 +49-53,2,2000-4999,55 +49-53,2,5000-9999,5 +49-53,2,10000-49999,0 +49-53,2,50000+,0 +49-53,3,0-49,345 +49-53,3,50-99,410 +49-53,3,100-249,920 +49-53,3,250-499,560 +49-53,3,500-999,310 +49-53,3,1000-1999,180 +49-53,3,2000-4999,80 +49-53,3,5000-9999,15 +49-53,3,10000-49999,0 +49-53,3,50000+,0 +49-53,4,0-49,0 +49-53,4,50-99,0 +49-53,4,100-249,5 +49-53,4,250-499,0 +49-53,4,500-999,0 +49-53,4,1000-1999,0 +49-53,4,2000-4999,0 +49-53,4,5000-9999,5 +49-53,4,10000-49999,20 +49-53,4,50000+,30 +49-53,5,0-49,0 +49-53,5,50-99,0 +49-53,5,100-249,0 +49-53,5,250-499,0 +49-53,5,500-999,0 +49-53,5,1000-1999,0 +49-53,5,2000-4999,5 +49-53,5,5000-9999,0 +49-53,5,10000-49999,5 +49-53,5,50000+,0 +49-53,6,0-49,5 +49-53,6,50-99,0 +49-53,6,100-249,0 +49-53,6,250-499,0 +49-53,6,500-999,0 +49-53,6,1000-1999,0 +49-53,6,2000-4999,0 +49-53,6,5000-9999,0 +49-53,6,10000-49999,5 +49-53,6,50000+,5 +49-53,7,0-49,150 +49-53,7,50-99,100 +49-53,7,100-249,130 +49-53,7,250-499,55 +49-53,7,500-999,55 +49-53,7,1000-1999,40 +49-53,7,2000-4999,20 +49-53,7,5000-9999,15 +49-53,7,10000-49999,5 +49-53,7,50000+,0 +55-56,1,0-49,10110 +55-56,1,50-99,22465 +55-56,1,100-249,50705 +55-56,1,250-499,25305 +55-56,1,500-999,15385 +55-56,1,1000-1999,7030 +55-56,1,2000-4999,3585 +55-56,1,5000-9999,1160 +55-56,1,10000-49999,940 +55-56,1,50000+,235 +55-56,2,0-49,780 +55-56,2,50-99,5240 +55-56,2,100-249,11690 +55-56,2,250-499,3475 +55-56,2,500-999,1005 +55-56,2,1000-1999,195 +55-56,2,2000-4999,40 +55-56,2,5000-9999,10 +55-56,2,10000-49999,5 +55-56,2,50000+,0 +55-56,3,0-49,520 +55-56,3,50-99,1235 +55-56,3,100-249,5515 +55-56,3,250-499,2915 +55-56,3,500-999,1270 +55-56,3,1000-1999,410 +55-56,3,2000-4999,100 +55-56,3,5000-9999,10 +55-56,3,10000-49999,5 +55-56,3,50000+,0 +55-56,4,0-49,0 +55-56,4,50-99,0 +55-56,4,100-249,0 +55-56,4,250-499,0 +55-56,4,500-999,0 +55-56,4,1000-1999,0 +55-56,4,2000-4999,0 +55-56,4,5000-9999,0 +55-56,4,10000-49999,0 +55-56,4,50000+,0 +55-56,5,0-49,0 +55-56,5,50-99,0 +55-56,5,100-249,5 +55-56,5,250-499,5 +55-56,5,500-999,5 +55-56,5,1000-1999,0 +55-56,5,2000-4999,0 +55-56,5,5000-9999,0 +55-56,5,10000-49999,0 +55-56,5,50000+,0 +55-56,6,0-49,0 +55-56,6,50-99,0 +55-56,6,100-249,0 +55-56,6,250-499,0 +55-56,6,500-999,5 +55-56,6,1000-1999,0 +55-56,6,2000-4999,0 +55-56,6,5000-9999,0 +55-56,6,10000-49999,0 +55-56,6,50000+,0 +55-56,7,0-49,405 +55-56,7,50-99,735 +55-56,7,100-249,2380 +55-56,7,250-499,1340 +55-56,7,500-999,350 +55-56,7,1000-1999,55 +55-56,7,2000-4999,30 +55-56,7,5000-9999,15 +55-56,7,10000-49999,10 +55-56,7,50000+,5 +58-63,1,0-49,29180 +58-63,1,50-99,45715 +58-63,1,100-249,62865 +58-63,1,250-499,15370 +58-63,1,500-999,9265 +58-63,1,1000-1999,6250 +58-63,1,2000-4999,5025 +58-63,1,5000-9999,2245 +58-63,1,10000-49999,2200 +58-63,1,50000+,815 +58-63,2,0-49,2140 +58-63,2,50-99,2250 +58-63,2,100-249,1960 +58-63,2,250-499,270 +58-63,2,500-999,100 +58-63,2,1000-1999,20 +58-63,2,2000-4999,15 +58-63,2,5000-9999,10 +58-63,2,10000-49999,0 +58-63,2,50000+,0 +58-63,3,0-49,270 +58-63,3,50-99,215 +58-63,3,100-249,285 +58-63,3,250-499,95 +58-63,3,500-999,40 +58-63,3,1000-1999,15 +58-63,3,2000-4999,10 +58-63,3,5000-9999,5 +58-63,3,10000-49999,5 +58-63,3,50000+,0 +58-63,4,0-49,0 +58-63,4,50-99,0 +58-63,4,100-249,0 +58-63,4,250-499,0 +58-63,4,500-999,0 +58-63,4,1000-1999,5 +58-63,4,2000-4999,0 +58-63,4,5000-9999,0 +58-63,4,10000-49999,0 +58-63,4,50000+,0 +58-63,5,0-49,0 +58-63,5,50-99,0 +58-63,5,100-249,0 +58-63,5,250-499,0 +58-63,5,500-999,0 +58-63,5,1000-1999,0 +58-63,5,2000-4999,0 +58-63,5,5000-9999,5 +58-63,5,10000-49999,0 +58-63,5,50000+,0 +58-63,6,0-49,0 +58-63,6,50-99,0 +58-63,6,100-249,0 +58-63,6,250-499,5 +58-63,6,500-999,0 +58-63,6,1000-1999,0 +58-63,6,2000-4999,0 +58-63,6,5000-9999,0 +58-63,6,10000-49999,0 +58-63,6,50000+,0 +58-63,7,0-49,185 +58-63,7,50-99,205 +58-63,7,100-249,290 +58-63,7,250-499,150 +58-63,7,500-999,110 +58-63,7,1000-1999,50 +58-63,7,2000-4999,25 +58-63,7,5000-9999,15 +58-63,7,10000-49999,10 +58-63,7,50000+,5 +64-66,1,0-49,14350 +64-66,1,50-99,2010 +64-66,1,100-249,13000 +64-66,1,250-499,6050 +64-66,1,500-999,3720 +64-66,1,1000-1999,2125 +64-66,1,2000-4999,1515 +64-66,1,5000-9999,815 +64-66,1,10000-49999,1080 +64-66,1,50000+,855 +64-66,2,0-49,45 +64-66,2,50-99,40 +64-66,2,100-249,625 +64-66,2,250-499,330 +64-66,2,500-999,120 +64-66,2,1000-1999,25 +64-66,2,2000-4999,5 +64-66,2,5000-9999,0 +64-66,2,10000-49999,0 +64-66,2,50000+,0 +64-66,3,0-49,75 +64-66,3,50-99,30 +64-66,3,100-249,30 +64-66,3,250-499,145 +64-66,3,500-999,130 +64-66,3,1000-1999,90 +64-66,3,2000-4999,30 +64-66,3,5000-9999,5 +64-66,3,10000-49999,5 +64-66,3,50000+,0 +64-66,4,0-49,5 +64-66,4,50-99,0 +64-66,4,100-249,0 +64-66,4,250-499,0 +64-66,4,500-999,0 +64-66,4,1000-1999,0 +64-66,4,2000-4999,0 +64-66,4,5000-9999,0 +64-66,4,10000-49999,0 +64-66,4,50000+,5 +64-66,5,0-49,5 +64-66,5,50-99,0 +64-66,5,100-249,0 +64-66,5,250-499,0 +64-66,5,500-999,0 +64-66,5,1000-1999,0 +64-66,5,2000-4999,0 +64-66,5,5000-9999,0 +64-66,5,10000-49999,5 +64-66,5,50000+,5 +64-66,6,0-49,0 +64-66,6,50-99,0 +64-66,6,100-249,0 +64-66,6,250-499,0 +64-66,6,500-999,0 +64-66,6,1000-1999,0 +64-66,6,2000-4999,0 +64-66,6,5000-9999,0 +64-66,6,10000-49999,0 +64-66,6,50000+,0 +64-66,7,0-49,8685 +64-66,7,50-99,90 +64-66,7,100-249,125 +64-66,7,250-499,85 +64-66,7,500-999,85 +64-66,7,1000-1999,55 +64-66,7,2000-4999,35 +64-66,7,5000-9999,20 +64-66,7,10000-49999,15 +64-66,7,50000+,20 +68,1,0-49,15785 +68,1,50-99,25365 +68,1,100-249,30060 +68,1,250-499,13560 +68,1,500-999,7515 +68,1,1000-1999,3830 +68,1,2000-4999,2115 +68,1,5000-9999,800 +68,1,10000-49999,640 +68,1,50000+,190 +68,2,0-49,3455 +68,2,50-99,1310 +68,2,100-249,2015 +68,2,250-499,615 +68,2,500-999,250 +68,2,1000-1999,75 +68,2,2000-4999,45 +68,2,5000-9999,10 +68,2,10000-49999,5 +68,2,50000+,0 +68,3,0-49,5205 +68,3,50-99,2370 +68,3,100-249,2245 +68,3,250-499,1030 +68,3,500-999,465 +68,3,1000-1999,170 +68,3,2000-4999,65 +68,3,5000-9999,30 +68,3,10000-49999,15 +68,3,50000+,5 +68,4,0-49,0 +68,4,50-99,0 +68,4,100-249,0 +68,4,250-499,0 +68,4,500-999,0 +68,4,1000-1999,0 +68,4,2000-4999,5 +68,4,5000-9999,0 +68,4,10000-49999,15 +68,4,50000+,5 +68,5,0-49,5 +68,5,50-99,0 +68,5,100-249,0 +68,5,250-499,5 +68,5,500-999,0 +68,5,1000-1999,0 +68,5,2000-4999,0 +68,5,5000-9999,0 +68,5,10000-49999,0 +68,5,50000+,0 +68,6,0-49,0 +68,6,50-99,0 +68,6,100-249,5 +68,6,250-499,5 +68,6,500-999,0 +68,6,1000-1999,0 +68,6,2000-4999,0 +68,6,5000-9999,0 +68,6,10000-49999,0 +68,6,50000+,0 +68,7,0-49,810 +68,7,50-99,600 +68,7,100-249,670 +68,7,250-499,335 +68,7,500-999,220 +68,7,1000-1999,140 +68,7,2000-4999,85 +68,7,5000-9999,45 +68,7,10000-49999,70 +68,7,50000+,50 +69-75,1,0-49,50195 +69-75,1,50-99,78510 +69-75,1,100-249,142875 +69-75,1,250-499,40640 +69-75,1,500-999,21825 +69-75,1,1000-1999,12885 +69-75,1,2000-4999,9120 +69-75,1,5000-9999,3630 +69-75,1,10000-49999,3300 +69-75,1,50000+,1015 +69-75,2,0-49,7380 +69-75,2,50-99,9315 +69-75,2,100-249,20520 +69-75,2,250-499,5300 +69-75,2,500-999,1925 +69-75,2,1000-1999,610 +69-75,2,2000-4999,160 +69-75,2,5000-9999,20 +69-75,2,10000-49999,0 +69-75,2,50000+,0 +69-75,3,0-49,990 +69-75,3,50-99,975 +69-75,3,100-249,2125 +69-75,3,250-499,1155 +69-75,3,500-999,940 +69-75,3,1000-1999,550 +69-75,3,2000-4999,275 +69-75,3,5000-9999,80 +69-75,3,10000-49999,55 +69-75,3,50000+,15 +69-75,4,0-49,0 +69-75,4,50-99,0 +69-75,4,100-249,0 +69-75,4,250-499,0 +69-75,4,500-999,0 +69-75,4,1000-1999,0 +69-75,4,2000-4999,5 +69-75,4,5000-9999,0 +69-75,4,10000-49999,5 +69-75,4,50000+,5 +69-75,5,0-49,5 +69-75,5,50-99,0 +69-75,5,100-249,0 +69-75,5,250-499,5 +69-75,5,500-999,5 +69-75,5,1000-1999,5 +69-75,5,2000-4999,5 +69-75,5,5000-9999,10 +69-75,5,10000-49999,5 +69-75,5,50000+,5 +69-75,6,0-49,0 +69-75,6,50-99,0 +69-75,6,100-249,0 +69-75,6,250-499,0 +69-75,6,500-999,0 +69-75,6,1000-1999,0 +69-75,6,2000-4999,0 +69-75,6,5000-9999,0 +69-75,6,10000-49999,0 +69-75,6,50000+,5 +69-75,7,0-49,290 +69-75,7,50-99,505 +69-75,7,100-249,825 +69-75,7,250-499,505 +69-75,7,500-999,405 +69-75,7,1000-1999,265 +69-75,7,2000-4999,175 +69-75,7,5000-9999,70 +69-75,7,10000-49999,65 +69-75,7,50000+,15 +77-82,1,0-49,21305 +77-82,1,50-99,25955 +77-82,1,100-249,62655 +77-82,1,250-499,26895 +77-82,1,500-999,16260 +77-82,1,1000-1999,10630 +77-82,1,2000-4999,8240 +77-82,1,5000-9999,2970 +77-82,1,10000-49999,2855 +77-82,1,50000+,865 +77-82,2,0-49,3560 +77-82,2,50-99,5515 +77-82,2,100-249,9120 +77-82,2,250-499,10700 +77-82,2,500-999,3515 +77-82,2,1000-1999,1040 +77-82,2,2000-4999,265 +77-82,2,5000-9999,25 +77-82,2,10000-49999,10 +77-82,2,50000+,0 +77-82,3,0-49,825 +77-82,3,50-99,820 +77-82,3,100-249,1610 +77-82,3,250-499,710 +77-82,3,500-999,1215 +77-82,3,1000-1999,355 +77-82,3,2000-4999,140 +77-82,3,5000-9999,25 +77-82,3,10000-49999,5 +77-82,3,50000+,5 +77-82,4,0-49,0 +77-82,4,50-99,0 +77-82,4,100-249,0 +77-82,4,250-499,0 +77-82,4,500-999,0 +77-82,4,1000-1999,0 +77-82,4,2000-4999,0 +77-82,4,5000-9999,0 +77-82,4,10000-49999,5 +77-82,4,50000+,5 +77-82,5,0-49,5 +77-82,5,50-99,0 +77-82,5,100-249,5 +77-82,5,250-499,5 +77-82,5,500-999,0 +77-82,5,1000-1999,5 +77-82,5,2000-4999,5 +77-82,5,5000-9999,10 +77-82,5,10000-49999,5 +77-82,5,50000+,0 +77-82,6,0-49,0 +77-82,6,50-99,0 +77-82,6,100-249,5 +77-82,6,250-499,5 +77-82,6,500-999,5 +77-82,6,1000-1999,0 +77-82,6,2000-4999,5 +77-82,6,5000-9999,0 +77-82,6,10000-49999,0 +77-82,6,50000+,0 +77-82,7,0-49,315 +77-82,7,50-99,205 +77-82,7,100-249,1230 +77-82,7,250-499,730 +77-82,7,500-999,550 +77-82,7,1000-1999,465 +77-82,7,2000-4999,335 +77-82,7,5000-9999,45 +77-82,7,10000-49999,20 +77-82,7,50000+,5 +84,1,0-49,0 +84,1,50-99,5 +84,1,100-249,15 +84,1,250-499,5 +84,1,500-999,0 +84,1,1000-1999,5 +84,1,2000-4999,0 +84,1,5000-9999,0 +84,1,10000-49999,0 +84,1,50000+,0 +84,2,0-49,0 +84,2,50-99,0 +84,2,100-249,0 +84,2,250-499,0 +84,2,500-999,0 +84,2,1000-1999,0 +84,2,2000-4999,0 +84,2,5000-9999,0 +84,2,10000-49999,0 +84,2,50000+,0 +84,3,0-49,0 +84,3,50-99,0 +84,3,100-249,0 +84,3,250-499,0 +84,3,500-999,0 +84,3,1000-1999,0 +84,3,2000-4999,0 +84,3,5000-9999,0 +84,3,10000-49999,0 +84,3,50000+,0 +84,4,0-49,0 +84,4,50-99,0 +84,4,100-249,0 +84,4,250-499,0 +84,4,500-999,0 +84,4,1000-1999,0 +84,4,2000-4999,0 +84,4,5000-9999,0 +84,4,10000-49999,5 +84,4,50000+,5 +84,5,0-49,0 +84,5,50-99,5 +84,5,100-249,10 +84,5,250-499,5 +84,5,500-999,10 +84,5,1000-1999,15 +84,5,2000-4999,30 +84,5,5000-9999,20 +84,5,10000-49999,55 +84,5,50000+,65 +84,6,0-49,300 +84,6,50-99,4930 +84,6,100-249,1300 +84,6,250-499,535 +84,6,500-999,210 +84,6,1000-1999,75 +84,6,2000-4999,60 +84,6,5000-9999,55 +84,6,10000-49999,130 +84,6,50000+,75 +84,7,0-49,0 +84,7,50-99,20 +84,7,100-249,5 +84,7,250-499,0 +84,7,500-999,5 +84,7,1000-1999,0 +84,7,2000-4999,0 +84,7,5000-9999,0 +84,7,10000-49999,5 +84,7,50000+,0 +85,1,0-49,3405 +85,1,50-99,10785 +85,1,100-249,10390 +85,1,250-499,4205 +85,1,500-999,2940 +85,1,1000-1999,1450 +85,1,2000-4999,905 +85,1,5000-9999,265 +85,1,10000-49999,260 +85,1,50000+,45 +85,2,0-49,380 +85,2,50-99,460 +85,2,100-249,1235 +85,2,250-499,745 +85,2,500-999,450 +85,2,1000-1999,95 +85,2,2000-4999,15 +85,2,5000-9999,0 +85,2,10000-49999,0 +85,2,50000+,0 +85,3,0-49,55 +85,3,50-99,70 +85,3,100-249,275 +85,3,250-499,210 +85,3,500-999,155 +85,3,1000-1999,45 +85,3,2000-4999,10 +85,3,5000-9999,0 +85,3,10000-49999,0 +85,3,50000+,0 +85,4,0-49,0 +85,4,50-99,0 +85,4,100-249,0 +85,4,250-499,5 +85,4,500-999,5 +85,4,1000-1999,0 +85,4,2000-4999,0 +85,4,5000-9999,0 +85,4,10000-49999,0 +85,4,50000+,0 +85,5,0-49,80 +85,5,50-99,35 +85,5,100-249,90 +85,5,250-499,95 +85,5,500-999,150 +85,5,1000-1999,320 +85,5,2000-4999,540 +85,5,5000-9999,505 +85,5,10000-49999,755 +85,5,50000+,60 +85,6,0-49,0 +85,6,50-99,5 +85,6,100-249,5 +85,6,250-499,20 +85,6,500-999,75 +85,6,1000-1999,250 +85,6,2000-4999,345 +85,6,5000-9999,170 +85,6,10000-49999,120 +85,6,50000+,55 +85,7,0-49,405 +85,7,50-99,785 +85,7,100-249,1340 +85,7,250-499,1360 +85,7,500-999,995 +85,7,1000-1999,530 +85,7,2000-4999,425 +85,7,5000-9999,270 +85,7,10000-49999,315 +85,7,50000+,130 +86-88,1,0-49,3635 +86-88,1,50-99,28350 +86-88,1,100-249,19245 +86-88,1,250-499,8855 +86-88,1,500-999,7595 +86-88,1,1000-1999,4580 +86-88,1,2000-4999,3680 +86-88,1,5000-9999,1030 +86-88,1,10000-49999,670 +86-88,1,50000+,125 +86-88,2,0-49,155 +86-88,2,50-99,1060 +86-88,2,100-249,3735 +86-88,2,250-499,2925 +86-88,2,500-999,1740 +86-88,2,1000-1999,595 +86-88,2,2000-4999,130 +86-88,2,5000-9999,5 +86-88,2,10000-49999,0 +86-88,2,50000+,0 +86-88,3,0-49,45 +86-88,3,50-99,35 +86-88,3,100-249,360 +86-88,3,250-499,1020 +86-88,3,500-999,1725 +86-88,3,1000-1999,2465 +86-88,3,2000-4999,2340 +86-88,3,5000-9999,275 +86-88,3,10000-49999,60 +86-88,3,50000+,0 +86-88,4,0-49,0 +86-88,4,50-99,5 +86-88,4,100-249,0 +86-88,4,250-499,0 +86-88,4,500-999,0 +86-88,4,1000-1999,0 +86-88,4,2000-4999,0 +86-88,4,5000-9999,0 +86-88,4,10000-49999,0 +86-88,4,50000+,0 +86-88,5,0-49,0 +86-88,5,50-99,0 +86-88,5,100-249,5 +86-88,5,250-499,5 +86-88,5,500-999,0 +86-88,5,1000-1999,5 +86-88,5,2000-4999,5 +86-88,5,5000-9999,0 +86-88,5,10000-49999,15 +86-88,5,50000+,245 +86-88,6,0-49,0 +86-88,6,50-99,15 +86-88,6,100-249,65 +86-88,6,250-499,45 +86-88,6,500-999,10 +86-88,6,1000-1999,10 +86-88,6,2000-4999,5 +86-88,6,5000-9999,5 +86-88,6,10000-49999,5 +86-88,6,50000+,0 +86-88,7,0-49,970 +86-88,7,50-99,3385 +86-88,7,100-249,5470 +86-88,7,250-499,4275 +86-88,7,500-999,2880 +86-88,7,1000-1999,1550 +86-88,7,2000-4999,1105 +86-88,7,5000-9999,380 +86-88,7,10000-49999,265 +86-88,7,50000+,75 +90-99,1,0-49,21965 +90-99,1,50-99,28805 +90-99,1,100-249,41760 +90-99,1,250-499,13700 +90-99,1,500-999,7460 +90-99,1,1000-1999,3890 +90-99,1,2000-4999,2305 +90-99,1,5000-9999,820 +90-99,1,10000-49999,605 +90-99,1,50000+,170 +90-99,2,0-49,5265 +90-99,2,50-99,12745 +90-99,2,100-249,12695 +90-99,2,250-499,2040 +90-99,2,500-999,795 +90-99,2,1000-1999,225 +90-99,2,2000-4999,85 +90-99,2,5000-9999,20 +90-99,2,10000-49999,10 +90-99,2,50000+,0 +90-99,3,0-49,2940 +90-99,3,50-99,1350 +90-99,3,100-249,2995 +90-99,3,250-499,930 +90-99,3,500-999,400 +90-99,3,1000-1999,130 +90-99,3,2000-4999,45 +90-99,3,5000-9999,15 +90-99,3,10000-49999,10 +90-99,3,50000+,0 +90-99,4,0-49,0 +90-99,4,50-99,0 +90-99,4,100-249,0 +90-99,4,250-499,0 +90-99,4,500-999,0 +90-99,4,1000-1999,0 +90-99,4,2000-4999,0 +90-99,4,5000-9999,0 +90-99,4,10000-49999,0 +90-99,4,50000+,5 +90-99,5,0-49,0 +90-99,5,50-99,0 +90-99,5,100-249,5 +90-99,5,250-499,5 +90-99,5,500-999,10 +90-99,5,1000-1999,10 +90-99,5,2000-4999,15 +90-99,5,5000-9999,5 +90-99,5,10000-49999,15 +90-99,5,50000+,5 +90-99,6,0-49,15 +90-99,6,50-99,15 +90-99,6,100-249,30 +90-99,6,250-499,20 +90-99,6,500-999,20 +90-99,6,1000-1999,10 +90-99,6,2000-4999,10 +90-99,6,5000-9999,5 +90-99,6,10000-49999,0 +90-99,6,50000+,0 +90-99,7,0-49,5110 +90-99,7,50-99,4785 +90-99,7,100-249,7745 +90-99,7,250-499,4385 +90-99,7,500-999,2710 +90-99,7,1000-1999,1520 +90-99,7,2000-4999,805 +90-99,7,5000-9999,255 +90-99,7,10000-49999,225 +90-99,7,50000+,40 diff --git a/packages/microcosm-build/tests/fixtures/uk/firm_attributes_2025/ons_region_turnover.csv b/packages/microcosm-build/tests/fixtures/uk/firm_attributes_2025/ons_region_turnover.csv new file mode 100644 index 0000000000..7aa2098f86 --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/uk/firm_attributes_2025/ons_region_turnover.csv @@ -0,0 +1,7393 @@ +sic_division,region_code,turnover_band,enterprises +01,E12000001,0-49,850 +01,E12000001,50-99,700 +01,E12000001,100-249,960 +01,E12000001,250-499,520 +01,E12000001,500-999,280 +01,E12000001,1000-4999,205 +01,E12000001,5000+,15 +01,E12000002,0-49,2830 +01,E12000002,50-99,2090 +01,E12000002,100-249,2595 +01,E12000002,250-499,1255 +01,E12000002,500-999,895 +01,E12000002,1000-4999,730 +01,E12000002,5000+,55 +01,E12000003,0-49,2390 +01,E12000003,50-99,1975 +01,E12000003,100-249,2515 +01,E12000003,250-499,1425 +01,E12000003,500-999,940 +01,E12000003,1000-4999,760 +01,E12000003,5000+,125 +01,E12000004,0-49,2225 +01,E12000004,50-99,1750 +01,E12000004,100-249,2470 +01,E12000004,250-499,1415 +01,E12000004,500-999,940 +01,E12000004,1000-4999,795 +01,E12000004,5000+,135 +01,E12000005,0-49,3070 +01,E12000005,50-99,2150 +01,E12000005,100-249,2600 +01,E12000005,250-499,1395 +01,E12000005,500-999,925 +01,E12000005,1000-4999,785 +01,E12000005,5000+,135 +01,E12000006,0-49,1795 +01,E12000006,50-99,1805 +01,E12000006,100-249,2430 +01,E12000006,250-499,1625 +01,E12000006,500-999,1115 +01,E12000006,1000-4999,1025 +01,E12000006,5000+,180 +01,E12000007,0-49,145 +01,E12000007,50-99,125 +01,E12000007,100-249,175 +01,E12000007,250-499,85 +01,E12000007,500-999,40 +01,E12000007,1000-4999,50 +01,E12000007,5000+,15 +01,E12000008,0-49,2210 +01,E12000008,50-99,1875 +01,E12000008,100-249,2525 +01,E12000008,250-499,1340 +01,E12000008,500-999,890 +01,E12000008,1000-4999,780 +01,E12000008,5000+,135 +01,E12000009,0-49,6335 +01,E12000009,50-99,4080 +01,E12000009,100-249,4930 +01,E12000009,250-499,2525 +01,E12000009,500-999,1650 +01,E12000009,1000-4999,1165 +01,E12000009,5000+,105 +01,W92000004,0-49,5655 +01,W92000004,50-99,2455 +01,W92000004,100-249,2620 +01,W92000004,250-499,1160 +01,W92000004,500-999,695 +01,W92000004,1000-4999,455 +01,W92000004,5000+,50 +01,S92000003,0-49,4390 +01,S92000003,50-99,2085 +01,S92000003,100-249,3105 +01,S92000003,250-499,2050 +01,S92000003,500-999,1330 +01,S92000003,1000-4999,975 +01,S92000003,5000+,100 +01,N92000002,0-49,9720 +01,N92000002,50-99,3015 +01,N92000002,100-249,2950 +01,N92000002,250-499,1560 +01,N92000002,500-999,975 +01,N92000002,1000-4999,520 +01,N92000002,5000+,35 +02,E12000001,0-49,20 +02,E12000001,50-99,35 +02,E12000001,100-249,60 +02,E12000001,250-499,20 +02,E12000001,500-999,10 +02,E12000001,1000-4999,10 +02,E12000001,5000+,5 +02,E12000002,0-49,35 +02,E12000002,50-99,85 +02,E12000002,100-249,115 +02,E12000002,250-499,35 +02,E12000002,500-999,20 +02,E12000002,1000-4999,15 +02,E12000002,5000+,5 +02,E12000003,0-49,35 +02,E12000003,50-99,60 +02,E12000003,100-249,90 +02,E12000003,250-499,35 +02,E12000003,500-999,20 +02,E12000003,1000-4999,15 +02,E12000003,5000+,0 +02,E12000004,0-49,35 +02,E12000004,50-99,60 +02,E12000004,100-249,100 +02,E12000004,250-499,35 +02,E12000004,500-999,15 +02,E12000004,1000-4999,15 +02,E12000004,5000+,0 +02,E12000005,0-49,65 +02,E12000005,50-99,70 +02,E12000005,100-249,130 +02,E12000005,250-499,40 +02,E12000005,500-999,15 +02,E12000005,1000-4999,25 +02,E12000005,5000+,5 +02,E12000006,0-49,40 +02,E12000006,50-99,85 +02,E12000006,100-249,135 +02,E12000006,250-499,65 +02,E12000006,500-999,25 +02,E12000006,1000-4999,20 +02,E12000006,5000+,0 +02,E12000007,0-49,30 +02,E12000007,50-99,65 +02,E12000007,100-249,70 +02,E12000007,250-499,25 +02,E12000007,500-999,20 +02,E12000007,1000-4999,10 +02,E12000007,5000+,0 +02,E12000008,0-49,100 +02,E12000008,50-99,180 +02,E12000008,100-249,335 +02,E12000008,250-499,130 +02,E12000008,500-999,60 +02,E12000008,1000-4999,35 +02,E12000008,5000+,15 +02,E12000009,0-49,135 +02,E12000009,50-99,165 +02,E12000009,100-249,240 +02,E12000009,250-499,80 +02,E12000009,500-999,30 +02,E12000009,1000-4999,25 +02,E12000009,5000+,5 +02,W92000004,0-49,95 +02,W92000004,50-99,65 +02,W92000004,100-249,130 +02,W92000004,250-499,55 +02,W92000004,500-999,30 +02,W92000004,1000-4999,10 +02,W92000004,5000+,5 +02,S92000003,0-49,245 +02,S92000003,50-99,185 +02,S92000003,100-249,290 +02,S92000003,250-499,150 +02,S92000003,500-999,90 +02,S92000003,1000-4999,85 +02,S92000003,5000+,10 +02,N92000002,0-49,15 +02,N92000002,50-99,10 +02,N92000002,100-249,10 +02,N92000002,250-499,10 +02,N92000002,500-999,10 +02,N92000002,1000-4999,5 +02,N92000002,5000+,0 +03,E12000001,0-49,45 +03,E12000001,50-99,20 +03,E12000001,100-249,25 +03,E12000001,250-499,10 +03,E12000001,500-999,5 +03,E12000001,1000-4999,5 +03,E12000001,5000+,0 +03,E12000002,0-49,25 +03,E12000002,50-99,20 +03,E12000002,100-249,20 +03,E12000002,250-499,5 +03,E12000002,500-999,5 +03,E12000002,1000-4999,5 +03,E12000002,5000+,0 +03,E12000003,0-49,40 +03,E12000003,50-99,20 +03,E12000003,100-249,60 +03,E12000003,250-499,30 +03,E12000003,500-999,5 +03,E12000003,1000-4999,15 +03,E12000003,5000+,5 +03,E12000004,0-49,10 +03,E12000004,50-99,15 +03,E12000004,100-249,15 +03,E12000004,250-499,10 +03,E12000004,500-999,0 +03,E12000004,1000-4999,0 +03,E12000004,5000+,0 +03,E12000005,0-49,10 +03,E12000005,50-99,10 +03,E12000005,100-249,10 +03,E12000005,250-499,5 +03,E12000005,500-999,0 +03,E12000005,1000-4999,0 +03,E12000005,5000+,0 +03,E12000006,0-49,55 +03,E12000006,50-99,45 +03,E12000006,100-249,50 +03,E12000006,250-499,15 +03,E12000006,500-999,10 +03,E12000006,1000-4999,5 +03,E12000006,5000+,0 +03,E12000007,0-49,5 +03,E12000007,50-99,5 +03,E12000007,100-249,10 +03,E12000007,250-499,5 +03,E12000007,500-999,5 +03,E12000007,1000-4999,0 +03,E12000007,5000+,0 +03,E12000008,0-49,105 +03,E12000008,50-99,70 +03,E12000008,100-249,65 +03,E12000008,250-499,30 +03,E12000008,500-999,10 +03,E12000008,1000-4999,15 +03,E12000008,5000+,0 +03,E12000009,0-49,250 +03,E12000009,50-99,130 +03,E12000009,100-249,150 +03,E12000009,250-499,60 +03,E12000009,500-999,35 +03,E12000009,1000-4999,40 +03,E12000009,5000+,5 +03,W92000004,0-49,85 +03,W92000004,50-99,30 +03,W92000004,100-249,40 +03,W92000004,250-499,15 +03,W92000004,500-999,10 +03,W92000004,1000-4999,5 +03,W92000004,5000+,0 +03,S92000003,0-49,490 +03,S92000003,50-99,360 +03,S92000003,100-249,535 +03,S92000003,250-499,285 +03,S92000003,500-999,110 +03,S92000003,1000-4999,120 +03,S92000003,5000+,40 +03,N92000002,0-49,60 +03,N92000002,50-99,25 +03,N92000002,100-249,35 +03,N92000002,250-499,20 +03,N92000002,500-999,20 +03,N92000002,1000-4999,10 +03,N92000002,5000+,0 +05,E12000001,0-49,0 +05,E12000001,50-99,0 +05,E12000001,100-249,0 +05,E12000001,250-499,0 +05,E12000001,500-999,0 +05,E12000001,1000-4999,0 +05,E12000001,5000+,0 +05,E12000002,0-49,0 +05,E12000002,50-99,0 +05,E12000002,100-249,0 +05,E12000002,250-499,0 +05,E12000002,500-999,0 +05,E12000002,1000-4999,0 +05,E12000002,5000+,0 +05,E12000003,0-49,0 +05,E12000003,50-99,0 +05,E12000003,100-249,0 +05,E12000003,250-499,0 +05,E12000003,500-999,0 +05,E12000003,1000-4999,0 +05,E12000003,5000+,0 +05,E12000004,0-49,0 +05,E12000004,50-99,0 +05,E12000004,100-249,0 +05,E12000004,250-499,0 +05,E12000004,500-999,0 +05,E12000004,1000-4999,0 +05,E12000004,5000+,0 +05,E12000005,0-49,0 +05,E12000005,50-99,0 +05,E12000005,100-249,0 +05,E12000005,250-499,0 +05,E12000005,500-999,0 +05,E12000005,1000-4999,0 +05,E12000005,5000+,0 +05,E12000006,0-49,0 +05,E12000006,50-99,0 +05,E12000006,100-249,0 +05,E12000006,250-499,0 +05,E12000006,500-999,0 +05,E12000006,1000-4999,0 +05,E12000006,5000+,0 +05,E12000007,0-49,0 +05,E12000007,50-99,0 +05,E12000007,100-249,0 +05,E12000007,250-499,0 +05,E12000007,500-999,0 +05,E12000007,1000-4999,0 +05,E12000007,5000+,0 +05,E12000008,0-49,0 +05,E12000008,50-99,0 +05,E12000008,100-249,0 +05,E12000008,250-499,0 +05,E12000008,500-999,0 +05,E12000008,1000-4999,0 +05,E12000008,5000+,0 +05,E12000009,0-49,0 +05,E12000009,50-99,0 +05,E12000009,100-249,0 +05,E12000009,250-499,0 +05,E12000009,500-999,0 +05,E12000009,1000-4999,0 +05,E12000009,5000+,0 +05,W92000004,0-49,0 +05,W92000004,50-99,0 +05,W92000004,100-249,0 +05,W92000004,250-499,0 +05,W92000004,500-999,0 +05,W92000004,1000-4999,0 +05,W92000004,5000+,0 +05,S92000003,0-49,0 +05,S92000003,50-99,0 +05,S92000003,100-249,0 +05,S92000003,250-499,0 +05,S92000003,500-999,0 +05,S92000003,1000-4999,0 +05,S92000003,5000+,0 +05,N92000002,0-49,0 +05,N92000002,50-99,0 +05,N92000002,100-249,0 +05,N92000002,250-499,0 +05,N92000002,500-999,0 +05,N92000002,1000-4999,0 +05,N92000002,5000+,0 +06,E12000001,0-49,5 +06,E12000001,50-99,0 +06,E12000001,100-249,5 +06,E12000001,250-499,0 +06,E12000001,500-999,0 +06,E12000001,1000-4999,0 +06,E12000001,5000+,5 +06,E12000002,0-49,0 +06,E12000002,50-99,0 +06,E12000002,100-249,0 +06,E12000002,250-499,0 +06,E12000002,500-999,0 +06,E12000002,1000-4999,0 +06,E12000002,5000+,0 +06,E12000003,0-49,5 +06,E12000003,50-99,0 +06,E12000003,100-249,5 +06,E12000003,250-499,0 +06,E12000003,500-999,0 +06,E12000003,1000-4999,0 +06,E12000003,5000+,5 +06,E12000004,0-49,0 +06,E12000004,50-99,0 +06,E12000004,100-249,0 +06,E12000004,250-499,0 +06,E12000004,500-999,5 +06,E12000004,1000-4999,0 +06,E12000004,5000+,0 +06,E12000005,0-49,0 +06,E12000005,50-99,0 +06,E12000005,100-249,0 +06,E12000005,250-499,0 +06,E12000005,500-999,0 +06,E12000005,1000-4999,0 +06,E12000005,5000+,0 +06,E12000006,0-49,0 +06,E12000006,50-99,0 +06,E12000006,100-249,0 +06,E12000006,250-499,5 +06,E12000006,500-999,0 +06,E12000006,1000-4999,0 +06,E12000006,5000+,0 +06,E12000007,0-49,5 +06,E12000007,50-99,5 +06,E12000007,100-249,5 +06,E12000007,250-499,5 +06,E12000007,500-999,0 +06,E12000007,1000-4999,5 +06,E12000007,5000+,20 +06,E12000008,0-49,0 +06,E12000008,50-99,0 +06,E12000008,100-249,0 +06,E12000008,250-499,0 +06,E12000008,500-999,0 +06,E12000008,1000-4999,0 +06,E12000008,5000+,0 +06,E12000009,0-49,0 +06,E12000009,50-99,0 +06,E12000009,100-249,0 +06,E12000009,250-499,0 +06,E12000009,500-999,0 +06,E12000009,1000-4999,0 +06,E12000009,5000+,0 +06,W92000004,0-49,0 +06,W92000004,50-99,0 +06,W92000004,100-249,0 +06,W92000004,250-499,0 +06,W92000004,500-999,0 +06,W92000004,1000-4999,0 +06,W92000004,5000+,0 +06,S92000003,0-49,5 +06,S92000003,50-99,5 +06,S92000003,100-249,5 +06,S92000003,250-499,0 +06,S92000003,500-999,0 +06,S92000003,1000-4999,5 +06,S92000003,5000+,10 +06,N92000002,0-49,0 +06,N92000002,50-99,0 +06,N92000002,100-249,0 +06,N92000002,250-499,0 +06,N92000002,500-999,0 +06,N92000002,1000-4999,0 +06,N92000002,5000+,0 +07,E12000001,0-49,0 +07,E12000001,50-99,0 +07,E12000001,100-249,0 +07,E12000001,250-499,0 +07,E12000001,500-999,0 +07,E12000001,1000-4999,0 +07,E12000001,5000+,0 +07,E12000002,0-49,0 +07,E12000002,50-99,0 +07,E12000002,100-249,0 +07,E12000002,250-499,0 +07,E12000002,500-999,0 +07,E12000002,1000-4999,0 +07,E12000002,5000+,0 +07,E12000003,0-49,0 +07,E12000003,50-99,0 +07,E12000003,100-249,0 +07,E12000003,250-499,0 +07,E12000003,500-999,0 +07,E12000003,1000-4999,0 +07,E12000003,5000+,0 +07,E12000004,0-49,0 +07,E12000004,50-99,0 +07,E12000004,100-249,0 +07,E12000004,250-499,0 +07,E12000004,500-999,0 +07,E12000004,1000-4999,0 +07,E12000004,5000+,0 +07,E12000005,0-49,0 +07,E12000005,50-99,0 +07,E12000005,100-249,0 +07,E12000005,250-499,0 +07,E12000005,500-999,0 +07,E12000005,1000-4999,0 +07,E12000005,5000+,0 +07,E12000006,0-49,0 +07,E12000006,50-99,0 +07,E12000006,100-249,0 +07,E12000006,250-499,0 +07,E12000006,500-999,0 +07,E12000006,1000-4999,0 +07,E12000006,5000+,0 +07,E12000007,0-49,0 +07,E12000007,50-99,0 +07,E12000007,100-249,0 +07,E12000007,250-499,0 +07,E12000007,500-999,0 +07,E12000007,1000-4999,0 +07,E12000007,5000+,0 +07,E12000008,0-49,0 +07,E12000008,50-99,0 +07,E12000008,100-249,0 +07,E12000008,250-499,0 +07,E12000008,500-999,0 +07,E12000008,1000-4999,0 +07,E12000008,5000+,0 +07,E12000009,0-49,0 +07,E12000009,50-99,0 +07,E12000009,100-249,0 +07,E12000009,250-499,0 +07,E12000009,500-999,0 +07,E12000009,1000-4999,0 +07,E12000009,5000+,0 +07,W92000004,0-49,0 +07,W92000004,50-99,0 +07,W92000004,100-249,0 +07,W92000004,250-499,0 +07,W92000004,500-999,0 +07,W92000004,1000-4999,0 +07,W92000004,5000+,0 +07,S92000003,0-49,0 +07,S92000003,50-99,0 +07,S92000003,100-249,0 +07,S92000003,250-499,0 +07,S92000003,500-999,0 +07,S92000003,1000-4999,0 +07,S92000003,5000+,0 +07,N92000002,0-49,0 +07,N92000002,50-99,0 +07,N92000002,100-249,0 +07,N92000002,250-499,0 +07,N92000002,500-999,0 +07,N92000002,1000-4999,0 +07,N92000002,5000+,0 +08,E12000001,0-49,0 +08,E12000001,50-99,0 +08,E12000001,100-249,0 +08,E12000001,250-499,0 +08,E12000001,500-999,5 +08,E12000001,1000-4999,5 +08,E12000001,5000+,5 +08,E12000002,0-49,5 +08,E12000002,50-99,0 +08,E12000002,100-249,10 +08,E12000002,250-499,0 +08,E12000002,500-999,5 +08,E12000002,1000-4999,5 +08,E12000002,5000+,10 +08,E12000003,0-49,5 +08,E12000003,50-99,10 +08,E12000003,100-249,10 +08,E12000003,250-499,15 +08,E12000003,500-999,10 +08,E12000003,1000-4999,10 +08,E12000003,5000+,10 +08,E12000004,0-49,5 +08,E12000004,50-99,5 +08,E12000004,100-249,10 +08,E12000004,250-499,10 +08,E12000004,500-999,5 +08,E12000004,1000-4999,10 +08,E12000004,5000+,10 +08,E12000005,0-49,0 +08,E12000005,50-99,0 +08,E12000005,100-249,5 +08,E12000005,250-499,5 +08,E12000005,500-999,0 +08,E12000005,1000-4999,15 +08,E12000005,5000+,10 +08,E12000006,0-49,10 +08,E12000006,50-99,5 +08,E12000006,100-249,10 +08,E12000006,250-499,0 +08,E12000006,500-999,5 +08,E12000006,1000-4999,15 +08,E12000006,5000+,10 +08,E12000007,0-49,20 +08,E12000007,50-99,10 +08,E12000007,100-249,20 +08,E12000007,250-499,10 +08,E12000007,500-999,5 +08,E12000007,1000-4999,10 +08,E12000007,5000+,0 +08,E12000008,0-49,10 +08,E12000008,50-99,5 +08,E12000008,100-249,15 +08,E12000008,250-499,10 +08,E12000008,500-999,5 +08,E12000008,1000-4999,15 +08,E12000008,5000+,15 +08,E12000009,0-49,5 +08,E12000009,50-99,5 +08,E12000009,100-249,15 +08,E12000009,250-499,10 +08,E12000009,500-999,10 +08,E12000009,1000-4999,15 +08,E12000009,5000+,10 +08,W92000004,0-49,10 +08,W92000004,50-99,5 +08,W92000004,100-249,10 +08,W92000004,250-499,10 +08,W92000004,500-999,5 +08,W92000004,1000-4999,15 +08,W92000004,5000+,5 +08,S92000003,0-49,10 +08,S92000003,50-99,0 +08,S92000003,100-249,10 +08,S92000003,250-499,5 +08,S92000003,500-999,10 +08,S92000003,1000-4999,15 +08,S92000003,5000+,10 +08,N92000002,0-49,5 +08,N92000002,50-99,10 +08,N92000002,100-249,10 +08,N92000002,250-499,10 +08,N92000002,500-999,10 +08,N92000002,1000-4999,20 +08,N92000002,5000+,15 +09,E12000001,0-49,0 +09,E12000001,50-99,0 +09,E12000001,100-249,10 +09,E12000001,250-499,0 +09,E12000001,500-999,0 +09,E12000001,1000-4999,0 +09,E12000001,5000+,0 +09,E12000002,0-49,5 +09,E12000002,50-99,5 +09,E12000002,100-249,5 +09,E12000002,250-499,0 +09,E12000002,500-999,0 +09,E12000002,1000-4999,0 +09,E12000002,5000+,5 +09,E12000003,0-49,5 +09,E12000003,50-99,5 +09,E12000003,100-249,10 +09,E12000003,250-499,5 +09,E12000003,500-999,0 +09,E12000003,1000-4999,5 +09,E12000003,5000+,0 +09,E12000004,0-49,5 +09,E12000004,50-99,5 +09,E12000004,100-249,10 +09,E12000004,250-499,0 +09,E12000004,500-999,5 +09,E12000004,1000-4999,5 +09,E12000004,5000+,5 +09,E12000005,0-49,0 +09,E12000005,50-99,0 +09,E12000005,100-249,10 +09,E12000005,250-499,0 +09,E12000005,500-999,0 +09,E12000005,1000-4999,0 +09,E12000005,5000+,0 +09,E12000006,0-49,10 +09,E12000006,50-99,0 +09,E12000006,100-249,10 +09,E12000006,250-499,5 +09,E12000006,500-999,0 +09,E12000006,1000-4999,0 +09,E12000006,5000+,5 +09,E12000007,0-49,15 +09,E12000007,50-99,5 +09,E12000007,100-249,25 +09,E12000007,250-499,5 +09,E12000007,500-999,10 +09,E12000007,1000-4999,10 +09,E12000007,5000+,15 +09,E12000008,0-49,0 +09,E12000008,50-99,5 +09,E12000008,100-249,10 +09,E12000008,250-499,0 +09,E12000008,500-999,0 +09,E12000008,1000-4999,5 +09,E12000008,5000+,5 +09,E12000009,0-49,5 +09,E12000009,50-99,0 +09,E12000009,100-249,15 +09,E12000009,250-499,5 +09,E12000009,500-999,0 +09,E12000009,1000-4999,5 +09,E12000009,5000+,5 +09,W92000004,0-49,0 +09,W92000004,50-99,0 +09,W92000004,100-249,5 +09,W92000004,250-499,0 +09,W92000004,500-999,0 +09,W92000004,1000-4999,0 +09,W92000004,5000+,0 +09,S92000003,0-49,5 +09,S92000003,50-99,0 +09,S92000003,100-249,10 +09,S92000003,250-499,5 +09,S92000003,500-999,0 +09,S92000003,1000-4999,10 +09,S92000003,5000+,35 +09,N92000002,0-49,5 +09,N92000002,50-99,0 +09,N92000002,100-249,0 +09,N92000002,250-499,0 +09,N92000002,500-999,0 +09,N92000002,1000-4999,0 +09,N92000002,5000+,0 +10,E12000001,0-49,25 +10,E12000001,50-99,30 +10,E12000001,100-249,55 +10,E12000001,250-499,30 +10,E12000001,500-999,20 +10,E12000001,1000-4999,45 +10,E12000001,5000+,25 +10,E12000002,0-49,130 +10,E12000002,50-99,125 +10,E12000002,100-249,240 +10,E12000002,250-499,135 +10,E12000002,500-999,100 +10,E12000002,1000-4999,130 +10,E12000002,5000+,145 +10,E12000003,0-49,100 +10,E12000003,50-99,90 +10,E12000003,100-249,185 +10,E12000003,250-499,90 +10,E12000003,500-999,60 +10,E12000003,1000-4999,105 +10,E12000003,5000+,160 +10,E12000004,0-49,100 +10,E12000004,50-99,70 +10,E12000004,100-249,130 +10,E12000004,250-499,70 +10,E12000004,500-999,65 +10,E12000004,1000-4999,85 +10,E12000004,5000+,90 +10,E12000005,0-49,110 +10,E12000005,50-99,105 +10,E12000005,100-249,160 +10,E12000005,250-499,110 +10,E12000005,500-999,65 +10,E12000005,1000-4999,105 +10,E12000005,5000+,115 +10,E12000006,0-49,130 +10,E12000006,50-99,110 +10,E12000006,100-249,165 +10,E12000006,250-499,105 +10,E12000006,500-999,80 +10,E12000006,1000-4999,90 +10,E12000006,5000+,110 +10,E12000007,0-49,310 +10,E12000007,50-99,245 +10,E12000007,100-249,410 +10,E12000007,250-499,215 +10,E12000007,500-999,175 +10,E12000007,1000-4999,190 +10,E12000007,5000+,115 +10,E12000008,0-49,200 +10,E12000008,50-99,125 +10,E12000008,100-249,240 +10,E12000008,250-499,135 +10,E12000008,500-999,90 +10,E12000008,1000-4999,110 +10,E12000008,5000+,95 +10,E12000009,0-49,135 +10,E12000009,50-99,120 +10,E12000009,100-249,215 +10,E12000009,250-499,105 +10,E12000009,500-999,80 +10,E12000009,1000-4999,120 +10,E12000009,5000+,85 +10,W92000004,0-49,75 +10,W92000004,50-99,55 +10,W92000004,100-249,90 +10,W92000004,250-499,55 +10,W92000004,500-999,30 +10,W92000004,1000-4999,45 +10,W92000004,5000+,60 +10,S92000003,0-49,100 +10,S92000003,50-99,95 +10,S92000003,100-249,195 +10,S92000003,250-499,105 +10,S92000003,500-999,80 +10,S92000003,1000-4999,125 +10,S92000003,5000+,120 +10,N92000002,0-49,60 +10,N92000002,50-99,45 +10,N92000002,100-249,95 +10,N92000002,250-499,65 +10,N92000002,500-999,45 +10,N92000002,1000-4999,85 +10,N92000002,5000+,100 +11,E12000001,0-49,25 +11,E12000001,50-99,10 +11,E12000001,100-249,20 +11,E12000001,250-499,10 +11,E12000001,500-999,5 +11,E12000001,1000-4999,10 +11,E12000001,5000+,5 +11,E12000002,0-49,55 +11,E12000002,50-99,35 +11,E12000002,100-249,55 +11,E12000002,250-499,35 +11,E12000002,500-999,25 +11,E12000002,1000-4999,20 +11,E12000002,5000+,5 +11,E12000003,0-49,40 +11,E12000003,50-99,20 +11,E12000003,100-249,50 +11,E12000003,250-499,25 +11,E12000003,500-999,25 +11,E12000003,1000-4999,20 +11,E12000003,5000+,10 +11,E12000004,0-49,30 +11,E12000004,50-99,25 +11,E12000004,100-249,40 +11,E12000004,250-499,25 +11,E12000004,500-999,15 +11,E12000004,1000-4999,10 +11,E12000004,5000+,10 +11,E12000005,0-49,40 +11,E12000005,50-99,25 +11,E12000005,100-249,65 +11,E12000005,250-499,15 +11,E12000005,500-999,20 +11,E12000005,1000-4999,15 +11,E12000005,5000+,15 +11,E12000006,0-49,45 +11,E12000006,50-99,25 +11,E12000006,100-249,55 +11,E12000006,250-499,30 +11,E12000006,500-999,15 +11,E12000006,1000-4999,20 +11,E12000006,5000+,10 +11,E12000007,0-49,95 +11,E12000007,50-99,55 +11,E12000007,100-249,65 +11,E12000007,250-499,30 +11,E12000007,500-999,35 +11,E12000007,1000-4999,40 +11,E12000007,5000+,15 +11,E12000008,0-49,95 +11,E12000008,50-99,50 +11,E12000008,100-249,85 +11,E12000008,250-499,45 +11,E12000008,500-999,50 +11,E12000008,1000-4999,45 +11,E12000008,5000+,15 +11,E12000009,0-49,70 +11,E12000009,50-99,60 +11,E12000009,100-249,75 +11,E12000009,250-499,40 +11,E12000009,500-999,35 +11,E12000009,1000-4999,30 +11,E12000009,5000+,15 +11,W92000004,0-49,30 +11,W92000004,50-99,30 +11,W92000004,100-249,30 +11,W92000004,250-499,15 +11,W92000004,500-999,10 +11,W92000004,1000-4999,10 +11,W92000004,5000+,10 +11,S92000003,0-49,85 +11,S92000003,50-99,65 +11,S92000003,100-249,80 +11,S92000003,250-499,40 +11,S92000003,500-999,30 +11,S92000003,1000-4999,50 +11,S92000003,5000+,40 +11,N92000002,0-49,20 +11,N92000002,50-99,5 +11,N92000002,100-249,20 +11,N92000002,250-499,5 +11,N92000002,500-999,5 +11,N92000002,1000-4999,5 +11,N92000002,5000+,5 +12,E12000001,0-49,0 +12,E12000001,50-99,0 +12,E12000001,100-249,0 +12,E12000001,250-499,0 +12,E12000001,500-999,0 +12,E12000001,1000-4999,0 +12,E12000001,5000+,0 +12,E12000002,0-49,0 +12,E12000002,50-99,0 +12,E12000002,100-249,0 +12,E12000002,250-499,0 +12,E12000002,500-999,0 +12,E12000002,1000-4999,0 +12,E12000002,5000+,0 +12,E12000003,0-49,0 +12,E12000003,50-99,0 +12,E12000003,100-249,0 +12,E12000003,250-499,0 +12,E12000003,500-999,0 +12,E12000003,1000-4999,0 +12,E12000003,5000+,0 +12,E12000004,0-49,0 +12,E12000004,50-99,0 +12,E12000004,100-249,0 +12,E12000004,250-499,0 +12,E12000004,500-999,0 +12,E12000004,1000-4999,0 +12,E12000004,5000+,0 +12,E12000005,0-49,0 +12,E12000005,50-99,0 +12,E12000005,100-249,0 +12,E12000005,250-499,0 +12,E12000005,500-999,0 +12,E12000005,1000-4999,0 +12,E12000005,5000+,0 +12,E12000006,0-49,0 +12,E12000006,50-99,0 +12,E12000006,100-249,0 +12,E12000006,250-499,0 +12,E12000006,500-999,0 +12,E12000006,1000-4999,0 +12,E12000006,5000+,0 +12,E12000007,0-49,0 +12,E12000007,50-99,0 +12,E12000007,100-249,0 +12,E12000007,250-499,0 +12,E12000007,500-999,0 +12,E12000007,1000-4999,0 +12,E12000007,5000+,0 +12,E12000008,0-49,0 +12,E12000008,50-99,0 +12,E12000008,100-249,0 +12,E12000008,250-499,0 +12,E12000008,500-999,0 +12,E12000008,1000-4999,0 +12,E12000008,5000+,0 +12,E12000009,0-49,0 +12,E12000009,50-99,0 +12,E12000009,100-249,0 +12,E12000009,250-499,0 +12,E12000009,500-999,0 +12,E12000009,1000-4999,0 +12,E12000009,5000+,0 +12,W92000004,0-49,0 +12,W92000004,50-99,0 +12,W92000004,100-249,0 +12,W92000004,250-499,0 +12,W92000004,500-999,0 +12,W92000004,1000-4999,0 +12,W92000004,5000+,0 +12,S92000003,0-49,0 +12,S92000003,50-99,0 +12,S92000003,100-249,0 +12,S92000003,250-499,0 +12,S92000003,500-999,0 +12,S92000003,1000-4999,0 +12,S92000003,5000+,0 +12,N92000002,0-49,0 +12,N92000002,50-99,0 +12,N92000002,100-249,0 +12,N92000002,250-499,0 +12,N92000002,500-999,0 +12,N92000002,1000-4999,0 +12,N92000002,5000+,0 +13,E12000001,0-49,10 +13,E12000001,50-99,15 +13,E12000001,100-249,30 +13,E12000001,250-499,15 +13,E12000001,500-999,15 +13,E12000001,1000-4999,15 +13,E12000001,5000+,5 +13,E12000002,0-49,50 +13,E12000002,50-99,85 +13,E12000002,100-249,125 +13,E12000002,250-499,85 +13,E12000002,500-999,55 +13,E12000002,1000-4999,90 +13,E12000002,5000+,45 +13,E12000003,0-49,40 +13,E12000003,50-99,75 +13,E12000003,100-249,105 +13,E12000003,250-499,70 +13,E12000003,500-999,55 +13,E12000003,1000-4999,70 +13,E12000003,5000+,55 +13,E12000004,0-49,55 +13,E12000004,50-99,70 +13,E12000004,100-249,140 +13,E12000004,250-499,60 +13,E12000004,500-999,55 +13,E12000004,1000-4999,75 +13,E12000004,5000+,30 +13,E12000005,0-49,40 +13,E12000005,50-99,60 +13,E12000005,100-249,105 +13,E12000005,250-499,50 +13,E12000005,500-999,25 +13,E12000005,1000-4999,35 +13,E12000005,5000+,15 +13,E12000006,0-49,45 +13,E12000006,50-99,80 +13,E12000006,100-249,115 +13,E12000006,250-499,45 +13,E12000006,500-999,40 +13,E12000006,1000-4999,35 +13,E12000006,5000+,5 +13,E12000007,0-49,70 +13,E12000007,50-99,140 +13,E12000007,100-249,165 +13,E12000007,250-499,65 +13,E12000007,500-999,45 +13,E12000007,1000-4999,40 +13,E12000007,5000+,5 +13,E12000008,0-49,60 +13,E12000008,50-99,115 +13,E12000008,100-249,160 +13,E12000008,250-499,65 +13,E12000008,500-999,25 +13,E12000008,1000-4999,45 +13,E12000008,5000+,15 +13,E12000009,0-49,30 +13,E12000009,50-99,65 +13,E12000009,100-249,100 +13,E12000009,250-499,50 +13,E12000009,500-999,40 +13,E12000009,1000-4999,35 +13,E12000009,5000+,10 +13,W92000004,0-49,10 +13,W92000004,50-99,30 +13,W92000004,100-249,60 +13,W92000004,250-499,35 +13,W92000004,500-999,15 +13,W92000004,1000-4999,15 +13,W92000004,5000+,5 +13,S92000003,0-49,45 +13,S92000003,50-99,45 +13,S92000003,100-249,95 +13,S92000003,250-499,40 +13,S92000003,500-999,25 +13,S92000003,1000-4999,40 +13,S92000003,5000+,15 +13,N92000002,0-49,15 +13,N92000002,50-99,30 +13,N92000002,100-249,50 +13,N92000002,250-499,20 +13,N92000002,500-999,20 +13,N92000002,1000-4999,15 +13,N92000002,5000+,10 +14,E12000001,0-49,15 +14,E12000001,50-99,10 +14,E12000001,100-249,30 +14,E12000001,250-499,10 +14,E12000001,500-999,5 +14,E12000001,1000-4999,0 +14,E12000001,5000+,0 +14,E12000002,0-49,40 +14,E12000002,50-99,60 +14,E12000002,100-249,135 +14,E12000002,250-499,55 +14,E12000002,500-999,35 +14,E12000002,1000-4999,25 +14,E12000002,5000+,10 +14,E12000003,0-49,30 +14,E12000003,50-99,35 +14,E12000003,100-249,85 +14,E12000003,250-499,25 +14,E12000003,500-999,20 +14,E12000003,1000-4999,5 +14,E12000003,5000+,5 +14,E12000004,0-49,60 +14,E12000004,50-99,60 +14,E12000004,100-249,145 +14,E12000004,250-499,55 +14,E12000004,500-999,45 +14,E12000004,1000-4999,55 +14,E12000004,5000+,15 +14,E12000005,0-49,35 +14,E12000005,50-99,40 +14,E12000005,100-249,105 +14,E12000005,250-499,35 +14,E12000005,500-999,15 +14,E12000005,1000-4999,15 +14,E12000005,5000+,0 +14,E12000006,0-49,40 +14,E12000006,50-99,55 +14,E12000006,100-249,75 +14,E12000006,250-499,25 +14,E12000006,500-999,15 +14,E12000006,1000-4999,20 +14,E12000006,5000+,5 +14,E12000007,0-49,185 +14,E12000007,50-99,245 +14,E12000007,100-249,395 +14,E12000007,250-499,125 +14,E12000007,500-999,75 +14,E12000007,1000-4999,60 +14,E12000007,5000+,25 +14,E12000008,0-49,60 +14,E12000008,50-99,75 +14,E12000008,100-249,155 +14,E12000008,250-499,25 +14,E12000008,500-999,15 +14,E12000008,1000-4999,15 +14,E12000008,5000+,0 +14,E12000009,0-49,30 +14,E12000009,50-99,40 +14,E12000009,100-249,70 +14,E12000009,250-499,25 +14,E12000009,500-999,10 +14,E12000009,1000-4999,15 +14,E12000009,5000+,5 +14,W92000004,0-49,25 +14,W92000004,50-99,20 +14,W92000004,100-249,30 +14,W92000004,250-499,5 +14,W92000004,500-999,5 +14,W92000004,1000-4999,5 +14,W92000004,5000+,0 +14,S92000003,0-49,20 +14,S92000003,50-99,30 +14,S92000003,100-249,65 +14,S92000003,250-499,15 +14,S92000003,500-999,15 +14,S92000003,1000-4999,20 +14,S92000003,5000+,5 +14,N92000002,0-49,10 +14,N92000002,50-99,5 +14,N92000002,100-249,20 +14,N92000002,250-499,5 +14,N92000002,500-999,5 +14,N92000002,1000-4999,5 +14,N92000002,5000+,5 +15,E12000001,0-49,5 +15,E12000001,50-99,0 +15,E12000001,100-249,5 +15,E12000001,250-499,0 +15,E12000001,500-999,0 +15,E12000001,1000-4999,0 +15,E12000001,5000+,0 +15,E12000002,0-49,10 +15,E12000002,50-99,5 +15,E12000002,100-249,10 +15,E12000002,250-499,10 +15,E12000002,500-999,0 +15,E12000002,1000-4999,5 +15,E12000002,5000+,0 +15,E12000003,0-49,5 +15,E12000003,50-99,10 +15,E12000003,100-249,10 +15,E12000003,250-499,5 +15,E12000003,500-999,0 +15,E12000003,1000-4999,0 +15,E12000003,5000+,5 +15,E12000004,0-49,10 +15,E12000004,50-99,15 +15,E12000004,100-249,10 +15,E12000004,250-499,5 +15,E12000004,500-999,5 +15,E12000004,1000-4999,10 +15,E12000004,5000+,10 +15,E12000005,0-49,10 +15,E12000005,50-99,15 +15,E12000005,100-249,25 +15,E12000005,250-499,10 +15,E12000005,500-999,10 +15,E12000005,1000-4999,10 +15,E12000005,5000+,0 +15,E12000006,0-49,10 +15,E12000006,50-99,10 +15,E12000006,100-249,10 +15,E12000006,250-499,5 +15,E12000006,500-999,5 +15,E12000006,1000-4999,5 +15,E12000006,5000+,5 +15,E12000007,0-49,25 +15,E12000007,50-99,30 +15,E12000007,100-249,30 +15,E12000007,250-499,10 +15,E12000007,500-999,5 +15,E12000007,1000-4999,10 +15,E12000007,5000+,5 +15,E12000008,0-49,15 +15,E12000008,50-99,15 +15,E12000008,100-249,5 +15,E12000008,250-499,5 +15,E12000008,500-999,10 +15,E12000008,1000-4999,10 +15,E12000008,5000+,0 +15,E12000009,0-49,5 +15,E12000009,50-99,10 +15,E12000009,100-249,10 +15,E12000009,250-499,10 +15,E12000009,500-999,0 +15,E12000009,1000-4999,5 +15,E12000009,5000+,5 +15,W92000004,0-49,5 +15,W92000004,50-99,5 +15,W92000004,100-249,10 +15,W92000004,250-499,0 +15,W92000004,500-999,0 +15,W92000004,1000-4999,0 +15,W92000004,5000+,0 +15,S92000003,0-49,5 +15,S92000003,50-99,5 +15,S92000003,100-249,5 +15,S92000003,250-499,0 +15,S92000003,500-999,5 +15,S92000003,1000-4999,5 +15,S92000003,5000+,0 +15,N92000002,0-49,0 +15,N92000002,50-99,0 +15,N92000002,100-249,0 +15,N92000002,250-499,0 +15,N92000002,500-999,0 +15,N92000002,1000-4999,0 +15,N92000002,5000+,0 +16,E12000001,0-49,10 +16,E12000001,50-99,80 +16,E12000001,100-249,120 +16,E12000001,250-499,30 +16,E12000001,500-999,30 +16,E12000001,1000-4999,45 +16,E12000001,5000+,15 +16,E12000002,0-49,45 +16,E12000002,50-99,330 +16,E12000002,100-249,385 +16,E12000002,250-499,110 +16,E12000002,500-999,90 +16,E12000002,1000-4999,105 +16,E12000002,5000+,25 +16,E12000003,0-49,50 +16,E12000003,50-99,265 +16,E12000003,100-249,335 +16,E12000003,250-499,110 +16,E12000003,500-999,85 +16,E12000003,1000-4999,85 +16,E12000003,5000+,55 +16,E12000004,0-49,65 +16,E12000004,50-99,195 +16,E12000004,100-249,265 +16,E12000004,250-499,90 +16,E12000004,500-999,75 +16,E12000004,1000-4999,85 +16,E12000004,5000+,45 +16,E12000005,0-49,60 +16,E12000005,50-99,190 +16,E12000005,100-249,250 +16,E12000005,250-499,110 +16,E12000005,500-999,95 +16,E12000005,1000-4999,110 +16,E12000005,5000+,50 +16,E12000006,0-49,90 +16,E12000006,50-99,225 +16,E12000006,100-249,330 +16,E12000006,250-499,150 +16,E12000006,500-999,110 +16,E12000006,1000-4999,105 +16,E12000006,5000+,35 +16,E12000007,0-49,55 +16,E12000007,50-99,210 +16,E12000007,100-249,260 +16,E12000007,250-499,105 +16,E12000007,500-999,65 +16,E12000007,1000-4999,50 +16,E12000007,5000+,10 +16,E12000008,0-49,105 +16,E12000008,50-99,330 +16,E12000008,100-249,480 +16,E12000008,250-499,215 +16,E12000008,500-999,125 +16,E12000008,1000-4999,135 +16,E12000008,5000+,30 +16,E12000009,0-49,90 +16,E12000009,50-99,215 +16,E12000009,100-249,370 +16,E12000009,250-499,165 +16,E12000009,500-999,120 +16,E12000009,1000-4999,105 +16,E12000009,5000+,20 +16,W92000004,0-49,40 +16,W92000004,50-99,100 +16,W92000004,100-249,160 +16,W92000004,250-499,65 +16,W92000004,500-999,45 +16,W92000004,1000-4999,40 +16,W92000004,5000+,15 +16,S92000003,0-49,55 +16,S92000003,50-99,300 +16,S92000003,100-249,470 +16,S92000003,250-499,105 +16,S92000003,500-999,75 +16,S92000003,1000-4999,100 +16,S92000003,5000+,45 +16,N92000002,0-49,50 +16,N92000002,50-99,50 +16,N92000002,100-249,90 +16,N92000002,250-499,50 +16,N92000002,500-999,35 +16,N92000002,1000-4999,65 +16,N92000002,5000+,15 +17,E12000001,0-49,0 +17,E12000001,50-99,5 +17,E12000001,100-249,5 +17,E12000001,250-499,0 +17,E12000001,500-999,5 +17,E12000001,1000-4999,5 +17,E12000001,5000+,10 +17,E12000002,0-49,15 +17,E12000002,50-99,10 +17,E12000002,100-249,25 +17,E12000002,250-499,15 +17,E12000002,500-999,20 +17,E12000002,1000-4999,40 +17,E12000002,5000+,65 +17,E12000003,0-49,15 +17,E12000003,50-99,20 +17,E12000003,100-249,20 +17,E12000003,250-499,10 +17,E12000003,500-999,10 +17,E12000003,1000-4999,25 +17,E12000003,5000+,35 +17,E12000004,0-49,15 +17,E12000004,50-99,15 +17,E12000004,100-249,20 +17,E12000004,250-499,5 +17,E12000004,500-999,10 +17,E12000004,1000-4999,40 +17,E12000004,5000+,35 +17,E12000005,0-49,15 +17,E12000005,50-99,20 +17,E12000005,100-249,20 +17,E12000005,250-499,15 +17,E12000005,500-999,15 +17,E12000005,1000-4999,30 +17,E12000005,5000+,30 +17,E12000006,0-49,20 +17,E12000006,50-99,20 +17,E12000006,100-249,25 +17,E12000006,250-499,15 +17,E12000006,500-999,15 +17,E12000006,1000-4999,25 +17,E12000006,5000+,35 +17,E12000007,0-49,25 +17,E12000007,50-99,30 +17,E12000007,100-249,40 +17,E12000007,250-499,15 +17,E12000007,500-999,10 +17,E12000007,1000-4999,20 +17,E12000007,5000+,10 +17,E12000008,0-49,25 +17,E12000008,50-99,20 +17,E12000008,100-249,20 +17,E12000008,250-499,20 +17,E12000008,500-999,15 +17,E12000008,1000-4999,30 +17,E12000008,5000+,30 +17,E12000009,0-49,15 +17,E12000009,50-99,15 +17,E12000009,100-249,25 +17,E12000009,250-499,10 +17,E12000009,500-999,5 +17,E12000009,1000-4999,15 +17,E12000009,5000+,20 +17,W92000004,0-49,5 +17,W92000004,50-99,5 +17,W92000004,100-249,0 +17,W92000004,250-499,5 +17,W92000004,500-999,0 +17,W92000004,1000-4999,10 +17,W92000004,5000+,15 +17,S92000003,0-49,5 +17,S92000003,50-99,5 +17,S92000003,100-249,15 +17,S92000003,250-499,5 +17,S92000003,500-999,5 +17,S92000003,1000-4999,10 +17,S92000003,5000+,15 +17,N92000002,0-49,5 +17,N92000002,50-99,5 +17,N92000002,100-249,5 +17,N92000002,250-499,0 +17,N92000002,500-999,5 +17,N92000002,1000-4999,10 +17,N92000002,5000+,15 +18,E12000001,0-49,40 +18,E12000001,50-99,45 +18,E12000001,100-249,75 +18,E12000001,250-499,35 +18,E12000001,500-999,20 +18,E12000001,1000-4999,25 +18,E12000001,5000+,15 +18,E12000002,0-49,150 +18,E12000002,50-99,210 +18,E12000002,100-249,265 +18,E12000002,250-499,120 +18,E12000002,500-999,85 +18,E12000002,1000-4999,90 +18,E12000002,5000+,25 +18,E12000003,0-49,115 +18,E12000003,50-99,160 +18,E12000003,100-249,215 +18,E12000003,250-499,90 +18,E12000003,500-999,70 +18,E12000003,1000-4999,85 +18,E12000003,5000+,40 +18,E12000004,0-49,135 +18,E12000004,50-99,145 +18,E12000004,100-249,200 +18,E12000004,250-499,115 +18,E12000004,500-999,75 +18,E12000004,1000-4999,100 +18,E12000004,5000+,30 +18,E12000005,0-49,125 +18,E12000005,50-99,165 +18,E12000005,100-249,235 +18,E12000005,250-499,125 +18,E12000005,500-999,65 +18,E12000005,1000-4999,60 +18,E12000005,5000+,15 +18,E12000006,0-49,205 +18,E12000006,50-99,230 +18,E12000006,100-249,315 +18,E12000006,250-499,155 +18,E12000006,500-999,85 +18,E12000006,1000-4999,120 +18,E12000006,5000+,40 +18,E12000007,0-49,275 +18,E12000007,50-99,355 +18,E12000007,100-249,435 +18,E12000007,250-499,145 +18,E12000007,500-999,125 +18,E12000007,1000-4999,105 +18,E12000007,5000+,35 +18,E12000008,0-49,265 +18,E12000008,50-99,285 +18,E12000008,100-249,415 +18,E12000008,250-499,215 +18,E12000008,500-999,140 +18,E12000008,1000-4999,155 +18,E12000008,5000+,45 +18,E12000009,0-49,155 +18,E12000009,50-99,180 +18,E12000009,100-249,255 +18,E12000009,250-499,120 +18,E12000009,500-999,60 +18,E12000009,1000-4999,85 +18,E12000009,5000+,20 +18,W92000004,0-49,70 +18,W92000004,50-99,65 +18,W92000004,100-249,85 +18,W92000004,250-499,50 +18,W92000004,500-999,30 +18,W92000004,1000-4999,25 +18,W92000004,5000+,10 +18,S92000003,0-49,65 +18,S92000003,50-99,100 +18,S92000003,100-249,130 +18,S92000003,250-499,60 +18,S92000003,500-999,35 +18,S92000003,1000-4999,30 +18,S92000003,5000+,10 +18,N92000002,0-49,20 +18,N92000002,50-99,40 +18,N92000002,100-249,60 +18,N92000002,250-499,25 +18,N92000002,500-999,15 +18,N92000002,1000-4999,20 +18,N92000002,5000+,5 +19,E12000001,0-49,0 +19,E12000001,50-99,0 +19,E12000001,100-249,0 +19,E12000001,250-499,0 +19,E12000001,500-999,0 +19,E12000001,1000-4999,0 +19,E12000001,5000+,5 +19,E12000002,0-49,5 +19,E12000002,50-99,0 +19,E12000002,100-249,0 +19,E12000002,250-499,0 +19,E12000002,500-999,5 +19,E12000002,1000-4999,0 +19,E12000002,5000+,10 +19,E12000003,0-49,0 +19,E12000003,50-99,0 +19,E12000003,100-249,0 +19,E12000003,250-499,0 +19,E12000003,500-999,0 +19,E12000003,1000-4999,0 +19,E12000003,5000+,5 +19,E12000004,0-49,0 +19,E12000004,50-99,0 +19,E12000004,100-249,0 +19,E12000004,250-499,0 +19,E12000004,500-999,0 +19,E12000004,1000-4999,0 +19,E12000004,5000+,5 +19,E12000005,0-49,0 +19,E12000005,50-99,0 +19,E12000005,100-249,0 +19,E12000005,250-499,0 +19,E12000005,500-999,0 +19,E12000005,1000-4999,0 +19,E12000005,5000+,5 +19,E12000006,0-49,0 +19,E12000006,50-99,0 +19,E12000006,100-249,0 +19,E12000006,250-499,0 +19,E12000006,500-999,0 +19,E12000006,1000-4999,0 +19,E12000006,5000+,0 +19,E12000007,0-49,0 +19,E12000007,50-99,0 +19,E12000007,100-249,5 +19,E12000007,250-499,0 +19,E12000007,500-999,0 +19,E12000007,1000-4999,0 +19,E12000007,5000+,5 +19,E12000008,0-49,0 +19,E12000008,50-99,0 +19,E12000008,100-249,0 +19,E12000008,250-499,0 +19,E12000008,500-999,0 +19,E12000008,1000-4999,5 +19,E12000008,5000+,5 +19,E12000009,0-49,0 +19,E12000009,50-99,0 +19,E12000009,100-249,0 +19,E12000009,250-499,5 +19,E12000009,500-999,0 +19,E12000009,1000-4999,0 +19,E12000009,5000+,0 +19,W92000004,0-49,0 +19,W92000004,50-99,0 +19,W92000004,100-249,0 +19,W92000004,250-499,0 +19,W92000004,500-999,0 +19,W92000004,1000-4999,0 +19,W92000004,5000+,0 +19,S92000003,0-49,0 +19,S92000003,50-99,0 +19,S92000003,100-249,0 +19,S92000003,250-499,0 +19,S92000003,500-999,0 +19,S92000003,1000-4999,0 +19,S92000003,5000+,5 +19,N92000002,0-49,0 +19,N92000002,50-99,0 +19,N92000002,100-249,5 +19,N92000002,250-499,0 +19,N92000002,500-999,0 +19,N92000002,1000-4999,0 +19,N92000002,5000+,0 +20,E12000001,0-49,10 +20,E12000001,50-99,15 +20,E12000001,100-249,10 +20,E12000001,250-499,10 +20,E12000001,500-999,5 +20,E12000001,1000-4999,15 +20,E12000001,5000+,30 +20,E12000002,0-49,50 +20,E12000002,50-99,55 +20,E12000002,100-249,65 +20,E12000002,250-499,45 +20,E12000002,500-999,45 +20,E12000002,1000-4999,75 +20,E12000002,5000+,150 +20,E12000003,0-49,40 +20,E12000003,50-99,30 +20,E12000003,100-249,60 +20,E12000003,250-499,25 +20,E12000003,500-999,20 +20,E12000003,1000-4999,45 +20,E12000003,5000+,60 +20,E12000004,0-49,25 +20,E12000004,50-99,30 +20,E12000004,100-249,50 +20,E12000004,250-499,20 +20,E12000004,500-999,35 +20,E12000004,1000-4999,60 +20,E12000004,5000+,55 +20,E12000005,0-49,35 +20,E12000005,50-99,40 +20,E12000005,100-249,50 +20,E12000005,250-499,35 +20,E12000005,500-999,25 +20,E12000005,1000-4999,65 +20,E12000005,5000+,55 +20,E12000006,0-49,50 +20,E12000006,50-99,40 +20,E12000006,100-249,45 +20,E12000006,250-499,30 +20,E12000006,500-999,30 +20,E12000006,1000-4999,55 +20,E12000006,5000+,55 +20,E12000007,0-49,95 +20,E12000007,50-99,95 +20,E12000007,100-249,110 +20,E12000007,250-499,50 +20,E12000007,500-999,35 +20,E12000007,1000-4999,30 +20,E12000007,5000+,40 +20,E12000008,0-49,75 +20,E12000008,50-99,50 +20,E12000008,100-249,75 +20,E12000008,250-499,40 +20,E12000008,500-999,35 +20,E12000008,1000-4999,50 +20,E12000008,5000+,75 +20,E12000009,0-49,40 +20,E12000009,50-99,40 +20,E12000009,100-249,45 +20,E12000009,250-499,30 +20,E12000009,500-999,15 +20,E12000009,1000-4999,45 +20,E12000009,5000+,25 +20,W92000004,0-49,15 +20,W92000004,50-99,15 +20,W92000004,100-249,30 +20,W92000004,250-499,15 +20,W92000004,500-999,15 +20,W92000004,1000-4999,20 +20,W92000004,5000+,35 +20,S92000003,0-49,35 +20,S92000003,50-99,30 +20,S92000003,100-249,50 +20,S92000003,250-499,20 +20,S92000003,500-999,10 +20,S92000003,1000-4999,30 +20,S92000003,5000+,35 +20,N92000002,0-49,10 +20,N92000002,50-99,10 +20,N92000002,100-249,10 +20,N92000002,250-499,10 +20,N92000002,500-999,5 +20,N92000002,1000-4999,10 +20,N92000002,5000+,10 +21,E12000001,0-49,0 +21,E12000001,50-99,5 +21,E12000001,100-249,5 +21,E12000001,250-499,0 +21,E12000001,500-999,0 +21,E12000001,1000-4999,0 +21,E12000001,5000+,10 +21,E12000002,0-49,15 +21,E12000002,50-99,15 +21,E12000002,100-249,15 +21,E12000002,250-499,5 +21,E12000002,500-999,5 +21,E12000002,1000-4999,15 +21,E12000002,5000+,15 +21,E12000003,0-49,5 +21,E12000003,50-99,0 +21,E12000003,100-249,5 +21,E12000003,250-499,10 +21,E12000003,500-999,5 +21,E12000003,1000-4999,0 +21,E12000003,5000+,10 +21,E12000004,0-49,5 +21,E12000004,50-99,0 +21,E12000004,100-249,5 +21,E12000004,250-499,5 +21,E12000004,500-999,5 +21,E12000004,1000-4999,5 +21,E12000004,5000+,15 +21,E12000005,0-49,5 +21,E12000005,50-99,5 +21,E12000005,100-249,10 +21,E12000005,250-499,5 +21,E12000005,500-999,0 +21,E12000005,1000-4999,5 +21,E12000005,5000+,5 +21,E12000006,0-49,5 +21,E12000006,50-99,10 +21,E12000006,100-249,15 +21,E12000006,250-499,10 +21,E12000006,500-999,5 +21,E12000006,1000-4999,10 +21,E12000006,5000+,15 +21,E12000007,0-49,30 +21,E12000007,50-99,20 +21,E12000007,100-249,25 +21,E12000007,250-499,20 +21,E12000007,500-999,10 +21,E12000007,1000-4999,10 +21,E12000007,5000+,15 +21,E12000008,0-49,15 +21,E12000008,50-99,5 +21,E12000008,100-249,20 +21,E12000008,250-499,10 +21,E12000008,500-999,10 +21,E12000008,1000-4999,10 +21,E12000008,5000+,25 +21,E12000009,0-49,5 +21,E12000009,50-99,0 +21,E12000009,100-249,10 +21,E12000009,250-499,10 +21,E12000009,500-999,0 +21,E12000009,1000-4999,10 +21,E12000009,5000+,5 +21,W92000004,0-49,0 +21,W92000004,50-99,0 +21,W92000004,100-249,5 +21,W92000004,250-499,0 +21,W92000004,500-999,5 +21,W92000004,1000-4999,5 +21,W92000004,5000+,15 +21,S92000003,0-49,5 +21,S92000003,50-99,5 +21,S92000003,100-249,5 +21,S92000003,250-499,0 +21,S92000003,500-999,0 +21,S92000003,1000-4999,5 +21,S92000003,5000+,15 +21,N92000002,0-49,0 +21,N92000002,50-99,0 +21,N92000002,100-249,5 +21,N92000002,250-499,0 +21,N92000002,500-999,0 +21,N92000002,1000-4999,5 +21,N92000002,5000+,5 +22,E12000001,0-49,15 +22,E12000001,50-99,20 +22,E12000001,100-249,25 +22,E12000001,250-499,20 +22,E12000001,500-999,30 +22,E12000001,1000-4999,35 +22,E12000001,5000+,45 +22,E12000002,0-49,35 +22,E12000002,50-99,55 +22,E12000002,100-249,95 +22,E12000002,250-499,75 +22,E12000002,500-999,90 +22,E12000002,1000-4999,160 +22,E12000002,5000+,130 +22,E12000003,0-49,35 +22,E12000003,50-99,45 +22,E12000003,100-249,85 +22,E12000003,250-499,60 +22,E12000003,500-999,65 +22,E12000003,1000-4999,135 +22,E12000003,5000+,90 +22,E12000004,0-49,35 +22,E12000004,50-99,35 +22,E12000004,100-249,100 +22,E12000004,250-499,70 +22,E12000004,500-999,80 +22,E12000004,1000-4999,140 +22,E12000004,5000+,125 +22,E12000005,0-49,45 +22,E12000005,50-99,55 +22,E12000005,100-249,90 +22,E12000005,250-499,70 +22,E12000005,500-999,85 +22,E12000005,1000-4999,150 +22,E12000005,5000+,110 +22,E12000006,0-49,40 +22,E12000006,50-99,45 +22,E12000006,100-249,95 +22,E12000006,250-499,65 +22,E12000006,500-999,70 +22,E12000006,1000-4999,145 +22,E12000006,5000+,85 +22,E12000007,0-49,45 +22,E12000007,50-99,35 +22,E12000007,100-249,65 +22,E12000007,250-499,40 +22,E12000007,500-999,30 +22,E12000007,1000-4999,40 +22,E12000007,5000+,20 +22,E12000008,0-49,55 +22,E12000008,50-99,50 +22,E12000008,100-249,115 +22,E12000008,250-499,65 +22,E12000008,500-999,75 +22,E12000008,1000-4999,175 +22,E12000008,5000+,90 +22,E12000009,0-49,40 +22,E12000009,50-99,40 +22,E12000009,100-249,80 +22,E12000009,250-499,55 +22,E12000009,500-999,60 +22,E12000009,1000-4999,120 +22,E12000009,5000+,65 +22,W92000004,0-49,20 +22,W92000004,50-99,10 +22,W92000004,100-249,40 +22,W92000004,250-499,35 +22,W92000004,500-999,30 +22,W92000004,1000-4999,65 +22,W92000004,5000+,60 +22,S92000003,0-49,15 +22,S92000003,50-99,20 +22,S92000003,100-249,35 +22,S92000003,250-499,25 +22,S92000003,500-999,35 +22,S92000003,1000-4999,55 +22,S92000003,5000+,25 +22,N92000002,0-49,15 +22,N92000002,50-99,15 +22,N92000002,100-249,40 +22,N92000002,250-499,70 +22,N92000002,500-999,25 +22,N92000002,1000-4999,40 +22,N92000002,5000+,35 +23,E12000001,0-49,10 +23,E12000001,50-99,10 +23,E12000001,100-249,35 +23,E12000001,250-499,15 +23,E12000001,500-999,20 +23,E12000001,1000-4999,25 +23,E12000001,5000+,15 +23,E12000002,0-49,20 +23,E12000002,50-99,40 +23,E12000002,100-249,110 +23,E12000002,250-499,55 +23,E12000002,500-999,40 +23,E12000002,1000-4999,60 +23,E12000002,5000+,50 +23,E12000003,0-49,20 +23,E12000003,50-99,55 +23,E12000003,100-249,85 +23,E12000003,250-499,55 +23,E12000003,500-999,50 +23,E12000003,1000-4999,85 +23,E12000003,5000+,55 +23,E12000004,0-49,20 +23,E12000004,50-99,35 +23,E12000004,100-249,65 +23,E12000004,250-499,40 +23,E12000004,500-999,45 +23,E12000004,1000-4999,65 +23,E12000004,5000+,40 +23,E12000005,0-49,30 +23,E12000005,50-99,40 +23,E12000005,100-249,105 +23,E12000005,250-499,50 +23,E12000005,500-999,35 +23,E12000005,1000-4999,75 +23,E12000005,5000+,50 +23,E12000006,0-49,20 +23,E12000006,50-99,60 +23,E12000006,100-249,110 +23,E12000006,250-499,60 +23,E12000006,500-999,50 +23,E12000006,1000-4999,70 +23,E12000006,5000+,45 +23,E12000007,0-49,50 +23,E12000007,50-99,95 +23,E12000007,100-249,95 +23,E12000007,250-499,45 +23,E12000007,500-999,45 +23,E12000007,1000-4999,60 +23,E12000007,5000+,25 +23,E12000008,0-49,25 +23,E12000008,50-99,65 +23,E12000008,100-249,120 +23,E12000008,250-499,60 +23,E12000008,500-999,65 +23,E12000008,1000-4999,100 +23,E12000008,5000+,35 +23,E12000009,0-49,20 +23,E12000009,50-99,45 +23,E12000009,100-249,105 +23,E12000009,250-499,70 +23,E12000009,500-999,45 +23,E12000009,1000-4999,75 +23,E12000009,5000+,30 +23,W92000004,0-49,20 +23,W92000004,50-99,30 +23,W92000004,100-249,60 +23,W92000004,250-499,40 +23,W92000004,500-999,20 +23,W92000004,1000-4999,35 +23,W92000004,5000+,20 +23,S92000003,0-49,15 +23,S92000003,50-99,40 +23,S92000003,100-249,60 +23,S92000003,250-499,35 +23,S92000003,500-999,35 +23,S92000003,1000-4999,35 +23,S92000003,5000+,20 +23,N92000002,0-49,15 +23,N92000002,50-99,25 +23,N92000002,100-249,60 +23,N92000002,250-499,35 +23,N92000002,500-999,25 +23,N92000002,1000-4999,40 +23,N92000002,5000+,30 +24,E12000001,0-49,5 +24,E12000001,50-99,5 +24,E12000001,100-249,10 +24,E12000001,250-499,5 +24,E12000001,500-999,5 +24,E12000001,1000-4999,10 +24,E12000001,5000+,15 +24,E12000002,0-49,20 +24,E12000002,50-99,20 +24,E12000002,100-249,40 +24,E12000002,250-499,25 +24,E12000002,500-999,25 +24,E12000002,1000-4999,35 +24,E12000002,5000+,30 +24,E12000003,0-49,15 +24,E12000003,50-99,25 +24,E12000003,100-249,55 +24,E12000003,250-499,20 +24,E12000003,500-999,15 +24,E12000003,1000-4999,40 +24,E12000003,5000+,45 +24,E12000004,0-49,10 +24,E12000004,50-99,20 +24,E12000004,100-249,25 +24,E12000004,250-499,25 +24,E12000004,500-999,10 +24,E12000004,1000-4999,25 +24,E12000004,5000+,30 +24,E12000005,0-49,25 +24,E12000005,50-99,20 +24,E12000005,100-249,60 +24,E12000005,250-499,30 +24,E12000005,500-999,40 +24,E12000005,1000-4999,85 +24,E12000005,5000+,70 +24,E12000006,0-49,15 +24,E12000006,50-99,25 +24,E12000006,100-249,40 +24,E12000006,250-499,25 +24,E12000006,500-999,15 +24,E12000006,1000-4999,35 +24,E12000006,5000+,15 +24,E12000007,0-49,15 +24,E12000007,50-99,25 +24,E12000007,100-249,45 +24,E12000007,250-499,15 +24,E12000007,500-999,15 +24,E12000007,1000-4999,15 +24,E12000007,5000+,5 +24,E12000008,0-49,20 +24,E12000008,50-99,30 +24,E12000008,100-249,50 +24,E12000008,250-499,20 +24,E12000008,500-999,20 +24,E12000008,1000-4999,25 +24,E12000008,5000+,15 +24,E12000009,0-49,15 +24,E12000009,50-99,15 +24,E12000009,100-249,30 +24,E12000009,250-499,15 +24,E12000009,500-999,10 +24,E12000009,1000-4999,15 +24,E12000009,5000+,15 +24,W92000004,0-49,5 +24,W92000004,50-99,10 +24,W92000004,100-249,15 +24,W92000004,250-499,5 +24,W92000004,500-999,10 +24,W92000004,1000-4999,15 +24,W92000004,5000+,20 +24,S92000003,0-49,10 +24,S92000003,50-99,10 +24,S92000003,100-249,20 +24,S92000003,250-499,10 +24,S92000003,500-999,10 +24,S92000003,1000-4999,15 +24,S92000003,5000+,15 +24,N92000002,0-49,5 +24,N92000002,50-99,25 +24,N92000002,100-249,35 +24,N92000002,250-499,10 +24,N92000002,500-999,15 +24,N92000002,1000-4999,10 +24,N92000002,5000+,10 +25,E12000001,0-49,35 +25,E12000001,50-99,160 +25,E12000001,100-249,165 +25,E12000001,250-499,80 +25,E12000001,500-999,85 +25,E12000001,1000-4999,150 +25,E12000001,5000+,80 +25,E12000002,0-49,175 +25,E12000002,50-99,445 +25,E12000002,100-249,510 +25,E12000002,250-499,300 +25,E12000002,500-999,290 +25,E12000002,1000-4999,425 +25,E12000002,5000+,160 +25,E12000003,0-49,170 +25,E12000003,50-99,350 +25,E12000003,100-249,530 +25,E12000003,250-499,300 +25,E12000003,500-999,285 +25,E12000003,1000-4999,440 +25,E12000003,5000+,155 +25,E12000004,0-49,155 +25,E12000004,50-99,350 +25,E12000004,100-249,400 +25,E12000004,250-499,275 +25,E12000004,500-999,225 +25,E12000004,1000-4999,380 +25,E12000004,5000+,130 +25,E12000005,0-49,265 +25,E12000005,50-99,430 +25,E12000005,100-249,645 +25,E12000005,250-499,420 +25,E12000005,500-999,425 +25,E12000005,1000-4999,660 +25,E12000005,5000+,285 +25,E12000006,0-49,170 +25,E12000006,50-99,405 +25,E12000006,100-249,500 +25,E12000006,250-499,350 +25,E12000006,500-999,235 +25,E12000006,1000-4999,410 +25,E12000006,5000+,135 +25,E12000007,0-49,115 +25,E12000007,50-99,350 +25,E12000007,100-249,340 +25,E12000007,250-499,170 +25,E12000007,500-999,110 +25,E12000007,1000-4999,135 +25,E12000007,5000+,65 +25,E12000008,0-49,265 +25,E12000008,50-99,505 +25,E12000008,100-249,630 +25,E12000008,250-499,370 +25,E12000008,500-999,340 +25,E12000008,1000-4999,460 +25,E12000008,5000+,140 +25,E12000009,0-49,200 +25,E12000009,50-99,320 +25,E12000009,100-249,460 +25,E12000009,250-499,270 +25,E12000009,500-999,220 +25,E12000009,1000-4999,325 +25,E12000009,5000+,110 +25,W92000004,0-49,90 +25,W92000004,50-99,230 +25,W92000004,100-249,220 +25,W92000004,250-499,110 +25,W92000004,500-999,95 +25,W92000004,1000-4999,135 +25,W92000004,5000+,75 +25,S92000003,0-49,115 +25,S92000003,50-99,280 +25,S92000003,100-249,340 +25,S92000003,250-499,195 +25,S92000003,500-999,130 +25,S92000003,1000-4999,245 +25,S92000003,5000+,110 +25,N92000002,0-49,125 +25,N92000002,50-99,145 +25,N92000002,100-249,200 +25,N92000002,250-499,115 +25,N92000002,500-999,95 +25,N92000002,1000-4999,150 +25,N92000002,5000+,60 +26,E12000001,0-49,15 +26,E12000001,50-99,10 +26,E12000001,100-249,35 +26,E12000001,250-499,20 +26,E12000001,500-999,15 +26,E12000001,1000-4999,25 +26,E12000001,5000+,15 +26,E12000002,0-49,65 +26,E12000002,50-99,70 +26,E12000002,100-249,130 +26,E12000002,250-499,45 +26,E12000002,500-999,55 +26,E12000002,1000-4999,75 +26,E12000002,5000+,55 +26,E12000003,0-49,50 +26,E12000003,50-99,50 +26,E12000003,100-249,85 +26,E12000003,250-499,40 +26,E12000003,500-999,30 +26,E12000003,1000-4999,60 +26,E12000003,5000+,30 +26,E12000004,0-49,55 +26,E12000004,50-99,55 +26,E12000004,100-249,80 +26,E12000004,250-499,40 +26,E12000004,500-999,35 +26,E12000004,1000-4999,65 +26,E12000004,5000+,40 +26,E12000005,0-49,65 +26,E12000005,50-99,50 +26,E12000005,100-249,90 +26,E12000005,250-499,60 +26,E12000005,500-999,35 +26,E12000005,1000-4999,90 +26,E12000005,5000+,45 +26,E12000006,0-49,115 +26,E12000006,50-99,80 +26,E12000006,100-249,150 +26,E12000006,250-499,75 +26,E12000006,500-999,55 +26,E12000006,1000-4999,140 +26,E12000006,5000+,95 +26,E12000007,0-49,135 +26,E12000007,50-99,100 +26,E12000007,100-249,175 +26,E12000007,250-499,65 +26,E12000007,500-999,45 +26,E12000007,1000-4999,40 +26,E12000007,5000+,50 +26,E12000008,0-49,175 +26,E12000008,50-99,115 +26,E12000008,100-249,215 +26,E12000008,250-499,105 +26,E12000008,500-999,95 +26,E12000008,1000-4999,220 +26,E12000008,5000+,170 +26,E12000009,0-49,75 +26,E12000009,50-99,80 +26,E12000009,100-249,100 +26,E12000009,250-499,55 +26,E12000009,500-999,55 +26,E12000009,1000-4999,85 +26,E12000009,5000+,55 +26,W92000004,0-49,35 +26,W92000004,50-99,25 +26,W92000004,100-249,45 +26,W92000004,250-499,15 +26,W92000004,500-999,20 +26,W92000004,1000-4999,25 +26,W92000004,5000+,30 +26,S92000003,0-49,45 +26,S92000003,50-99,35 +26,S92000003,100-249,70 +26,S92000003,250-499,25 +26,S92000003,500-999,30 +26,S92000003,1000-4999,50 +26,S92000003,5000+,45 +26,N92000002,0-49,15 +26,N92000002,50-99,5 +26,N92000002,100-249,15 +26,N92000002,250-499,15 +26,N92000002,500-999,10 +26,N92000002,1000-4999,15 +26,N92000002,5000+,10 +27,E12000001,0-49,10 +27,E12000001,50-99,10 +27,E12000001,100-249,20 +27,E12000001,250-499,5 +27,E12000001,500-999,10 +27,E12000001,1000-4999,15 +27,E12000001,5000+,25 +27,E12000002,0-49,40 +27,E12000002,50-99,30 +27,E12000002,100-249,65 +27,E12000002,250-499,35 +27,E12000002,500-999,20 +27,E12000002,1000-4999,80 +27,E12000002,5000+,50 +27,E12000003,0-49,25 +27,E12000003,50-99,30 +27,E12000003,100-249,55 +27,E12000003,250-499,25 +27,E12000003,500-999,25 +27,E12000003,1000-4999,60 +27,E12000003,5000+,60 +27,E12000004,0-49,25 +27,E12000004,50-99,20 +27,E12000004,100-249,50 +27,E12000004,250-499,25 +27,E12000004,500-999,30 +27,E12000004,1000-4999,60 +27,E12000004,5000+,50 +27,E12000005,0-49,35 +27,E12000005,50-99,40 +27,E12000005,100-249,50 +27,E12000005,250-499,30 +27,E12000005,500-999,25 +27,E12000005,1000-4999,70 +27,E12000005,5000+,50 +27,E12000006,0-49,40 +27,E12000006,50-99,30 +27,E12000006,100-249,70 +27,E12000006,250-499,45 +27,E12000006,500-999,40 +27,E12000006,1000-4999,80 +27,E12000006,5000+,45 +27,E12000007,0-49,45 +27,E12000007,50-99,30 +27,E12000007,100-249,75 +27,E12000007,250-499,35 +27,E12000007,500-999,35 +27,E12000007,1000-4999,35 +27,E12000007,5000+,25 +27,E12000008,0-49,70 +27,E12000008,50-99,55 +27,E12000008,100-249,95 +27,E12000008,250-499,60 +27,E12000008,500-999,55 +27,E12000008,1000-4999,110 +27,E12000008,5000+,80 +27,E12000009,0-49,25 +27,E12000009,50-99,25 +27,E12000009,100-249,60 +27,E12000009,250-499,35 +27,E12000009,500-999,25 +27,E12000009,1000-4999,45 +27,E12000009,5000+,50 +27,W92000004,0-49,15 +27,W92000004,50-99,15 +27,W92000004,100-249,15 +27,W92000004,250-499,10 +27,W92000004,500-999,10 +27,W92000004,1000-4999,25 +27,W92000004,5000+,20 +27,S92000003,0-49,15 +27,S92000003,50-99,15 +27,S92000003,100-249,25 +27,S92000003,250-499,15 +27,S92000003,500-999,25 +27,S92000003,1000-4999,35 +27,S92000003,5000+,15 +27,N92000002,0-49,10 +27,N92000002,50-99,5 +27,N92000002,100-249,15 +27,N92000002,250-499,10 +27,N92000002,500-999,5 +27,N92000002,1000-4999,25 +27,N92000002,5000+,10 +28,E12000001,0-49,20 +28,E12000001,50-99,40 +28,E12000001,100-249,60 +28,E12000001,250-499,25 +28,E12000001,500-999,20 +28,E12000001,1000-4999,50 +28,E12000001,5000+,35 +28,E12000002,0-49,75 +28,E12000002,50-99,90 +28,E12000002,100-249,155 +28,E12000002,250-499,85 +28,E12000002,500-999,75 +28,E12000002,1000-4999,140 +28,E12000002,5000+,110 +28,E12000003,0-49,65 +28,E12000003,50-99,85 +28,E12000003,100-249,160 +28,E12000003,250-499,85 +28,E12000003,500-999,80 +28,E12000003,1000-4999,165 +28,E12000003,5000+,100 +28,E12000004,0-49,65 +28,E12000004,50-99,55 +28,E12000004,100-249,145 +28,E12000004,250-499,80 +28,E12000004,500-999,85 +28,E12000004,1000-4999,165 +28,E12000004,5000+,100 +28,E12000005,0-49,90 +28,E12000005,50-99,90 +28,E12000005,100-249,200 +28,E12000005,250-499,140 +28,E12000005,500-999,100 +28,E12000005,1000-4999,210 +28,E12000005,5000+,140 +28,E12000006,0-49,85 +28,E12000006,50-99,70 +28,E12000006,100-249,150 +28,E12000006,250-499,85 +28,E12000006,500-999,75 +28,E12000006,1000-4999,165 +28,E12000006,5000+,125 +28,E12000007,0-49,75 +28,E12000007,50-99,65 +28,E12000007,100-249,145 +28,E12000007,250-499,45 +28,E12000007,500-999,35 +28,E12000007,1000-4999,30 +28,E12000007,5000+,25 +28,E12000008,0-49,105 +28,E12000008,50-99,95 +28,E12000008,100-249,180 +28,E12000008,250-499,100 +28,E12000008,500-999,110 +28,E12000008,1000-4999,175 +28,E12000008,5000+,120 +28,E12000009,0-49,70 +28,E12000009,50-99,55 +28,E12000009,100-249,115 +28,E12000009,250-499,85 +28,E12000009,500-999,65 +28,E12000009,1000-4999,115 +28,E12000009,5000+,95 +28,W92000004,0-49,40 +28,W92000004,50-99,35 +28,W92000004,100-249,60 +28,W92000004,250-499,30 +28,W92000004,500-999,30 +28,W92000004,1000-4999,55 +28,W92000004,5000+,30 +28,S92000003,0-49,50 +28,S92000003,50-99,60 +28,S92000003,100-249,85 +28,S92000003,250-499,50 +28,S92000003,500-999,45 +28,S92000003,1000-4999,70 +28,S92000003,5000+,65 +28,N92000002,0-49,40 +28,N92000002,50-99,35 +28,N92000002,100-249,50 +28,N92000002,250-499,35 +28,N92000002,500-999,40 +28,N92000002,1000-4999,55 +28,N92000002,5000+,50 +29,E12000001,0-49,10 +29,E12000001,50-99,10 +29,E12000001,100-249,30 +29,E12000001,250-499,15 +29,E12000001,500-999,10 +29,E12000001,1000-4999,5 +29,E12000001,5000+,20 +29,E12000002,0-49,30 +29,E12000002,50-99,45 +29,E12000002,100-249,135 +29,E12000002,250-499,55 +29,E12000002,500-999,30 +29,E12000002,1000-4999,55 +29,E12000002,5000+,35 +29,E12000003,0-49,30 +29,E12000003,50-99,30 +29,E12000003,100-249,105 +29,E12000003,250-499,55 +29,E12000003,500-999,35 +29,E12000003,1000-4999,40 +29,E12000003,5000+,50 +29,E12000004,0-49,25 +29,E12000004,50-99,50 +29,E12000004,100-249,120 +29,E12000004,250-499,45 +29,E12000004,500-999,30 +29,E12000004,1000-4999,50 +29,E12000004,5000+,40 +29,E12000005,0-49,40 +29,E12000005,50-99,60 +29,E12000005,100-249,135 +29,E12000005,250-499,75 +29,E12000005,500-999,35 +29,E12000005,1000-4999,80 +29,E12000005,5000+,85 +29,E12000006,0-49,40 +29,E12000006,50-99,65 +29,E12000006,100-249,85 +29,E12000006,250-499,45 +29,E12000006,500-999,30 +29,E12000006,1000-4999,55 +29,E12000006,5000+,25 +29,E12000007,0-49,30 +29,E12000007,50-99,30 +29,E12000007,100-249,125 +29,E12000007,250-499,25 +29,E12000007,500-999,20 +29,E12000007,1000-4999,10 +29,E12000007,5000+,10 +29,E12000008,0-49,50 +29,E12000008,50-99,85 +29,E12000008,100-249,150 +29,E12000008,250-499,75 +29,E12000008,500-999,40 +29,E12000008,1000-4999,50 +29,E12000008,5000+,35 +29,E12000009,0-49,35 +29,E12000009,50-99,55 +29,E12000009,100-249,125 +29,E12000009,250-499,40 +29,E12000009,500-999,30 +29,E12000009,1000-4999,35 +29,E12000009,5000+,25 +29,W92000004,0-49,10 +29,W92000004,50-99,15 +29,W92000004,100-249,55 +29,W92000004,250-499,25 +29,W92000004,500-999,20 +29,W92000004,1000-4999,25 +29,W92000004,5000+,30 +29,S92000003,0-49,10 +29,S92000003,50-99,20 +29,S92000003,100-249,50 +29,S92000003,250-499,15 +29,S92000003,500-999,5 +29,S92000003,1000-4999,20 +29,S92000003,5000+,15 +29,N92000002,0-49,5 +29,N92000002,50-99,15 +29,N92000002,100-249,25 +29,N92000002,250-499,15 +29,N92000002,500-999,15 +29,N92000002,1000-4999,20 +29,N92000002,5000+,15 +30,E12000001,0-49,5 +30,E12000001,50-99,5 +30,E12000001,100-249,5 +30,E12000001,250-499,10 +30,E12000001,500-999,5 +30,E12000001,1000-4999,5 +30,E12000001,5000+,5 +30,E12000002,0-49,20 +30,E12000002,50-99,45 +30,E12000002,100-249,30 +30,E12000002,250-499,20 +30,E12000002,500-999,10 +30,E12000002,1000-4999,20 +30,E12000002,5000+,20 +30,E12000003,0-49,10 +30,E12000003,50-99,20 +30,E12000003,100-249,20 +30,E12000003,250-499,20 +30,E12000003,500-999,0 +30,E12000003,1000-4999,5 +30,E12000003,5000+,10 +30,E12000004,0-49,15 +30,E12000004,50-99,40 +30,E12000004,100-249,40 +30,E12000004,250-499,10 +30,E12000004,500-999,10 +30,E12000004,1000-4999,10 +30,E12000004,5000+,20 +30,E12000005,0-49,25 +30,E12000005,50-99,20 +30,E12000005,100-249,30 +30,E12000005,250-499,15 +30,E12000005,500-999,15 +30,E12000005,1000-4999,15 +30,E12000005,5000+,30 +30,E12000006,0-49,35 +30,E12000006,50-99,50 +30,E12000006,100-249,55 +30,E12000006,250-499,25 +30,E12000006,500-999,20 +30,E12000006,1000-4999,20 +30,E12000006,5000+,15 +30,E12000007,0-49,25 +30,E12000007,50-99,35 +30,E12000007,100-249,40 +30,E12000007,250-499,10 +30,E12000007,500-999,10 +30,E12000007,1000-4999,15 +30,E12000007,5000+,10 +30,E12000008,0-49,60 +30,E12000008,50-99,85 +30,E12000008,100-249,95 +30,E12000008,250-499,45 +30,E12000008,500-999,30 +30,E12000008,1000-4999,40 +30,E12000008,5000+,40 +30,E12000009,0-49,45 +30,E12000009,50-99,70 +30,E12000009,100-249,80 +30,E12000009,250-499,35 +30,E12000009,500-999,25 +30,E12000009,1000-4999,30 +30,E12000009,5000+,25 +30,W92000004,0-49,5 +30,W92000004,50-99,15 +30,W92000004,100-249,10 +30,W92000004,250-499,5 +30,W92000004,500-999,0 +30,W92000004,1000-4999,10 +30,W92000004,5000+,10 +30,S92000003,0-49,20 +30,S92000003,50-99,25 +30,S92000003,100-249,35 +30,S92000003,250-499,15 +30,S92000003,500-999,5 +30,S92000003,1000-4999,15 +30,S92000003,5000+,10 +30,N92000002,0-49,5 +30,N92000002,50-99,15 +30,N92000002,100-249,15 +30,N92000002,250-499,5 +30,N92000002,500-999,0 +30,N92000002,1000-4999,10 +30,N92000002,5000+,10 +31,E12000001,0-49,10 +31,E12000001,50-99,25 +31,E12000001,100-249,60 +31,E12000001,250-499,20 +31,E12000001,500-999,30 +31,E12000001,1000-4999,25 +31,E12000001,5000+,10 +31,E12000002,0-49,25 +31,E12000002,50-99,95 +31,E12000002,100-249,205 +31,E12000002,250-499,105 +31,E12000002,500-999,105 +31,E12000002,1000-4999,115 +31,E12000002,5000+,40 +31,E12000003,0-49,50 +31,E12000003,50-99,130 +31,E12000003,100-249,265 +31,E12000003,250-499,150 +31,E12000003,500-999,85 +31,E12000003,1000-4999,130 +31,E12000003,5000+,65 +31,E12000004,0-49,45 +31,E12000004,50-99,90 +31,E12000004,100-249,165 +31,E12000004,250-499,80 +31,E12000004,500-999,60 +31,E12000004,1000-4999,90 +31,E12000004,5000+,30 +31,E12000005,0-49,35 +31,E12000005,50-99,110 +31,E12000005,100-249,205 +31,E12000005,250-499,75 +31,E12000005,500-999,70 +31,E12000005,1000-4999,70 +31,E12000005,5000+,25 +31,E12000006,0-49,50 +31,E12000006,50-99,115 +31,E12000006,100-249,210 +31,E12000006,250-499,115 +31,E12000006,500-999,75 +31,E12000006,1000-4999,90 +31,E12000006,5000+,35 +31,E12000007,0-49,80 +31,E12000007,50-99,160 +31,E12000007,100-249,235 +31,E12000007,250-499,90 +31,E12000007,500-999,80 +31,E12000007,1000-4999,70 +31,E12000007,5000+,15 +31,E12000008,0-49,75 +31,E12000008,50-99,170 +31,E12000008,100-249,290 +31,E12000008,250-499,120 +31,E12000008,500-999,110 +31,E12000008,1000-4999,85 +31,E12000008,5000+,30 +31,E12000009,0-49,55 +31,E12000009,50-99,125 +31,E12000009,100-249,185 +31,E12000009,250-499,80 +31,E12000009,500-999,70 +31,E12000009,1000-4999,100 +31,E12000009,5000+,30 +31,W92000004,0-49,15 +31,W92000004,50-99,40 +31,W92000004,100-249,45 +31,W92000004,250-499,25 +31,W92000004,500-999,15 +31,W92000004,1000-4999,20 +31,W92000004,5000+,15 +31,S92000003,0-49,20 +31,S92000003,50-99,40 +31,S92000003,100-249,75 +31,S92000003,250-499,45 +31,S92000003,500-999,20 +31,S92000003,1000-4999,35 +31,S92000003,5000+,5 +31,N92000002,0-49,25 +31,N92000002,50-99,50 +31,N92000002,100-249,110 +31,N92000002,250-499,55 +31,N92000002,500-999,45 +31,N92000002,1000-4999,40 +31,N92000002,5000+,15 +32,E12000001,0-49,45 +32,E12000001,50-99,55 +32,E12000001,100-249,75 +32,E12000001,250-499,35 +32,E12000001,500-999,25 +32,E12000001,1000-4999,25 +32,E12000001,5000+,5 +32,E12000002,0-49,125 +32,E12000002,50-99,180 +32,E12000002,100-249,265 +32,E12000002,250-499,120 +32,E12000002,500-999,95 +32,E12000002,1000-4999,105 +32,E12000002,5000+,35 +32,E12000003,0-49,95 +32,E12000003,50-99,120 +32,E12000003,100-249,190 +32,E12000003,250-499,120 +32,E12000003,500-999,90 +32,E12000003,1000-4999,85 +32,E12000003,5000+,30 +32,E12000004,0-49,120 +32,E12000004,50-99,135 +32,E12000004,100-249,190 +32,E12000004,250-499,85 +32,E12000004,500-999,60 +32,E12000004,1000-4999,65 +32,E12000004,5000+,25 +32,E12000005,0-49,130 +32,E12000005,50-99,185 +32,E12000005,100-249,245 +32,E12000005,250-499,130 +32,E12000005,500-999,100 +32,E12000005,1000-4999,95 +32,E12000005,5000+,35 +32,E12000006,0-49,135 +32,E12000006,50-99,180 +32,E12000006,100-249,240 +32,E12000006,250-499,125 +32,E12000006,500-999,85 +32,E12000006,1000-4999,90 +32,E12000006,5000+,40 +32,E12000007,0-49,320 +32,E12000007,50-99,340 +32,E12000007,100-249,460 +32,E12000007,250-499,175 +32,E12000007,500-999,135 +32,E12000007,1000-4999,130 +32,E12000007,5000+,40 +32,E12000008,0-49,215 +32,E12000008,50-99,275 +32,E12000008,100-249,385 +32,E12000008,250-499,165 +32,E12000008,500-999,130 +32,E12000008,1000-4999,130 +32,E12000008,5000+,70 +32,E12000009,0-49,160 +32,E12000009,50-99,165 +32,E12000009,100-249,265 +32,E12000009,250-499,130 +32,E12000009,500-999,95 +32,E12000009,1000-4999,85 +32,E12000009,5000+,30 +32,W92000004,0-49,55 +32,W92000004,50-99,80 +32,W92000004,100-249,105 +32,W92000004,250-499,65 +32,W92000004,500-999,35 +32,W92000004,1000-4999,35 +32,W92000004,5000+,25 +32,S92000003,0-49,90 +32,S92000003,50-99,95 +32,S92000003,100-249,175 +32,S92000003,250-499,75 +32,S92000003,500-999,55 +32,S92000003,1000-4999,45 +32,S92000003,5000+,15 +32,N92000002,0-49,30 +32,N92000002,50-99,35 +32,N92000002,100-249,55 +32,N92000002,250-499,15 +32,N92000002,500-999,20 +32,N92000002,1000-4999,30 +32,N92000002,5000+,10 +33,E12000001,0-49,40 +33,E12000001,50-99,155 +33,E12000001,100-249,200 +33,E12000001,250-499,55 +33,E12000001,500-999,35 +33,E12000001,1000-4999,45 +33,E12000001,5000+,15 +33,E12000002,0-49,140 +33,E12000002,50-99,385 +33,E12000002,100-249,465 +33,E12000002,250-499,185 +33,E12000002,500-999,140 +33,E12000002,1000-4999,175 +33,E12000002,5000+,45 +33,E12000003,0-49,130 +33,E12000003,50-99,305 +33,E12000003,100-249,375 +33,E12000003,250-499,150 +33,E12000003,500-999,135 +33,E12000003,1000-4999,130 +33,E12000003,5000+,35 +33,E12000004,0-49,135 +33,E12000004,50-99,290 +33,E12000004,100-249,390 +33,E12000004,250-499,185 +33,E12000004,500-999,120 +33,E12000004,1000-4999,160 +33,E12000004,5000+,40 +33,E12000005,0-49,145 +33,E12000005,50-99,290 +33,E12000005,100-249,420 +33,E12000005,250-499,210 +33,E12000005,500-999,140 +33,E12000005,1000-4999,145 +33,E12000005,5000+,50 +33,E12000006,0-49,145 +33,E12000006,50-99,390 +33,E12000006,100-249,515 +33,E12000006,250-499,190 +33,E12000006,500-999,140 +33,E12000006,1000-4999,150 +33,E12000006,5000+,60 +33,E12000007,0-49,105 +33,E12000007,50-99,320 +33,E12000007,100-249,405 +33,E12000007,250-499,130 +33,E12000007,500-999,80 +33,E12000007,1000-4999,75 +33,E12000007,5000+,40 +33,E12000008,0-49,185 +33,E12000008,50-99,515 +33,E12000008,100-249,730 +33,E12000008,250-499,295 +33,E12000008,500-999,185 +33,E12000008,1000-4999,215 +33,E12000008,5000+,75 +33,E12000009,0-49,175 +33,E12000009,50-99,345 +33,E12000009,100-249,535 +33,E12000009,250-499,195 +33,E12000009,500-999,100 +33,E12000009,1000-4999,110 +33,E12000009,5000+,35 +33,W92000004,0-49,70 +33,W92000004,50-99,185 +33,W92000004,100-249,230 +33,W92000004,250-499,80 +33,W92000004,500-999,75 +33,W92000004,1000-4999,65 +33,W92000004,5000+,20 +33,S92000003,0-49,120 +33,S92000003,50-99,305 +33,S92000003,100-249,390 +33,S92000003,250-499,145 +33,S92000003,500-999,95 +33,S92000003,1000-4999,115 +33,S92000003,5000+,45 +33,N92000002,0-49,105 +33,N92000002,50-99,165 +33,N92000002,100-249,135 +33,N92000002,250-499,75 +33,N92000002,500-999,35 +33,N92000002,1000-4999,40 +33,N92000002,5000+,5 +35,E12000001,0-49,40 +35,E12000001,50-99,25 +35,E12000001,100-249,35 +35,E12000001,250-499,15 +35,E12000001,500-999,15 +35,E12000001,1000-4999,20 +35,E12000001,5000+,20 +35,E12000002,0-49,130 +35,E12000002,50-99,40 +35,E12000002,100-249,100 +35,E12000002,250-499,55 +35,E12000002,500-999,35 +35,E12000002,1000-4999,55 +35,E12000002,5000+,35 +35,E12000003,0-49,65 +35,E12000003,50-99,35 +35,E12000003,100-249,80 +35,E12000003,250-499,40 +35,E12000003,500-999,30 +35,E12000003,1000-4999,50 +35,E12000003,5000+,15 +35,E12000004,0-49,60 +35,E12000004,50-99,25 +35,E12000004,100-249,70 +35,E12000004,250-499,25 +35,E12000004,500-999,30 +35,E12000004,1000-4999,35 +35,E12000004,5000+,15 +35,E12000005,0-49,80 +35,E12000005,50-99,30 +35,E12000005,100-249,50 +35,E12000005,250-499,25 +35,E12000005,500-999,25 +35,E12000005,1000-4999,45 +35,E12000005,5000+,25 +35,E12000006,0-49,70 +35,E12000006,50-99,40 +35,E12000006,100-249,65 +35,E12000006,250-499,40 +35,E12000006,500-999,40 +35,E12000006,1000-4999,70 +35,E12000006,5000+,30 +35,E12000007,0-49,675 +35,E12000007,50-99,100 +35,E12000007,100-249,285 +35,E12000007,250-499,215 +35,E12000007,500-999,245 +35,E12000007,1000-4999,330 +35,E12000007,5000+,155 +35,E12000008,0-49,290 +35,E12000008,50-99,50 +35,E12000008,100-249,95 +35,E12000008,250-499,75 +35,E12000008,500-999,80 +35,E12000008,1000-4999,95 +35,E12000008,5000+,55 +35,E12000009,0-49,250 +35,E12000009,50-99,70 +35,E12000009,100-249,120 +35,E12000009,250-499,70 +35,E12000009,500-999,60 +35,E12000009,1000-4999,65 +35,E12000009,5000+,25 +35,W92000004,0-49,75 +35,W92000004,50-99,35 +35,W92000004,100-249,45 +35,W92000004,250-499,20 +35,W92000004,500-999,30 +35,W92000004,1000-4999,20 +35,W92000004,5000+,15 +35,S92000003,0-49,215 +35,S92000003,50-99,95 +35,S92000003,100-249,160 +35,S92000003,250-499,135 +35,S92000003,500-999,90 +35,S92000003,1000-4999,110 +35,S92000003,5000+,45 +35,N92000002,0-49,65 +35,N92000002,50-99,70 +35,N92000002,100-249,155 +35,N92000002,250-499,105 +35,N92000002,500-999,40 +35,N92000002,1000-4999,70 +35,N92000002,5000+,25 +36,E12000001,0-49,0 +36,E12000001,50-99,0 +36,E12000001,100-249,0 +36,E12000001,250-499,0 +36,E12000001,500-999,0 +36,E12000001,1000-4999,0 +36,E12000001,5000+,0 +36,E12000002,0-49,0 +36,E12000002,50-99,0 +36,E12000002,100-249,0 +36,E12000002,250-499,5 +36,E12000002,500-999,5 +36,E12000002,1000-4999,0 +36,E12000002,5000+,5 +36,E12000003,0-49,0 +36,E12000003,50-99,0 +36,E12000003,100-249,0 +36,E12000003,250-499,0 +36,E12000003,500-999,0 +36,E12000003,1000-4999,0 +36,E12000003,5000+,5 +36,E12000004,0-49,0 +36,E12000004,50-99,0 +36,E12000004,100-249,0 +36,E12000004,250-499,0 +36,E12000004,500-999,0 +36,E12000004,1000-4999,0 +36,E12000004,5000+,0 +36,E12000005,0-49,5 +36,E12000005,50-99,0 +36,E12000005,100-249,0 +36,E12000005,250-499,0 +36,E12000005,500-999,0 +36,E12000005,1000-4999,0 +36,E12000005,5000+,5 +36,E12000006,0-49,0 +36,E12000006,50-99,0 +36,E12000006,100-249,0 +36,E12000006,250-499,0 +36,E12000006,500-999,5 +36,E12000006,1000-4999,5 +36,E12000006,5000+,5 +36,E12000007,0-49,0 +36,E12000007,50-99,0 +36,E12000007,100-249,0 +36,E12000007,250-499,0 +36,E12000007,500-999,0 +36,E12000007,1000-4999,5 +36,E12000007,5000+,0 +36,E12000008,0-49,5 +36,E12000008,50-99,0 +36,E12000008,100-249,5 +36,E12000008,250-499,0 +36,E12000008,500-999,0 +36,E12000008,1000-4999,0 +36,E12000008,5000+,5 +36,E12000009,0-49,0 +36,E12000009,50-99,0 +36,E12000009,100-249,0 +36,E12000009,250-499,0 +36,E12000009,500-999,0 +36,E12000009,1000-4999,5 +36,E12000009,5000+,5 +36,W92000004,0-49,0 +36,W92000004,50-99,0 +36,W92000004,100-249,0 +36,W92000004,250-499,0 +36,W92000004,500-999,0 +36,W92000004,1000-4999,0 +36,W92000004,5000+,0 +36,S92000003,0-49,0 +36,S92000003,50-99,0 +36,S92000003,100-249,0 +36,S92000003,250-499,0 +36,S92000003,500-999,0 +36,S92000003,1000-4999,5 +36,S92000003,5000+,5 +36,N92000002,0-49,0 +36,N92000002,50-99,5 +36,N92000002,100-249,5 +36,N92000002,250-499,5 +36,N92000002,500-999,0 +36,N92000002,1000-4999,5 +36,N92000002,5000+,5 +37,E12000001,0-49,0 +37,E12000001,50-99,5 +37,E12000001,100-249,0 +37,E12000001,250-499,5 +37,E12000001,500-999,5 +37,E12000001,1000-4999,5 +37,E12000001,5000+,0 +37,E12000002,0-49,5 +37,E12000002,50-99,20 +37,E12000002,100-249,45 +37,E12000002,250-499,25 +37,E12000002,500-999,15 +37,E12000002,1000-4999,25 +37,E12000002,5000+,10 +37,E12000003,0-49,20 +37,E12000003,50-99,5 +37,E12000003,100-249,30 +37,E12000003,250-499,15 +37,E12000003,500-999,15 +37,E12000003,1000-4999,15 +37,E12000003,5000+,5 +37,E12000004,0-49,10 +37,E12000004,50-99,20 +37,E12000004,100-249,25 +37,E12000004,250-499,15 +37,E12000004,500-999,15 +37,E12000004,1000-4999,20 +37,E12000004,5000+,0 +37,E12000005,0-49,5 +37,E12000005,50-99,15 +37,E12000005,100-249,25 +37,E12000005,250-499,20 +37,E12000005,500-999,15 +37,E12000005,1000-4999,10 +37,E12000005,5000+,5 +37,E12000006,0-49,20 +37,E12000006,50-99,30 +37,E12000006,100-249,50 +37,E12000006,250-499,40 +37,E12000006,500-999,25 +37,E12000006,1000-4999,20 +37,E12000006,5000+,5 +37,E12000007,0-49,10 +37,E12000007,50-99,20 +37,E12000007,100-249,30 +37,E12000007,250-499,15 +37,E12000007,500-999,10 +37,E12000007,1000-4999,5 +37,E12000007,5000+,5 +37,E12000008,0-49,15 +37,E12000008,50-99,35 +37,E12000008,100-249,50 +37,E12000008,250-499,40 +37,E12000008,500-999,35 +37,E12000008,1000-4999,30 +37,E12000008,5000+,10 +37,E12000009,0-49,5 +37,E12000009,50-99,30 +37,E12000009,100-249,40 +37,E12000009,250-499,25 +37,E12000009,500-999,20 +37,E12000009,1000-4999,20 +37,E12000009,5000+,5 +37,W92000004,0-49,5 +37,W92000004,50-99,10 +37,W92000004,100-249,20 +37,W92000004,250-499,0 +37,W92000004,500-999,10 +37,W92000004,1000-4999,10 +37,W92000004,5000+,5 +37,S92000003,0-49,0 +37,S92000003,50-99,10 +37,S92000003,100-249,20 +37,S92000003,250-499,15 +37,S92000003,500-999,5 +37,S92000003,1000-4999,5 +37,S92000003,5000+,5 +37,N92000002,0-49,0 +37,N92000002,50-99,5 +37,N92000002,100-249,5 +37,N92000002,250-499,5 +37,N92000002,500-999,5 +37,N92000002,1000-4999,5 +37,N92000002,5000+,0 +38,E12000001,0-49,20 +38,E12000001,50-99,15 +38,E12000001,100-249,60 +38,E12000001,250-499,30 +38,E12000001,500-999,25 +38,E12000001,1000-4999,35 +38,E12000001,5000+,20 +38,E12000002,0-49,55 +38,E12000002,50-99,55 +38,E12000002,100-249,155 +38,E12000002,250-499,120 +38,E12000002,500-999,80 +38,E12000002,1000-4999,140 +38,E12000002,5000+,100 +38,E12000003,0-49,40 +38,E12000003,50-99,45 +38,E12000003,100-249,115 +38,E12000003,250-499,85 +38,E12000003,500-999,60 +38,E12000003,1000-4999,120 +38,E12000003,5000+,65 +38,E12000004,0-49,40 +38,E12000004,50-99,50 +38,E12000004,100-249,100 +38,E12000004,250-499,70 +38,E12000004,500-999,45 +38,E12000004,1000-4999,95 +38,E12000004,5000+,65 +38,E12000005,0-49,40 +38,E12000005,50-99,60 +38,E12000005,100-249,150 +38,E12000005,250-499,90 +38,E12000005,500-999,80 +38,E12000005,1000-4999,125 +38,E12000005,5000+,70 +38,E12000006,0-49,35 +38,E12000006,50-99,80 +38,E12000006,100-249,175 +38,E12000006,250-499,110 +38,E12000006,500-999,80 +38,E12000006,1000-4999,135 +38,E12000006,5000+,65 +38,E12000007,0-49,70 +38,E12000007,50-99,105 +38,E12000007,100-249,255 +38,E12000007,250-499,135 +38,E12000007,500-999,85 +38,E12000007,1000-4999,80 +38,E12000007,5000+,65 +38,E12000008,0-49,70 +38,E12000008,50-99,90 +38,E12000008,100-249,275 +38,E12000008,250-499,145 +38,E12000008,500-999,105 +38,E12000008,1000-4999,135 +38,E12000008,5000+,95 +38,E12000009,0-49,45 +38,E12000009,50-99,45 +38,E12000009,100-249,135 +38,E12000009,250-499,65 +38,E12000009,500-999,55 +38,E12000009,1000-4999,80 +38,E12000009,5000+,40 +38,W92000004,0-49,25 +38,W92000004,50-99,25 +38,W92000004,100-249,80 +38,W92000004,250-499,40 +38,W92000004,500-999,45 +38,W92000004,1000-4999,75 +38,W92000004,5000+,35 +38,S92000003,0-49,30 +38,S92000003,50-99,30 +38,S92000003,100-249,85 +38,S92000003,250-499,50 +38,S92000003,500-999,45 +38,S92000003,1000-4999,75 +38,S92000003,5000+,40 +38,N92000002,0-49,20 +38,N92000002,50-99,10 +38,N92000002,100-249,30 +38,N92000002,250-499,20 +38,N92000002,500-999,15 +38,N92000002,1000-4999,35 +38,N92000002,5000+,30 +39,E12000001,0-49,0 +39,E12000001,50-99,5 +39,E12000001,100-249,10 +39,E12000001,250-499,5 +39,E12000001,500-999,5 +39,E12000001,1000-4999,10 +39,E12000001,5000+,5 +39,E12000002,0-49,10 +39,E12000002,50-99,20 +39,E12000002,100-249,40 +39,E12000002,250-499,20 +39,E12000002,500-999,25 +39,E12000002,1000-4999,35 +39,E12000002,5000+,10 +39,E12000003,0-49,10 +39,E12000003,50-99,10 +39,E12000003,100-249,30 +39,E12000003,250-499,15 +39,E12000003,500-999,20 +39,E12000003,1000-4999,15 +39,E12000003,5000+,10 +39,E12000004,0-49,10 +39,E12000004,50-99,15 +39,E12000004,100-249,25 +39,E12000004,250-499,15 +39,E12000004,500-999,10 +39,E12000004,1000-4999,15 +39,E12000004,5000+,0 +39,E12000005,0-49,15 +39,E12000005,50-99,20 +39,E12000005,100-249,25 +39,E12000005,250-499,15 +39,E12000005,500-999,15 +39,E12000005,1000-4999,30 +39,E12000005,5000+,5 +39,E12000006,0-49,15 +39,E12000006,50-99,20 +39,E12000006,100-249,45 +39,E12000006,250-499,25 +39,E12000006,500-999,20 +39,E12000006,1000-4999,40 +39,E12000006,5000+,10 +39,E12000007,0-49,15 +39,E12000007,50-99,25 +39,E12000007,100-249,35 +39,E12000007,250-499,15 +39,E12000007,500-999,10 +39,E12000007,1000-4999,20 +39,E12000007,5000+,10 +39,E12000008,0-49,15 +39,E12000008,50-99,40 +39,E12000008,100-249,45 +39,E12000008,250-499,25 +39,E12000008,500-999,20 +39,E12000008,1000-4999,30 +39,E12000008,5000+,10 +39,E12000009,0-49,10 +39,E12000009,50-99,10 +39,E12000009,100-249,20 +39,E12000009,250-499,10 +39,E12000009,500-999,15 +39,E12000009,1000-4999,15 +39,E12000009,5000+,5 +39,W92000004,0-49,5 +39,W92000004,50-99,5 +39,W92000004,100-249,15 +39,W92000004,250-499,5 +39,W92000004,500-999,5 +39,W92000004,1000-4999,10 +39,W92000004,5000+,0 +39,S92000003,0-49,10 +39,S92000003,50-99,15 +39,S92000003,100-249,15 +39,S92000003,250-499,10 +39,S92000003,500-999,5 +39,S92000003,1000-4999,10 +39,S92000003,5000+,5 +39,N92000002,0-49,5 +39,N92000002,50-99,0 +39,N92000002,100-249,5 +39,N92000002,250-499,5 +39,N92000002,500-999,5 +39,N92000002,1000-4999,5 +39,N92000002,5000+,0 +41,E12000001,0-49,270 +41,E12000001,50-99,270 +41,E12000001,100-249,645 +41,E12000001,250-499,530 +41,E12000001,500-999,420 +41,E12000001,1000-4999,280 +41,E12000001,5000+,75 +41,E12000002,0-49,1230 +41,E12000002,50-99,1040 +41,E12000002,100-249,2255 +41,E12000002,250-499,2450 +41,E12000002,500-999,1900 +41,E12000002,1000-4999,1120 +41,E12000002,5000+,275 +41,E12000003,0-49,1025 +41,E12000003,50-99,770 +41,E12000003,100-249,1660 +41,E12000003,250-499,1630 +41,E12000003,500-999,1175 +41,E12000003,1000-4999,790 +41,E12000003,5000+,190 +41,E12000004,0-49,1025 +41,E12000004,50-99,945 +41,E12000004,100-249,1880 +41,E12000004,250-499,1805 +41,E12000004,500-999,1275 +41,E12000004,1000-4999,735 +41,E12000004,5000+,225 +41,E12000005,0-49,1145 +41,E12000005,50-99,1000 +41,E12000005,100-249,1995 +41,E12000005,250-499,2115 +41,E12000005,500-999,1435 +41,E12000005,1000-4999,825 +41,E12000005,5000+,205 +41,E12000006,0-49,1705 +41,E12000006,50-99,1700 +41,E12000006,100-249,3395 +41,E12000006,250-499,3350 +41,E12000006,500-999,2385 +41,E12000006,1000-4999,1400 +41,E12000006,5000+,405 +41,E12000007,0-49,2965 +41,E12000007,50-99,3075 +41,E12000007,100-249,5815 +41,E12000007,250-499,7780 +41,E12000007,500-999,5555 +41,E12000007,1000-4999,3000 +41,E12000007,5000+,645 +41,E12000008,0-49,2330 +41,E12000008,50-99,2290 +41,E12000008,100-249,4595 +41,E12000008,250-499,4470 +41,E12000008,500-999,3050 +41,E12000008,1000-4999,1950 +41,E12000008,5000+,440 +41,E12000009,0-49,1545 +41,E12000009,50-99,1310 +41,E12000009,100-249,2735 +41,E12000009,250-499,2450 +41,E12000009,500-999,1685 +41,E12000009,1000-4999,1040 +41,E12000009,5000+,250 +41,W92000004,0-49,550 +41,W92000004,50-99,510 +41,W92000004,100-249,1015 +41,W92000004,250-499,885 +41,W92000004,500-999,670 +41,W92000004,1000-4999,340 +41,W92000004,5000+,100 +41,S92000003,0-49,715 +41,S92000003,50-99,535 +41,S92000003,100-249,1080 +41,S92000003,250-499,990 +41,S92000003,500-999,745 +41,S92000003,1000-4999,605 +41,S92000003,5000+,210 +41,N92000002,0-49,715 +41,N92000002,50-99,465 +41,N92000002,100-249,775 +41,N92000002,250-499,565 +41,N92000002,500-999,435 +41,N92000002,1000-4999,455 +41,N92000002,5000+,120 +42,E12000001,0-49,60 +42,E12000001,50-99,135 +42,E12000001,100-249,325 +42,E12000001,250-499,125 +42,E12000001,500-999,65 +42,E12000001,1000-4999,85 +42,E12000001,5000+,40 +42,E12000002,0-49,195 +42,E12000002,50-99,315 +42,E12000002,100-249,820 +42,E12000002,250-499,315 +42,E12000002,500-999,235 +42,E12000002,1000-4999,260 +42,E12000002,5000+,140 +42,E12000003,0-49,130 +42,E12000003,50-99,235 +42,E12000003,100-249,560 +42,E12000003,250-499,260 +42,E12000003,500-999,150 +42,E12000003,1000-4999,215 +42,E12000003,5000+,105 +42,E12000004,0-49,140 +42,E12000004,50-99,225 +42,E12000004,100-249,575 +42,E12000004,250-499,250 +42,E12000004,500-999,175 +42,E12000004,1000-4999,200 +42,E12000004,5000+,95 +42,E12000005,0-49,185 +42,E12000005,50-99,250 +42,E12000005,100-249,620 +42,E12000005,250-499,290 +42,E12000005,500-999,175 +42,E12000005,1000-4999,240 +42,E12000005,5000+,100 +42,E12000006,0-49,240 +42,E12000006,50-99,335 +42,E12000006,100-249,920 +42,E12000006,250-499,375 +42,E12000006,500-999,270 +42,E12000006,1000-4999,320 +42,E12000006,5000+,160 +42,E12000007,0-49,310 +42,E12000007,50-99,340 +42,E12000007,100-249,1075 +42,E12000007,250-499,310 +42,E12000007,500-999,200 +42,E12000007,1000-4999,215 +42,E12000007,5000+,125 +42,E12000008,0-49,345 +42,E12000008,50-99,435 +42,E12000008,100-249,1185 +42,E12000008,250-499,515 +42,E12000008,500-999,375 +42,E12000008,1000-4999,430 +42,E12000008,5000+,195 +42,E12000009,0-49,220 +42,E12000009,50-99,250 +42,E12000009,100-249,620 +42,E12000009,250-499,345 +42,E12000009,500-999,200 +42,E12000009,1000-4999,220 +42,E12000009,5000+,85 +42,W92000004,0-49,145 +42,W92000004,50-99,140 +42,W92000004,100-249,390 +42,W92000004,250-499,155 +42,W92000004,500-999,115 +42,W92000004,1000-4999,150 +42,W92000004,5000+,55 +42,S92000003,0-49,135 +42,S92000003,50-99,190 +42,S92000003,100-249,480 +42,S92000003,250-499,190 +42,S92000003,500-999,130 +42,S92000003,1000-4999,150 +42,S92000003,5000+,115 +42,N92000002,0-49,135 +42,N92000002,50-99,140 +42,N92000002,100-249,225 +42,N92000002,250-499,135 +42,N92000002,500-999,115 +42,N92000002,1000-4999,120 +42,N92000002,5000+,70 +43,E12000001,0-49,395 +43,E12000001,50-99,1660 +43,E12000001,100-249,2880 +43,E12000001,250-499,1040 +43,E12000001,500-999,560 +43,E12000001,1000-4999,510 +43,E12000001,5000+,140 +43,E12000002,0-49,1255 +43,E12000002,50-99,4990 +43,E12000002,100-249,8780 +43,E12000002,250-499,3260 +43,E12000002,500-999,1850 +43,E12000002,1000-4999,1725 +43,E12000002,5000+,450 +43,E12000003,0-49,1015 +43,E12000003,50-99,3620 +43,E12000003,100-249,6955 +43,E12000003,250-499,2595 +43,E12000003,500-999,1475 +43,E12000003,1000-4999,1490 +43,E12000003,5000+,355 +43,E12000004,0-49,1070 +43,E12000004,50-99,3705 +43,E12000004,100-249,6655 +43,E12000004,250-499,2560 +43,E12000004,500-999,1340 +43,E12000004,1000-4999,1230 +43,E12000004,5000+,280 +43,E12000005,0-49,1225 +43,E12000005,50-99,4070 +43,E12000005,100-249,7055 +43,E12000005,250-499,2595 +43,E12000005,500-999,1475 +43,E12000005,1000-4999,1475 +43,E12000005,5000+,335 +43,E12000006,0-49,2030 +43,E12000006,50-99,6965 +43,E12000006,100-249,11690 +43,E12000006,250-499,4565 +43,E12000006,500-999,2645 +43,E12000006,1000-4999,2480 +43,E12000006,5000+,595 +43,E12000007,0-49,2300 +43,E12000007,50-99,7455 +43,E12000007,100-249,11450 +43,E12000007,250-499,4445 +43,E12000007,500-999,2470 +43,E12000007,1000-4999,2125 +43,E12000007,5000+,490 +43,E12000008,0-49,2460 +43,E12000008,50-99,9090 +43,E12000008,100-249,15790 +43,E12000008,250-499,5930 +43,E12000008,500-999,3540 +43,E12000008,1000-4999,3180 +43,E12000008,5000+,680 +43,E12000009,0-49,1450 +43,E12000009,50-99,4800 +43,E12000009,100-249,9090 +43,E12000009,250-499,3475 +43,E12000009,500-999,1975 +43,E12000009,1000-4999,1585 +43,E12000009,5000+,300 +43,W92000004,0-49,755 +43,W92000004,50-99,1960 +43,W92000004,100-249,3710 +43,W92000004,250-499,1440 +43,W92000004,500-999,705 +43,W92000004,1000-4999,685 +43,W92000004,5000+,110 +43,S92000003,0-49,970 +43,S92000003,50-99,3580 +43,S92000003,100-249,6385 +43,S92000003,250-499,2600 +43,S92000003,500-999,1420 +43,S92000003,1000-4999,1300 +43,S92000003,5000+,275 +43,N92000002,0-49,1220 +43,N92000002,50-99,1515 +43,N92000002,100-249,2275 +43,N92000002,250-499,910 +43,N92000002,500-999,520 +43,N92000002,1000-4999,455 +43,N92000002,5000+,125 +45,E12000001,0-49,165 +45,E12000001,50-99,355 +45,E12000001,100-249,920 +45,E12000001,250-499,505 +45,E12000001,500-999,305 +45,E12000001,1000-4999,295 +45,E12000001,5000+,105 +45,E12000002,0-49,530 +45,E12000002,50-99,1370 +45,E12000002,100-249,3010 +45,E12000002,250-499,1725 +45,E12000002,500-999,1010 +45,E12000002,1000-4999,1010 +45,E12000002,5000+,380 +45,E12000003,0-49,400 +45,E12000003,50-99,1070 +45,E12000003,100-249,2430 +45,E12000003,250-499,1460 +45,E12000003,500-999,835 +45,E12000003,1000-4999,820 +45,E12000003,5000+,315 +45,E12000004,0-49,545 +45,E12000004,50-99,1170 +45,E12000004,100-249,2190 +45,E12000004,250-499,1345 +45,E12000004,500-999,800 +45,E12000004,1000-4999,800 +45,E12000004,5000+,305 +45,E12000005,0-49,565 +45,E12000005,50-99,1340 +45,E12000005,100-249,2785 +45,E12000005,250-499,1555 +45,E12000005,500-999,940 +45,E12000005,1000-4999,880 +45,E12000005,5000+,285 +45,E12000006,0-49,745 +45,E12000006,50-99,1410 +45,E12000006,100-249,2680 +45,E12000006,250-499,1790 +45,E12000006,500-999,1195 +45,E12000006,1000-4999,1095 +45,E12000006,5000+,365 +45,E12000007,0-49,550 +45,E12000007,50-99,1375 +45,E12000007,100-249,2445 +45,E12000007,250-499,1425 +45,E12000007,500-999,790 +45,E12000007,1000-4999,660 +45,E12000007,5000+,170 +45,E12000008,0-49,810 +45,E12000008,50-99,1820 +45,E12000008,100-249,3465 +45,E12000008,250-499,2255 +45,E12000008,500-999,1550 +45,E12000008,1000-4999,1395 +45,E12000008,5000+,460 +45,E12000009,0-49,490 +45,E12000009,50-99,1065 +45,E12000009,100-249,2475 +45,E12000009,250-499,1670 +45,E12000009,500-999,1015 +45,E12000009,1000-4999,870 +45,E12000009,5000+,270 +45,W92000004,0-49,255 +45,W92000004,50-99,580 +45,W92000004,100-249,1265 +45,W92000004,250-499,780 +45,W92000004,500-999,440 +45,W92000004,1000-4999,425 +45,W92000004,5000+,180 +45,S92000003,0-49,310 +45,S92000003,50-99,770 +45,S92000003,100-249,1625 +45,S92000003,250-499,1060 +45,S92000003,500-999,590 +45,S92000003,1000-4999,550 +45,S92000003,5000+,190 +45,N92000002,0-49,270 +45,N92000002,50-99,390 +45,N92000002,100-249,890 +45,N92000002,250-499,495 +45,N92000002,500-999,345 +45,N92000002,1000-4999,465 +45,N92000002,5000+,165 +46,E12000001,0-49,220 +46,E12000001,50-99,180 +46,E12000001,100-249,400 +46,E12000001,250-499,315 +46,E12000001,500-999,280 +46,E12000001,1000-4999,445 +46,E12000001,5000+,235 +46,E12000002,0-49,1190 +46,E12000002,50-99,1135 +46,E12000002,100-249,2225 +46,E12000002,250-499,1665 +46,E12000002,500-999,1535 +46,E12000002,1000-4999,2380 +46,E12000002,5000+,1385 +46,E12000003,0-49,800 +46,E12000003,50-99,680 +46,E12000003,100-249,1415 +46,E12000003,250-499,1080 +46,E12000003,500-999,985 +46,E12000003,1000-4999,1610 +46,E12000003,5000+,1005 +46,E12000004,0-49,815 +46,E12000004,50-99,665 +46,E12000004,100-249,1395 +46,E12000004,250-499,960 +46,E12000004,500-999,925 +46,E12000004,1000-4999,1570 +46,E12000004,5000+,895 +46,E12000005,0-49,1020 +46,E12000005,50-99,925 +46,E12000005,100-249,1655 +46,E12000005,250-499,1345 +46,E12000005,500-999,1240 +46,E12000005,1000-4999,2070 +46,E12000005,5000+,1250 +46,E12000006,0-49,1200 +46,E12000006,50-99,990 +46,E12000006,100-249,1845 +46,E12000006,250-499,1380 +46,E12000006,500-999,1250 +46,E12000006,1000-4999,2140 +46,E12000006,5000+,1355 +46,E12000007,0-49,3080 +46,E12000007,50-99,2170 +46,E12000007,100-249,4090 +46,E12000007,250-499,3095 +46,E12000007,500-999,2660 +46,E12000007,1000-4999,3555 +46,E12000007,5000+,2000 +46,E12000008,0-49,1760 +46,E12000008,50-99,1240 +46,E12000008,100-249,2370 +46,E12000008,250-499,1795 +46,E12000008,500-999,1620 +46,E12000008,1000-4999,2840 +46,E12000008,5000+,1905 +46,E12000009,0-49,905 +46,E12000009,50-99,685 +46,E12000009,100-249,1305 +46,E12000009,250-499,975 +46,E12000009,500-999,845 +46,E12000009,1000-4999,1395 +46,E12000009,5000+,735 +46,W92000004,0-49,400 +46,W92000004,50-99,310 +46,W92000004,100-249,640 +46,W92000004,250-499,445 +46,W92000004,500-999,430 +46,W92000004,1000-4999,675 +46,W92000004,5000+,310 +46,S92000003,0-49,615 +46,S92000003,50-99,505 +46,S92000003,100-249,940 +46,S92000003,250-499,695 +46,S92000003,500-999,645 +46,S92000003,1000-4999,1035 +46,S92000003,5000+,580 +46,N92000002,0-49,425 +46,N92000002,50-99,405 +46,N92000002,100-249,585 +46,N92000002,250-499,440 +46,N92000002,500-999,410 +46,N92000002,1000-4999,750 +46,N92000002,5000+,400 +47,E12000001,0-49,485 +47,E12000001,50-99,725 +47,E12000001,100-249,1990 +47,E12000001,250-499,1330 +47,E12000001,500-999,955 +47,E12000001,1000-4999,590 +47,E12000001,5000+,115 +47,E12000002,0-49,1945 +47,E12000002,50-99,3340 +47,E12000002,100-249,8185 +47,E12000002,250-499,5005 +47,E12000002,500-999,3115 +47,E12000002,1000-4999,2415 +47,E12000002,5000+,500 +47,E12000003,0-49,1320 +47,E12000003,50-99,2245 +47,E12000003,100-249,5620 +47,E12000003,250-499,3505 +47,E12000003,500-999,2065 +47,E12000003,1000-4999,1520 +47,E12000003,5000+,325 +47,E12000004,0-49,1310 +47,E12000004,50-99,1840 +47,E12000004,100-249,4515 +47,E12000004,250-499,2945 +47,E12000004,500-999,1835 +47,E12000004,1000-4999,1370 +47,E12000004,5000+,265 +47,E12000005,0-49,1625 +47,E12000005,50-99,2555 +47,E12000005,100-249,5940 +47,E12000005,250-499,3820 +47,E12000005,500-999,2435 +47,E12000005,1000-4999,1780 +47,E12000005,5000+,310 +47,E12000006,0-49,1845 +47,E12000006,50-99,2435 +47,E12000006,100-249,5470 +47,E12000006,250-499,3635 +47,E12000006,500-999,2450 +47,E12000006,1000-4999,1975 +47,E12000006,5000+,385 +47,E12000007,0-49,5485 +47,E12000007,50-99,6135 +47,E12000007,100-249,12355 +47,E12000007,250-499,8445 +47,E12000007,500-999,5400 +47,E12000007,1000-4999,4350 +47,E12000007,5000+,1105 +47,E12000008,0-49,3010 +47,E12000008,50-99,3545 +47,E12000008,100-249,7745 +47,E12000008,250-499,5315 +47,E12000008,500-999,3885 +47,E12000008,1000-4999,3325 +47,E12000008,5000+,535 +47,E12000009,0-49,1475 +47,E12000009,50-99,2170 +47,E12000009,100-249,5275 +47,E12000009,250-499,3245 +47,E12000009,500-999,2105 +47,E12000009,1000-4999,1585 +47,E12000009,5000+,330 +47,W92000004,0-49,745 +47,W92000004,50-99,960 +47,W92000004,100-249,2420 +47,W92000004,250-499,1705 +47,W92000004,500-999,1150 +47,W92000004,1000-4999,805 +47,W92000004,5000+,140 +47,S92000003,0-49,1120 +47,S92000003,50-99,1600 +47,S92000003,100-249,4565 +47,S92000003,250-499,2835 +47,S92000003,500-999,2110 +47,S92000003,1000-4999,1545 +47,S92000003,5000+,255 +47,N92000002,0-49,525 +47,N92000002,50-99,685 +47,N92000002,100-249,1530 +47,N92000002,250-499,1075 +47,N92000002,500-999,925 +47,N92000002,1000-4999,1080 +47,N92000002,5000+,270 +49,E12000001,0-49,155 +49,E12000001,50-99,225 +49,E12000001,100-249,445 +49,E12000001,250-499,180 +49,E12000001,500-999,145 +49,E12000001,1000-4999,150 +49,E12000001,5000+,65 +49,E12000002,0-49,770 +49,E12000002,50-99,1100 +49,E12000002,100-249,2030 +49,E12000002,250-499,575 +49,E12000002,500-999,370 +49,E12000002,1000-4999,490 +49,E12000002,5000+,170 +49,E12000003,0-49,1015 +49,E12000003,50-99,1325 +49,E12000003,100-249,1830 +49,E12000003,250-499,485 +49,E12000003,500-999,395 +49,E12000003,1000-4999,420 +49,E12000003,5000+,150 +49,E12000004,0-49,855 +49,E12000004,50-99,1170 +49,E12000004,100-249,2565 +49,E12000004,250-499,580 +49,E12000004,500-999,370 +49,E12000004,1000-4999,440 +49,E12000004,5000+,145 +49,E12000005,0-49,1275 +49,E12000005,50-99,1720 +49,E12000005,100-249,2795 +49,E12000005,250-499,705 +49,E12000005,500-999,450 +49,E12000005,1000-4999,480 +49,E12000005,5000+,155 +49,E12000006,0-49,1270 +49,E12000006,50-99,1675 +49,E12000006,100-249,2785 +49,E12000006,250-499,780 +49,E12000006,500-999,465 +49,E12000006,1000-4999,635 +49,E12000006,5000+,180 +49,E12000007,0-49,1260 +49,E12000007,50-99,2885 +49,E12000007,100-249,2915 +49,E12000007,250-499,705 +49,E12000007,500-999,380 +49,E12000007,1000-4999,395 +49,E12000007,5000+,135 +49,E12000008,0-49,1245 +49,E12000008,50-99,1860 +49,E12000008,100-249,2580 +49,E12000008,250-499,745 +49,E12000008,500-999,545 +49,E12000008,1000-4999,610 +49,E12000008,5000+,180 +49,E12000009,0-49,580 +49,E12000009,50-99,900 +49,E12000009,100-249,1280 +49,E12000009,250-499,450 +49,E12000009,500-999,340 +49,E12000009,1000-4999,350 +49,E12000009,5000+,100 +49,W92000004,0-49,280 +49,W92000004,50-99,420 +49,W92000004,100-249,785 +49,W92000004,250-499,300 +49,W92000004,500-999,220 +49,W92000004,1000-4999,230 +49,W92000004,5000+,55 +49,S92000003,0-49,330 +49,S92000003,50-99,615 +49,S92000003,100-249,920 +49,S92000003,250-499,400 +49,S92000003,500-999,305 +49,S92000003,1000-4999,380 +49,S92000003,5000+,135 +49,N92000002,0-49,185 +49,N92000002,50-99,285 +49,N92000002,100-249,530 +49,N92000002,250-499,265 +49,N92000002,500-999,200 +49,N92000002,1000-4999,220 +49,N92000002,5000+,60 +50,E12000001,0-49,5 +50,E12000001,50-99,0 +50,E12000001,100-249,5 +50,E12000001,250-499,5 +50,E12000001,500-999,0 +50,E12000001,1000-4999,0 +50,E12000001,5000+,0 +50,E12000002,0-49,20 +50,E12000002,50-99,10 +50,E12000002,100-249,20 +50,E12000002,250-499,10 +50,E12000002,500-999,10 +50,E12000002,1000-4999,20 +50,E12000002,5000+,10 +50,E12000003,0-49,10 +50,E12000003,50-99,10 +50,E12000003,100-249,15 +50,E12000003,250-499,5 +50,E12000003,500-999,5 +50,E12000003,1000-4999,5 +50,E12000003,5000+,5 +50,E12000004,0-49,5 +50,E12000004,50-99,5 +50,E12000004,100-249,10 +50,E12000004,250-499,5 +50,E12000004,500-999,5 +50,E12000004,1000-4999,0 +50,E12000004,5000+,5 +50,E12000005,0-49,10 +50,E12000005,50-99,10 +50,E12000005,100-249,15 +50,E12000005,250-499,10 +50,E12000005,500-999,5 +50,E12000005,1000-4999,5 +50,E12000005,5000+,0 +50,E12000006,0-49,30 +50,E12000006,50-99,20 +50,E12000006,100-249,25 +50,E12000006,250-499,10 +50,E12000006,500-999,15 +50,E12000006,1000-4999,25 +50,E12000006,5000+,15 +50,E12000007,0-49,125 +50,E12000007,50-99,45 +50,E12000007,100-249,70 +50,E12000007,250-499,30 +50,E12000007,500-999,35 +50,E12000007,1000-4999,50 +50,E12000007,5000+,50 +50,E12000008,0-49,65 +50,E12000008,50-99,45 +50,E12000008,100-249,40 +50,E12000008,250-499,15 +50,E12000008,500-999,20 +50,E12000008,1000-4999,20 +50,E12000008,5000+,20 +50,E12000009,0-49,55 +50,E12000009,50-99,45 +50,E12000009,100-249,40 +50,E12000009,250-499,20 +50,E12000009,500-999,10 +50,E12000009,1000-4999,5 +50,E12000009,5000+,5 +50,W92000004,0-49,35 +50,W92000004,50-99,10 +50,W92000004,100-249,15 +50,W92000004,250-499,0 +50,W92000004,500-999,0 +50,W92000004,1000-4999,0 +50,W92000004,5000+,5 +50,S92000003,0-49,35 +50,S92000003,50-99,30 +50,S92000003,100-249,40 +50,S92000003,250-499,20 +50,S92000003,500-999,5 +50,S92000003,1000-4999,25 +50,S92000003,5000+,20 +50,N92000002,0-49,5 +50,N92000002,50-99,5 +50,N92000002,100-249,5 +50,N92000002,250-499,5 +50,N92000002,500-999,0 +50,N92000002,1000-4999,5 +50,N92000002,5000+,5 +51,E12000001,0-49,0 +51,E12000001,50-99,0 +51,E12000001,100-249,0 +51,E12000001,250-499,5 +51,E12000001,500-999,0 +51,E12000001,1000-4999,0 +51,E12000001,5000+,0 +51,E12000002,0-49,5 +51,E12000002,50-99,5 +51,E12000002,100-249,10 +51,E12000002,250-499,25 +51,E12000002,500-999,10 +51,E12000002,1000-4999,10 +51,E12000002,5000+,0 +51,E12000003,0-49,10 +51,E12000003,50-99,0 +51,E12000003,100-249,10 +51,E12000003,250-499,25 +51,E12000003,500-999,5 +51,E12000003,1000-4999,0 +51,E12000003,5000+,5 +51,E12000004,0-49,20 +51,E12000004,50-99,5 +51,E12000004,100-249,5 +51,E12000004,250-499,30 +51,E12000004,500-999,10 +51,E12000004,1000-4999,10 +51,E12000004,5000+,5 +51,E12000005,0-49,10 +51,E12000005,50-99,10 +51,E12000005,100-249,10 +51,E12000005,250-499,30 +51,E12000005,500-999,15 +51,E12000005,1000-4999,10 +51,E12000005,5000+,0 +51,E12000006,0-49,15 +51,E12000006,50-99,10 +51,E12000006,100-249,5 +51,E12000006,250-499,45 +51,E12000006,500-999,20 +51,E12000006,1000-4999,15 +51,E12000006,5000+,10 +51,E12000007,0-49,35 +51,E12000007,50-99,15 +51,E12000007,100-249,20 +51,E12000007,250-499,35 +51,E12000007,500-999,30 +51,E12000007,1000-4999,30 +51,E12000007,5000+,60 +51,E12000008,0-49,45 +51,E12000008,50-99,15 +51,E12000008,100-249,25 +51,E12000008,250-499,50 +51,E12000008,500-999,35 +51,E12000008,1000-4999,20 +51,E12000008,5000+,20 +51,E12000009,0-49,10 +51,E12000009,50-99,5 +51,E12000009,100-249,10 +51,E12000009,250-499,10 +51,E12000009,500-999,5 +51,E12000009,1000-4999,5 +51,E12000009,5000+,10 +51,W92000004,0-49,5 +51,W92000004,50-99,5 +51,W92000004,100-249,5 +51,W92000004,250-499,10 +51,W92000004,500-999,0 +51,W92000004,1000-4999,5 +51,W92000004,5000+,0 +51,S92000003,0-49,5 +51,S92000003,50-99,0 +51,S92000003,100-249,5 +51,S92000003,250-499,5 +51,S92000003,500-999,0 +51,S92000003,1000-4999,0 +51,S92000003,5000+,5 +51,N92000002,0-49,5 +51,N92000002,50-99,5 +51,N92000002,100-249,5 +51,N92000002,250-499,0 +51,N92000002,500-999,0 +51,N92000002,1000-4999,0 +51,N92000002,5000+,0 +52,E12000001,0-49,70 +52,E12000001,50-99,90 +52,E12000001,100-249,100 +52,E12000001,250-499,50 +52,E12000001,500-999,50 +52,E12000001,1000-4999,65 +52,E12000001,5000+,40 +52,E12000002,0-49,160 +52,E12000002,50-99,380 +52,E12000002,100-249,375 +52,E12000002,250-499,175 +52,E12000002,500-999,215 +52,E12000002,1000-4999,255 +52,E12000002,5000+,165 +52,E12000003,0-49,185 +52,E12000003,50-99,310 +52,E12000003,100-249,285 +52,E12000003,250-499,130 +52,E12000003,500-999,125 +52,E12000003,1000-4999,175 +52,E12000003,5000+,115 +52,E12000004,0-49,155 +52,E12000004,50-99,225 +52,E12000004,100-249,240 +52,E12000004,250-499,135 +52,E12000004,500-999,145 +52,E12000004,1000-4999,180 +52,E12000004,5000+,90 +52,E12000005,0-49,180 +52,E12000005,50-99,510 +52,E12000005,100-249,340 +52,E12000005,250-499,175 +52,E12000005,500-999,210 +52,E12000005,1000-4999,215 +52,E12000005,5000+,120 +52,E12000006,0-49,225 +52,E12000006,50-99,365 +52,E12000006,100-249,400 +52,E12000006,250-499,215 +52,E12000006,500-999,245 +52,E12000006,1000-4999,355 +52,E12000006,5000+,240 +52,E12000007,0-49,395 +52,E12000007,50-99,550 +52,E12000007,100-249,585 +52,E12000007,250-499,320 +52,E12000007,500-999,415 +52,E12000007,1000-4999,470 +52,E12000007,5000+,310 +52,E12000008,0-49,305 +52,E12000008,50-99,415 +52,E12000008,100-249,590 +52,E12000008,250-499,305 +52,E12000008,500-999,350 +52,E12000008,1000-4999,435 +52,E12000008,5000+,260 +52,E12000009,0-49,180 +52,E12000009,50-99,215 +52,E12000009,100-249,290 +52,E12000009,250-499,165 +52,E12000009,500-999,140 +52,E12000009,1000-4999,160 +52,E12000009,5000+,65 +52,W92000004,0-49,45 +52,W92000004,50-99,85 +52,W92000004,100-249,135 +52,W92000004,250-499,65 +52,W92000004,500-999,50 +52,W92000004,1000-4999,65 +52,W92000004,5000+,25 +52,S92000003,0-49,90 +52,S92000003,50-99,100 +52,S92000003,100-249,205 +52,S92000003,250-499,75 +52,S92000003,500-999,95 +52,S92000003,1000-4999,130 +52,S92000003,5000+,100 +52,N92000002,0-49,35 +52,N92000002,50-99,45 +52,N92000002,100-249,80 +52,N92000002,250-499,35 +52,N92000002,500-999,40 +52,N92000002,1000-4999,70 +52,N92000002,5000+,45 +53,E12000001,0-49,905 +53,E12000001,50-99,165 +53,E12000001,100-249,95 +53,E12000001,250-499,40 +53,E12000001,500-999,15 +53,E12000001,1000-4999,15 +53,E12000001,5000+,0 +53,E12000002,0-49,2515 +53,E12000002,50-99,600 +53,E12000002,100-249,470 +53,E12000002,250-499,120 +53,E12000002,500-999,65 +53,E12000002,1000-4999,75 +53,E12000002,5000+,20 +53,E12000003,0-49,2080 +53,E12000003,50-99,515 +53,E12000003,100-249,310 +53,E12000003,250-499,105 +53,E12000003,500-999,50 +53,E12000003,1000-4999,40 +53,E12000003,5000+,10 +53,E12000004,0-49,1485 +53,E12000004,50-99,540 +53,E12000004,100-249,420 +53,E12000004,250-499,130 +53,E12000004,500-999,65 +53,E12000004,1000-4999,60 +53,E12000004,5000+,15 +53,E12000005,0-49,1930 +53,E12000005,50-99,640 +53,E12000005,100-249,505 +53,E12000005,250-499,145 +53,E12000005,500-999,75 +53,E12000005,1000-4999,55 +53,E12000005,5000+,20 +53,E12000006,0-49,1845 +53,E12000006,50-99,710 +53,E12000006,100-249,400 +53,E12000006,250-499,110 +53,E12000006,500-999,65 +53,E12000006,1000-4999,80 +53,E12000006,5000+,20 +53,E12000007,0-49,2275 +53,E12000007,50-99,1010 +53,E12000007,100-249,780 +53,E12000007,250-499,215 +53,E12000007,500-999,105 +53,E12000007,1000-4999,115 +53,E12000007,5000+,45 +53,E12000008,0-49,1780 +53,E12000008,50-99,995 +53,E12000008,100-249,595 +53,E12000008,250-499,180 +53,E12000008,500-999,135 +53,E12000008,1000-4999,115 +53,E12000008,5000+,55 +53,E12000009,0-49,1765 +53,E12000009,50-99,620 +53,E12000009,100-249,305 +53,E12000009,250-499,95 +53,E12000009,500-999,60 +53,E12000009,1000-4999,35 +53,E12000009,5000+,5 +53,W92000004,0-49,970 +53,W92000004,50-99,255 +53,W92000004,100-249,120 +53,W92000004,250-499,40 +53,W92000004,500-999,25 +53,W92000004,1000-4999,25 +53,W92000004,5000+,0 +53,S92000003,0-49,1625 +53,S92000003,50-99,355 +53,S92000003,100-249,240 +53,S92000003,250-499,90 +53,S92000003,500-999,45 +53,S92000003,1000-4999,35 +53,S92000003,5000+,5 +53,N92000002,0-49,530 +53,N92000002,50-99,75 +53,N92000002,100-249,65 +53,N92000002,250-499,20 +53,N92000002,500-999,10 +53,N92000002,1000-4999,30 +53,N92000002,5000+,5 +55,E12000001,0-49,55 +55,E12000001,50-99,70 +55,E12000001,100-249,170 +55,E12000001,250-499,95 +55,E12000001,500-999,70 +55,E12000001,1000-4999,115 +55,E12000001,5000+,20 +55,E12000002,0-49,180 +55,E12000002,50-99,330 +55,E12000002,100-249,625 +55,E12000002,250-499,285 +55,E12000002,500-999,220 +55,E12000002,1000-4999,325 +55,E12000002,5000+,100 +55,E12000003,0-49,125 +55,E12000003,50-99,230 +55,E12000003,100-249,455 +55,E12000003,250-499,220 +55,E12000003,500-999,185 +55,E12000003,1000-4999,210 +55,E12000003,5000+,45 +55,E12000004,0-49,80 +55,E12000004,50-99,165 +55,E12000004,100-249,330 +55,E12000004,250-499,165 +55,E12000004,500-999,115 +55,E12000004,1000-4999,165 +55,E12000004,5000+,40 +55,E12000005,0-49,120 +55,E12000005,50-99,190 +55,E12000005,100-249,370 +55,E12000005,250-499,150 +55,E12000005,500-999,145 +55,E12000005,1000-4999,165 +55,E12000005,5000+,60 +55,E12000006,0-49,140 +55,E12000006,50-99,205 +55,E12000006,100-249,455 +55,E12000006,250-499,215 +55,E12000006,500-999,140 +55,E12000006,1000-4999,235 +55,E12000006,5000+,70 +55,E12000007,0-49,315 +55,E12000007,50-99,345 +55,E12000007,100-249,530 +55,E12000007,250-499,280 +55,E12000007,500-999,275 +55,E12000007,1000-4999,545 +55,E12000007,5000+,420 +55,E12000008,0-49,215 +55,E12000008,50-99,310 +55,E12000008,100-249,685 +55,E12000008,250-499,330 +55,E12000008,500-999,250 +55,E12000008,1000-4999,340 +55,E12000008,5000+,100 +55,E12000009,0-49,300 +55,E12000009,50-99,535 +55,E12000009,100-249,1125 +55,E12000009,250-499,455 +55,E12000009,500-999,320 +55,E12000009,1000-4999,395 +55,E12000009,5000+,90 +55,W92000004,0-49,150 +55,W92000004,50-99,305 +55,W92000004,100-249,650 +55,W92000004,250-499,275 +55,W92000004,500-999,235 +55,W92000004,1000-4999,240 +55,W92000004,5000+,40 +55,S92000003,0-49,230 +55,S92000003,50-99,445 +55,S92000003,100-249,1025 +55,S92000003,250-499,520 +55,S92000003,500-999,395 +55,S92000003,1000-4999,415 +55,S92000003,5000+,95 +55,N92000002,0-49,40 +55,N92000002,50-99,50 +55,N92000002,100-249,100 +55,N92000002,250-499,50 +55,N92000002,500-999,40 +55,N92000002,1000-4999,100 +55,N92000002,5000+,35 +56,E12000001,0-49,295 +56,E12000001,50-99,940 +56,E12000001,100-249,2805 +56,E12000001,250-499,1210 +56,E12000001,500-999,605 +56,E12000001,1000-4999,300 +56,E12000001,5000+,25 +56,E12000002,0-49,1075 +56,E12000002,50-99,3110 +56,E12000002,100-249,7580 +56,E12000002,250-499,3080 +56,E12000002,500-999,1590 +56,E12000002,1000-4999,730 +56,E12000002,5000+,105 +56,E12000003,0-49,775 +56,E12000003,50-99,2475 +56,E12000003,100-249,5720 +56,E12000003,250-499,2500 +56,E12000003,500-999,1135 +56,E12000003,1000-4999,530 +56,E12000003,5000+,65 +56,E12000004,0-49,620 +56,E12000004,50-99,1795 +56,E12000004,100-249,4480 +56,E12000004,250-499,2025 +56,E12000004,500-999,970 +56,E12000004,1000-4999,385 +56,E12000004,5000+,50 +56,E12000005,0-49,825 +56,E12000005,50-99,2225 +56,E12000005,100-249,5185 +56,E12000005,250-499,2345 +56,E12000005,500-999,1020 +56,E12000005,1000-4999,485 +56,E12000005,5000+,60 +56,E12000006,0-49,825 +56,E12000006,50-99,2220 +56,E12000006,100-249,5430 +56,E12000006,250-499,2655 +56,E12000006,500-999,1290 +56,E12000006,1000-4999,520 +56,E12000006,5000+,85 +56,E12000007,0-49,2365 +56,E12000007,50-99,4895 +56,E12000007,100-249,9205 +56,E12000007,250-499,4170 +56,E12000007,500-999,2865 +56,E12000007,1000-4999,2350 +56,E12000007,5000+,520 +56,E12000008,0-49,1185 +56,E12000008,50-99,3025 +56,E12000008,100-249,7800 +56,E12000008,250-499,4230 +56,E12000008,500-999,2190 +56,E12000008,1000-4999,965 +56,E12000008,5000+,170 +56,E12000009,0-49,715 +56,E12000009,50-99,2030 +56,E12000009,100-249,5375 +56,E12000009,250-499,3045 +56,E12000009,500-999,1565 +56,E12000009,1000-4999,725 +56,E12000009,5000+,70 +56,W92000004,0-49,410 +56,W92000004,50-99,1300 +56,W92000004,100-249,3480 +56,W92000004,250-499,1395 +56,W92000004,500-999,615 +56,W92000004,1000-4999,245 +56,W92000004,5000+,30 +56,S92000003,0-49,635 +56,S92000003,50-99,1850 +56,S92000003,100-249,5045 +56,S92000003,250-499,2585 +56,S92000003,500-999,1325 +56,S92000003,1000-4999,655 +56,S92000003,5000+,70 +56,N92000002,0-49,145 +56,N92000002,50-99,630 +56,N92000002,100-249,1670 +56,N92000002,250-499,760 +56,N92000002,500-999,460 +56,N92000002,1000-4999,305 +56,N92000002,5000+,30 +58,E12000001,0-49,45 +58,E12000001,50-99,40 +58,E12000001,100-249,75 +58,E12000001,250-499,25 +58,E12000001,500-999,10 +58,E12000001,1000-4999,10 +58,E12000001,5000+,5 +58,E12000002,0-49,155 +58,E12000002,50-99,180 +58,E12000002,100-249,235 +58,E12000002,250-499,105 +58,E12000002,500-999,65 +58,E12000002,1000-4999,65 +58,E12000002,5000+,20 +58,E12000003,0-49,135 +58,E12000003,50-99,110 +58,E12000003,100-249,200 +58,E12000003,250-499,65 +58,E12000003,500-999,50 +58,E12000003,1000-4999,35 +58,E12000003,5000+,10 +58,E12000004,0-49,105 +58,E12000004,50-99,105 +58,E12000004,100-249,180 +58,E12000004,250-499,75 +58,E12000004,500-999,35 +58,E12000004,1000-4999,40 +58,E12000004,5000+,15 +58,E12000005,0-49,145 +58,E12000005,50-99,150 +58,E12000005,100-249,225 +58,E12000005,250-499,70 +58,E12000005,500-999,40 +58,E12000005,1000-4999,40 +58,E12000005,5000+,15 +58,E12000006,0-49,250 +58,E12000006,50-99,210 +58,E12000006,100-249,370 +58,E12000006,250-499,140 +58,E12000006,500-999,75 +58,E12000006,1000-4999,90 +58,E12000006,5000+,35 +58,E12000007,0-49,930 +58,E12000007,50-99,795 +58,E12000007,100-249,1120 +58,E12000007,250-499,475 +58,E12000007,500-999,300 +58,E12000007,1000-4999,390 +58,E12000007,5000+,230 +58,E12000008,0-49,465 +58,E12000008,50-99,415 +58,E12000008,100-249,635 +58,E12000008,250-499,285 +58,E12000008,500-999,145 +58,E12000008,1000-4999,175 +58,E12000008,5000+,55 +58,E12000009,0-49,220 +58,E12000009,50-99,225 +58,E12000009,100-249,325 +58,E12000009,250-499,135 +58,E12000009,500-999,75 +58,E12000009,1000-4999,75 +58,E12000009,5000+,20 +58,W92000004,0-49,75 +58,W92000004,50-99,55 +58,W92000004,100-249,80 +58,W92000004,250-499,50 +58,W92000004,500-999,10 +58,W92000004,1000-4999,10 +58,W92000004,5000+,0 +58,S92000003,0-49,115 +58,S92000003,50-99,135 +58,S92000003,100-249,155 +58,S92000003,250-499,60 +58,S92000003,500-999,30 +58,S92000003,1000-4999,40 +58,S92000003,5000+,10 +58,N92000002,0-49,20 +58,N92000002,50-99,30 +58,N92000002,100-249,30 +58,N92000002,250-499,20 +58,N92000002,500-999,20 +58,N92000002,1000-4999,10 +58,N92000002,5000+,5 +59,E12000001,0-49,65 +59,E12000001,50-99,80 +59,E12000001,100-249,100 +59,E12000001,250-499,25 +59,E12000001,500-999,5 +59,E12000001,1000-4999,5 +59,E12000001,5000+,0 +59,E12000002,0-49,275 +59,E12000002,50-99,525 +59,E12000002,100-249,720 +59,E12000002,250-499,160 +59,E12000002,500-999,60 +59,E12000002,1000-4999,60 +59,E12000002,5000+,10 +59,E12000003,0-49,170 +59,E12000003,50-99,260 +59,E12000003,100-249,440 +59,E12000003,250-499,100 +59,E12000003,500-999,40 +59,E12000003,1000-4999,45 +59,E12000003,5000+,10 +59,E12000004,0-49,135 +59,E12000004,50-99,245 +59,E12000004,100-249,290 +59,E12000004,250-499,65 +59,E12000004,500-999,35 +59,E12000004,1000-4999,20 +59,E12000004,5000+,10 +59,E12000005,0-49,200 +59,E12000005,50-99,285 +59,E12000005,100-249,390 +59,E12000005,250-499,110 +59,E12000005,500-999,40 +59,E12000005,1000-4999,25 +59,E12000005,5000+,0 +59,E12000006,0-49,385 +59,E12000006,50-99,800 +59,E12000006,100-249,1115 +59,E12000006,250-499,195 +59,E12000006,500-999,95 +59,E12000006,1000-4999,75 +59,E12000006,5000+,25 +59,E12000007,0-49,2865 +59,E12000007,50-99,3875 +59,E12000007,100-249,5285 +59,E12000007,250-499,1340 +59,E12000007,500-999,775 +59,E12000007,1000-4999,1155 +59,E12000007,5000+,640 +59,E12000008,0-49,965 +59,E12000008,50-99,1635 +59,E12000008,100-249,2395 +59,E12000008,250-499,475 +59,E12000008,500-999,235 +59,E12000008,1000-4999,200 +59,E12000008,5000+,40 +59,E12000009,0-49,425 +59,E12000009,50-99,615 +59,E12000009,100-249,810 +59,E12000009,250-499,210 +59,E12000009,500-999,90 +59,E12000009,1000-4999,65 +59,E12000009,5000+,30 +59,W92000004,0-49,165 +59,W92000004,50-99,250 +59,W92000004,100-249,355 +59,W92000004,250-499,75 +59,W92000004,500-999,30 +59,W92000004,1000-4999,35 +59,W92000004,5000+,15 +59,S92000003,0-49,255 +59,S92000003,50-99,355 +59,S92000003,100-249,400 +59,S92000003,250-499,85 +59,S92000003,500-999,35 +59,S92000003,1000-4999,50 +59,S92000003,5000+,10 +59,N92000002,0-49,65 +59,N92000002,50-99,90 +59,N92000002,100-249,150 +59,N92000002,250-499,50 +59,N92000002,500-999,20 +59,N92000002,1000-4999,25 +59,N92000002,5000+,10 +60,E12000001,0-49,5 +60,E12000001,50-99,10 +60,E12000001,100-249,15 +60,E12000001,250-499,5 +60,E12000001,500-999,5 +60,E12000001,1000-4999,0 +60,E12000001,5000+,0 +60,E12000002,0-49,25 +60,E12000002,50-99,50 +60,E12000002,100-249,65 +60,E12000002,250-499,20 +60,E12000002,500-999,5 +60,E12000002,1000-4999,5 +60,E12000002,5000+,0 +60,E12000003,0-49,20 +60,E12000003,50-99,20 +60,E12000003,100-249,50 +60,E12000003,250-499,10 +60,E12000003,500-999,5 +60,E12000003,1000-4999,5 +60,E12000003,5000+,0 +60,E12000004,0-49,10 +60,E12000004,50-99,25 +60,E12000004,100-249,35 +60,E12000004,250-499,10 +60,E12000004,500-999,0 +60,E12000004,1000-4999,5 +60,E12000004,5000+,0 +60,E12000005,0-49,20 +60,E12000005,50-99,30 +60,E12000005,100-249,30 +60,E12000005,250-499,10 +60,E12000005,500-999,5 +60,E12000005,1000-4999,5 +60,E12000005,5000+,0 +60,E12000006,0-49,30 +60,E12000006,50-99,25 +60,E12000006,100-249,75 +60,E12000006,250-499,20 +60,E12000006,500-999,5 +60,E12000006,1000-4999,5 +60,E12000006,5000+,5 +60,E12000007,0-49,105 +60,E12000007,50-99,140 +60,E12000007,100-249,290 +60,E12000007,250-499,95 +60,E12000007,500-999,45 +60,E12000007,1000-4999,60 +60,E12000007,5000+,55 +60,E12000008,0-49,55 +60,E12000008,50-99,95 +60,E12000008,100-249,155 +60,E12000008,250-499,40 +60,E12000008,500-999,30 +60,E12000008,1000-4999,15 +60,E12000008,5000+,5 +60,E12000009,0-49,20 +60,E12000009,50-99,40 +60,E12000009,100-249,50 +60,E12000009,250-499,10 +60,E12000009,500-999,5 +60,E12000009,1000-4999,0 +60,E12000009,5000+,0 +60,W92000004,0-49,15 +60,W92000004,50-99,20 +60,W92000004,100-249,30 +60,W92000004,250-499,10 +60,W92000004,500-999,5 +60,W92000004,1000-4999,0 +60,W92000004,5000+,0 +60,S92000003,0-49,20 +60,S92000003,50-99,25 +60,S92000003,100-249,30 +60,S92000003,250-499,10 +60,S92000003,500-999,5 +60,S92000003,1000-4999,5 +60,S92000003,5000+,5 +60,N92000002,0-49,5 +60,N92000002,50-99,5 +60,N92000002,100-249,0 +60,N92000002,250-499,0 +60,N92000002,500-999,5 +60,N92000002,1000-4999,0 +60,N92000002,5000+,0 +61,E12000001,0-49,25 +61,E12000001,50-99,30 +61,E12000001,100-249,55 +61,E12000001,250-499,45 +61,E12000001,500-999,25 +61,E12000001,1000-4999,20 +61,E12000001,5000+,5 +61,E12000002,0-49,100 +61,E12000002,50-99,115 +61,E12000002,100-249,190 +61,E12000002,250-499,180 +61,E12000002,500-999,90 +61,E12000002,1000-4999,105 +61,E12000002,5000+,50 +61,E12000003,0-49,70 +61,E12000003,50-99,60 +61,E12000003,100-249,125 +61,E12000003,250-499,80 +61,E12000003,500-999,60 +61,E12000003,1000-4999,60 +61,E12000003,5000+,30 +61,E12000004,0-49,80 +61,E12000004,50-99,75 +61,E12000004,100-249,130 +61,E12000004,250-499,100 +61,E12000004,500-999,45 +61,E12000004,1000-4999,55 +61,E12000004,5000+,20 +61,E12000005,0-49,85 +61,E12000005,50-99,100 +61,E12000005,100-249,165 +61,E12000005,250-499,130 +61,E12000005,500-999,75 +61,E12000005,1000-4999,70 +61,E12000005,5000+,30 +61,E12000006,0-49,125 +61,E12000006,50-99,115 +61,E12000006,100-249,215 +61,E12000006,250-499,160 +61,E12000006,500-999,95 +61,E12000006,1000-4999,100 +61,E12000006,5000+,40 +61,E12000007,0-49,240 +61,E12000007,50-99,195 +61,E12000007,100-249,350 +61,E12000007,250-499,300 +61,E12000007,500-999,225 +61,E12000007,1000-4999,205 +61,E12000007,5000+,170 +61,E12000008,0-49,180 +61,E12000008,50-99,190 +61,E12000008,100-249,360 +61,E12000008,250-499,225 +61,E12000008,500-999,130 +61,E12000008,1000-4999,165 +61,E12000008,5000+,135 +61,E12000009,0-49,90 +61,E12000009,50-99,90 +61,E12000009,100-249,140 +61,E12000009,250-499,100 +61,E12000009,500-999,55 +61,E12000009,1000-4999,65 +61,E12000009,5000+,35 +61,W92000004,0-49,35 +61,W92000004,50-99,35 +61,W92000004,100-249,55 +61,W92000004,250-499,30 +61,W92000004,500-999,20 +61,W92000004,1000-4999,20 +61,W92000004,5000+,15 +61,S92000003,0-49,65 +61,S92000003,50-99,50 +61,S92000003,100-249,90 +61,S92000003,250-499,55 +61,S92000003,500-999,35 +61,S92000003,1000-4999,45 +61,S92000003,5000+,15 +61,N92000002,0-49,15 +61,N92000002,50-99,10 +61,N92000002,100-249,25 +61,N92000002,250-499,25 +61,N92000002,500-999,15 +61,N92000002,1000-4999,15 +61,N92000002,5000+,5 +62,E12000001,0-49,360 +62,E12000001,50-99,560 +62,E12000001,100-249,745 +62,E12000001,250-499,140 +62,E12000001,500-999,105 +62,E12000001,1000-4999,120 +62,E12000001,5000+,40 +62,E12000002,0-49,1395 +62,E12000002,50-99,2645 +62,E12000002,100-249,3515 +62,E12000002,250-499,710 +62,E12000002,500-999,445 +62,E12000002,1000-4999,525 +62,E12000002,5000+,200 +62,E12000003,0-49,945 +62,E12000003,50-99,1585 +62,E12000003,100-249,2175 +62,E12000003,250-499,460 +62,E12000003,500-999,285 +62,E12000003,1000-4999,355 +62,E12000003,5000+,120 +62,E12000004,0-49,1015 +62,E12000004,50-99,1550 +62,E12000004,100-249,2155 +62,E12000004,250-499,475 +62,E12000004,500-999,305 +62,E12000004,1000-4999,335 +62,E12000004,5000+,110 +62,E12000005,0-49,1280 +62,E12000005,50-99,2215 +62,E12000005,100-249,2900 +62,E12000005,250-499,615 +62,E12000005,500-999,395 +62,E12000005,1000-4999,445 +62,E12000005,5000+,175 +62,E12000006,0-49,2050 +62,E12000006,50-99,3130 +62,E12000006,100-249,4500 +62,E12000006,250-499,910 +62,E12000006,500-999,555 +62,E12000006,1000-4999,585 +62,E12000006,5000+,210 +62,E12000007,0-49,6115 +62,E12000007,50-99,10000 +62,E12000007,100-249,12430 +62,E12000007,250-499,2645 +62,E12000007,500-999,1690 +62,E12000007,1000-4999,2315 +62,E12000007,5000+,1340 +62,E12000008,0-49,3950 +62,E12000008,50-99,6310 +62,E12000008,100-249,9585 +62,E12000008,250-499,1835 +62,E12000008,500-999,1025 +62,E12000008,1000-4999,1365 +62,E12000008,5000+,625 +62,E12000009,0-49,1565 +62,E12000009,50-99,2420 +62,E12000009,100-249,3265 +62,E12000009,250-499,655 +62,E12000009,500-999,420 +62,E12000009,1000-4999,505 +62,E12000009,5000+,190 +62,W92000004,0-49,490 +62,W92000004,50-99,730 +62,W92000004,100-249,895 +62,W92000004,250-499,180 +62,W92000004,500-999,105 +62,W92000004,1000-4999,120 +62,W92000004,5000+,25 +62,S92000003,0-49,870 +62,S92000003,50-99,1470 +62,S92000003,100-249,1810 +62,S92000003,250-499,350 +62,S92000003,500-999,210 +62,S92000003,1000-4999,250 +62,S92000003,5000+,95 +62,N92000002,0-49,220 +62,N92000002,50-99,375 +62,N92000002,100-249,475 +62,N92000002,250-499,125 +62,N92000002,500-999,85 +62,N92000002,1000-4999,125 +62,N92000002,5000+,40 +63,E12000001,0-49,35 +63,E12000001,50-99,80 +63,E12000001,100-249,45 +63,E12000001,250-499,20 +63,E12000001,500-999,15 +63,E12000001,1000-4999,15 +63,E12000001,5000+,0 +63,E12000002,0-49,95 +63,E12000002,50-99,210 +63,E12000002,100-249,205 +63,E12000002,250-499,65 +63,E12000002,500-999,35 +63,E12000002,1000-4999,50 +63,E12000002,5000+,10 +63,E12000003,0-49,65 +63,E12000003,50-99,110 +63,E12000003,100-249,110 +63,E12000003,250-499,35 +63,E12000003,500-999,20 +63,E12000003,1000-4999,20 +63,E12000003,5000+,10 +63,E12000004,0-49,60 +63,E12000004,50-99,120 +63,E12000004,100-249,100 +63,E12000004,250-499,35 +63,E12000004,500-999,30 +63,E12000004,1000-4999,20 +63,E12000004,5000+,5 +63,E12000005,0-49,70 +63,E12000005,50-99,125 +63,E12000005,100-249,140 +63,E12000005,250-499,40 +63,E12000005,500-999,30 +63,E12000005,1000-4999,30 +63,E12000005,5000+,10 +63,E12000006,0-49,125 +63,E12000006,50-99,230 +63,E12000006,100-249,235 +63,E12000006,250-499,80 +63,E12000006,500-999,80 +63,E12000006,1000-4999,65 +63,E12000006,5000+,15 +63,E12000007,0-49,485 +63,E12000007,50-99,775 +63,E12000007,100-249,615 +63,E12000007,250-499,245 +63,E12000007,500-999,195 +63,E12000007,1000-4999,230 +63,E12000007,5000+,190 +63,E12000008,0-49,270 +63,E12000008,50-99,390 +63,E12000008,100-249,355 +63,E12000008,250-499,105 +63,E12000008,500-999,95 +63,E12000008,1000-4999,105 +63,E12000008,5000+,35 +63,E12000009,0-49,120 +63,E12000009,50-99,145 +63,E12000009,100-249,170 +63,E12000009,250-499,55 +63,E12000009,500-999,50 +63,E12000009,1000-4999,35 +63,E12000009,5000+,15 +63,W92000004,0-49,35 +63,W92000004,50-99,55 +63,W92000004,100-249,40 +63,W92000004,250-499,15 +63,W92000004,500-999,10 +63,W92000004,1000-4999,5 +63,W92000004,5000+,5 +63,S92000003,0-49,75 +63,S92000003,50-99,115 +63,S92000003,100-249,115 +63,S92000003,250-499,25 +63,S92000003,500-999,15 +63,S92000003,1000-4999,15 +63,S92000003,5000+,5 +63,N92000002,0-49,15 +63,N92000002,50-99,25 +63,N92000002,100-249,20 +63,N92000002,250-499,5 +63,N92000002,500-999,5 +63,N92000002,1000-4999,10 +63,N92000002,5000+,5 +64,E12000001,0-49,250 +64,E12000001,50-99,30 +64,E12000001,100-249,75 +64,E12000001,250-499,55 +64,E12000001,500-999,25 +64,E12000001,1000-4999,15 +64,E12000001,5000+,10 +64,E12000002,0-49,1125 +64,E12000002,50-99,105 +64,E12000002,100-249,310 +64,E12000002,250-499,220 +64,E12000002,500-999,110 +64,E12000002,1000-4999,110 +64,E12000002,5000+,70 +64,E12000003,0-49,720 +64,E12000003,50-99,85 +64,E12000003,100-249,185 +64,E12000003,250-499,165 +64,E12000003,500-999,55 +64,E12000003,1000-4999,40 +64,E12000003,5000+,40 +64,E12000004,0-49,720 +64,E12000004,50-99,60 +64,E12000004,100-249,175 +64,E12000004,250-499,125 +64,E12000004,500-999,45 +64,E12000004,1000-4999,30 +64,E12000004,5000+,25 +64,E12000005,0-49,845 +64,E12000005,50-99,70 +64,E12000005,100-249,190 +64,E12000005,250-499,145 +64,E12000005,500-999,65 +64,E12000005,1000-4999,40 +64,E12000005,5000+,40 +64,E12000006,0-49,985 +64,E12000006,50-99,105 +64,E12000006,100-249,325 +64,E12000006,250-499,240 +64,E12000006,500-999,75 +64,E12000006,1000-4999,60 +64,E12000006,5000+,35 +64,E12000007,0-49,4765 +64,E12000007,50-99,295 +64,E12000007,100-249,935 +64,E12000007,250-499,705 +64,E12000007,500-999,380 +64,E12000007,1000-4999,485 +64,E12000007,5000+,560 +64,E12000008,0-49,1720 +64,E12000008,50-99,155 +64,E12000008,100-249,440 +64,E12000008,250-499,325 +64,E12000008,500-999,125 +64,E12000008,1000-4999,100 +64,E12000008,5000+,70 +64,E12000009,0-49,715 +64,E12000009,50-99,60 +64,E12000009,100-249,225 +64,E12000009,250-499,165 +64,E12000009,500-999,70 +64,E12000009,1000-4999,55 +64,E12000009,5000+,25 +64,W92000004,0-49,210 +64,W92000004,50-99,35 +64,W92000004,100-249,85 +64,W92000004,250-499,60 +64,W92000004,500-999,30 +64,W92000004,1000-4999,25 +64,W92000004,5000+,15 +64,S92000003,0-49,480 +64,S92000003,50-99,40 +64,S92000003,100-249,150 +64,S92000003,250-499,110 +64,S92000003,500-999,70 +64,S92000003,1000-4999,60 +64,S92000003,5000+,60 +64,N92000002,0-49,165 +64,N92000002,50-99,10 +64,N92000002,100-249,40 +64,N92000002,250-499,50 +64,N92000002,500-999,45 +64,N92000002,1000-4999,45 +64,N92000002,5000+,15 +65,E12000001,0-49,85 +65,E12000001,50-99,0 +65,E12000001,100-249,5 +65,E12000001,250-499,5 +65,E12000001,500-999,5 +65,E12000001,1000-4999,0 +65,E12000001,5000+,0 +65,E12000002,0-49,695 +65,E12000002,50-99,0 +65,E12000002,100-249,10 +65,E12000002,250-499,15 +65,E12000002,500-999,10 +65,E12000002,1000-4999,10 +65,E12000002,5000+,15 +65,E12000003,0-49,405 +65,E12000003,50-99,0 +65,E12000003,100-249,10 +65,E12000003,250-499,10 +65,E12000003,500-999,15 +65,E12000003,1000-4999,10 +65,E12000003,5000+,15 +65,E12000004,0-49,935 +65,E12000004,50-99,5 +65,E12000004,100-249,10 +65,E12000004,250-499,10 +65,E12000004,500-999,10 +65,E12000004,1000-4999,10 +65,E12000004,5000+,0 +65,E12000005,0-49,265 +65,E12000005,50-99,5 +65,E12000005,100-249,5 +65,E12000005,250-499,10 +65,E12000005,500-999,10 +65,E12000005,1000-4999,5 +65,E12000005,5000+,10 +65,E12000006,0-49,320 +65,E12000006,50-99,0 +65,E12000006,100-249,10 +65,E12000006,250-499,25 +65,E12000006,500-999,15 +65,E12000006,1000-4999,35 +65,E12000006,5000+,15 +65,E12000007,0-49,380 +65,E12000007,50-99,10 +65,E12000007,100-249,25 +65,E12000007,250-499,50 +65,E12000007,500-999,30 +65,E12000007,1000-4999,55 +65,E12000007,5000+,95 +65,E12000008,0-49,585 +65,E12000008,50-99,5 +65,E12000008,100-249,25 +65,E12000008,250-499,35 +65,E12000008,500-999,30 +65,E12000008,1000-4999,30 +65,E12000008,5000+,35 +65,E12000009,0-49,395 +65,E12000009,50-99,0 +65,E12000009,100-249,10 +65,E12000009,250-499,10 +65,E12000009,500-999,5 +65,E12000009,1000-4999,15 +65,E12000009,5000+,15 +65,W92000004,0-49,110 +65,W92000004,50-99,0 +65,W92000004,100-249,5 +65,W92000004,250-499,5 +65,W92000004,500-999,5 +65,W92000004,1000-4999,5 +65,W92000004,5000+,5 +65,S92000003,0-49,240 +65,S92000003,50-99,0 +65,S92000003,100-249,5 +65,S92000003,250-499,5 +65,S92000003,500-999,5 +65,S92000003,1000-4999,5 +65,S92000003,5000+,5 +65,N92000002,0-49,100 +65,N92000002,50-99,0 +65,N92000002,100-249,5 +65,N92000002,250-499,5 +65,N92000002,500-999,0 +65,N92000002,1000-4999,10 +65,N92000002,5000+,0 +66,E12000001,0-49,75 +66,E12000001,50-99,20 +66,E12000001,100-249,270 +66,E12000001,250-499,105 +66,E12000001,500-999,65 +66,E12000001,1000-4999,40 +66,E12000001,5000+,15 +66,E12000002,0-49,635 +66,E12000002,50-99,100 +66,E12000002,100-249,945 +66,E12000002,250-499,350 +66,E12000002,500-999,230 +66,E12000002,1000-4999,235 +66,E12000002,5000+,70 +66,E12000003,0-49,335 +66,E12000003,50-99,60 +66,E12000003,100-249,760 +66,E12000003,250-499,240 +66,E12000003,500-999,170 +66,E12000003,1000-4999,150 +66,E12000003,5000+,45 +66,E12000004,0-49,885 +66,E12000004,50-99,55 +66,E12000004,100-249,785 +66,E12000004,250-499,255 +66,E12000004,500-999,160 +66,E12000004,1000-4999,120 +66,E12000004,5000+,40 +66,E12000005,0-49,335 +66,E12000005,50-99,55 +66,E12000005,100-249,735 +66,E12000005,250-499,285 +66,E12000005,500-999,200 +66,E12000005,1000-4999,130 +66,E12000005,5000+,30 +66,E12000006,0-49,600 +66,E12000006,50-99,110 +66,E12000006,100-249,1255 +66,E12000006,250-499,425 +66,E12000006,500-999,290 +66,E12000006,1000-4999,175 +66,E12000006,5000+,75 +66,E12000007,0-49,1205 +66,E12000007,50-99,335 +66,E12000007,100-249,1905 +66,E12000007,250-499,865 +66,E12000007,500-999,750 +66,E12000007,1000-4999,1110 +66,E12000007,5000+,1125 +66,E12000008,0-49,825 +66,E12000008,50-99,155 +66,E12000008,100-249,1680 +66,E12000008,250-499,630 +66,E12000008,500-999,430 +66,E12000008,1000-4999,285 +66,E12000008,5000+,125 +66,E12000009,0-49,515 +66,E12000009,50-99,80 +66,E12000009,100-249,985 +66,E12000009,250-499,375 +66,E12000009,500-999,225 +66,E12000009,1000-4999,160 +66,E12000009,5000+,60 +66,W92000004,0-49,150 +66,W92000004,50-99,40 +66,W92000004,100-249,425 +66,W92000004,250-499,155 +66,W92000004,500-999,90 +66,W92000004,1000-4999,55 +66,W92000004,5000+,15 +66,S92000003,0-49,235 +66,S92000003,50-99,60 +66,S92000003,100-249,575 +66,S92000003,250-499,245 +66,S92000003,500-999,140 +66,S92000003,1000-4999,100 +66,S92000003,5000+,40 +66,N92000002,0-49,155 +66,N92000002,50-99,25 +66,N92000002,100-249,200 +66,N92000002,250-499,130 +66,N92000002,500-999,70 +66,N92000002,1000-4999,65 +66,N92000002,5000+,15 +68,E12000001,0-49,585 +68,E12000001,50-99,670 +68,E12000001,100-249,855 +68,E12000001,250-499,350 +68,E12000001,500-999,160 +68,E12000001,1000-4999,105 +68,E12000001,5000+,30 +68,E12000002,0-49,2560 +68,E12000002,50-99,2920 +68,E12000002,100-249,3560 +68,E12000002,250-499,1525 +68,E12000002,500-999,810 +68,E12000002,1000-4999,570 +68,E12000002,5000+,165 +68,E12000003,0-49,1900 +68,E12000003,50-99,2000 +68,E12000003,100-249,2325 +68,E12000003,250-499,950 +68,E12000003,500-999,515 +68,E12000003,1000-4999,370 +68,E12000003,5000+,95 +68,E12000004,0-49,1990 +68,E12000004,50-99,1885 +68,E12000004,100-249,2190 +68,E12000004,250-499,840 +68,E12000004,500-999,435 +68,E12000004,1000-4999,305 +68,E12000004,5000+,55 +68,E12000005,0-49,2330 +68,E12000005,50-99,2250 +68,E12000005,100-249,2590 +68,E12000005,250-499,1165 +68,E12000005,500-999,590 +68,E12000005,1000-4999,455 +68,E12000005,5000+,115 +68,E12000006,0-49,2455 +68,E12000006,50-99,2940 +68,E12000006,100-249,3460 +68,E12000006,250-499,1450 +68,E12000006,500-999,725 +68,E12000006,1000-4999,470 +68,E12000006,5000+,130 +68,E12000007,0-49,4425 +68,E12000007,50-99,7515 +68,E12000007,100-249,8880 +68,E12000007,250-499,4450 +68,E12000007,500-999,2730 +68,E12000007,1000-4999,2455 +68,E12000007,5000+,820 +68,E12000008,0-49,3400 +68,E12000008,50-99,4160 +68,E12000008,100-249,4840 +68,E12000008,250-499,2080 +68,E12000008,500-999,1070 +68,E12000008,1000-4999,785 +68,E12000008,5000+,175 +68,E12000009,0-49,2445 +68,E12000009,50-99,2415 +68,E12000009,100-249,2785 +68,E12000009,250-499,1205 +68,E12000009,500-999,580 +68,E12000009,1000-4999,420 +68,E12000009,5000+,100 +68,W92000004,0-49,850 +68,W92000004,50-99,870 +68,W92000004,100-249,1015 +68,W92000004,250-499,400 +68,W92000004,500-999,185 +68,W92000004,1000-4999,120 +68,W92000004,5000+,40 +68,S92000003,0-49,1555 +68,S92000003,50-99,1490 +68,S92000003,100-249,1855 +68,S92000003,250-499,845 +68,S92000003,500-999,490 +68,S92000003,1000-4999,345 +68,S92000003,5000+,130 +68,N92000002,0-49,765 +68,N92000002,50-99,530 +68,N92000002,100-249,645 +68,N92000002,250-499,290 +68,N92000002,500-999,160 +68,N92000002,1000-4999,130 +68,N92000002,5000+,20 +69,E12000001,0-49,155 +69,E12000001,50-99,300 +69,E12000001,100-249,585 +69,E12000001,250-499,190 +69,E12000001,500-999,120 +69,E12000001,1000-4999,110 +69,E12000001,5000+,30 +69,E12000002,0-49,880 +69,E12000002,50-99,1490 +69,E12000002,100-249,2855 +69,E12000002,250-499,1045 +69,E12000002,500-999,555 +69,E12000002,1000-4999,575 +69,E12000002,5000+,170 +69,E12000003,0-49,510 +69,E12000003,50-99,970 +69,E12000003,100-249,1640 +69,E12000003,250-499,520 +69,E12000003,500-999,290 +69,E12000003,1000-4999,320 +69,E12000003,5000+,90 +69,E12000004,0-49,475 +69,E12000004,50-99,855 +69,E12000004,100-249,1330 +69,E12000004,250-499,460 +69,E12000004,500-999,225 +69,E12000004,1000-4999,240 +69,E12000004,5000+,60 +69,E12000005,0-49,640 +69,E12000005,50-99,1160 +69,E12000005,100-249,1880 +69,E12000005,250-499,685 +69,E12000005,500-999,370 +69,E12000005,1000-4999,305 +69,E12000005,5000+,80 +69,E12000006,0-49,935 +69,E12000006,50-99,1485 +69,E12000006,100-249,2205 +69,E12000006,250-499,705 +69,E12000006,500-999,380 +69,E12000006,1000-4999,340 +69,E12000006,5000+,110 +69,E12000007,0-49,2710 +69,E12000007,50-99,4530 +69,E12000007,100-249,8105 +69,E12000007,250-499,3565 +69,E12000007,500-999,2030 +69,E12000007,1000-4999,1610 +69,E12000007,5000+,560 +69,E12000008,0-49,1520 +69,E12000008,50-99,2355 +69,E12000008,100-249,3350 +69,E12000008,250-499,1125 +69,E12000008,500-999,590 +69,E12000008,1000-4999,570 +69,E12000008,5000+,180 +69,E12000009,0-49,710 +69,E12000009,50-99,1185 +69,E12000009,100-249,1830 +69,E12000009,250-499,580 +69,E12000009,500-999,310 +69,E12000009,1000-4999,300 +69,E12000009,5000+,120 +69,W92000004,0-49,245 +69,W92000004,50-99,460 +69,W92000004,100-249,800 +69,W92000004,250-499,265 +69,W92000004,500-999,175 +69,W92000004,1000-4999,155 +69,W92000004,5000+,30 +69,S92000003,0-49,390 +69,S92000003,50-99,680 +69,S92000003,100-249,1140 +69,S92000003,250-499,590 +69,S92000003,500-999,335 +69,S92000003,1000-4999,300 +69,S92000003,5000+,75 +69,N92000002,0-49,130 +69,N92000002,50-99,265 +69,N92000002,100-249,595 +69,N92000002,250-499,340 +69,N92000002,500-999,215 +69,N92000002,1000-4999,155 +69,N92000002,5000+,25 +70,E12000001,0-49,450 +70,E12000001,50-99,550 +70,E12000001,100-249,1410 +70,E12000001,250-499,360 +70,E12000001,500-999,165 +70,E12000001,1000-4999,135 +70,E12000001,5000+,40 +70,E12000002,0-49,2065 +70,E12000002,50-99,2355 +70,E12000002,100-249,5860 +70,E12000002,250-499,1620 +70,E12000002,500-999,715 +70,E12000002,1000-4999,600 +70,E12000002,5000+,170 +70,E12000003,0-49,1420 +70,E12000003,50-99,1500 +70,E12000003,100-249,3680 +70,E12000003,250-499,1000 +70,E12000003,500-999,470 +70,E12000003,1000-4999,370 +70,E12000003,5000+,110 +70,E12000004,0-49,1465 +70,E12000004,50-99,1635 +70,E12000004,100-249,3785 +70,E12000004,250-499,1045 +70,E12000004,500-999,490 +70,E12000004,1000-4999,385 +70,E12000004,5000+,90 +70,E12000005,0-49,1785 +70,E12000005,50-99,1880 +70,E12000005,100-249,4410 +70,E12000005,250-499,1250 +70,E12000005,500-999,565 +70,E12000005,1000-4999,445 +70,E12000005,5000+,130 +70,E12000006,0-49,2610 +70,E12000006,50-99,2805 +70,E12000006,100-249,7080 +70,E12000006,250-499,1850 +70,E12000006,500-999,820 +70,E12000006,1000-4999,570 +70,E12000006,5000+,180 +70,E12000007,0-49,6995 +70,E12000007,50-99,6780 +70,E12000007,100-249,17500 +70,E12000007,250-499,5260 +70,E12000007,500-999,2805 +70,E12000007,1000-4999,2895 +70,E12000007,5000+,1250 +70,E12000008,0-49,5185 +70,E12000008,50-99,5730 +70,E12000008,100-249,13270 +70,E12000008,250-499,3510 +70,E12000008,500-999,1395 +70,E12000008,1000-4999,1165 +70,E12000008,5000+,350 +70,E12000009,0-49,2065 +70,E12000009,50-99,2175 +70,E12000009,100-249,5060 +70,E12000009,250-499,1400 +70,E12000009,500-999,595 +70,E12000009,1000-4999,460 +70,E12000009,5000+,125 +70,W92000004,0-49,615 +70,W92000004,50-99,640 +70,W92000004,100-249,1450 +70,W92000004,250-499,410 +70,W92000004,500-999,165 +70,W92000004,1000-4999,110 +70,W92000004,5000+,35 +70,S92000003,0-49,1275 +70,S92000003,50-99,1370 +70,S92000003,100-249,3290 +70,S92000003,250-499,830 +70,S92000003,500-999,380 +70,S92000003,1000-4999,280 +70,S92000003,5000+,100 +70,N92000002,0-49,270 +70,N92000002,50-99,310 +70,N92000002,100-249,630 +70,N92000002,250-499,245 +70,N92000002,500-999,150 +70,N92000002,1000-4999,85 +70,N92000002,5000+,25 +71,E12000001,0-49,315 +71,E12000001,50-99,1000 +71,E12000001,100-249,1270 +71,E12000001,250-499,265 +71,E12000001,500-999,135 +71,E12000001,1000-4999,160 +71,E12000001,5000+,60 +71,E12000002,0-49,810 +71,E12000002,50-99,2350 +71,E12000002,100-249,3050 +71,E12000002,250-499,745 +71,E12000002,500-999,450 +71,E12000002,1000-4999,525 +71,E12000002,5000+,205 +71,E12000003,0-49,535 +71,E12000003,50-99,1395 +71,E12000003,100-249,1925 +71,E12000003,250-499,540 +71,E12000003,500-999,325 +71,E12000003,1000-4999,370 +71,E12000003,5000+,120 +71,E12000004,0-49,540 +71,E12000004,50-99,1420 +71,E12000004,100-249,1835 +71,E12000004,250-499,585 +71,E12000004,500-999,310 +71,E12000004,1000-4999,360 +71,E12000004,5000+,115 +71,E12000005,0-49,640 +71,E12000005,50-99,1585 +71,E12000005,100-249,2095 +71,E12000005,250-499,600 +71,E12000005,500-999,365 +71,E12000005,1000-4999,420 +71,E12000005,5000+,135 +71,E12000006,0-49,850 +71,E12000006,50-99,1985 +71,E12000006,100-249,2805 +71,E12000006,250-499,825 +71,E12000006,500-999,505 +71,E12000006,1000-4999,530 +71,E12000006,5000+,190 +71,E12000007,0-49,1415 +71,E12000007,50-99,3475 +71,E12000007,100-249,4270 +71,E12000007,250-499,1250 +71,E12000007,500-999,745 +71,E12000007,1000-4999,895 +71,E12000007,5000+,450 +71,E12000008,0-49,1430 +71,E12000008,50-99,3325 +71,E12000008,100-249,4930 +71,E12000008,250-499,1290 +71,E12000008,500-999,690 +71,E12000008,1000-4999,845 +71,E12000008,5000+,285 +71,E12000009,0-49,790 +71,E12000009,50-99,1780 +71,E12000009,100-249,2565 +71,E12000009,250-499,790 +71,E12000009,500-999,405 +71,E12000009,1000-4999,395 +71,E12000009,5000+,135 +71,W92000004,0-49,285 +71,W92000004,50-99,685 +71,W92000004,100-249,1005 +71,W92000004,250-499,245 +71,W92000004,500-999,170 +71,W92000004,1000-4999,160 +71,W92000004,5000+,50 +71,S92000003,0-49,935 +71,S92000003,50-99,2055 +71,S92000003,100-249,3175 +71,S92000003,250-499,700 +71,S92000003,500-999,360 +71,S92000003,1000-4999,410 +71,S92000003,5000+,185 +71,N92000002,0-49,220 +71,N92000002,50-99,435 +71,N92000002,100-249,585 +71,N92000002,250-499,225 +71,N92000002,500-999,115 +71,N92000002,1000-4999,110 +71,N92000002,5000+,30 +72,E12000001,0-49,35 +72,E12000001,50-99,25 +72,E12000001,100-249,30 +72,E12000001,250-499,15 +72,E12000001,500-999,5 +72,E12000001,1000-4999,15 +72,E12000001,5000+,5 +72,E12000002,0-49,130 +72,E12000002,50-99,75 +72,E12000002,100-249,100 +72,E12000002,250-499,40 +72,E12000002,500-999,25 +72,E12000002,1000-4999,40 +72,E12000002,5000+,20 +72,E12000003,0-49,65 +72,E12000003,50-99,35 +72,E12000003,100-249,65 +72,E12000003,250-499,20 +72,E12000003,500-999,15 +72,E12000003,1000-4999,30 +72,E12000003,5000+,15 +72,E12000004,0-49,80 +72,E12000004,50-99,45 +72,E12000004,100-249,65 +72,E12000004,250-499,25 +72,E12000004,500-999,15 +72,E12000004,1000-4999,30 +72,E12000004,5000+,15 +72,E12000005,0-49,75 +72,E12000005,50-99,50 +72,E12000005,100-249,75 +72,E12000005,250-499,35 +72,E12000005,500-999,25 +72,E12000005,1000-4999,25 +72,E12000005,5000+,15 +72,E12000006,0-49,220 +72,E12000006,50-99,120 +72,E12000006,100-249,220 +72,E12000006,250-499,90 +72,E12000006,500-999,60 +72,E12000006,1000-4999,95 +72,E12000006,5000+,90 +72,E12000007,0-49,310 +72,E12000007,50-99,220 +72,E12000007,100-249,300 +72,E12000007,250-499,165 +72,E12000007,500-999,110 +72,E12000007,1000-4999,140 +72,E12000007,5000+,90 +72,E12000008,0-49,250 +72,E12000008,50-99,165 +72,E12000008,100-249,275 +72,E12000008,250-499,115 +72,E12000008,500-999,95 +72,E12000008,1000-4999,115 +72,E12000008,5000+,115 +72,E12000009,0-49,120 +72,E12000009,50-99,60 +72,E12000009,100-249,130 +72,E12000009,250-499,50 +72,E12000009,500-999,20 +72,E12000009,1000-4999,35 +72,E12000009,5000+,25 +72,W92000004,0-49,45 +72,W92000004,50-99,30 +72,W92000004,100-249,55 +72,W92000004,250-499,20 +72,W92000004,500-999,15 +72,W92000004,1000-4999,20 +72,W92000004,5000+,10 +72,S92000003,0-49,115 +72,S92000003,50-99,70 +72,S92000003,100-249,95 +72,S92000003,250-499,35 +72,S92000003,500-999,35 +72,S92000003,1000-4999,40 +72,S92000003,5000+,25 +72,N92000002,0-49,25 +72,N92000002,50-99,10 +72,N92000002,100-249,35 +72,N92000002,250-499,10 +72,N92000002,500-999,5 +72,N92000002,1000-4999,10 +72,N92000002,5000+,5 +73,E12000001,0-49,55 +73,E12000001,50-99,70 +73,E12000001,100-249,175 +73,E12000001,250-499,65 +73,E12000001,500-999,30 +73,E12000001,1000-4999,35 +73,E12000001,5000+,10 +73,E12000002,0-49,275 +73,E12000002,50-99,335 +73,E12000002,100-249,920 +73,E12000002,250-499,340 +73,E12000002,500-999,210 +73,E12000002,1000-4999,180 +73,E12000002,5000+,55 +73,E12000003,0-49,160 +73,E12000003,50-99,200 +73,E12000003,100-249,520 +73,E12000003,250-499,175 +73,E12000003,500-999,105 +73,E12000003,1000-4999,130 +73,E12000003,5000+,35 +73,E12000004,0-49,145 +73,E12000004,50-99,175 +73,E12000004,100-249,415 +73,E12000004,250-499,160 +73,E12000004,500-999,75 +73,E12000004,1000-4999,70 +73,E12000004,5000+,15 +73,E12000005,0-49,175 +73,E12000005,50-99,215 +73,E12000005,100-249,580 +73,E12000005,250-499,165 +73,E12000005,500-999,120 +73,E12000005,1000-4999,85 +73,E12000005,5000+,25 +73,E12000006,0-49,340 +73,E12000006,50-99,395 +73,E12000006,100-249,900 +73,E12000006,250-499,340 +73,E12000006,500-999,150 +73,E12000006,1000-4999,150 +73,E12000006,5000+,35 +73,E12000007,0-49,1115 +73,E12000007,50-99,1085 +73,E12000007,100-249,2880 +73,E12000007,250-499,870 +73,E12000007,500-999,575 +73,E12000007,1000-4999,865 +73,E12000007,5000+,565 +73,E12000008,0-49,550 +73,E12000008,50-99,680 +73,E12000008,100-249,1670 +73,E12000008,250-499,490 +73,E12000008,500-999,275 +73,E12000008,1000-4999,310 +73,E12000008,5000+,115 +73,E12000009,0-49,260 +73,E12000009,50-99,295 +73,E12000009,100-249,660 +73,E12000009,250-499,245 +73,E12000009,500-999,120 +73,E12000009,1000-4999,120 +73,E12000009,5000+,50 +73,W92000004,0-49,75 +73,W92000004,50-99,70 +73,W92000004,100-249,160 +73,W92000004,250-499,65 +73,W92000004,500-999,35 +73,W92000004,1000-4999,35 +73,W92000004,5000+,0 +73,S92000003,0-49,115 +73,S92000003,50-99,125 +73,S92000003,100-249,330 +73,S92000003,250-499,105 +73,S92000003,500-999,50 +73,S92000003,1000-4999,60 +73,S92000003,5000+,20 +73,N92000002,0-49,40 +73,N92000002,50-99,45 +73,N92000002,100-249,90 +73,N92000002,250-499,35 +73,N92000002,500-999,25 +73,N92000002,1000-4999,20 +73,N92000002,5000+,5 +74,E12000001,0-49,225 +74,E12000001,50-99,490 +74,E12000001,100-249,870 +74,E12000001,250-499,170 +74,E12000001,500-999,85 +74,E12000001,1000-4999,60 +74,E12000001,5000+,15 +74,E12000002,0-49,685 +74,E12000002,50-99,1780 +74,E12000002,100-249,2760 +74,E12000002,250-499,620 +74,E12000002,500-999,305 +74,E12000002,1000-4999,260 +74,E12000002,5000+,75 +74,E12000003,0-49,505 +74,E12000003,50-99,1105 +74,E12000003,100-249,1985 +74,E12000003,250-499,400 +74,E12000003,500-999,220 +74,E12000003,1000-4999,170 +74,E12000003,5000+,40 +74,E12000004,0-49,560 +74,E12000004,50-99,1075 +74,E12000004,100-249,1765 +74,E12000004,250-499,340 +74,E12000004,500-999,190 +74,E12000004,1000-4999,155 +74,E12000004,5000+,35 +74,E12000005,0-49,550 +74,E12000005,50-99,1220 +74,E12000005,100-249,1980 +74,E12000005,250-499,430 +74,E12000005,500-999,245 +74,E12000005,1000-4999,170 +74,E12000005,5000+,40 +74,E12000006,0-49,880 +74,E12000006,50-99,1880 +74,E12000006,100-249,3045 +74,E12000006,250-499,575 +74,E12000006,500-999,315 +74,E12000006,1000-4999,270 +74,E12000006,5000+,55 +74,E12000007,0-49,2685 +74,E12000007,50-99,4680 +74,E12000007,100-249,7905 +74,E12000007,250-499,1650 +74,E12000007,500-999,975 +74,E12000007,1000-4999,975 +74,E12000007,5000+,300 +74,E12000008,0-49,1640 +74,E12000008,50-99,3270 +74,E12000008,100-249,5315 +74,E12000008,250-499,1115 +74,E12000008,500-999,550 +74,E12000008,1000-4999,465 +74,E12000008,5000+,100 +74,E12000009,0-49,890 +74,E12000009,50-99,1560 +74,E12000009,100-249,2685 +74,E12000009,250-499,550 +74,E12000009,500-999,285 +74,E12000009,1000-4999,210 +74,E12000009,5000+,40 +74,W92000004,0-49,255 +74,W92000004,50-99,555 +74,W92000004,100-249,980 +74,W92000004,250-499,195 +74,W92000004,500-999,95 +74,W92000004,1000-4999,80 +74,W92000004,5000+,15 +74,S92000003,0-49,540 +74,S92000003,50-99,1150 +74,S92000003,100-249,1790 +74,S92000003,250-499,445 +74,S92000003,500-999,200 +74,S92000003,1000-4999,150 +74,S92000003,5000+,25 +74,N92000002,0-49,120 +74,N92000002,50-99,215 +74,N92000002,100-249,455 +74,N92000002,250-499,130 +74,N92000002,500-999,45 +74,N92000002,1000-4999,35 +74,N92000002,5000+,0 +75,E12000001,0-49,10 +75,E12000001,50-99,15 +75,E12000001,100-249,15 +75,E12000001,250-499,10 +75,E12000001,500-999,5 +75,E12000001,1000-4999,25 +75,E12000001,5000+,0 +75,E12000002,0-49,20 +75,E12000002,50-99,85 +75,E12000002,100-249,60 +75,E12000002,250-499,45 +75,E12000002,500-999,55 +75,E12000002,1000-4999,60 +75,E12000002,5000+,10 +75,E12000003,0-49,25 +75,E12000003,50-99,45 +75,E12000003,100-249,55 +75,E12000003,250-499,25 +75,E12000003,500-999,30 +75,E12000003,1000-4999,50 +75,E12000003,5000+,20 +75,E12000004,0-49,20 +75,E12000004,50-99,50 +75,E12000004,100-249,70 +75,E12000004,250-499,30 +75,E12000004,500-999,30 +75,E12000004,1000-4999,40 +75,E12000004,5000+,5 +75,E12000005,0-49,25 +75,E12000005,50-99,65 +75,E12000005,100-249,60 +75,E12000005,250-499,20 +75,E12000005,500-999,40 +75,E12000005,1000-4999,55 +75,E12000005,5000+,10 +75,E12000006,0-49,20 +75,E12000006,50-99,95 +75,E12000006,100-249,100 +75,E12000006,250-499,40 +75,E12000006,500-999,80 +75,E12000006,1000-4999,115 +75,E12000006,5000+,5 +75,E12000007,0-49,25 +75,E12000007,50-99,100 +75,E12000007,100-249,70 +75,E12000007,250-499,30 +75,E12000007,500-999,40 +75,E12000007,1000-4999,40 +75,E12000007,5000+,5 +75,E12000008,0-49,40 +75,E12000008,50-99,130 +75,E12000008,100-249,160 +75,E12000008,250-499,80 +75,E12000008,500-999,65 +75,E12000008,1000-4999,110 +75,E12000008,5000+,15 +75,E12000009,0-49,45 +75,E12000009,50-99,95 +75,E12000009,100-249,110 +75,E12000009,250-499,65 +75,E12000009,500-999,70 +75,E12000009,1000-4999,95 +75,E12000009,5000+,20 +75,W92000004,0-49,10 +75,W92000004,50-99,35 +75,W92000004,100-249,45 +75,W92000004,250-499,15 +75,W92000004,500-999,25 +75,W92000004,1000-4999,50 +75,W92000004,5000+,5 +75,S92000003,0-49,30 +75,S92000003,50-99,45 +75,S92000003,100-249,55 +75,S92000003,250-499,25 +75,S92000003,500-999,50 +75,S92000003,1000-4999,70 +75,S92000003,5000+,5 +75,N92000002,0-49,15 +75,N92000002,50-99,20 +75,N92000002,100-249,15 +75,N92000002,250-499,15 +75,N92000002,500-999,20 +75,N92000002,1000-4999,30 +75,N92000002,5000+,5 +77,E12000001,0-49,95 +77,E12000001,50-99,70 +77,E12000001,100-249,115 +77,E12000001,250-499,75 +77,E12000001,500-999,60 +77,E12000001,1000-4999,75 +77,E12000001,5000+,20 +77,E12000002,0-49,275 +77,E12000002,50-99,250 +77,E12000002,100-249,440 +77,E12000002,250-499,285 +77,E12000002,500-999,230 +77,E12000002,1000-4999,280 +77,E12000002,5000+,130 +77,E12000003,0-49,245 +77,E12000003,50-99,200 +77,E12000003,100-249,320 +77,E12000003,250-499,220 +77,E12000003,500-999,150 +77,E12000003,1000-4999,220 +77,E12000003,5000+,85 +77,E12000004,0-49,235 +77,E12000004,50-99,190 +77,E12000004,100-249,285 +77,E12000004,250-499,170 +77,E12000004,500-999,160 +77,E12000004,1000-4999,175 +77,E12000004,5000+,65 +77,E12000005,0-49,260 +77,E12000005,50-99,225 +77,E12000005,100-249,395 +77,E12000005,250-499,260 +77,E12000005,500-999,185 +77,E12000005,1000-4999,235 +77,E12000005,5000+,110 +77,E12000006,0-49,315 +77,E12000006,50-99,285 +77,E12000006,100-249,460 +77,E12000006,250-499,290 +77,E12000006,500-999,195 +77,E12000006,1000-4999,300 +77,E12000006,5000+,115 +77,E12000007,0-49,420 +77,E12000007,50-99,325 +77,E12000007,100-249,520 +77,E12000007,250-499,475 +77,E12000007,500-999,315 +77,E12000007,1000-4999,365 +77,E12000007,5000+,155 +77,E12000008,0-49,445 +77,E12000008,50-99,400 +77,E12000008,100-249,630 +77,E12000008,250-499,410 +77,E12000008,500-999,315 +77,E12000008,1000-4999,370 +77,E12000008,5000+,145 +77,E12000009,0-49,260 +77,E12000009,50-99,255 +77,E12000009,100-249,415 +77,E12000009,250-499,225 +77,E12000009,500-999,170 +77,E12000009,1000-4999,200 +77,E12000009,5000+,65 +77,W92000004,0-49,170 +77,W92000004,50-99,130 +77,W92000004,100-249,190 +77,W92000004,250-499,130 +77,W92000004,500-999,100 +77,W92000004,1000-4999,100 +77,W92000004,5000+,20 +77,S92000003,0-49,180 +77,S92000003,50-99,175 +77,S92000003,100-249,275 +77,S92000003,250-499,200 +77,S92000003,500-999,155 +77,S92000003,1000-4999,175 +77,S92000003,5000+,75 +77,N92000002,0-49,125 +77,N92000002,50-99,100 +77,N92000002,100-249,155 +77,N92000002,250-499,80 +77,N92000002,500-999,65 +77,N92000002,1000-4999,70 +77,N92000002,5000+,20 +78,E12000001,0-49,60 +78,E12000001,50-99,70 +78,E12000001,100-249,140 +78,E12000001,250-499,80 +78,E12000001,500-999,55 +78,E12000001,1000-4999,90 +78,E12000001,5000+,55 +78,E12000002,0-49,335 +78,E12000002,50-99,425 +78,E12000002,100-249,830 +78,E12000002,250-499,400 +78,E12000002,500-999,325 +78,E12000002,1000-4999,480 +78,E12000002,5000+,215 +78,E12000003,0-49,190 +78,E12000003,50-99,260 +78,E12000003,100-249,535 +78,E12000003,250-499,275 +78,E12000003,500-999,235 +78,E12000003,1000-4999,305 +78,E12000003,5000+,110 +78,E12000004,0-49,160 +78,E12000004,50-99,210 +78,E12000004,100-249,385 +78,E12000004,250-499,485 +78,E12000004,500-999,170 +78,E12000004,1000-4999,275 +78,E12000004,5000+,100 +78,E12000005,0-49,255 +78,E12000005,50-99,375 +78,E12000005,100-249,710 +78,E12000005,250-499,405 +78,E12000005,500-999,300 +78,E12000005,1000-4999,450 +78,E12000005,5000+,170 +78,E12000006,0-49,410 +78,E12000006,50-99,520 +78,E12000006,100-249,1020 +78,E12000006,250-499,480 +78,E12000006,500-999,355 +78,E12000006,1000-4999,575 +78,E12000006,5000+,225 +78,E12000007,0-49,930 +78,E12000007,50-99,995 +78,E12000007,100-249,2885 +78,E12000007,250-499,1205 +78,E12000007,500-999,970 +78,E12000007,1000-4999,1265 +78,E12000007,5000+,665 +78,E12000008,0-49,605 +78,E12000008,50-99,775 +78,E12000008,100-249,1645 +78,E12000008,250-499,680 +78,E12000008,500-999,510 +78,E12000008,1000-4999,740 +78,E12000008,5000+,320 +78,E12000009,0-49,215 +78,E12000009,50-99,285 +78,E12000009,100-249,610 +78,E12000009,250-499,275 +78,E12000009,500-999,225 +78,E12000009,1000-4999,325 +78,E12000009,5000+,125 +78,W92000004,0-49,70 +78,W92000004,50-99,100 +78,W92000004,100-249,165 +78,W92000004,250-499,75 +78,W92000004,500-999,55 +78,W92000004,1000-4999,105 +78,W92000004,5000+,50 +78,S92000003,0-49,130 +78,S92000003,50-99,155 +78,S92000003,100-249,305 +78,S92000003,250-499,135 +78,S92000003,500-999,95 +78,S92000003,1000-4999,195 +78,S92000003,5000+,90 +78,N92000002,0-49,25 +78,N92000002,50-99,40 +78,N92000002,100-249,70 +78,N92000002,250-499,40 +78,N92000002,500-999,30 +78,N92000002,1000-4999,50 +78,N92000002,5000+,30 +79,E12000001,0-49,30 +79,E12000001,50-99,25 +79,E12000001,100-249,30 +79,E12000001,250-499,30 +79,E12000001,500-999,30 +79,E12000001,1000-4999,20 +79,E12000001,5000+,10 +79,E12000002,0-49,140 +79,E12000002,50-99,95 +79,E12000002,100-249,190 +79,E12000002,250-499,165 +79,E12000002,500-999,115 +79,E12000002,1000-4999,100 +79,E12000002,5000+,55 +79,E12000003,0-49,125 +79,E12000003,50-99,70 +79,E12000003,100-249,105 +79,E12000003,250-499,145 +79,E12000003,500-999,80 +79,E12000003,1000-4999,60 +79,E12000003,5000+,15 +79,E12000004,0-49,95 +79,E12000004,50-99,40 +79,E12000004,100-249,105 +79,E12000004,250-499,90 +79,E12000004,500-999,50 +79,E12000004,1000-4999,45 +79,E12000004,5000+,20 +79,E12000005,0-49,110 +79,E12000005,50-99,75 +79,E12000005,100-249,110 +79,E12000005,250-499,130 +79,E12000005,500-999,90 +79,E12000005,1000-4999,85 +79,E12000005,5000+,35 +79,E12000006,0-49,145 +79,E12000006,50-99,65 +79,E12000006,100-249,165 +79,E12000006,250-499,130 +79,E12000006,500-999,95 +79,E12000006,1000-4999,75 +79,E12000006,5000+,35 +79,E12000007,0-49,355 +79,E12000007,50-99,245 +79,E12000007,100-249,575 +79,E12000007,250-499,605 +79,E12000007,500-999,365 +79,E12000007,1000-4999,420 +79,E12000007,5000+,260 +79,E12000008,0-49,235 +79,E12000008,50-99,130 +79,E12000008,100-249,295 +79,E12000008,250-499,235 +79,E12000008,500-999,145 +79,E12000008,1000-4999,175 +79,E12000008,5000+,80 +79,E12000009,0-49,135 +79,E12000009,50-99,80 +79,E12000009,100-249,165 +79,E12000009,250-499,125 +79,E12000009,500-999,60 +79,E12000009,1000-4999,80 +79,E12000009,5000+,30 +79,W92000004,0-49,55 +79,W92000004,50-99,25 +79,W92000004,100-249,65 +79,W92000004,250-499,50 +79,W92000004,500-999,35 +79,W92000004,1000-4999,35 +79,W92000004,5000+,5 +79,S92000003,0-49,115 +79,S92000003,50-99,60 +79,S92000003,100-249,175 +79,S92000003,250-499,145 +79,S92000003,500-999,90 +79,S92000003,1000-4999,60 +79,S92000003,5000+,25 +79,N92000002,0-49,15 +79,N92000002,50-99,20 +79,N92000002,100-249,35 +79,N92000002,250-499,20 +79,N92000002,500-999,10 +79,N92000002,1000-4999,15 +79,N92000002,5000+,10 +80,E12000001,0-49,15 +80,E12000001,50-99,40 +80,E12000001,100-249,120 +80,E12000001,250-499,35 +80,E12000001,500-999,20 +80,E12000001,1000-4999,35 +80,E12000001,5000+,10 +80,E12000002,0-49,85 +80,E12000002,50-99,215 +80,E12000002,100-249,430 +80,E12000002,250-499,160 +80,E12000002,500-999,115 +80,E12000002,1000-4999,110 +80,E12000002,5000+,45 +80,E12000003,0-49,50 +80,E12000003,50-99,105 +80,E12000003,100-249,255 +80,E12000003,250-499,95 +80,E12000003,500-999,80 +80,E12000003,1000-4999,80 +80,E12000003,5000+,25 +80,E12000004,0-49,60 +80,E12000004,50-99,125 +80,E12000004,100-249,260 +80,E12000004,250-499,90 +80,E12000004,500-999,60 +80,E12000004,1000-4999,65 +80,E12000004,5000+,20 +80,E12000005,0-49,85 +80,E12000005,50-99,145 +80,E12000005,100-249,355 +80,E12000005,250-499,115 +80,E12000005,500-999,75 +80,E12000005,1000-4999,115 +80,E12000005,5000+,25 +80,E12000006,0-49,130 +80,E12000006,50-99,195 +80,E12000006,100-249,505 +80,E12000006,250-499,195 +80,E12000006,500-999,100 +80,E12000006,1000-4999,135 +80,E12000006,5000+,35 +80,E12000007,0-49,235 +80,E12000007,50-99,395 +80,E12000007,100-249,1185 +80,E12000007,250-499,330 +80,E12000007,500-999,220 +80,E12000007,1000-4999,235 +80,E12000007,5000+,85 +80,E12000008,0-49,165 +80,E12000008,50-99,265 +80,E12000008,100-249,690 +80,E12000008,250-499,215 +80,E12000008,500-999,155 +80,E12000008,1000-4999,195 +80,E12000008,5000+,55 +80,E12000009,0-49,65 +80,E12000009,50-99,120 +80,E12000009,100-249,255 +80,E12000009,250-499,105 +80,E12000009,500-999,65 +80,E12000009,1000-4999,85 +80,E12000009,5000+,15 +80,W92000004,0-49,30 +80,W92000004,50-99,55 +80,W92000004,100-249,115 +80,W92000004,250-499,60 +80,W92000004,500-999,20 +80,W92000004,1000-4999,45 +80,W92000004,5000+,0 +80,S92000003,0-49,35 +80,S92000003,50-99,90 +80,S92000003,100-249,150 +80,S92000003,250-499,50 +80,S92000003,500-999,30 +80,S92000003,1000-4999,40 +80,S92000003,5000+,10 +80,N92000002,0-49,10 +80,N92000002,50-99,25 +80,N92000002,100-249,45 +80,N92000002,250-499,20 +80,N92000002,500-999,15 +80,N92000002,1000-4999,15 +80,N92000002,5000+,5 +81,E12000001,0-49,180 +81,E12000001,50-99,320 +81,E12000001,100-249,575 +81,E12000001,250-499,215 +81,E12000001,500-999,90 +81,E12000001,1000-4999,70 +81,E12000001,5000+,20 +81,E12000002,0-49,630 +81,E12000002,50-99,1075 +81,E12000002,100-249,2170 +81,E12000002,250-499,700 +81,E12000002,500-999,320 +81,E12000002,1000-4999,225 +81,E12000002,5000+,75 +81,E12000003,0-49,490 +81,E12000003,50-99,750 +81,E12000003,100-249,1415 +81,E12000003,250-499,495 +81,E12000003,500-999,215 +81,E12000003,1000-4999,165 +81,E12000003,5000+,35 +81,E12000004,0-49,455 +81,E12000004,50-99,720 +81,E12000004,100-249,1495 +81,E12000004,250-499,450 +81,E12000004,500-999,190 +81,E12000004,1000-4999,185 +81,E12000004,5000+,30 +81,E12000005,0-49,560 +81,E12000005,50-99,845 +81,E12000005,100-249,1590 +81,E12000005,250-499,555 +81,E12000005,500-999,255 +81,E12000005,1000-4999,220 +81,E12000005,5000+,45 +81,E12000006,0-49,775 +81,E12000006,50-99,1225 +81,E12000006,100-249,2505 +81,E12000006,250-499,825 +81,E12000006,500-999,400 +81,E12000006,1000-4999,350 +81,E12000006,5000+,85 +81,E12000007,0-49,1380 +81,E12000007,50-99,1545 +81,E12000007,100-249,2495 +81,E12000007,250-499,1045 +81,E12000007,500-999,490 +81,E12000007,1000-4999,430 +81,E12000007,5000+,155 +81,E12000008,0-49,1155 +81,E12000008,50-99,1845 +81,E12000008,100-249,4055 +81,E12000008,250-499,1335 +81,E12000008,500-999,635 +81,E12000008,1000-4999,495 +81,E12000008,5000+,125 +81,E12000009,0-49,635 +81,E12000009,50-99,1130 +81,E12000009,100-249,2295 +81,E12000009,250-499,745 +81,E12000009,500-999,285 +81,E12000009,1000-4999,220 +81,E12000009,5000+,40 +81,W92000004,0-49,425 +81,W92000004,50-99,525 +81,W92000004,100-249,895 +81,W92000004,250-499,330 +81,W92000004,500-999,125 +81,W92000004,1000-4999,90 +81,W92000004,5000+,15 +81,S92000003,0-49,435 +81,S92000003,50-99,775 +81,S92000003,100-249,1500 +81,S92000003,250-499,530 +81,S92000003,500-999,230 +81,S92000003,1000-4999,220 +81,S92000003,5000+,55 +81,N92000002,0-49,180 +81,N92000002,50-99,210 +81,N92000002,100-249,385 +81,N92000002,250-499,155 +81,N92000002,500-999,55 +81,N92000002,1000-4999,45 +81,N92000002,5000+,15 +82,E12000001,0-49,180 +82,E12000001,50-99,335 +82,E12000001,100-249,850 +82,E12000001,250-499,600 +82,E12000001,500-999,280 +82,E12000001,1000-4999,215 +82,E12000001,5000+,40 +82,E12000002,0-49,855 +82,E12000002,50-99,1310 +82,E12000002,100-249,3425 +82,E12000002,250-499,2065 +82,E12000002,500-999,1160 +82,E12000002,1000-4999,990 +82,E12000002,5000+,190 +82,E12000003,0-49,500 +82,E12000003,50-99,845 +82,E12000003,100-249,1905 +82,E12000003,250-499,1370 +82,E12000003,500-999,760 +82,E12000003,1000-4999,570 +82,E12000003,5000+,120 +82,E12000004,0-49,520 +82,E12000004,50-99,900 +82,E12000004,100-249,1890 +82,E12000004,250-499,1205 +82,E12000004,500-999,650 +82,E12000004,1000-4999,470 +82,E12000004,5000+,105 +82,E12000005,0-49,700 +82,E12000005,50-99,1390 +82,E12000005,100-249,2560 +82,E12000005,250-499,1670 +82,E12000005,500-999,925 +82,E12000005,1000-4999,735 +82,E12000005,5000+,130 +82,E12000006,0-49,870 +82,E12000006,50-99,1105 +82,E12000006,100-249,3330 +82,E12000006,250-499,1905 +82,E12000006,500-999,955 +82,E12000006,1000-4999,735 +82,E12000006,5000+,160 +82,E12000007,0-49,2825 +82,E12000007,50-99,2215 +82,E12000007,100-249,8605 +82,E12000007,250-499,5275 +82,E12000007,500-999,2405 +82,E12000007,1000-4999,2405 +82,E12000007,5000+,775 +82,E12000008,0-49,1710 +82,E12000008,50-99,1785 +82,E12000008,100-249,5460 +82,E12000008,250-499,3160 +82,E12000008,500-999,1470 +82,E12000008,1000-4999,1330 +82,E12000008,5000+,270 +82,E12000009,0-49,710 +82,E12000009,50-99,895 +82,E12000009,100-249,2275 +82,E12000009,250-499,1600 +82,E12000009,500-999,885 +82,E12000009,1000-4999,705 +82,E12000009,5000+,135 +82,W92000004,0-49,270 +82,W92000004,50-99,375 +82,W92000004,100-249,930 +82,W92000004,250-499,690 +82,W92000004,500-999,445 +82,W92000004,1000-4999,295 +82,W92000004,5000+,50 +82,S92000003,0-49,560 +82,S92000003,50-99,735 +82,S92000003,100-249,1890 +82,S92000003,250-499,1150 +82,S92000003,500-999,655 +82,S92000003,1000-4999,485 +82,S92000003,5000+,95 +82,N92000002,0-49,80 +82,N92000002,50-99,120 +82,N92000002,100-249,245 +82,N92000002,250-499,275 +82,N92000002,500-999,125 +82,N92000002,1000-4999,95 +82,N92000002,5000+,15 +84,E12000001,0-49,10 +84,E12000001,50-99,150 +84,E12000001,100-249,40 +84,E12000001,250-499,15 +84,E12000001,500-999,10 +84,E12000001,1000-4999,5 +84,E12000001,5000+,20 +84,E12000002,0-49,15 +84,E12000002,50-99,365 +84,E12000002,100-249,90 +84,E12000002,250-499,30 +84,E12000002,500-999,15 +84,E12000002,1000-4999,10 +84,E12000002,5000+,30 +84,E12000003,0-49,20 +84,E12000003,50-99,430 +84,E12000003,100-249,130 +84,E12000003,250-499,40 +84,E12000003,500-999,10 +84,E12000003,1000-4999,10 +84,E12000003,5000+,15 +84,E12000004,0-49,30 +84,E12000004,50-99,585 +84,E12000004,100-249,205 +84,E12000004,250-499,80 +84,E12000004,500-999,25 +84,E12000004,1000-4999,20 +84,E12000004,5000+,30 +84,E12000005,0-49,20 +84,E12000005,50-99,535 +84,E12000005,100-249,80 +84,E12000005,250-499,35 +84,E12000005,500-999,20 +84,E12000005,1000-4999,10 +84,E12000005,5000+,30 +84,E12000006,0-49,45 +84,E12000006,50-99,935 +84,E12000006,100-249,240 +84,E12000006,250-499,85 +84,E12000006,500-999,30 +84,E12000006,1000-4999,20 +84,E12000006,5000+,50 +84,E12000007,0-49,5 +84,E12000007,50-99,5 +84,E12000007,100-249,5 +84,E12000007,250-499,5 +84,E12000007,500-999,5 +84,E12000007,1000-4999,15 +84,E12000007,5000+,70 +84,E12000008,0-49,70 +84,E12000008,50-99,690 +84,E12000008,100-249,255 +84,E12000008,250-499,110 +84,E12000008,500-999,45 +84,E12000008,1000-4999,30 +84,E12000008,5000+,65 +84,E12000009,0-49,60 +84,E12000009,50-99,890 +84,E12000009,100-249,170 +84,E12000009,250-499,85 +84,E12000009,500-999,40 +84,E12000009,1000-4999,30 +84,E12000009,5000+,35 +84,W92000004,0-49,25 +84,W92000004,50-99,365 +84,W92000004,100-249,100 +84,W92000004,250-499,55 +84,W92000004,500-999,20 +84,W92000004,1000-4999,10 +84,W92000004,5000+,20 +84,S92000003,0-49,0 +84,S92000003,50-99,10 +84,S92000003,100-249,5 +84,S92000003,250-499,5 +84,S92000003,500-999,5 +84,S92000003,1000-4999,15 +84,S92000003,5000+,25 +84,N92000002,0-49,0 +84,N92000002,50-99,0 +84,N92000002,100-249,5 +84,N92000002,250-499,0 +84,N92000002,500-999,0 +84,N92000002,1000-4999,10 +84,N92000002,5000+,25 +85,E12000001,0-49,125 +85,E12000001,50-99,310 +85,E12000001,100-249,385 +85,E12000001,250-499,180 +85,E12000001,500-999,120 +85,E12000001,1000-4999,140 +85,E12000001,5000+,90 +85,E12000002,0-49,405 +85,E12000002,50-99,1215 +85,E12000002,100-249,1320 +85,E12000002,250-499,670 +85,E12000002,500-999,480 +85,E12000002,1000-4999,495 +85,E12000002,5000+,295 +85,E12000003,0-49,275 +85,E12000003,50-99,830 +85,E12000003,100-249,925 +85,E12000003,250-499,445 +85,E12000003,500-999,330 +85,E12000003,1000-4999,305 +85,E12000003,5000+,165 +85,E12000004,0-49,290 +85,E12000004,50-99,815 +85,E12000004,100-249,830 +85,E12000004,250-499,450 +85,E12000004,500-999,345 +85,E12000004,1000-4999,335 +85,E12000004,5000+,175 +85,E12000005,0-49,345 +85,E12000005,50-99,1015 +85,E12000005,100-249,1090 +85,E12000005,250-499,495 +85,E12000005,500-999,380 +85,E12000005,1000-4999,325 +85,E12000005,5000+,255 +85,E12000006,0-49,430 +85,E12000006,50-99,1215 +85,E12000006,100-249,1260 +85,E12000006,250-499,790 +85,E12000006,500-999,515 +85,E12000006,1000-4999,640 +85,E12000006,5000+,315 +85,E12000007,0-49,960 +85,E12000007,50-99,2790 +85,E12000007,100-249,2790 +85,E12000007,250-499,1325 +85,E12000007,500-999,985 +85,E12000007,1000-4999,1225 +85,E12000007,5000+,630 +85,E12000008,0-49,735 +85,E12000008,50-99,1935 +85,E12000008,100-249,2130 +85,E12000008,250-499,1090 +85,E12000008,500-999,745 +85,E12000008,1000-4999,795 +85,E12000008,5000+,550 +85,E12000009,0-49,355 +85,E12000009,50-99,930 +85,E12000009,100-249,1150 +85,E12000009,250-499,605 +85,E12000009,500-999,430 +85,E12000009,1000-4999,360 +85,E12000009,5000+,240 +85,W92000004,0-49,115 +85,W92000004,50-99,380 +85,W92000004,100-249,495 +85,W92000004,250-499,210 +85,W92000004,500-999,155 +85,W92000004,1000-4999,90 +85,W92000004,5000+,70 +85,S92000003,0-49,225 +85,S92000003,50-99,530 +85,S92000003,100-249,705 +85,S92000003,250-499,300 +85,S92000003,500-999,225 +85,S92000003,1000-4999,160 +85,S92000003,5000+,95 +85,N92000002,0-49,65 +85,N92000002,50-99,180 +85,N92000002,100-249,255 +85,N92000002,250-499,80 +85,N92000002,500-999,60 +85,N92000002,1000-4999,60 +85,N92000002,5000+,70 +86,E12000001,0-49,30 +86,E12000001,50-99,645 +86,E12000001,100-249,435 +86,E12000001,250-499,220 +86,E12000001,500-999,185 +86,E12000001,1000-4999,280 +86,E12000001,5000+,50 +86,E12000002,0-49,180 +86,E12000002,50-99,3265 +86,E12000002,100-249,2240 +86,E12000002,250-499,855 +86,E12000002,500-999,760 +86,E12000002,1000-4999,820 +86,E12000002,5000+,135 +86,E12000003,0-49,110 +86,E12000003,50-99,2070 +86,E12000003,100-249,1470 +86,E12000003,250-499,550 +86,E12000003,500-999,430 +86,E12000003,1000-4999,585 +86,E12000003,5000+,100 +86,E12000004,0-49,195 +86,E12000004,50-99,1755 +86,E12000004,100-249,1235 +86,E12000004,250-499,475 +86,E12000004,500-999,350 +86,E12000004,1000-4999,495 +86,E12000004,5000+,95 +86,E12000005,0-49,105 +86,E12000005,50-99,2395 +86,E12000005,100-249,1680 +86,E12000005,250-499,670 +86,E12000005,500-999,590 +86,E12000005,1000-4999,595 +86,E12000005,5000+,100 +86,E12000006,0-49,150 +86,E12000006,50-99,2550 +86,E12000006,100-249,1805 +86,E12000006,250-499,700 +86,E12000006,500-999,530 +86,E12000006,1000-4999,615 +86,E12000006,5000+,125 +86,E12000007,0-49,430 +86,E12000007,50-99,5565 +86,E12000007,100-249,3795 +86,E12000007,250-499,1585 +86,E12000007,500-999,1065 +86,E12000007,1000-4999,1015 +86,E12000007,5000+,195 +86,E12000008,0-49,210 +86,E12000008,50-99,3665 +86,E12000008,100-249,2790 +86,E12000008,250-499,1325 +86,E12000008,500-999,760 +86,E12000008,1000-4999,960 +86,E12000008,5000+,225 +86,E12000009,0-49,205 +86,E12000009,50-99,1715 +86,E12000009,100-249,1385 +86,E12000009,250-499,630 +86,E12000009,500-999,395 +86,E12000009,1000-4999,575 +86,E12000009,5000+,130 +86,W92000004,0-49,45 +86,W92000004,50-99,685 +86,W92000004,100-249,530 +86,W92000004,250-499,310 +86,W92000004,500-999,245 +86,W92000004,1000-4999,355 +86,W92000004,5000+,30 +86,S92000003,0-49,80 +86,S92000003,50-99,1005 +86,S92000003,100-249,870 +86,S92000003,250-499,670 +86,S92000003,500-999,545 +86,S92000003,1000-4999,570 +86,S92000003,5000+,40 +86,N92000002,0-49,40 +86,N92000002,50-99,310 +86,N92000002,100-249,395 +86,N92000002,250-499,250 +86,N92000002,500-999,215 +86,N92000002,1000-4999,205 +86,N92000002,5000+,15 +87,E12000001,0-49,30 +87,E12000001,50-99,20 +87,E12000001,100-249,25 +87,E12000001,250-499,25 +87,E12000001,500-999,40 +87,E12000001,1000-4999,125 +87,E12000001,5000+,45 +87,E12000002,0-49,135 +87,E12000002,50-99,110 +87,E12000002,100-249,130 +87,E12000002,250-499,175 +87,E12000002,500-999,195 +87,E12000002,1000-4999,490 +87,E12000002,5000+,115 +87,E12000003,0-49,80 +87,E12000003,50-99,95 +87,E12000003,100-249,90 +87,E12000003,250-499,90 +87,E12000003,500-999,115 +87,E12000003,1000-4999,310 +87,E12000003,5000+,85 +87,E12000004,0-49,110 +87,E12000004,50-99,95 +87,E12000004,100-249,85 +87,E12000004,250-499,110 +87,E12000004,500-999,125 +87,E12000004,1000-4999,350 +87,E12000004,5000+,85 +87,E12000005,0-49,140 +87,E12000005,50-99,155 +87,E12000005,100-249,145 +87,E12000005,250-499,175 +87,E12000005,500-999,200 +87,E12000005,1000-4999,385 +87,E12000005,5000+,110 +87,E12000006,0-49,135 +87,E12000006,50-99,115 +87,E12000006,100-249,125 +87,E12000006,250-499,140 +87,E12000006,500-999,180 +87,E12000006,1000-4999,350 +87,E12000006,5000+,105 +87,E12000007,0-49,295 +87,E12000007,50-99,270 +87,E12000007,100-249,265 +87,E12000007,250-499,285 +87,E12000007,500-999,275 +87,E12000007,1000-4999,460 +87,E12000007,5000+,145 +87,E12000008,0-49,190 +87,E12000008,50-99,170 +87,E12000008,100-249,195 +87,E12000008,250-499,200 +87,E12000008,500-999,285 +87,E12000008,1000-4999,685 +87,E12000008,5000+,175 +87,E12000009,0-49,85 +87,E12000009,50-99,70 +87,E12000009,100-249,125 +87,E12000009,250-499,100 +87,E12000009,500-999,175 +87,E12000009,1000-4999,490 +87,E12000009,5000+,95 +87,W92000004,0-49,35 +87,W92000004,50-99,25 +87,W92000004,100-249,30 +87,W92000004,250-499,60 +87,W92000004,500-999,75 +87,W92000004,1000-4999,220 +87,W92000004,5000+,50 +87,S92000003,0-49,40 +87,S92000003,50-99,35 +87,S92000003,100-249,50 +87,S92000003,250-499,50 +87,S92000003,500-999,70 +87,S92000003,1000-4999,220 +87,S92000003,5000+,65 +87,N92000002,0-49,10 +87,N92000002,50-99,10 +87,N92000002,100-249,15 +87,N92000002,250-499,10 +87,N92000002,500-999,20 +87,N92000002,1000-4999,130 +87,N92000002,5000+,30 +88,E12000001,0-49,25 +88,E12000001,50-99,170 +88,E12000001,100-249,260 +88,E12000001,250-499,225 +88,E12000001,500-999,180 +88,E12000001,1000-4999,175 +88,E12000001,5000+,30 +88,E12000002,0-49,200 +88,E12000002,50-99,560 +88,E12000002,100-249,820 +88,E12000002,250-499,670 +88,E12000002,500-999,700 +88,E12000002,1000-4999,575 +88,E12000002,5000+,90 +88,E12000003,0-49,95 +88,E12000003,50-99,445 +88,E12000003,100-249,635 +88,E12000003,250-499,565 +88,E12000003,500-999,500 +88,E12000003,1000-4999,365 +88,E12000003,5000+,60 +88,E12000004,0-49,100 +88,E12000004,50-99,410 +88,E12000004,100-249,560 +88,E12000004,250-499,545 +88,E12000004,500-999,400 +88,E12000004,1000-4999,400 +88,E12000004,5000+,65 +88,E12000005,0-49,120 +88,E12000005,50-99,520 +88,E12000005,100-249,685 +88,E12000005,250-499,545 +88,E12000005,500-999,540 +88,E12000005,1000-4999,430 +88,E12000005,5000+,60 +88,E12000006,0-49,165 +88,E12000006,50-99,555 +88,E12000006,100-249,760 +88,E12000006,250-499,675 +88,E12000006,500-999,540 +88,E12000006,1000-4999,470 +88,E12000006,5000+,55 +88,E12000007,0-49,475 +88,E12000007,50-99,1235 +88,E12000007,100-249,1635 +88,E12000007,250-499,1205 +88,E12000007,500-999,965 +88,E12000007,1000-4999,795 +88,E12000007,5000+,190 +88,E12000008,0-49,225 +88,E12000008,50-99,835 +88,E12000008,100-249,1150 +88,E12000008,250-499,1020 +88,E12000008,500-999,805 +88,E12000008,1000-4999,700 +88,E12000008,5000+,100 +88,E12000009,0-49,110 +88,E12000009,50-99,515 +88,E12000009,100-249,785 +88,E12000009,250-499,720 +88,E12000009,500-999,510 +88,E12000009,1000-4999,460 +88,E12000009,5000+,45 +88,W92000004,0-49,55 +88,W92000004,50-99,235 +88,W92000004,100-249,525 +88,W92000004,250-499,445 +88,W92000004,500-999,290 +88,W92000004,1000-4999,240 +88,W92000004,5000+,30 +88,S92000003,0-49,120 +88,S92000003,50-99,405 +88,S92000003,100-249,710 +88,S92000003,250-499,655 +88,S92000003,500-999,515 +88,S92000003,1000-4999,400 +88,S92000003,5000+,70 +88,N92000002,0-49,50 +88,N92000002,50-99,170 +88,N92000002,100-249,445 +88,N92000002,250-499,200 +88,N92000002,500-999,180 +88,N92000002,1000-4999,180 +88,N92000002,5000+,15 +90,E12000001,0-49,60 +90,E12000001,50-99,110 +90,E12000001,100-249,205 +90,E12000001,250-499,80 +90,E12000001,500-999,40 +90,E12000001,1000-4999,35 +90,E12000001,5000+,5 +90,E12000002,0-49,265 +90,E12000002,50-99,420 +90,E12000002,100-249,825 +90,E12000002,250-499,335 +90,E12000002,500-999,170 +90,E12000002,1000-4999,110 +90,E12000002,5000+,20 +90,E12000003,0-49,190 +90,E12000003,50-99,240 +90,E12000003,100-249,495 +90,E12000003,250-499,210 +90,E12000003,500-999,115 +90,E12000003,1000-4999,65 +90,E12000003,5000+,10 +90,E12000004,0-49,185 +90,E12000004,50-99,225 +90,E12000004,100-249,405 +90,E12000004,250-499,175 +90,E12000004,500-999,80 +90,E12000004,1000-4999,50 +90,E12000004,5000+,5 +90,E12000005,0-49,180 +90,E12000005,50-99,250 +90,E12000005,100-249,520 +90,E12000005,250-499,190 +90,E12000005,500-999,120 +90,E12000005,1000-4999,80 +90,E12000005,5000+,20 +90,E12000006,0-49,465 +90,E12000006,50-99,600 +90,E12000006,100-249,1040 +90,E12000006,250-499,315 +90,E12000006,500-999,160 +90,E12000006,1000-4999,100 +90,E12000006,5000+,15 +90,E12000007,0-49,2605 +90,E12000007,50-99,2755 +90,E12000007,100-249,4545 +90,E12000007,250-499,1840 +90,E12000007,500-999,1060 +90,E12000007,1000-4999,1045 +90,E12000007,5000+,275 +90,E12000008,0-49,925 +90,E12000008,50-99,1145 +90,E12000008,100-249,1840 +90,E12000008,250-499,590 +90,E12000008,500-999,305 +90,E12000008,1000-4999,220 +90,E12000008,5000+,40 +90,E12000009,0-49,440 +90,E12000009,50-99,505 +90,E12000009,100-249,910 +90,E12000009,250-499,295 +90,E12000009,500-999,165 +90,E12000009,1000-4999,120 +90,E12000009,5000+,15 +90,W92000004,0-49,130 +90,W92000004,50-99,150 +90,W92000004,100-249,285 +90,W92000004,250-499,100 +90,W92000004,500-999,60 +90,W92000004,1000-4999,35 +90,W92000004,5000+,5 +90,S92000003,0-49,230 +90,S92000003,50-99,240 +90,S92000003,100-249,520 +90,S92000003,250-499,195 +90,S92000003,500-999,90 +90,S92000003,1000-4999,75 +90,S92000003,5000+,10 +90,N92000002,0-49,50 +90,N92000002,50-99,60 +90,N92000002,100-249,130 +90,N92000002,250-499,60 +90,N92000002,500-999,35 +90,N92000002,1000-4999,15 +90,N92000002,5000+,5 +91,E12000001,0-49,5 +91,E12000001,50-99,10 +91,E12000001,100-249,5 +91,E12000001,250-499,10 +91,E12000001,500-999,5 +91,E12000001,1000-4999,10 +91,E12000001,5000+,5 +91,E12000002,0-49,15 +91,E12000002,50-99,25 +91,E12000002,100-249,35 +91,E12000002,250-499,20 +91,E12000002,500-999,10 +91,E12000002,1000-4999,15 +91,E12000002,5000+,10 +91,E12000003,0-49,20 +91,E12000003,50-99,15 +91,E12000003,100-249,25 +91,E12000003,250-499,15 +91,E12000003,500-999,15 +91,E12000003,1000-4999,25 +91,E12000003,5000+,10 +91,E12000004,0-49,15 +91,E12000004,50-99,20 +91,E12000004,100-249,30 +91,E12000004,250-499,10 +91,E12000004,500-999,20 +91,E12000004,1000-4999,20 +91,E12000004,5000+,5 +91,E12000005,0-49,10 +91,E12000005,50-99,15 +91,E12000005,100-249,30 +91,E12000005,250-499,10 +91,E12000005,500-999,10 +91,E12000005,1000-4999,15 +91,E12000005,5000+,10 +91,E12000006,0-49,25 +91,E12000006,50-99,20 +91,E12000006,100-249,55 +91,E12000006,250-499,30 +91,E12000006,500-999,20 +91,E12000006,1000-4999,25 +91,E12000006,5000+,10 +91,E12000007,0-49,45 +91,E12000007,50-99,45 +91,E12000007,100-249,80 +91,E12000007,250-499,35 +91,E12000007,500-999,30 +91,E12000007,1000-4999,40 +91,E12000007,5000+,30 +91,E12000008,0-49,40 +91,E12000008,50-99,45 +91,E12000008,100-249,65 +91,E12000008,250-499,35 +91,E12000008,500-999,40 +91,E12000008,1000-4999,40 +91,E12000008,5000+,20 +91,E12000009,0-49,35 +91,E12000009,50-99,35 +91,E12000009,100-249,60 +91,E12000009,250-499,45 +91,E12000009,500-999,35 +91,E12000009,1000-4999,35 +91,E12000009,5000+,20 +91,W92000004,0-49,10 +91,W92000004,50-99,20 +91,W92000004,100-249,25 +91,W92000004,250-499,15 +91,W92000004,500-999,15 +91,W92000004,1000-4999,15 +91,W92000004,5000+,0 +91,S92000003,0-49,30 +91,S92000003,50-99,35 +91,S92000003,100-249,75 +91,S92000003,250-499,35 +91,S92000003,500-999,30 +91,S92000003,1000-4999,25 +91,S92000003,5000+,10 +91,N92000002,0-49,10 +91,N92000002,50-99,5 +91,N92000002,100-249,15 +91,N92000002,250-499,10 +91,N92000002,500-999,5 +91,N92000002,1000-4999,5 +91,N92000002,5000+,0 +92,E12000001,0-49,5 +92,E12000001,50-99,5 +92,E12000001,100-249,10 +92,E12000001,250-499,5 +92,E12000001,500-999,5 +92,E12000001,1000-4999,10 +92,E12000001,5000+,10 +92,E12000002,0-49,0 +92,E12000002,50-99,5 +92,E12000002,100-249,25 +92,E12000002,250-499,15 +92,E12000002,500-999,5 +92,E12000002,1000-4999,10 +92,E12000002,5000+,15 +92,E12000003,0-49,5 +92,E12000003,50-99,10 +92,E12000003,100-249,25 +92,E12000003,250-499,15 +92,E12000003,500-999,5 +92,E12000003,1000-4999,15 +92,E12000003,5000+,0 +92,E12000004,0-49,5 +92,E12000004,50-99,10 +92,E12000004,100-249,15 +92,E12000004,250-499,10 +92,E12000004,500-999,10 +92,E12000004,1000-4999,15 +92,E12000004,5000+,10 +92,E12000005,0-49,5 +92,E12000005,50-99,0 +92,E12000005,100-249,10 +92,E12000005,250-499,5 +92,E12000005,500-999,5 +92,E12000005,1000-4999,10 +92,E12000005,5000+,10 +92,E12000006,0-49,5 +92,E12000006,50-99,15 +92,E12000006,100-249,20 +92,E12000006,250-499,20 +92,E12000006,500-999,15 +92,E12000006,1000-4999,15 +92,E12000006,5000+,10 +92,E12000007,0-49,10 +92,E12000007,50-99,15 +92,E12000007,100-249,20 +92,E12000007,250-499,10 +92,E12000007,500-999,15 +92,E12000007,1000-4999,10 +92,E12000007,5000+,20 +92,E12000008,0-49,10 +92,E12000008,50-99,15 +92,E12000008,100-249,15 +92,E12000008,250-499,25 +92,E12000008,500-999,15 +92,E12000008,1000-4999,15 +92,E12000008,5000+,5 +92,E12000009,0-49,5 +92,E12000009,50-99,10 +92,E12000009,100-249,20 +92,E12000009,250-499,10 +92,E12000009,500-999,10 +92,E12000009,1000-4999,10 +92,E12000009,5000+,0 +92,W92000004,0-49,0 +92,W92000004,50-99,5 +92,W92000004,100-249,15 +92,W92000004,250-499,15 +92,W92000004,500-999,10 +92,W92000004,1000-4999,5 +92,W92000004,5000+,5 +92,S92000003,0-49,0 +92,S92000003,50-99,5 +92,S92000003,100-249,5 +92,S92000003,250-499,15 +92,S92000003,500-999,10 +92,S92000003,1000-4999,5 +92,S92000003,5000+,5 +92,N92000002,0-49,5 +92,N92000002,50-99,5 +92,N92000002,100-249,20 +92,N92000002,250-499,15 +92,N92000002,500-999,15 +92,N92000002,1000-4999,20 +92,N92000002,5000+,5 +93,E12000001,0-49,245 +93,E12000001,50-99,175 +93,E12000001,100-249,440 +93,E12000001,250-499,200 +93,E12000001,500-999,110 +93,E12000001,1000-4999,70 +93,E12000001,5000+,15 +93,E12000002,0-49,715 +93,E12000002,50-99,550 +93,E12000002,100-249,1330 +93,E12000002,250-499,585 +93,E12000002,500-999,385 +93,E12000002,1000-4999,260 +93,E12000002,5000+,60 +93,E12000003,0-49,730 +93,E12000003,50-99,440 +93,E12000003,100-249,1035 +93,E12000003,250-499,415 +93,E12000003,500-999,255 +93,E12000003,1000-4999,175 +93,E12000003,5000+,35 +93,E12000004,0-49,1945 +93,E12000004,50-99,460 +93,E12000004,100-249,980 +93,E12000004,250-499,385 +93,E12000004,500-999,250 +93,E12000004,1000-4999,185 +93,E12000004,5000+,50 +93,E12000005,0-49,500 +93,E12000005,50-99,385 +93,E12000005,100-249,925 +93,E12000005,250-499,380 +93,E12000005,500-999,255 +93,E12000005,1000-4999,180 +93,E12000005,5000+,35 +93,E12000006,0-49,735 +93,E12000006,50-99,590 +93,E12000006,100-249,1310 +93,E12000006,250-499,530 +93,E12000006,500-999,325 +93,E12000006,1000-4999,300 +93,E12000006,5000+,55 +93,E12000007,0-49,915 +93,E12000007,50-99,710 +93,E12000007,100-249,1555 +93,E12000007,250-499,655 +93,E12000007,500-999,420 +93,E12000007,1000-4999,410 +93,E12000007,5000+,155 +93,E12000008,0-49,1465 +93,E12000008,50-99,850 +93,E12000008,100-249,2020 +93,E12000008,250-499,835 +93,E12000008,500-999,550 +93,E12000008,1000-4999,530 +93,E12000008,5000+,115 +93,E12000009,0-49,880 +93,E12000009,50-99,560 +93,E12000009,100-249,1255 +93,E12000009,250-499,480 +93,E12000009,500-999,300 +93,E12000009,1000-4999,300 +93,E12000009,5000+,55 +93,W92000004,0-49,240 +93,W92000004,50-99,235 +93,W92000004,100-249,625 +93,W92000004,250-499,290 +93,W92000004,500-999,135 +93,W92000004,1000-4999,90 +93,W92000004,5000+,20 +93,S92000003,0-49,470 +93,S92000003,50-99,500 +93,S92000003,100-249,1070 +93,S92000003,250-499,460 +93,S92000003,500-999,305 +93,S92000003,1000-4999,220 +93,S92000003,5000+,55 +93,N92000002,0-49,160 +93,N92000002,50-99,195 +93,N92000002,100-249,360 +93,N92000002,250-499,145 +93,N92000002,500-999,95 +93,N92000002,1000-4999,50 +93,N92000002,5000+,5 +94,E12000001,0-49,110 +94,E12000001,50-99,125 +94,E12000001,100-249,200 +94,E12000001,250-499,110 +94,E12000001,500-999,55 +94,E12000001,1000-4999,35 +94,E12000001,5000+,5 +94,E12000002,0-49,415 +94,E12000002,50-99,380 +94,E12000002,100-249,605 +94,E12000002,250-499,295 +94,E12000002,500-999,150 +94,E12000002,1000-4999,85 +94,E12000002,5000+,20 +94,E12000003,0-49,300 +94,E12000003,50-99,280 +94,E12000003,100-249,405 +94,E12000003,250-499,240 +94,E12000003,500-999,120 +94,E12000003,1000-4999,85 +94,E12000003,5000+,10 +94,E12000004,0-49,255 +94,E12000004,50-99,260 +94,E12000004,100-249,370 +94,E12000004,250-499,205 +94,E12000004,500-999,100 +94,E12000004,1000-4999,70 +94,E12000004,5000+,15 +94,E12000005,0-49,320 +94,E12000005,50-99,320 +94,E12000005,100-249,675 +94,E12000005,250-499,280 +94,E12000005,500-999,130 +94,E12000005,1000-4999,90 +94,E12000005,5000+,15 +94,E12000006,0-49,465 +94,E12000006,50-99,400 +94,E12000006,100-249,610 +94,E12000006,250-499,285 +94,E12000006,500-999,140 +94,E12000006,1000-4999,80 +94,E12000006,5000+,20 +94,E12000007,0-49,765 +94,E12000007,50-99,735 +94,E12000007,100-249,1120 +94,E12000007,250-499,620 +94,E12000007,500-999,425 +94,E12000007,1000-4999,485 +94,E12000007,5000+,195 +94,E12000008,0-49,640 +94,E12000008,50-99,635 +94,E12000008,100-249,950 +94,E12000008,250-499,475 +94,E12000008,500-999,215 +94,E12000008,1000-4999,170 +94,E12000008,5000+,35 +94,E12000009,0-49,425 +94,E12000009,50-99,370 +94,E12000009,100-249,645 +94,E12000009,250-499,275 +94,E12000009,500-999,95 +94,E12000009,1000-4999,85 +94,E12000009,5000+,10 +94,W92000004,0-49,235 +94,W92000004,50-99,195 +94,W92000004,100-249,330 +94,W92000004,250-499,145 +94,W92000004,500-999,65 +94,W92000004,1000-4999,30 +94,W92000004,5000+,10 +94,S92000003,0-49,440 +94,S92000003,50-99,380 +94,S92000003,100-249,555 +94,S92000003,250-499,270 +94,S92000003,500-999,115 +94,S92000003,1000-4999,80 +94,S92000003,5000+,10 +94,N92000002,0-49,300 +94,N92000002,50-99,260 +94,N92000002,100-249,355 +94,N92000002,250-499,135 +94,N92000002,500-999,70 +94,N92000002,1000-4999,40 +94,N92000002,5000+,5 +95,E12000001,0-49,25 +95,E12000001,50-99,50 +95,E12000001,100-249,120 +95,E12000001,250-499,25 +95,E12000001,500-999,10 +95,E12000001,1000-4999,10 +95,E12000001,5000+,0 +95,E12000002,0-49,95 +95,E12000002,50-99,175 +95,E12000002,100-249,505 +95,E12000002,250-499,105 +95,E12000002,500-999,45 +95,E12000002,1000-4999,40 +95,E12000002,5000+,15 +95,E12000003,0-49,55 +95,E12000003,50-99,130 +95,E12000003,100-249,360 +95,E12000003,250-499,80 +95,E12000003,500-999,35 +95,E12000003,1000-4999,25 +95,E12000003,5000+,15 +95,E12000004,0-49,65 +95,E12000004,50-99,130 +95,E12000004,100-249,310 +95,E12000004,250-499,60 +95,E12000004,500-999,20 +95,E12000004,1000-4999,25 +95,E12000004,5000+,10 +95,E12000005,0-49,75 +95,E12000005,50-99,170 +95,E12000005,100-249,435 +95,E12000005,250-499,85 +95,E12000005,500-999,45 +95,E12000005,1000-4999,35 +95,E12000005,5000+,10 +95,E12000006,0-49,90 +95,E12000006,50-99,205 +95,E12000006,100-249,495 +95,E12000006,250-499,90 +95,E12000006,500-999,55 +95,E12000006,1000-4999,45 +95,E12000006,5000+,15 +95,E12000007,0-49,185 +95,E12000007,50-99,305 +95,E12000007,100-249,1100 +95,E12000007,250-499,195 +95,E12000007,500-999,80 +95,E12000007,1000-4999,60 +95,E12000007,5000+,15 +95,E12000008,0-49,165 +95,E12000008,50-99,280 +95,E12000008,100-249,690 +95,E12000008,250-499,160 +95,E12000008,500-999,70 +95,E12000008,1000-4999,80 +95,E12000008,5000+,25 +95,E12000009,0-49,65 +95,E12000009,50-99,145 +95,E12000009,100-249,360 +95,E12000009,250-499,80 +95,E12000009,500-999,40 +95,E12000009,1000-4999,35 +95,E12000009,5000+,10 +95,W92000004,0-49,40 +95,W92000004,50-99,60 +95,W92000004,100-249,170 +95,W92000004,250-499,30 +95,W92000004,500-999,10 +95,W92000004,1000-4999,5 +95,W92000004,5000+,0 +95,S92000003,0-49,60 +95,S92000003,50-99,115 +95,S92000003,100-249,265 +95,S92000003,250-499,75 +95,S92000003,500-999,25 +95,S92000003,1000-4999,30 +95,S92000003,5000+,5 +95,N92000002,0-49,20 +95,N92000002,50-99,30 +95,N92000002,100-249,65 +95,N92000002,250-499,20 +95,N92000002,500-999,10 +95,N92000002,1000-4999,5 +95,N92000002,5000+,0 +96,E12000001,0-49,400 +96,E12000001,50-99,1235 +96,E12000001,100-249,1005 +96,E12000001,250-499,215 +96,E12000001,500-999,75 +96,E12000001,1000-4999,35 +96,E12000001,5000+,10 +96,E12000002,0-49,1715 +96,E12000002,50-99,3510 +96,E12000002,100-249,2950 +96,E12000002,250-499,630 +96,E12000002,500-999,300 +96,E12000002,1000-4999,220 +96,E12000002,5000+,40 +96,E12000003,0-49,975 +96,E12000003,50-99,2310 +96,E12000003,100-249,1930 +96,E12000003,250-499,410 +96,E12000003,500-999,195 +96,E12000003,1000-4999,135 +96,E12000003,5000+,15 +96,E12000004,0-49,910 +96,E12000004,50-99,1930 +96,E12000004,100-249,1765 +96,E12000004,250-499,450 +96,E12000004,500-999,205 +96,E12000004,1000-4999,145 +96,E12000004,5000+,25 +96,E12000005,0-49,1170 +96,E12000005,50-99,2530 +96,E12000005,100-249,2190 +96,E12000005,250-499,505 +96,E12000005,500-999,250 +96,E12000005,1000-4999,215 +96,E12000005,5000+,40 +96,E12000006,0-49,1450 +96,E12000006,50-99,2510 +96,E12000006,100-249,2755 +96,E12000006,250-499,655 +96,E12000006,500-999,290 +96,E12000006,1000-4999,210 +96,E12000006,5000+,35 +96,E12000007,0-49,3345 +96,E12000007,50-99,4935 +96,E12000007,100-249,5350 +96,E12000007,250-499,1125 +96,E12000007,500-999,630 +96,E12000007,1000-4999,445 +96,E12000007,5000+,115 +96,E12000008,0-49,1925 +96,E12000008,50-99,3465 +96,E12000008,100-249,4270 +96,E12000008,250-499,1185 +96,E12000008,500-999,570 +96,E12000008,1000-4999,395 +96,E12000008,5000+,90 +96,E12000009,0-49,985 +96,E12000009,50-99,1950 +96,E12000009,100-249,2125 +96,E12000009,250-499,530 +96,E12000009,500-999,275 +96,E12000009,1000-4999,180 +96,E12000009,5000+,30 +96,W92000004,0-49,455 +96,W92000004,50-99,1290 +96,W92000004,100-249,1115 +96,W92000004,250-499,235 +96,W92000004,500-999,85 +96,W92000004,1000-4999,65 +96,W92000004,5000+,10 +96,S92000003,0-49,1050 +96,S92000003,50-99,2320 +96,S92000003,100-249,1995 +96,S92000003,250-499,485 +96,S92000003,500-999,215 +96,S92000003,1000-4999,125 +96,S92000003,5000+,20 +96,N92000002,0-49,260 +96,N92000002,50-99,840 +96,N92000002,100-249,765 +96,N92000002,250-499,135 +96,N92000002,500-999,40 +96,N92000002,1000-4999,25 +96,N92000002,5000+,0 +97,E12000001,0-49,0 +97,E12000001,50-99,0 +97,E12000001,100-249,0 +97,E12000001,250-499,0 +97,E12000001,500-999,0 +97,E12000001,1000-4999,0 +97,E12000001,5000+,0 +97,E12000002,0-49,0 +97,E12000002,50-99,0 +97,E12000002,100-249,0 +97,E12000002,250-499,0 +97,E12000002,500-999,0 +97,E12000002,1000-4999,0 +97,E12000002,5000+,0 +97,E12000003,0-49,0 +97,E12000003,50-99,0 +97,E12000003,100-249,0 +97,E12000003,250-499,0 +97,E12000003,500-999,0 +97,E12000003,1000-4999,0 +97,E12000003,5000+,0 +97,E12000004,0-49,0 +97,E12000004,50-99,0 +97,E12000004,100-249,0 +97,E12000004,250-499,0 +97,E12000004,500-999,0 +97,E12000004,1000-4999,0 +97,E12000004,5000+,0 +97,E12000005,0-49,0 +97,E12000005,50-99,0 +97,E12000005,100-249,0 +97,E12000005,250-499,0 +97,E12000005,500-999,0 +97,E12000005,1000-4999,0 +97,E12000005,5000+,0 +97,E12000006,0-49,0 +97,E12000006,50-99,0 +97,E12000006,100-249,0 +97,E12000006,250-499,0 +97,E12000006,500-999,0 +97,E12000006,1000-4999,0 +97,E12000006,5000+,0 +97,E12000007,0-49,0 +97,E12000007,50-99,0 +97,E12000007,100-249,0 +97,E12000007,250-499,0 +97,E12000007,500-999,0 +97,E12000007,1000-4999,0 +97,E12000007,5000+,0 +97,E12000008,0-49,0 +97,E12000008,50-99,0 +97,E12000008,100-249,0 +97,E12000008,250-499,0 +97,E12000008,500-999,0 +97,E12000008,1000-4999,0 +97,E12000008,5000+,0 +97,E12000009,0-49,0 +97,E12000009,50-99,0 +97,E12000009,100-249,0 +97,E12000009,250-499,0 +97,E12000009,500-999,0 +97,E12000009,1000-4999,0 +97,E12000009,5000+,0 +97,W92000004,0-49,0 +97,W92000004,50-99,0 +97,W92000004,100-249,0 +97,W92000004,250-499,0 +97,W92000004,500-999,0 +97,W92000004,1000-4999,0 +97,W92000004,5000+,0 +97,S92000003,0-49,0 +97,S92000003,50-99,0 +97,S92000003,100-249,0 +97,S92000003,250-499,0 +97,S92000003,500-999,0 +97,S92000003,1000-4999,0 +97,S92000003,5000+,0 +97,N92000002,0-49,0 +97,N92000002,50-99,0 +97,N92000002,100-249,0 +97,N92000002,250-499,0 +97,N92000002,500-999,0 +97,N92000002,1000-4999,0 +97,N92000002,5000+,0 +98,E12000001,0-49,0 +98,E12000001,50-99,0 +98,E12000001,100-249,0 +98,E12000001,250-499,0 +98,E12000001,500-999,0 +98,E12000001,1000-4999,0 +98,E12000001,5000+,0 +98,E12000002,0-49,0 +98,E12000002,50-99,0 +98,E12000002,100-249,0 +98,E12000002,250-499,0 +98,E12000002,500-999,0 +98,E12000002,1000-4999,0 +98,E12000002,5000+,0 +98,E12000003,0-49,0 +98,E12000003,50-99,0 +98,E12000003,100-249,0 +98,E12000003,250-499,0 +98,E12000003,500-999,0 +98,E12000003,1000-4999,0 +98,E12000003,5000+,0 +98,E12000004,0-49,0 +98,E12000004,50-99,0 +98,E12000004,100-249,0 +98,E12000004,250-499,0 +98,E12000004,500-999,0 +98,E12000004,1000-4999,0 +98,E12000004,5000+,0 +98,E12000005,0-49,0 +98,E12000005,50-99,0 +98,E12000005,100-249,0 +98,E12000005,250-499,0 +98,E12000005,500-999,0 +98,E12000005,1000-4999,0 +98,E12000005,5000+,0 +98,E12000006,0-49,0 +98,E12000006,50-99,0 +98,E12000006,100-249,0 +98,E12000006,250-499,0 +98,E12000006,500-999,0 +98,E12000006,1000-4999,0 +98,E12000006,5000+,0 +98,E12000007,0-49,0 +98,E12000007,50-99,0 +98,E12000007,100-249,0 +98,E12000007,250-499,0 +98,E12000007,500-999,0 +98,E12000007,1000-4999,0 +98,E12000007,5000+,0 +98,E12000008,0-49,0 +98,E12000008,50-99,0 +98,E12000008,100-249,0 +98,E12000008,250-499,0 +98,E12000008,500-999,0 +98,E12000008,1000-4999,0 +98,E12000008,5000+,0 +98,E12000009,0-49,0 +98,E12000009,50-99,0 +98,E12000009,100-249,0 +98,E12000009,250-499,0 +98,E12000009,500-999,0 +98,E12000009,1000-4999,0 +98,E12000009,5000+,0 +98,W92000004,0-49,0 +98,W92000004,50-99,0 +98,W92000004,100-249,0 +98,W92000004,250-499,0 +98,W92000004,500-999,0 +98,W92000004,1000-4999,0 +98,W92000004,5000+,0 +98,S92000003,0-49,0 +98,S92000003,50-99,0 +98,S92000003,100-249,0 +98,S92000003,250-499,0 +98,S92000003,500-999,0 +98,S92000003,1000-4999,0 +98,S92000003,5000+,0 +98,N92000002,0-49,0 +98,N92000002,50-99,0 +98,N92000002,100-249,0 +98,N92000002,250-499,0 +98,N92000002,500-999,0 +98,N92000002,1000-4999,0 +98,N92000002,5000+,0 +99,E12000001,0-49,0 +99,E12000001,50-99,0 +99,E12000001,100-249,0 +99,E12000001,250-499,0 +99,E12000001,500-999,0 +99,E12000001,1000-4999,0 +99,E12000001,5000+,0 +99,E12000002,0-49,0 +99,E12000002,50-99,0 +99,E12000002,100-249,0 +99,E12000002,250-499,0 +99,E12000002,500-999,0 +99,E12000002,1000-4999,0 +99,E12000002,5000+,0 +99,E12000003,0-49,0 +99,E12000003,50-99,0 +99,E12000003,100-249,0 +99,E12000003,250-499,0 +99,E12000003,500-999,0 +99,E12000003,1000-4999,0 +99,E12000003,5000+,0 +99,E12000004,0-49,0 +99,E12000004,50-99,0 +99,E12000004,100-249,0 +99,E12000004,250-499,0 +99,E12000004,500-999,0 +99,E12000004,1000-4999,0 +99,E12000004,5000+,0 +99,E12000005,0-49,0 +99,E12000005,50-99,0 +99,E12000005,100-249,0 +99,E12000005,250-499,0 +99,E12000005,500-999,0 +99,E12000005,1000-4999,0 +99,E12000005,5000+,0 +99,E12000006,0-49,0 +99,E12000006,50-99,0 +99,E12000006,100-249,0 +99,E12000006,250-499,0 +99,E12000006,500-999,0 +99,E12000006,1000-4999,0 +99,E12000006,5000+,0 +99,E12000007,0-49,0 +99,E12000007,50-99,0 +99,E12000007,100-249,0 +99,E12000007,250-499,0 +99,E12000007,500-999,0 +99,E12000007,1000-4999,0 +99,E12000007,5000+,0 +99,E12000008,0-49,0 +99,E12000008,50-99,0 +99,E12000008,100-249,0 +99,E12000008,250-499,0 +99,E12000008,500-999,0 +99,E12000008,1000-4999,0 +99,E12000008,5000+,0 +99,E12000009,0-49,0 +99,E12000009,50-99,0 +99,E12000009,100-249,0 +99,E12000009,250-499,0 +99,E12000009,500-999,0 +99,E12000009,1000-4999,0 +99,E12000009,5000+,0 +99,W92000004,0-49,0 +99,W92000004,50-99,0 +99,W92000004,100-249,0 +99,W92000004,250-499,0 +99,W92000004,500-999,0 +99,W92000004,1000-4999,0 +99,W92000004,5000+,0 +99,S92000003,0-49,0 +99,S92000003,50-99,0 +99,S92000003,100-249,0 +99,S92000003,250-499,0 +99,S92000003,500-999,0 +99,S92000003,1000-4999,0 +99,S92000003,5000+,0 +99,N92000002,0-49,0 +99,N92000002,50-99,0 +99,N92000002,100-249,0 +99,N92000002,250-499,0 +99,N92000002,500-999,0 +99,N92000002,1000-4999,0 +99,N92000002,5000+,0 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/test_support/microcosm_build/uk_firm_target_keys.py b/test_support/microcosm_build/uk_firm_target_keys.py new file mode 100644 index 0000000000..3ac1673158 --- /dev/null +++ b/test_support/microcosm_build/uk_firm_target_keys.py @@ -0,0 +1,54 @@ +"""The forbidden-key walk UK firm target declarations must pass, for tests. + +A target declaration carries no observed value and no runtime hook: none of +``FORBIDDEN_VALUE_KEYS`` or ``FORBIDDEN_RUNTIME_KEYS`` may appear at any depth, +except ``value`` in a filter predicate and ``operation`` in resolution +defaults. +""" + +from __future__ import annotations + +from collections.abc import Mapping + +FORBIDDEN_VALUE_KEYS = {"aggregation", "operation", "registry", "target_value", "value"} +FORBIDDEN_RUNTIME_KEYS = { + "callable", + "command", + "execute", + "executable", + "function", + "import", + "imports", + "module", + "python_code", + "runtime_code", + "script", + "solver", +} + + +def is_filter_predicate(node: Mapping) -> bool: + return ( + "value" in node + and "operator" in node + and ("concept" in node or "variable" in node) + ) + + +def carried_forbidden_keys(node, *, in_defaults: bool = False) -> set[str]: + """The forbidden keys ``node`` carries at any depth.""" + + carried: set[str] = set() + if isinstance(node, Mapping): + forbidden = set(FORBIDDEN_VALUE_KEYS | FORBIDDEN_RUNTIME_KEYS) + if is_filter_predicate(node): + forbidden.discard("value") + if in_defaults: + forbidden.discard("operation") + carried.update(forbidden.intersection(node)) + for child in node.values(): + carried.update(carried_forbidden_keys(child)) + elif isinstance(node, (list, tuple)): + for child in node: + carried.update(carried_forbidden_keys(child)) + return carried diff --git a/tools/build_uk_firms.py b/tools/build_uk_firms.py new file mode 100644 index 0000000000..2f3cae6a73 --- /dev/null +++ b/tools/build_uk_firms.py @@ -0,0 +1,103 @@ +"""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 the ONS attribute tables +in ``--attributes-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("--attributes-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, + attributes_dir=args.attributes_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/extract_uk_firm_ons_attribute_tables.py b/tools/extract_uk_firm_ons_attribute_tables.py new file mode 100644 index 0000000000..b08c927d4f --- /dev/null +++ b/tools/extract_uk_firm_ons_attribute_tables.py @@ -0,0 +1,596 @@ +#!/usr/bin/env python3 +"""Extract ONS UK Business 2025 attribute tables for the experimental UK firm table. + +Reads four sheets of the ONS *UK Business: Activity, Size and Location, 2025* +workbook (``ukbusinessworkbook2025new.xlsx``, tracked in +PolicyEngine/firm-microsim-paper under ``data/raw/ons/``) and writes long-format +CSVs of enterprise counts: + +* ``ons_region_turnover.csv`` from **Table 8**: SIC division x region x the + seven ONS turnover sizebands (``sic_division,region_code,turnover_band, + enterprises``). +* ``ons_legal_status_turnover.csv`` from **Table 13**: broad industry group x + legal status x the ten Table 13 turnover sizebands (``industry_group, + legal_status,turnover_band,enterprises``). +* ``ons_legal_status_employment.csv`` from **Table 12**: broad industry group + x legal status x the seven employment sizebands (``industry_group, + legal_status,employment_band,enterprises``). +* ``ons_legal_status_region_turnover.csv`` from **Table 15**: region x legal + status x the ten sizebands (``region_code,legal_status,turnover_band, + enterprises``). Held out: not a draw input. + +Each CSV is the full rectangular grid in workbook order, zero cells included. +The aggregate geographies (United Kingdom, Great Britain, England and Wales, +England), every ``Total`` column and row and Table 12/13/15's ``Total`` legal +status block are dropped. Counts are control-rounded to base 5 by ONS (note 7: +values may be rounded down to zero, so a zero is not necessarily a true zero). +A blank or non-numeric cell inside a table's data block is written as 0 and +counted in ``.provenance.json``; the 2025 workbook has none. + +Region codes are the GSS codes from the workbook's own headers (E12000001 to +E12000009, W92000004, S92000003, N92000002). ``rowwise_geography`` writes +placeholder codes for the devolved nations (``W99999999`` and so on), so its +map is not reused here; the engine-free fixture test checks the codes, in +order, against ``microcosm.calibrate.geography_constants.UK_REGION_TIER`` and +``UK_REGION_TIER_ENUM``. + +openpyxl is imported only when a workbook is read, so engine-free CI, which +runs the fixture test against the committed CSVs, never needs it. + +Usage:: + + uv run --no-sync python tools/extract_uk_firm_ons_attribute_tables.py \\ + --workbook ../firm-microsim-paper/data/raw/ons/ukbusinessworkbook2025new.xlsx + + # Exit 1 if re-extraction would change any committed CSV byte. + uv run --no-sync python tools/extract_uk_firm_ons_attribute_tables.py \\ + --workbook ../firm-microsim-paper/data/raw/ons/ukbusinessworkbook2025new.xlsx \\ + --check +""" + +from __future__ import annotations + +import argparse +import csv +import datetime as dt +import hashlib +import io +import json +import subprocess +import sys +from collections.abc import Sequence +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any + +REPOSITORY_ROOT = Path(__file__).resolve().parents[1] +DEFAULT_OUT = ( + REPOSITORY_ROOT + / "packages" + / "microcosm-build" + / "tests" + / "fixtures" + / "uk" + / "firm_attributes_2025" +) +PROVENANCE_NAME = ".provenance.json" + +SOURCE_URL = ( + "https://www.ons.gov.uk/businessindustryandtrade/business/" + "activitysizeandlocation/datasets/ukbusinessactivitysizeandlocation" +) +SOURCE_URL_NOTE = ( + "ONS dataset landing page, as recorded for the 2025 edition in " + "firm-microsim-paper data/README.md; not a direct file link." +) +PAPER_REPOSITORY = "PolicyEngine/firm-microsim-paper" +WORKBOOK_SOURCE_PATH = "data/raw/ons/ukbusinessworkbook2025new.xlsx" + +#: The 12 UK regions in workbook order, with their GSS codes. +REGIONS: tuple[tuple[str, str], ...] = ( + ("E12000001", "North East"), + ("E12000002", "North West"), + ("E12000003", "Yorkshire and The Humber"), + ("E12000004", "East Midlands"), + ("E12000005", "West Midlands"), + ("E12000006", "East"), + ("E12000007", "London"), + ("E12000008", "South East"), + ("E12000009", "South West"), + ("W92000004", "Wales"), + ("S92000003", "Scotland"), + ("N92000002", "Northern Ireland"), +) +REGION_CODES = tuple(code for code, _ in REGIONS) +AGGREGATE_GEOGRAPHY_CODES = ("K02000001", "K03000001", "K04000001", "E92000001") + +#: Table 8's seven sizebands (GBP thousands), as in the paper's +#: ``ons_firm_turnover.csv`` columns. +TABLE_8_BANDS = ("0-49", "50-99", "100-249", "250-499", "500-999", "1000-4999", "5000+") +#: Tables 13 and 15 split Table 8's top two bands. +TABLE_13_BANDS = ( + "0-49", + "50-99", + "100-249", + "250-499", + "500-999", + "1000-1999", + "2000-4999", + "5000-9999", + "10000-49999", + "50000+", +) +TABLE_13_TO_TABLE_8_BAND = { + "0-49": "0-49", + "50-99": "50-99", + "100-249": "100-249", + "250-499": "250-499", + "500-999": "500-999", + "1000-1999": "1000-4999", + "2000-4999": "1000-4999", + "5000-9999": "5000+", + "10000-49999": "5000+", + "50000+": "5000+", +} + +#: Table 12's seven employment sizebands (persons employed; workbook note 5). +TABLE_12_BANDS = ("0-4", "5-9", "10-19", "20-49", "50-99", "100-249", "250+") + +#: ONS IDBR legal status codes, labels verbatim from Tables 12, 13 and 15 row 4. +LEGAL_STATUSES: tuple[tuple[int, str], ...] = ( + (1, "Company (incl. Building Society)"), + (2, "Sole Proprietor"), + (3, "Partnership"), + (4, "Public Corporation/Nationalised Body"), + (5, "Central Government"), + (6, "Local Authority"), + (7, "Non-profit Body or Mutual Association"), +) + +#: Table 13's broad industry groups (SIC 2007 division ranges), in order. +INDUSTRY_GROUPS: tuple[tuple[str, str], ...] = ( + ("01-03", "Agriculture, forestry & fishing"), + ("05-39", "Production"), + ("41-43", "Construction"), + ("45", "Motor trades"), + ("46", "Wholesale"), + ("47", "Retail"), + ("49-53", "Transport & Storage (inc. postal)"), + ("55-56", "Accommodation & food services"), + ("58-63", "Information & communication"), + ("64-66", "Finance & insurance"), + ("68", "Property"), + ("69-75", "Professional, scientific & technical"), + ("77-82", "Business administration & support services"), + ("84", "Public administration & defence"), + ("85", "Education"), + ("86-88", "Health"), + ("90-99", "Arts, entertainment, recreation & other services"), +) + +SIC_DIVISION_COUNT = 88 +GEOGRAPHY_ROW = 4 +BAND_ROW = 5 +FIRST_DATA_ROW = 6 + +REGION_TURNOVER = "ons_region_turnover.csv" +LEGAL_STATUS_TURNOVER = "ons_legal_status_turnover.csv" +LEGAL_STATUS_REGION_TURNOVER = "ons_legal_status_region_turnover.csv" +LEGAL_STATUS_EMPLOYMENT = "ons_legal_status_employment.csv" + + +@dataclass +class Extracted: + """One CSV's rows plus the source cells it read.""" + + sheet: str + title: str + header: tuple[str, ...] + rows: list[tuple[Any, ...]] = field(default_factory=list) + blank_cells: int = 0 + non_numeric_cells: dict[str, int] = field(default_factory=dict) + zero_cells: int = 0 + + def to_csv_bytes(self) -> bytes: + buffer = io.StringIO() + writer = csv.writer(buffer, lineterminator="\n") + writer.writerow(self.header) + writer.writerows(self.rows) + return buffer.getvalue().encode("utf-8") + + +def _split_label(value: Any) -> tuple[str, str]: + code, separator, label = str(value).strip().partition(" : ") + if not separator: + raise ValueError(f"expected 'CODE : label', got {value!r}") + return code.strip(), label.strip() + + +def _forward_fill(row: Sequence[Any]) -> list[Any]: + filled: list[Any] = [] + current = None + for value in row: + if value is not None: + current = value + filled.append(current) + return filled + + +def _count(value: Any, table: Extracted) -> int: + """Return a cell's count; blank or non-numeric cells are 0 and counted.""" + + if value is None or (isinstance(value, str) and not value.strip()): + table.blank_cells += 1 + return 0 + if isinstance(value, bool) or not isinstance(value, (int, float)): + marker = str(value).strip() + table.non_numeric_cells[marker] = table.non_numeric_cells.get(marker, 0) + 1 + return 0 + if value != int(value) or value < 0: + raise ValueError( + f"{table.sheet}: count {value!r} is not a non-negative integer" + ) + count = int(value) + if count == 0: + table.zero_cells += 1 + return count + + +def _band_columns( + rows: list[tuple[Any, ...]], sheet: str, bands: Sequence[str] +) -> dict[str, dict[str, int]]: + """Map each row-4 block header to ``{band: column index}``; checks bands.""" + + blocks = _forward_fill(rows[GEOGRAPHY_ROW - 1]) + labels = rows[BAND_ROW - 1] + columns: dict[str, dict[str, int]] = {} + for index, (block, band) in enumerate(zip(blocks, labels, strict=False)): + if index == 0 or block is None or band is None: + continue + columns.setdefault(str(block).strip(), {})[str(band).strip()] = index + expected = [*bands, "Total"] + for block, by_band in columns.items(): + if list(by_band) != expected: + raise ValueError(f"{sheet} {block!r}: bands {list(by_band)} != {expected}") + return columns + + +def _data_rows(rows: list[tuple[Any, ...]], sheet: str) -> list[tuple[Any, ...]]: + """Rows from the first data row up to, not including, ``Total``/the end.""" + + out = [] + for row in rows[FIRST_DATA_ROW - 1 :]: + label = row[0] + if label is None: + break + if str(label).strip() == "Total": + break + out.append(row) + if not out: + raise ValueError(f"{sheet}: no data rows") + return out + + +def _title(rows: list[tuple[Any, ...]]) -> str: + return str(rows[0][0]).strip() + + +def extract_region_turnover(rows: list[tuple[Any, ...]]) -> Extracted: + sheet = "Table 8" + table = Extracted( + sheet=sheet, + title=_title(rows), + header=("sic_division", "region_code", "turnover_band", "enterprises"), + ) + columns = _band_columns(rows, sheet, TABLE_8_BANDS) + by_code = {_split_label(block)[0]: block for block in columns} + expected_codes = [*AGGREGATE_GEOGRAPHY_CODES, *REGION_CODES] + if list(by_code) != expected_codes: + raise ValueError( + f"{sheet}: geography headers {list(by_code)} != {expected_codes}" + ) + for code, name in REGIONS: + if _split_label(by_code[code])[1] != name: + raise ValueError( + f"{sheet}: {code} is labelled {by_code[code]!r}, not {name!r}" + ) + data = _data_rows(rows, sheet) + if len(data) != SIC_DIVISION_COUNT: + raise ValueError( + f"{sheet}: expected {SIC_DIVISION_COUNT} SIC divisions, got {len(data)}" + ) + for row in data: + division, _ = _split_label(row[0]) + if len(division) != 2 or not division.isdigit(): + raise ValueError(f"{sheet}: unexpected SIC division label {row[0]!r}") + for code in REGION_CODES: + for band in TABLE_8_BANDS: + value = _count(row[columns[by_code[code]][band]], table) + table.rows.append((division, code, band, value)) + return table + + +def _status_columns( + rows: list[tuple[Any, ...]], sheet: str, bands: Sequence[str] = TABLE_13_BANDS +) -> dict[int, dict[str, int]]: + columns = _band_columns(rows, sheet, bands) + by_status: dict[int, dict[str, int]] = {} + expected = [*(f"{code} - {label}" for code, label in LEGAL_STATUSES), "Total"] + if list(columns) != expected: + raise ValueError(f"{sheet}: legal status headers {list(columns)} != {expected}") + for code, label in LEGAL_STATUSES: + by_status[code] = columns[f"{code} - {label}"] + return by_status + + +def _extract_legal_status_by_group( + rows: list[tuple[Any, ...]], + sheet: str, + band_column: str, + bands: Sequence[str], +) -> Extracted: + table = Extracted( + sheet=sheet, + title=_title(rows), + header=("industry_group", "legal_status", band_column, "enterprises"), + ) + columns = _status_columns(rows, sheet, bands) + data = _data_rows(rows, sheet) + groups = [_split_label(row[0]) for row in data] + if groups != list(INDUSTRY_GROUPS): + raise ValueError( + f"{sheet}: industry groups {groups} != {list(INDUSTRY_GROUPS)}" + ) + for row, (group, _) in zip(data, groups, strict=True): + for status, _label in LEGAL_STATUSES: + for band in bands: + value = _count(row[columns[status][band]], table) + table.rows.append((group, status, band, value)) + return table + + +def extract_legal_status_turnover(rows: list[tuple[Any, ...]]) -> Extracted: + return _extract_legal_status_by_group( + rows, "Table 13", "turnover_band", TABLE_13_BANDS + ) + + +def extract_legal_status_employment(rows: list[tuple[Any, ...]]) -> Extracted: + return _extract_legal_status_by_group( + rows, "Table 12", "employment_band", TABLE_12_BANDS + ) + + +def extract_legal_status_region_turnover(rows: list[tuple[Any, ...]]) -> Extracted: + sheet = "Table 15" + table = Extracted( + sheet=sheet, + title=_title(rows), + header=("region_code", "legal_status", "turnover_band", "enterprises"), + ) + columns = _status_columns(rows, sheet) + data = _data_rows(rows, sheet) + geographies = [_split_label(row[0])[0] for row in data] + expected = [*AGGREGATE_GEOGRAPHY_CODES, *REGION_CODES] + if geographies != expected: + raise ValueError(f"{sheet}: geography rows {geographies} != {expected}") + for row, code in zip(data, geographies, strict=True): + if code in AGGREGATE_GEOGRAPHY_CODES: + continue + for status, _label in LEGAL_STATUSES: + for band in TABLE_13_BANDS: + value = _count(row[columns[status][band]], table) + table.rows.append((code, status, band, value)) + return table + + +EXTRACTORS = { + REGION_TURNOVER: ("Table 8", extract_region_turnover), + LEGAL_STATUS_TURNOVER: ("Table 13", extract_legal_status_turnover), + LEGAL_STATUS_EMPLOYMENT: ("Table 12", extract_legal_status_employment), + LEGAL_STATUS_REGION_TURNOVER: ("Table 15", extract_legal_status_region_turnover), +} + + +def extract(workbook: Path) -> dict[str, Extracted]: + import openpyxl # noqa: PLC0415 - local-only dependency, kept out of CI imports + + book = openpyxl.load_workbook(workbook, read_only=True, data_only=True) + try: + return { + name: extractor(list(book[sheet].iter_rows(values_only=True))) + for name, (sheet, extractor) in EXTRACTORS.items() + } + finally: + book.close() + + +def _sha256(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def _git(workbook: Path, *args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + ["git", "-C", str(workbook.parent), *args], + capture_output=True, + text=True, + check=False, + ) + + +def _paper_state(workbook: Path) -> dict[str, Any]: + """The paper checkout's HEAD and whether the workbook is tracked, unmodified.""" + + head = _git(workbook, "rev-parse", "HEAD") + if head.returncode != 0: + return {"paper_commit": None, "workbook_tracked_at_paper_commit": False} + commit = head.stdout.strip() + tracked = ( + _git(workbook, "ls-files", "--error-unmatch", workbook.name).returncode == 0 + ) + unmodified = ( + _git(workbook, "diff", "--quiet", "HEAD", "--", workbook.name).returncode == 0 + ) + return { + "paper_commit": commit, + "paper_commit_short": commit[:7], + "workbook_tracked_at_paper_commit": tracked and unmodified, + } + + +def provenance( + workbook: Path, tables: dict[str, Extracted], payloads: dict[str, bytes] +) -> dict[str, Any]: + data = workbook.read_bytes() + files = {} + for name, table in tables.items(): + files[name] = { + "sha256": _sha256(payloads[name]), + "bytes": len(payloads[name]), + "rows": len(table.rows), + "columns": list(table.header), + "source_sheet": table.sheet, + "source_title": table.title, + "blank_cells_written_as_zero": table.blank_cells, + "non_numeric_cells_written_as_zero": dict( + sorted(table.non_numeric_cells.items()) + ), + "zero_cells": table.zero_cells, + } + files[LEGAL_STATUS_REGION_TURNOVER]["role"] = ( + "held out: a check on drawn legal status by region, not a draw input" + ) + files[LEGAL_STATUS_EMPLOYMENT]["role"] = ( + "draw input: conditions legal status on employment within industry group" + ) + return { + "source_repository": PAPER_REPOSITORY, + **_paper_state(workbook), + "workbook": { + "source_path": WORKBOOK_SOURCE_PATH, + "sha256": _sha256(data), + "bytes": len(data), + "publication": "ONS, UK Business: Activity, Size and Location, 2025", + "published": "2025-09-24", + "source_url": SOURCE_URL, + "source_url_note": SOURCE_URL_NOTE, + "reference_period_note": ( + "Workbook note 4: turnover for most traders is from VAT returns " + "covering the financial year 2023/2024." + ), + "employment_note": ( + "Workbook note 5: IDBR employment is drawn mainly from BRES, with " + "PAYE jobs or employment imputed from VAT turnover for the " + "smallest units." + ), + }, + "extraction_date": dt.date.today().isoformat(), + "tool": "tools/extract_uk_firm_ons_attribute_tables.py", + "command": ( + "uv run --no-sync python tools/extract_uk_firm_ons_attribute_tables.py " + "--workbook /data/raw/ons/ukbusinessworkbook2025new.xlsx" + ), + "unit": "VAT and/or PAYE based enterprises", + "disclosure": { + "rounding": "Counts are control rounded to base 5 by ONS (workbook row 3).", + "zeros": ( + "Workbook note 7: values may be rounded down to zero, so zeros " + "are not necessarily true zeros; totals across tables may differ " + "by minor amounts. Zeros are kept as 0." + ), + "suppressed_or_blank_cells": ( + "A blank or non-numeric cell inside a data block is written as 0 " + "and counted per file (blank_cells_written_as_zero, " + "non_numeric_cells_written_as_zero). The 2025 workbook has none: " + "disclosure control is by rounding, not suppression markers." + ), + }, + "excluded": [ + "Table 8 aggregate geographies K02000001 (UK), K03000001 (GB), " + "K04000001 (England and Wales), E92000001 (England)", + "Table 15 aggregate geography rows (the same four codes)", + "every Total column and the Total row of each table", + "the Total legal status block of Tables 12, 13 and 15", + ], + "region_codes": dict(REGIONS), + "legal_status": { + str(code): { + "label": label, + "source": "Tables 12, 13 and 15 row 4, verbatim", + } + for code, label in LEGAL_STATUSES + }, + "industry_groups": { + group: {"label": label, "sic_divisions": group} + for group, label in INDUSTRY_GROUPS + }, + "turnover_bands": { + "unit": "GBP thousands", + "ons_region_turnover.csv": list(TABLE_8_BANDS), + "ons_legal_status_turnover.csv": list(TABLE_13_BANDS), + "ons_legal_status_region_turnover.csv": list(TABLE_13_BANDS), + "table_8_labels_note": ( + "The same seven labels as the columns of " + "tests/fixtures/uk/firm_2024_25/ons_firm_turnover.csv." + ), + "table_13_to_table_8": dict(TABLE_13_TO_TABLE_8_BAND), + }, + "employment_bands": { + "unit": "persons employed (IDBR employment, workbook note 5)", + LEGAL_STATUS_EMPLOYMENT: list(TABLE_12_BANDS), + }, + "sic_division_key": ( + "Two-digit SIC 2007 division as text ('01'); read with dtype=str. " + "All 88 divisions of Table 8, all-zero divisions included." + ), + "files": files, + } + + +def _write(out: Path, workbook: Path, tables: dict[str, Extracted]) -> None: + out.mkdir(parents=True, exist_ok=True) + payloads = {name: table.to_csv_bytes() for name, table in tables.items()} + for name, payload in payloads.items(): + (out / name).write_bytes(payload) + record = provenance(workbook, tables, payloads) + (out / PROVENANCE_NAME).write_text( + json.dumps(record, indent=2) + "\n", encoding="utf-8" + ) + for name, table in tables.items(): + print(f"wrote {out / name} ({len(table.rows)} rows)") + print(f"wrote {out / PROVENANCE_NAME}") + + +def _check(out: Path, tables: dict[str, Extracted]) -> int: + stale = [] + for name, table in tables.items(): + path = out / name + if not path.is_file() or path.read_bytes() != table.to_csv_bytes(): + stale.append(name) + if stale: + print(f"stale or missing: {', '.join(stale)}", file=sys.stderr) + return 1 + print(f"{len(tables)} CSVs match the workbook") + return 0 + + +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--workbook", type=Path, required=True) + parser.add_argument("--out", type=Path, default=DEFAULT_OUT) + parser.add_argument( + "--check", + action="store_true", + help="re-extract and compare bytes with the committed CSVs; write nothing", + ) + args = parser.parse_args(argv) + workbook = args.workbook.resolve() + tables = extract(workbook) + if args.check: + return _check(args.out, tables) + _write(args.out, workbook, tables) + 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..7be62424c7 --- /dev/null +++ b/tools/snapshot_policyengine_uk_firm_inputs.py @@ -0,0 +1,192 @@ +"""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`` come from the region and +#: legal-status draws (``uk_runtime/firm_attributes.py``). +#: 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())